import os
import sys
import random
from os.path import dirname, basename, isfile
import glob
import inspect
import re
import copy
import numpy as np

from collections import deque, defaultdict
from string import Formatter
import generatorUtils as gu

CUR_DIR = os.path.dirname(__file__)
CODEORG_DIR = os.path.join(CUR_DIR, '..', 'utils', 'codeorg_utils')
CODEORG_DIR = os.path.realpath(CODEORG_DIR)
sys.path.append(CODEORG_DIR)

import blockToTree, treeToString

GRAMMAR = 'liftoff'

class Engine:
    _nonterminalCache = None

    def __init__(self, grammar_dir):
        self.reset()
        self._nonterminals, self._reusableNonterminals = self._getNonTerminals(grammar_dir)

        # we need to do this bc we need special processing to handle this
        self._isCodeOrg = 'codeorg' in grammar_dir

    def reset(self):
        self.state = {}
        self.choices = {}
        self.rubric = {}

    def processCodeOrgProgram(self, program, rubricItems, choices):

        def applyPostFunctions(program, rubricItems, choices, proba=0.05):
            # https://github.com/mhw32/program-vae/blob/master/programvae/tools/run/simulate.py
            choices['doesNotGetNesting'] = False

            if 'Repeat' in program:
                if random.random() < proba:
                    repeatStart = program.index('Repeat')
                    blockStart = program.index('{', repeatStart) + 1
                    blockEnd = program.index('}', repeatStart)
                    body = program[blockStart:blockEnd].strip()

                    # punt on bodies with nesting loops
                    if '{' in body:
                        return program, rubricItems, choices

                    lines = body.split('\n')
                    # punt if num lines is less that or equal to 2
                    if len(lines) < 2:
                        return program, rubricItems, choices

                    # put only the first line in the repeat
                    newBlock = lines[0] +  '\n'
                    newBlock += '}\n'
                    for line in lines[1:]:
                        newBlock += line + '\n'
                    beforeBlock = program[:blockStart]
                    afterBlock = program[blockEnd+1:]

                    program = beforeBlock + '\n' + newBlock + '\n' + afterBlock
                    choices['doesNotGetNesting'] = True

                    return program, rubricItems, choices

            return program, rubricItems, choices

        program = program.replace('Program\n', '')
        # program, rubricItems, choices = applyPostFunctions(
        #     program, rubricItems, choices)
        tree = blockToTree.convert(program)
        tokenList = treeToString.flatten_tree(tree)

        return ' '.join(tokenList), rubricItems, choices, program

    def renderProgram(self):
        while True:
            self.reset()

            try:
                program = self.render('Program')
            except BaseException as e:
                if 'Choice name' in str(e):
                    continue
                else:
                    raise e

            program = gu.fixWhitespace(program)
            rubricItems = self.getRubricItems()
            choices = self.choices

            code = None
            if self._isCodeOrg:
                program, rubricItems, choices, code = self.processCodeOrgProgram(
                    program, rubricItems, choices)

            return program, rubricItems, choices, code

    def getRubricItems(self):
        return self.rubric

    def _pick_rv(self, choice_name, values):
        if type(values) is list:
            # reduce uniform case to dictionary case
            values = {val: 1 for val in values}

        tuples = [(v, p) for v, p in values.items()]
        # unpack list of pairs to pair of lists
        choices, ps = list(zip(*tuples))
        ps /= np.sum(ps)

        # operate on indices so numpy doesnt do weird typecasts
        choice_idx = np.random.choice(range(len(choices)), p=ps)
        return choices[choice_idx]

    def addGlobalChoice(self, choice_name, val):
        if choice_name in self.choices:
            raise ValueError('Key [{}] already in global choices'.format(choice_name))

        self.choices[choice_name] = val

    def _compileRegisteredIds(self, nonterminals, reusableNonterminals):
        '''
         This method should loop through all decisions and get their preregistered ids.
         This will give us an overview of how each reusable decision is intended to be used.

         We group these registered ids by the ReusableDecision they are relevatn to and
         return a dictionary from ReusableDecision name to set of valid ids for that decision.
        '''
        # we keep track of the reusable non terminals

        allRegisteredIds = defaultdict(list)
        for nonterminal in nonterminals.values():
            registeredIds = nonterminal.preregisterDecisionIds()
            if registeredIds is None:   # no ids registered
                continue

            for reusable_decision, valid_ids in registeredIds.items():
                allRegisteredIds[reusable_decision].extend(list(valid_ids))

        registeredButNotReusable = set(allRegisteredIds.keys()) - reusableNonterminals
        reusableButNotRegistered = reusableNonterminals - set(allRegisteredIds.keys())
        # make sure evely registeredId corresponds to a reusable decision.
        if registeredButNotReusable:
            raise ValueError(f'Invalid registration of non-reusable decisions {registeredButNotReusable}')

        # print warnings for reusable decisions that dont have valid ids registered?
        if reusableButNotRegistered:
            print(f'WARNING: reusable decisions not registered anywhere: {reusableButNotRegistered}')
            input('Press enter to continue: ')

        return allRegisteredIds

        # TODO: make it so that any runtime registerChoices is not dynamic---throw error if. Like rubric pipeline

    def _setResusableDecisionIds(self, nonterminals, reusableNonterminals):
        registeredIds  = self._compileRegisteredIds(nonterminals, reusableNonterminals)
        for reusable in reusableNonterminals:
            validIds = registeredIds[reusable]
            nonterminals[reusable].registerValidIds(validIds)

    def _getNonTerminals(self, grammar_dir):
        nonterminals, reusableNonterminals = self._loadNonTerminals(grammar_dir)
        self._setResusableDecisionIds(nonterminals, reusableNonterminals)   # modifies params in place
        return nonterminals, reusableNonterminals

    def _loadNonTerminals(self, grammar_dir):
        # if Engine._nonterminalCache != None:
        #   return Engine._nonterminalCache
        nonterminals = {}
        reusableNonterminals = set()
        file_paths = glob.glob(os.path.join(grammar_dir, "*.py"))
        files = [ f[:-3].replace(os.path.sep, '.') for f in file_paths if isfile(f) and not f.endswith('__init__.py')]
        for f in files:
            module = __import__(f, fromlist=['object'])
            for obj in  dir(module):
                if not obj.startswith('__'):
                    clazz = module.__getattribute__(obj)
                    # TODO: fix hacky conditions

                    if inspect.isclass(clazz) and clazz.__base__.__name__.endswith('Decision') and not clazz.__name__ == 'ReusableDecision':
                        name = clazz.__name__
                        if clazz.__base__.__name__ == 'ReusableDecision':
                            reusableNonterminals.add(name)

                        if name in nonterminals:
                            raise ValueError('Repeated name for nonterminal: {}'.format(name))
                        nonterminals[name] =  clazz(self)
        Engine._nonterminalCache = nonterminals
        return nonterminals, reusableNonterminals

    def symbol_from_key(self, format_key):
        match = re.search(r'([A-Za-z]+)(_\d)?', format_key)
        return match.group(1)

    def render(self, nonterminal, params = {}):
        curr = self._nonterminals[nonterminal]
        curr._setParams(params)

        curr.registerChoices()
        curr.updateRubric()
        render = curr.renderCode()

        to_generate = [t[1] for t in Formatter().parse(render) if t[1] is not None]

        formatter = dict()
        for format_key in to_generate:
            symbol_to_gen = self.symbol_from_key(format_key)
            formatter[format_key] = self.render(symbol_to_gen)
        curr._setParams({}) # clear params

        return render.format(**formatter)

if __name__ == "__main__":
    e = Engine('grammars/'+GRAMMAR)
    for i in range(1000):
        program, rubric, choices, _ = e.renderProgram()
        print(choices)
        print(program)
        print(rubric)
        print('----')


# [백준]1904번-동적계획법-01타일-S3
# https://github.com/irishNoah/Algorithm-Study
# https://www.acmicpc.net/problem/1904

'''
00인 타일을 'X'로, 1인 타일을 'Y'로 치환해서
N이 1~6일 때의 경우의 수를 각각 구하다보면
N이 증가할 때마다 발생할 수 있는 경우의 수가 피보나치 수열을
형성한다는 것을 파악할 수 있다.
'''

def tile(n):
    if n == 1:
        return tableFib[1]

    for cnt in range(2, n+1):
        tableFib[cnt] = (tableFib[cnt-2] + tableFib[cnt-1]) % 15746

    return tableFib[n]

n = int(input())

# DP 활용 위한 리스트 테이블 생성
tableFib = [0] * 1000001
tableFib[0] = 1; tableFib[1] = 1

print(tile(n))

'''
- 처음에는 마지막 print문에서 tile() 함수를 통해 얻어온 값에서
15746로 나눈 나머지 값을 출력하게 했다. 하지만, 이렇게 제출한 것에서
메모리 초과 판정을 얻게 됐다.
- dp로 피보나치와 같은 경우를 풀게 될 경우, 재귀 함수에 비해 시간을 비약적으로
줄일 수 있다는 것은 확실히 알 수 있다.
- 하지만, 리스트 자체의 각각의 값은 n이 값이 클 수록 각 피보나치 n에 대한 결과값은 매우 커지게 된다.
- 이 문제에서의 n의 최대값은 1,000,000이다. 즉, 1,000,000을 입력하게 되면, 이에 대한 값은 매우 커지게 될 것이다.
- 그렇기 때문에, 이 문제에서 메모리 초과 판정을 받게 된 것이다.
- 그렇다면, 어떻게 해결할 수 있을까?
- 그 방법은 마지막 print문에서 나머지 값을 구하는 것이 아니라,
애초에 각 리스트 값에서 나머지로 나눈 값을 구하는 것이다.
이렇게 할 경우 각 리스트의 값이 매우 작은 수가 될 것이기 때문이다!
'''

알고리즘/파이썬(Python)/002-동적계획법(DP)/002-[백준]1904번-동적계획법-01타일-S3.py


import scipy.special as spe
import numpy as np
from bessel import rj,rh,d_rh, d_rj

##################################################################################
###       Script for the caclulation of coefficient for the internal field     ###
##################################################################################

def calc_coeff_int(n,k_int, k_ext, a):
      """
      Calculate the internal field coefficient c_n and d_n
      Calculation derived from [1] C. F. ohren, D. R. Huffman, Absorption and scattering of light by small particle

      Here, rj (resp rh) is the Riccati Bessel's function of the first kind (resp third kind)
      and d_rj (resp d_rh) is its derivative. These functions are calculated in the bessel.py file.

      Params :
      --------
                  n     : int  | mode
                  k_int : real | wave vector of the internal medium
                  k_ext : real | wave vector of the external medium
                  a     : real | radius of the sphere

      Returns :
      ---------

                  c_n :   real | coefficient for the ...
                  d_n :   real | coefficient for the ...

      """

      ## usefull parameters for calculations
      x = k_ext*a
      m = k_int/k_ext

      ## calculation of the coefficient from boundary conditions (see [1])
      c_n = ( m*rj(n,x) *  d_rh(n,x)  -  m* rh(n,x) * d_rj(n,x)    )/  \
            (   rj(n,m*x)* d_rh(n,x)  -  m* rh(n,x) * d_rj(n,m*x)  )

      d_n = ( m* rj(n,x )  * d_rh(n,x) - m* rh(n,x) * d_rj(n,x)    )/  \
            (m**2* rj(n,m*x) * d_rh(n,x) -    rh(n,x) * d_rj(n,m*x)  )

      return (c_n, d_n)


import sys
dp={}
def minCoins(coins, m, V):
    if V==0:
        return 0
    if V<0:
        return 999999
    res=999999
    if V in dp:
        return dp[V]
    for i in range(m):
        if V>=coins[i]:
            if (V-coins[i]) in dp:
                a=dp[V-coins[i]]
            else:
                a=minCoins(coins,m,V-coins[i])
            sub=1+a
            if sub!=99999:
                res=min(sub,res)
    dp[V]=res
    return dp[V]

# Driver program to test above function
coins = [ 5,11]
m = len(coins)
V = 43
print("Minimum coins required is",minCoins(coins, m, V))


USER_TYPE_CHOICE = (
        ("COACH", "Mentor"),
        ("STUDENT", "Mentee"),
    )

GENDER_TYPE_CHOICES = (
        ("MALE", "Male"),
        ("FEMALE", "Female"),
        ("OTHER","Other"),
    )
ETHNICITY_TYPE_CHOICES = (
        ("BRITISH", "British"),
        ("OTHER", "Other"),
    )
LANGUAGE_TYPE_CHOICE = (
        ("ENGLISH", "English"),
        ("SPANISH", "Spanish"),
        ("OTHER","Other"),
    )
PEROSNALITY_TYPE_CHOICE = (
        ("EXTROVERT", "Extrovert"),
        ("INTROVERT", "Introvert"),
    )
FACULTY_TYPE_CHOICE = (
        ("SCIENCE_AND_TECH", "Science and Technology"),
        ("OTHER", "Other"),

    )
DISCPLINARY_ACTION_CHOICES = (
        ("YES","Yes I have previous record of discplinary actions"),
        ("NO","No I dont have any previous discplinary actions")
    )
TEACHING_EXPERIENCE_TYPE_CHOICE = (
        ("NO_EXPERIENCE", "I don't have any experience"),
        ("ONE_OR_MORE", "I have experience"),

    )
MENTORING_EXPERIENCE_TYPE_CHOICE = (
        ("NO_EXPERIENCE", "I don't have any mentoring experience"),
        ("ONE_OR_MORE", "I have mentoring experience"),

    )
TIME_AVALIBILITY_TYPE_CHOICE = (
        ("ONE_TO_FIVE_HOURS", "1-5 hours per week"),
        ("MORE_THAN_FIVE_HOURS", "More than 5 hours"),

    )
ACCEPT_DISCPLINARY_ACTION_CHOICES = (
        ("ACCEPT_YES","Yes I accept student with previous record of discplinary actions"),
        ("ACCEPT_NO","No I dont prefer student with any previous discplinary actions")
    )


def solution(N):
    # write your code in Python 3.6
    binary = bin(N).replace("0b", "")

    gap = []
    lis = [int(s) for s in binary]
    # import pdb;pdb.set_trace()
    for i in range(0,len(lis)):
        if lis[i] == 0:
            continue
        elif lis[i] == 1:
            if i == len(lis) -1:
                break
            til_end = lis[i:]
            gap.append(find_gap(til_end))

        # if i == len(lis):
    gap = [0 if v is None else v for v in gap]
    # if None in gap:
    #     return 0
    return max(gap)

def find_gap(end):
    length = len(end) -1
    count=0
    for i in range(1,len(end)):
        if end[i] ==0:
            count+=1
        elif end[i] == 1 or length == i:
            return count

print(solution(9))
print(solution(15))
print(solution(1041))
print(solution(32))
print(solution(529))
print(solution(20))


'''
@author: jmc
'''
from setuptools import setup, find_packages

version = '1.3.0'

setup(
    name='odn-ckancommons',
    version=version,
    description="""
    CKAN's commons for development of ODN related extensions
    """,
    long_description="""
    """,
    classifiers=[], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
    keywords='',
    author='Jan Marcek',
    author_email='jmc@eea.sk',
    url='',
    license='',
    packages=find_packages(exclude=['examples', 'tests']),
    namespace_packages=['odn_ckancommons'],
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        ''
    ],
)


#!/usr/bin/env python
"""Distutils setup file"""
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup

# Metadata
PACKAGE_NAME = "BytecodeAssembler"
PACKAGE_VERSION = "0.6.1"
PACKAGES = ['peak', 'peak.util']

def get_description():
    # Get our long description from the documentation
    f = open('README.txt')
    lines = []
    for line in f:
        if not line.strip():
            break     # skip to first blank line
    for line in f:
        if line.startswith('.. contents::'):
            break     # read to table of contents
        lines.append(line)
    f.close()
    return ''.join(lines)

setup(
    name=PACKAGE_NAME,
    version=PACKAGE_VERSION,
    url = "http://pypi.python.org/pypi/BytecodeAssembler",
    description='Generate Python code objects by "assembling" bytecode'
        ' (Now includes a functional/AST-oriented API, too!)',
    long_description = get_description(),
    author="Phillip J. Eby",
    author_email="peak@eby-sarna.com",
    license="ZPL 2.1",
    install_requires = ['DecoratorTools>=1.2', 'SymbolType>=1.0'],
    test_suite = 'test_assembler',
    packages = PACKAGES,
    namespace_packages = PACKAGES,
)


import pickle
from pathlib import Path

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as ptc

from nicpy import nic_misc, nic_pic
import a_star
from geometry import Square, SquareGrid

def algo_animation(history_directory, fps=2, frame_skip=1):

    matplotlib.use('Agg')   # Gets rid of plot popups, faster to produce frames
    max_iteration = 0       # Find the number of iterations saved
    for file in history_directory.iterdir():
        if file.is_file():
            string_iter_num = str(file.stem).split('_')[0]
            if string_iter_num != 'graph':
                if int(string_iter_num)>max_iteration: max_iteration = int(string_iter_num)

    # Save a frame for each algo iteration
    counter = 0
    frames_directory = history_directory/'frames'
    nic_misc.mkdir_if_DNE(frames_directory)
    its = list(range(0, max_iteration+1, frame_skip))
    if its[-1] != max_iteration: its.append(max_iteration)
    for iteration in its:
        print('Producing image {} of {}'.format(iteration+1, max_iteration+1))
        frame = plot_algo_state(history_directory, iteration)
        frame.savefig(frames_directory/'frame_{}.png'.format(str(counter).zfill(5)), bbox_inches='tight')
        counter += 1
        plt.close(frame)

    nic_pic.frames_to_video(frames_directory, video_name_with_format='video.avi', image_format='png', fps=fps)

def plot_algo_state(history_directory, iteration):
    maze = pickle.load(open(str(history_directory/'graph.dat'.format(iteration)), 'rb'))
    closed_list = pickle.load(open(str(history_directory/'{}_closed_list.dat'.format(iteration)), 'rb'))
    open_list = pickle.load(open(str(history_directory/'{}_open_list.dat'.format(iteration)), 'rb'))
    current_node = pickle.load(open(str(history_directory/'{}_current_node.dat'.format(iteration)), 'rb'))
    current_path = a_star.reconstruct_path(current_node)
    fig = plot_maze(maze, current_path, closed_list, open_list)
    return fig

def plot_maze(maze, current_path=None, closed_list=None, open_list=None):
    maze.check_graph()
    fig, ax = plt.subplots(1, dpi=100)
    plt.gca().invert_yaxis()
    ax.axis('equal')
    ax.set_facecolor([0.5, 0.5, 0.5])
    patch_width = 1

    # Add lines on top layers
    for row in range(maze.dimensions[0]+1):
        ax.plot([0, maze.dimensions[1]], [row, row], 'k', zorder=102, linewidth=3)
    for col in range(maze.dimensions[1]+1):
        ax.plot([col, col], [0, maze.dimensions[0]], 'k', zorder=103, linewidth=3)

    # Add colour patches
    for row in range(maze.dimensions[0]):
        for col in range(maze.dimensions[1]):
            if maze.maze_array[row, col] > 0: ax.add_patch(ptc.Rectangle([col, row], patch_width, patch_width, color = [1, 1, 1]))
            if maze.maze_array[row, col] == 0: ax.add_patch(ptc.Rectangle([col, row], patch_width, patch_width, color=[0.3, 0.2, 0.1], zorder=100))
            elif (row, col) == maze.start: ax.add_patch(ptc.Rectangle([col, row], patch_width, patch_width, color='r', zorder=101))
            elif (row, col) == maze.end: ax.add_patch(ptc.Rectangle([col, row], patch_width, patch_width, color='g'))

    # These elements change each time
    if closed_list:
        for node in closed_list:
            ax.add_patch(ptc.Rectangle((node.label[1], node.label[0]), patch_width, patch_width, color='y'))
    if open_list:
        for pair in open_list.elements:
            node = pair[1]
            ax.add_patch(ptc.Rectangle((node.label[1], node.label[0]), patch_width, patch_width, color='m'))
    if current_path:
        for i, step in enumerate(current_path[1:-1]):
            # ax.add_patch(ptc.Rectangle((step[1], step[0]), 1, 1, color='b'))
            ax.text(step[1]+0.5, step[0]+0.5, 'x', color='b', horizontalalignment='center', verticalalignment='center')

    return fig

if __name__ == '__main__':
    # Plot an algo state
    plot_algo_state(Path(r'E:\dev\python_projects\pathfinding\saved_histories\2020-08-16_15_13_19'), 40)

    # Create an animation
    algo_animation(Path(r'E:\dev\python_projects\pathfinding\saved_histories\2020-08-16_15_13_19'), fps=5, frame_skip = 1)


from mininet.topo import Topo
from mininet.net import Mininet
from mininet.log import setLogLevel, info
from mininet.link import TCLink
from mininet.node import RemoteController
from mininet.node import Node
from mininet.cli import CLI
import os
import sys

num = int(sys.argv[1])

class Topo(Topo):
    Hs = []
    Ss = []
    Cs = []

    def __init__(self, k, **opts):
        super(Topo, self).__init__(**opts)
        # generate the core switch and assign the dpid
        # info('*** Add switches\n')
        # switch = self.addSwitch('Switch', dpid='0000000000000001')
        # print('Switch added: dpid = 0000000000000001')

        # generate the servers
        info('*** Add servers\n')
        for i in range(1, 4):
            self.Ss.append(self.addHost('s%s' %
                                        (i - 1), mac='00:00:00:00:00:0%s' % i))
            print('Server s%s added' % i)

        info('*** Add a ctrl switch\n')
        self.Cs.append(self.addSwitch(
            'ctrlSw0', dpid='0000000000000001'))
        print('Switch added: dpid = 0000000000000001')

        # generate the hosts
        info('*** Add hosts\n')
        for i in range(1, k + 1):
            self.Hs.append(self.addHost('h%s' %
                                        i, mac='00:00:00:00:00:0%s' % (i + 3)))
            print('Host h%s added' % i)

        # connect the host with switch
        for i in range(1, k + 1):
            self.addLink(self.Cs[0], self.Hs[i - 1])

        # connect the servers with switch
        for i in range(1, 4):
            self.addLink(self.Cs[0], self.Ss[i - 1])

    def setOvs(self):
        self.setproto(self.Cs)

    def setproto(self, list):
        for sw in list:
            cmd = "sudo ovs-vsctl set bridge %s protocols=OpenFlow13" % sw
            os.system(cmd)

# run the mininet test
def simpleTest():
    topo = Topo(k=num)
    net = Mininet(topo=topo, link=TCLink, controller=None,
                  autoSetMacs=False, autoStaticArp=True)
    net.addController('controller', controller=RemoteController,
                      ip="127.0.0.1", port=6633, protocols="OpenFlow13")
    net.start()
    topo.setOvs()
    CLI(net)
    net.stop()

if __name__ == '__main__':
    setLogLevel('info')
    simpleTest()


from . import app
from .models import Survey
from flask import url_for, session, request
from twilio.twiml.messaging_response import MessagingResponse
from sms_app.send_sms import client
from sms_app.scan_email import survey_prompt, welcome_message
import datetime

@app.route('/message')
def sms_survey():
    response = MessagingResponse()

    now = datetime.datetime.now()

    # Get the to/from numbers from the latest request
    from_num = request.values['From']
    to_num = request.values['To']

    # Get the message most recently sent from us
    messages = client.messages.list(from_=to_num, to=from_num, limit=1)
    message_text = messages[0].body

    # new code with 5 minute time limit, and reprompt reset

    if message_text == survey_prompt:
        if 'instance_id' in session:
            del session['instance_id']
        if 'question_id' in session:
            del session['question_id']
        if 'start_time' in session:
            del session['start_time']
        session['instance_id'] = messages[0].sid

    if 'question_id' in session:
        delta = now - session['start_time']
        if delta.seconds > 300:
            del session['start_time']
            del session['question_id']
            del session['instance_id']
            response.message("The time to complete the survey has expired")
        else:
            response.redirect(url_for('answer', question_id=session['question_id']))
    else:
        survey = Survey.query.first()

        if survey_error(survey, response.message):
            return str(response)

        welcome_user(survey, response.message)
        redirect_to_first_question(response, survey)
    return str(response)

def redirect_to_first_question(response, survey):
    first_question = survey.questions.order_by('id').first()
    first_question_url = url_for('question', question_id=first_question.id)
    session['start_time'] = datetime.datetime.now()
    response.redirect(url=first_question_url, method='GET')

def welcome_user(survey, send_function):
    welcome_text = welcome_message
    send_function(welcome_text)

def survey_error(survey, send_function):
    if not survey:
        send_function('Sorry, but there are no surveys to be answered.')
        return True
    elif not survey.has_questions:
        send_function('Sorry, there are no questions for this survey.')
        return True
    return False

# Static Response
@app.route('/static')
def sms_static():
    resp = MessagingResponse()

    resp.message("If you have any issues accessing the survey, please contact us at jmrosenberg@utk.edu")

    return str(resp)


"""Defines functions for standard shell operations that are common on Unix but
   are not readily available on Windows in a cross platform way; this is
   intended to replace shutil which is less usable for copying and removing
   trees."""

import cx_Logging
import os
import stat
import sys

def CopyFile(source, target, bufferSize = 16 * 1024, log = True):
    """Copy the source to the target."""
    if log:
        cx_Logging.Info("copying %s to %s...", source, target)
    sourceFile = open(source, "rb")
    if os.path.exists(target):
        Remove(target, log = log)
    targetFile = open(target, "wb")
    while True:
        buffer = sourceFile.read(bufferSize)
        if not buffer:
            break
        targetFile.write(buffer)

def CopyStat(source, target, includeTimes = False):
    """Copy the stat information from the source to the target."""
    sourceStat = os.stat(source)
    mode = stat.S_IMODE(sourceStat.st_mode)
    os.chmod(target, mode)
    if includeTimes:
        os.utime(target, (sourceStat.st_atime, sourceStat.st_mtime))

def Copy(source, target, includeTimes = False):
    """Copy the source to the target."""
    if os.path.isdir(target):
        target = os.path.join(target, os.path.basename(source))
    CopyFile(source, target)
    CopyStat(source, target, includeTimes)

def CopyTree(source, target, includeTimes = False, log = True):
    """Recursively copy a directory tree."""
    for name in os.listdir(source):
        sourceName = os.path.join(source, name)
        targetName = os.path.join(target, name)
        if os.path.isdir(sourceName):
            if os.path.exists(targetName):
                RemoveTree(targetName, log)
            os.mkdir(targetName)
            CopyTree(sourceName, targetName, includeTimes)
        else:
            CopyFile(sourceName, targetName)
            CopyStat(sourceName, targetName, includeTimes)

def Remove(path, log = True):
    """Remove a file or a directory tree recursively."""
    if os.path.isdir(path):
        RemoveTree(path, log)
    else:
        if log:
            cx_Logging.Info("removing file %s...", path)
        if sys.platform == "win32":
            os.chmod(path, 0x1ff)
        os.remove(path)

def RemoveTree(path, log = True):
    """Recursively remove a directory tree."""
    try:
        currentDir = os.getcwd()
    except OSError:
        currentDir = None
    if currentDir is None or currentDir.startswith(path):
        os.chdir("/")
    if log:
        cx_Logging.Info("removing directory %s...", path)
    for name in os.listdir(path):
        fullName = os.path.join(path, name)
        Remove(fullName, log = log)
    if sys.platform == "win32":
        os.chmod(path, 0x1ff)
    os.rmdir(path)


from HoG_SVM_SlidingWindow import *
from define_parameter_dict import params_dict
from moviepy.editor import VideoFileClip
import numpy as np

with open(params_dict['svm_pickel_file_for_video'],'rb') as fp:
    [cl_svm_vid, std_scaler_vid] = pickle.load(fp)
scale_list = params_dict['detection_scales']
consecutive_appearance = params_dict['consecutive_number_of_frames']

#This function takes two rectangles R1 and R2.  Returns ratio of areas of intersection of R1,R2 to the area of R1
def rect_overlap(rect1, rect2):
    overlap = 0.0
    row_top = max(rect1[0], rect2[0])
    row_bottom = min(rect1[1], rect2[1])
    col_left = max(rect1[2], rect2[2])
    col_right = min(rect1[3], rect2[3])
    if col_right>col_left and row_bottom>row_top:
        overlap = (col_right-col_left)*(row_bottom-row_top)/(rect1[1]-rect1[0])/(rect1[3]-rect1[2])
    return overlap

def process_video_frame(img):
    process_video_frame.counter += 1
    if params_dict['cvtTransformVideoFrame']:
        img_process = cv2.cvtColor(img, params_dict['cvtTransformVideoFrame'])
    else:
        img_process = np.copy(img)
    car_boxes = find_cars(img_process, scale_list, cl_svm_vid, std_scaler_vid)
    #res_image = add_result_thumbnail(img, car_boxes)
    consolidated_boxes_cur_frame = detect_and_consolidate(img, car_boxes)
    retain_box = []
    if len(process_video_frame.prev_boxes) >= consecutive_appearance:
        for box in consolidated_boxes_cur_frame: #For each box in the curret frame
            retain_box.append(True)
            for prev_box_list in process_video_frame.prev_boxes: #Get the list of boxes in one of the previous frames
                max_overlap = 0
                for prev_box in prev_box_list: #For each box in the previous frame
                    overlap = rect_overlap(box, prev_box)
                    if overlap>max_overlap:
                        max_overlap = overlap
                if max_overlap<.5:
                    retain_box[-1] = False
    process_video_frame.prev_boxes.append(consolidated_boxes_cur_frame)
    if len(process_video_frame.prev_boxes) > consecutive_appearance:
        process_video_frame.prev_boxes.pop(0)

    consistent_boxes = []
    if retain_box:
        consistent_boxes = [consolidated_boxes_cur_frame[i] for i in range(len(consolidated_boxes_cur_frame)) if retain_box[i]]
    res_image = np.copy(img)
    for box in consistent_boxes:
        cv2.rectangle(res_image, (box[2], box[0]), (box[3], box[1]), color=(255, 0, 0), thickness=6)
    return res_image

input_video_file = params_dict['input_video_file']
out_video_file = params_dict['out_video_file']
in_clip = VideoFileClip(input_video_file)
process_video_frame.counter = 0
process_video_frame.prev_boxes = []
out_clip = in_clip.fl_image(process_video_frame)
out_clip.write_videofile(out_video_file, audio=False)


import sys

#sys.stdin = open("in1.txt","r")

grid = list(list(map(int,input().strip().split())) for _ in range(9))

t = {1,2,3,4,5,6,7,8,9}

result = True

def test(grid):
    #행 / 열끼리 비교
    for i in range(9):
        ch1 = [0]*9
        ch2 = [0]*9

        for j in range(
            9):
            ch1[grid[i][j]-1]=1
            ch2[grid[j][i]-1]=1

        if sum(ch1) != 9 or sum(ch2) != 9:
            return False

    ch3 = {0:[0]*9,1:[0]*9,2:[0]*9}
    for i in range(9):
        if i!=0 and i%3 ==0:
            for val in ch3.values():
                if sum(val) != 9 :
                    return False
            ch3 = {0:[0]*9,1:[0]*9,2:[0]*9}
        for j in range(9):
            ch3[j//3][grid[i][j]-1]=1
    return True

if test(grid):
    print('YES')
else:
    print('NO')


from collections import defaultdict
try:
    from itertools import zip_longest
except ImportError:
    from itertools import izip_longest as zip_longest

_NONE_TYPE = type(None)
_EMPTY_TYPE = type('', (object,), {})
_MIXED_TYPE = type('<mixed-type>', (object,), {})

class AttrDict(dict):
    """A dict with keys accessible as attributes."""
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self

class Structure(object):
    """An object that reflects the structure of any python data structure.

    Any object may be passed to the constructor and a complete traverse of the
    structure occurs, making all the appropriate links so that the hierarchy
    may be examined. The str function will turn these objects into a simple
    representation of the structure with notations for lists and whether or
    not an attribute will be guaranteed for each particular branch.
    Also supported is adding different Structure objects, which will show only
    the structure common to both. Wherever the structure differs, it will
    be noted as a '<mixed-type>'
    """
    def __init__(self, value, key=None, parent=None):
        """Initialize a structure

        Takes the type of the value, and recursively creates sub-structures
        as children if the type is a list, tuple, or dict.
        """
        self.key = key
        self.parent = parent
        self.type_ = type(value)
        self.key_guaranteed = True
        self.val_guaranteed = True
        self.children = []

        if self.is_list:
            # Make a structure out of each item in the list
            list_items = [Structure(item, parent=self) for item in value]
            if list_items:
                # Add all structures together to get the common structure
                merged_structure = list_items[0]
                for item in list_items[1:]:
                    merged_structure += item
                # Set the only list child to the common structure
                merged_structure.parent = self
                self.children.append(merged_structure)
            else:
                self.children.append(Structure(_EMPTY_TYPE(), parent=self))
        elif self.is_tuple:
            # Make a structure out of each item in the tuple
            tuple_items = [Structure(item, parent=self) for item in value]
            if tuple_items:
                self.children = tuple_items
        elif self.is_dict:
            for key, val in value.items():
                self.children.append(Structure(val, key, self))
            self.children.sort(key=lambda child: child.key)

    def __add__(self, other):
        """Add structures to get a new structure that is common to both.

        The returned structure is a newly created structure that reflects the
        similarities and differences between the two structures added.
        """

        key_guaranteed = self.key_guaranteed and other.key_guaranteed
        val_guaranteed = self.val_guaranteed and other.val_guaranteed

        if self.type_ is other.type_:
            new = Structure(None, key=self.key)
            new.type_ = self.type_
            new.key_guaranteed = key_guaranteed
            new.val_guaranteed = val_guaranteed

            if self.is_list and other.is_list:
                listchild = self.children[0] + other.children[0]
                listchild.parent = new
                new.children.append(listchild)
                return new
            elif self.is_tuple and other.is_tuple:
                zipped = zip_longest(self.children, other.children)
                for schild, ochild in zipped:
                    if schild is None:
                        newchild = ochild.copy(new)
                        newchild.val_guaranteed = False
                        new.children.append(newchild)
                    elif ochild is None:
                        newchild = schild.copy(new)
                        newchild.val_guaranteed = False
                        new.children.append(newchild)
                    else:
                        newchild = schild + ochild
                        newchild.parent = new
                        new.children.append(newchild)
                return new
            elif self.is_dict and other.is_dict:
                keysdict = defaultdict(lambda: [None, None])
                for child in self.children:
                    keysdict[child.key][0] = child
                for child in other.children:
                    keysdict[child.key][1] = child
                for c1, c2 in keysdict.values():
                    if c1 is None:
                        newchild = c2.copy(new)
                        newchild.key_guaranteed = False
                    elif c2 is None:
                        newchild = c1.copy(new)
                        newchild.key_guaranteed = False
                    else:
                        newchild = c1 + c2
                        newchild.parent = new
                    new.children.append(newchild)
                new.children.sort(key=lambda child: child.key)
                return new
            else:
                return new
        else:
            if self.type_ is _EMPTY_TYPE:
                new = other.copy()
            elif other.type_ is _EMPTY_TYPE:
                new = self.copy()
            elif self.type_ is _NONE_TYPE:
                new = other.copy()
                new.key_guaranteed = key_guaranteed
                new.val_guaranteed = False
            elif other.type_ is _NONE_TYPE:
                new = self.copy()
                new.key_guaranteed = key_guaranteed
                new.val_guaranteed = False
            else:
                new = Structure(None, key=self.key)
                new.key_guaranteed = key_guaranteed
                new.val_guaranteed = val_guaranteed
                new.type_ = _MIXED_TYPE
            return new

    def __str__(self):
        """A structured representation of the underlying structure"""
        if self.parent:
            string = '{}{}{} - {}\n'.format(
                '  ' * (self.generation),
                '' if self.key_guaranteed else '*',
                self.key,
                self.type_string)
        else:
            string = '{}\n'.format(self.type_string)
        if self.children:
            if self.is_list:
                sub = self.children[0]
                while sub.is_list:
                    sub = sub.children[0]
                if sub.is_dict:
                    for child in sub.children:
                        string += str(child) + '\n'
            elif self.is_dict:
                for child in self.children:
                    string += str(child) + '\n'
        return string[:-1]

    def copy(self, parent=None):
        """Copies an existing structure and all of it's children"""
        new = Structure(None, parent=parent)
        new.key = self.key
        new.type_ = self.type_
        new.val_guaranteed = self.val_guaranteed
        new.key_guaranteed = self.key_guaranteed
        for child in self.children:
            new.children.append(child.copy(new))
        return new

    @property
    def generation(self):
        """Returns the number of ancestors that are dictionaries"""
        if not self.parent:
            return 0
        elif self.parent.is_dict:
            return 1 + self.parent.generation
        else:
            return self.parent.generation

    @property
    def type_string(self):
        """Returns a string representing the type of the structure"""
        if self.is_tuple:
            subtypes = [item.type_string for item in self.children]
            return '{}({})'.format(
                '' if self.val_guaranteed else '*',
                ', '.join(subtypes))
        elif self.is_list:
            return '{}[{}]'.format(
                '' if self.val_guaranteed else '*',
                self.children[0].type_string)
        else:
            return '{}{}'.format(
                '' if self.val_guaranteed else '*',
                self.type_.__name__)

    @property
    def is_list(self):
        return issubclass(self.type_, list)

    @property
    def is_tuple(self):
        return issubclass(self.type_, tuple)

    @property
    def is_dict(self):
        return issubclass(self.type_, dict)


import aiohttp
from furl import furl
from typing import Optional

class PapaJohnsClient:
    def __init__(self, url: str, city_id: int, restaurant_id: int):
        self.base_url = url
        self.city_id = city_id
        self.restaurant_id = restaurant_id

    @staticmethod
    async def _query(
        url: furl, method: Optional[str] = 'GET', json: Optional[dict] = None
    ) -> dict:
        async with aiohttp.ClientSession() as session:
            async with session.request(method, url.tostr(), json=json) as response:
                return await response.json()

    async def init_cart(self, goods_to_check: list) -> str:
        url = furl(self.base_url) / '/cart/add'
        json = {
            'city_id': self.city_id,
            'composition': [
                {'good_id': good_id, 'ingredients': [], 'type': 'good'}
                for good_id in goods_to_check
            ],
        }
        response = await self._query(url, method='POST', json=json)
        return response.get('unauthorized_token')

    async def get_goods_out_of_stock(self, goods_to_check: list) -> list[int]:
        """
        :return: массив из id отсутствующих товаров в корзине
        """
        unauthorized_token = await self.init_cart(goods_to_check)
        url = furl(self.base_url) / '/cart/stop-list'
        url.add(
            {
                'city_id': self.city_id,
                'restaurant_id': self.restaurant_id,
                'unauthorized_token': unauthorized_token,
            }
        )
        response = await self._query(url)
        return [row.get('good') for row in response]

    async def check_goods_in_stock(self, good_id: int) -> bool:
        goods_out_of_stock = await self.get_goods_out_of_stock([good_id])
        return good_id not in goods_out_of_stock

    async def get_delivery_time(self, location: tuple) -> str:
        """
        :return: примерное время доставки
        """
        url = furl(self.base_url) / '/restaurant/delivery-time'
        url.add(
            {
                'city_id': self.city_id,
                'restaurant_id': self.restaurant_id,
                'address_coordinates': f'[{",".join(location)}]',
            }
        )
        response = await self._query(url)
        return response.get('delivery_time')


import datetime
from django.conf import settings
from django.utils.timezone import now
from celery import shared_task
from monascaclient import client as monasca_client
from decouple import config
from core.conf import conf_file
from nova.models import Hypervisors, Servers

monasca = monasca_client.Client(
    api_version=config("MONASCA_API_VERSION"),
    session=settings.OPENSTACK_SESSION,
    endpoint=config("MONASCA_ENDPOINT"),
    interface=config("MONASCA_INTERFACE"),
)

def influx_query(measurement, resource_name, resource_id):
    """
    funciona como uma facade, retorna uma consulta no influxdb
    """
    bucket_name = config("INFLUX_BUCKET")
    # pega os dados apenas da ultima hora
    start = '-720m'
    from_bucket = ('from(bucket:"%s")' % bucket_name)
    start_date = (' |> range(start: %s)' % start)
    filter_measurement = (' |> filter(fn:(r) => r._measurement == "%s")' % measurement)
    filter_resource = (' |> filter(fn:(r) => r.%s == "%s")' % (resource_name, resource_id))

    query = from_bucket + start_date + filter_measurement + filter_resource
    points = settings.INFLUX_CLIENT.query_api().query(query)

    result = []
    for table in points:
        for row in table.records:
            result.append(row.values)

    return result

@shared_task
def schedule_save_statistics() -> None:
    """
    Collect all metrics declared in yaml configuration file.

    Sera a funcao no schedule beat responsavel por disparar todas as tasks que vao coletar no monasca

    cada funcao dessa sera responsavel por coletar a metrica de apenas uma instancia de um tenant

    a task sempre vai consultar o influx antes, o start_time da coleta sera o ultimo dado do influxdb
    o end_time sera o o datetime.now()

    nao me importamos se tivermos duas tasks na fila para o mesmo periodo de tempo, ja que
    posteriormente isso sera resolvido e a fila anda

    o type,name e period da metrica sera recuperado atraves do arquivo de configuracao

    o tenant_name sera consultado direto na database django, assim como o nome de cada instancia ativa
    ambos serao incorporados no atributo dimensions
    """
    # servers = Servers.objects.all().values()

    # statistics_list = conf_file['monasca']['statistics'][0]['name']
    # resource_name = conf_file['monasca']['statistics'][0]['dimension']

    for statistic_definition in conf_file['monasca']['statistics']:
        statistics_list = statistic_definition['name']
        resource_name = statistic_definition['dimension']

        if resource_name == "resource_id":
            resource_objects = Servers.objects.all().values()
        elif resource_name == "hostname":
            resource_objects = Hypervisors.objects.all().values()

        for statistic_name in statistics_list:
            for resource in resource_objects:
                # check the date which metrics begin, if not found, begin save from now
                date_influx = influx_query(
                    measurement=statistic_name,
                    resource_name=resource_name,
                    resource_id=str(resource['id'])
                )
                if not date_influx:
                    start_date = now() - datetime.timedelta(minutes=1)
                else:
                    start_date = date_influx[-1]['_time']

                # define which metrics must be saved
                name = statistic_name
                dimensions = {
                    # "vm_name": server['id'],
                    # "tenant_name": server['tenant_id_id']
                    "resource_id": str(resource['id'])
                }
                metric_type = statistic_definition['type']
                start_time = start_date.isoformat(' ', 'seconds')
                end_time = now().isoformat(' ', 'seconds')
                period = statistic_definition['period']

                save_statistics(name, dimensions, metric_type, start_time, end_time, period)

def save_statistics(name, dimensions, metric_type, start_time, end_time, period):
    """
    Save a statistic from Monasca on InfluxDB.
    """
    statistics = monasca.metrics.list_statistics(
        name=name,
        dimensions=dimensions,
        statistics=metric_type,
        start_time=start_time,
        end_time=end_time,
        period=period,
    )

    statistics_to_save = []
    if not len(statistics):
        print('Not Found')
        return

    statistics = statistics[0]
    for statistic in statistics['statistics']:
        statistic_point = {}
        statistic_point['measurement'] = statistics['name']
        statistic_point['tags'] = statistics['dimensions']
        statistic_point['fields'] = {}
        statistic_point['fields']['value'] = float(statistic[1])
        statistic_point['time'] = statistic[0]
        statistics_to_save.append(statistic_point)

    settings.INFLUX_CLIENT.write_api().write(bucket='monasca', record=statistics_to_save)


from django.shortcuts import render
from .models import *
from django.http import HttpResponse
# Create your views here.

def parent_views(request):
    return render(request, 'parent.html')

def child_views(request):
    return render(request, 'child.html')

def add_author_views(request):
    obj = Author(name='jianailiang',age=35,email='jia@green.com')
    obj.save()
    # Author.objects.create(name='baoqiang', age=33, email='baoqiang@163.com')
    return HttpResponse('Add OK')

def add_book_views(request):
    Book.objects.create(title='红楼梦',publication_date='1995-12-12')

    obj = Book(title='西游记',publication_date='1982-10-12')
    obj.save()

    dic = {
        'title' : '三国演义',
        'publication_date': '1990-3-5'
    }
    book = Book(**dic)
    book.save()

    return HttpResponse('Add Book OK')

def add_publisher_views(request):
    Publisher.objects.create(name='中国人民出版社',address='五道口',\
                             city='北京',country='北京',website='http://www.renmin.com')

    obj = Publisher(name='中国动画出版社',address='潘家园',\
                    city='北京',country='中国',website='http://www.donghuapian.com')
    obj.save()

    dic = {
        'name': '中国文化出版社',
        'address': '潘家园',
        'city': '北京',
        'country':'中国',
        'website':'http://wenhua.com'
    }
    publisher = Publisher(**dic)
    publisher.save()

    return HttpResponse("Add Publisher OK")

def get_author_views(request):
    # authors = Author.objects.all()
    # authors =Author.objects.values("name", "age", "id")
    # authors = Author.objects.all().values("name","age")
    # auth = Author.objects.get(id=1)
    # authors = Author.objects.exclude(age=35)
    authors = Author.objects.all().order_by('-age')

    return render(request, 'show_authors.html', locals())

def all_authors_views(request):
    author = Author.objects.all()
    return render(request, 'all_authors.html',locals())

def oto_views(request):
    w = Wife.objects.get(id=1)
    a = w.author

    au = Author.objects.get(id=2)
    wi = au.wife
    return render(request, 'oto.html', locals())

def otm_views(request):
    book = Book.objects.get(id=1)
    publisher = book.publisher

    pub = Publisher.objects.get(id=1)
    books = pub.book_set.all()

    return render(request,'otm.html',locals())

def mtm_views(request):
    author = Author.objects.get(id=2)
    pubLish = author.publisher.all()

    pub = Publisher.objects.get(id=3)
    authors = pub.author_set.all()

    return render(request,'mtm.html',locals())

def book_author_views(request):
    book = Book.objects.get(id=3)
    auList = book.author.all()

    au = Author.objects.get(id=3)
    bookList = au.book_set.all()
    return render(request,'12.html',locals())


"""
PyCSP3 Model (see pycsp.org)

Data can come:
 - either directly from a JSON file
 - or from an intermediate parser

Examples:
  python Nonogram.py -data=Nonogram_example.json
  python Nonogram.py -data=Nonogram_example.json -variant=table
  python Nonogram.py -data=Nonogram_example.txt -dataparser=Nonogram_Parser.py
"""

from pycsp3 import *

rows, cols = data  # patterns for row and columns
nRows, nCols = len(rows), len(cols)

# x[i][j] is 1 iff the cell at row i and col j is colored in black
x = VarArray(size=[nRows, nCols], dom={0, 1})

if not variant():
    def automaton(pattern):
        q = Automaton.q  # for building state names
        transitions = []
        if len(pattern) == 0:
            n_states = 1
            transitions.append((q(0), 0, q(0)))
        else:
            n_states = sum(pattern) + len(pattern)
            num = 0
            for i, size in enumerate(pattern):
                transitions.append((q(num), 0, q(num)))
                transitions.extend((q(num + j), 1, q(num + j + 1)) for j in range(size))
                transitions.append((q(num + size), 0, q(num + size + (1 if i < len(pattern) - 1 else 0))))
                num += size + 1
        return Automaton(start=q(0), final=q(n_states - 1), transitions=transitions)

    satisfy(
        [x[i] in automaton(rows[i]) for i in range(nRows)],

        [x[:, j] in automaton(cols[j]) for j in range(nCols)]
    )

elif variant("table"):
    cache = dict()

    def table(pattern, row):
        def build_from(lst, tmp, i, k):
            s = sum([pattern[e] for e in range(k, len(pattern))])
            if i + s + (len(pattern) - 1 - k) > len(tmp):
                return lst
            if i == len(tmp):
                lst.append(tuple(tmp))
            else:
                tmp[i] = 0
                build_from(lst, tmp, i + 1, k)
                if k < len(pattern):
                    for j in range(i, i + pattern[k]):
                        tmp[j] = 1
                    if i + pattern[k] == len(tmp):
                        build_from(lst, tmp, i + pattern[k], k + 1)
                    else:
                        tmp[i + pattern[k]] = 0
                        build_from(lst, tmp, i + pattern[k] + 1, k + 1)
            return lst

        key = str("R" if row else "C") + "".join(str(pattern))
        if key not in cache:
            cache[key] = build_from([], [0] * (nCols if row else nRows), 0, 0)
        return cache[key]

    satisfy(
        [x[i] in table(rows[i], row=True) for i in range(nRows)],

        [x[:, j] in table(cols[j], row=False) for j in range(nCols)]
    )


from rest_framework import serializers
from django_redis import get_redis_connection
from redis.exceptions import RedisError
import logging

logger = logging.getLogger('django')

class CheckImageCodeSerializer(serializers.Serializer):
    """
    图片验证码校验序列化器
    """
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(min_length=4, max_length=4)

    def validate(self, attrs):
        """校验图片验证码是否正确"""
        image_code_id = attrs['image_code_id']  # attrs 中以字典的形式存了上面所有的数据
        text = attrs['text']

        # 查询 redis 数据库，查询真实的验证码
        redis_conn = get_redis_connection('verify_codes')
        real_image_code = redis_conn.get('img_%s' % image_code_id)

        if real_image_code is None:
            # 说明验证码过期或者不存在
            raise serializers.ValidationError('无效的图片验证码')

        # 进行对比
        real_image_code = real_image_code.decode()  # 数据库中的验证码是字节类型，需要转码
        if real_image_code.lower() != text.lower():
            raise serializers.ValidationError('图片验证码错误')

        # 删除 redis 中的图片验证码，防止用户对同一个进行多次请求验证
        # 提前删除可能会导致，当用户第一次输入错误后，哪怕再次输入正确也会提示验证码错误，必须刷新才行
        try:
            redis_conn.delete('img_%s' % image_code_id)
        except RedisError as e:
            logger.error(e)

        # redis 中发送短信验证码的标志 send_flag_<mobile>: 1, 由 redis 维护 60s 的有效期
        mobile = self.context['view'].kwargs.get('mobile')
        if mobile:
            send_flag = redis_conn.get('send_flag_%s' % mobile)
            if send_flag:
                raise serializers.ValidationError('发送短信次数过于频繁')

        return attrs


import re

NUM_OR_DOT_REGEX = re.compile(r"^[0-9.]$")
CODECS = (
    ("MP4", "libx264"),
    ("WEBM", "libvpx"),
    ("MOV", "mov"),
    ("MPEG-1", "mpeg1video"),
    ("MPEG-2", "mpeg2video"),
    ("MPG", "mpeg2video"),
    ("MPEGPS", "mpeg2video"),
    ("MPEG4", "mpeg4"),
    ("AVI", "msmpeg4"),
    ("WMV", "wmv2"),
    ("FLV", "flv"),
    ("3GPP", "h263p"),
)

def is_num_or_dot(string: str) -> bool:
    """
    Check if a string contains only digits or a dot.
    Args:
        string (str): The input string to be checked.
    Returns:
        bool: True if the string contains only digits or a dot, False
        otherwise.
    """
    return NUM_OR_DOT_REGEX.search(string)

def is_valid_number(string: str) -> bool:
    valid = False
    try:
        float(string)
        valid = True
        return valid
    except ValueError:
        valid = False
        return valid

def convert_to_number(string: str):
    """
    Converts a string to a number.

    Args:
        string (str): The string to be converted to a number.

    Returns:
        int or float: The converted number. If the string represents an integer, it returns an int. Otherwise, it returns a float.
    """
    if not is_valid_number(string):
        return

    number = float(string)
    if number.is_integer():
        return int(number)
    return number

def is_empty(string: str) -> bool:
    """
    Check if a given string is empty.
    Args:
        string (str): The string to check.
    Returns:
        bool: True if the string is empty, False otherwise.
    """
    return len(string) == 0

def formmat_result(result):
    if isinstance(result, int) or result.is_integer():
        return int(result)
    else:
        return round(result, 2)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Cidade',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('nome', models.CharField(max_length=200)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Coleta',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('quantidade_coletada', models.IntegerField()),
                ('enviado_cartorio', models.BooleanField(default=False)),
                ('quantidade_validada', models.IntegerField()),
                ('local_atual', models.ForeignKey(related_name=b'local_atual', to='contador.Cidade')),
                ('local_coleta', models.ForeignKey(related_name=b'local_coleta', to='contador.Cidade')),
                ('responsavel_atual', models.ForeignKey(related_name=b'responsavel_atual', to=settings.AUTH_USER_MODEL)),
                ('responsavel_coleta', models.ForeignKey(related_name=b'responsavel_coleta', to=settings.AUTH_USER_MODEL)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Estado',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('nome', models.CharField(max_length=200)),
                ('sigla', models.CharField(max_length=2)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Secao',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('numero', models.CharField(max_length=5)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Zona',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('zona', models.CharField(max_length=3)),
                ('secoes', models.ManyToManyField(to='contador.Secao')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='coleta',
            name='zona',
            field=models.ForeignKey(to='contador.Zona'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='cidade',
            name='uf',
            field=models.ForeignKey(to='contador.Estado'),
            preserve_default=True,
        ),
    ]


def open_file(file_name):
    ''' Opens file '''
    try:
        file_object = open(file_name, "r")
        return file_object
    except FileNotFoundError:
        print("File", file_name, "not found")

def read_file_parts(file_object):
    ''' Reads and processes grade parts from file 1 '''
    list_of_parts = []
    tuple_list = [] # Temp list that converts to tuple
    counter = 1

    # Create two lists
    for line in file_object:
        if counter == 1: # Create list for line 1
            line_1 = line.strip().split()
            counter += 1
        elif counter == 2: # Create list for line 2
            line_2 = line.strip().split()
            line_2 = [float(num) for num in line_2] # Change all digits to float in list

    # Create tuples
    for index in range(5):
        tuple_list.append(line_1[index])
        tuple_list.append(line_2[index])
        list_of_parts.append(tuple(tuple_list))
        tuple_list = [] # Reset

    print(list_of_parts)
    return list_of_parts

def read_file_grades(file_object):
    ''' Reads and processes info about students and grades from file 2 '''
    student_grades = []
    tuple_list = [] # Temp list that converts to tuple

    for line in file_object:
        line_list = line.strip().split()

        tuple_list.append(line_list[0]) # Add first element (name@email)
        line_list.remove(line_list[0])

        line_list = [float(num) for num in line_list]
        tuple_list.append(line_list) # Add list of grades
        student_grades.append(tuple(tuple_list))
        tuple_list = [] # Reset

    print(student_grades)
    return student_grades

def calculate_final(student_grades, list_of_parts):
    ''' Calculates weighted course grade for each student '''
    weighted_grade = 0
    w_grade_list = []
    index = 0

    for element in student_grades: # Get grade list for specific student
        grades = element[1] # Grade list for student x

        for item in list_of_parts: # Calculate weighted grade
            weight = item[1]

            specific_grade = weight * grades[index]
            weighted_grade += specific_grade
            index += 1

        w_grade_list.append(weighted_grade)
        # Reset
        weighted_grade = 0
        index = 0

    for grade in w_grade_list: ## Only way I found to append to tuple is through lists
        temp = []
        temp.append(grade)
        student_grades[index] += tuple(temp)
        # Reset
        temp = []
        index += 1

    print(student_grades)
    print()
    return student_grades

def print_outcome(student_grades):
    ''' Prints outcome in an orderly manner '''
    ROUND = 2
    print("{:>16}{:>14}{:>14}{:>14}{:>14}{:>14}{:>14}".format("Student ID", "Quizzes", "Assignments", "Projects", "Midterms", "Final", "Course grade"))

    for element in student_grades:
        for item in element:
            try: # Print course grade
                item = float(item)
                item = round(item, ROUND)
                print("{:>14}".format(item))
            except ValueError: # Print student emails
                item = str(item)
                print("{:>16}".format(item), end='')
            except TypeError: # Print grade list
                for number in item:
                    print("{:>14}".format(number), end='')

def close_file(file_object_parts, file_object_grades):
    ''' Closes files '''
    file_object_parts.close()
    file_object_grades.close()

# Main program starts here
file_name_parts = input("Enter filename for parts: ").strip() # File 1
file_object_parts = open_file(file_name_parts)
if file_object_parts != None:
    list_of_parts = read_file_parts(file_object_parts)

    file_name_grades = input("Enter filename for grades: ").strip() # File 2
    file_object_grades = open_file(file_name_grades)
    if file_object_grades != None:
        student_grades = read_file_grades(file_object_grades)

        calculate_final(student_grades, list_of_parts)
        print_outcome(student_grades)

        close_file(file_object_parts, file_object_grades)


# data_loader.py
import os
import torch
import numpy as np
from torchvision import datasets, transforms
from torch.utils.data import DataLoader, Subset

def load_and_split_dataset(num_classes, num_clients, alpha, non_iid=False):
    transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])

    try:
        trainset = datasets.FashionMNIST(root='./data', train=True, download=True, transform=transform)
    except Exception as e:
        raise RuntimeError(f"Error loading the dataset: {e}")

    num_samples_per_class = len(trainset) // num_clients
    indices = torch.arange(0, len(trainset))
    dataset_labels = trainset.targets
    class_indices = [indices[i * num_samples_per_class:(i + 1) * num_samples_per_class] for i in range(num_clients)]

    # Initialize data structures
    client_indices = [[] for _ in range(num_clients)]

    if non_iid:
        min_size = 0
        K = num_classes
        N = len(dataset_labels)

        while min_size < num_classes:
            idx_batch = [[] for _ in range(num_clients)]
            for k in range(K):
                idx_k = np.where(dataset_labels == k)[0]
                np.random.shuffle(idx_k)
                proportions = np.random.dirichlet(np.repeat(alpha, num_clients))
                proportions = np.array([p * (len(idx_j) < N / num_clients) for p, idx_j in zip(proportions, idx_batch)])
                proportions = proportions / proportions.sum()
                proportions = (np.cumsum(proportions) * len(idx_k)).astype(int)[:-1]
                idx_batch = [idx_j + idx.tolist() for idx_j, idx in zip(idx_batch, np.split(idx_k, proportions))]
                min_size = min([len(idx_j) for idx_j in idx_batch])
        # Assign data samples to clients
        for j in range(num_clients):
            client_indices[j] = idx_batch[j]
    else:
        print("IID partition")
        num_samples_per_client = len(trainset) // num_clients  # Each client has an equal number of samples
        #Shuffle the dataset to create an IID partition
        indices = torch.randperm(len(trainset))
        # Divide the dataset into equal-sized subsets for each client
        client_indices = [indices[i * num_samples_per_client: (i + 1) * num_samples_per_client] for i in range(num_clients)]

    return trainset, client_indices, class_indices

def create_client_loaders(trainset, client_indices):
    client_loaders = [DataLoader(Subset(trainset, client_indices[i]), batch_size=64, shuffle=True) for i in range(len(client_indices))]
    return client_loaders


BACKGROUND_COLOR = (0, 0, 0)  # Colors.black
DATETIME_FORMAT = "%Y%m%d_%H%M%S_%f"
DEFAULT_IMAGE_SIZE = (1080, 1080)
IMAGE_DIRECTORY_NAME = 'files'
IMAGE_FORMAT_COLOR_MODE = 'RGB'
IMAGE_FORMAT = 'jpeg'
IMAGE_EXTENSION = 'jpeg'

# Video settings
BITRATE = 3000
FRAMES_PER_SECOND = 30
VIDEO_EXTENSION = 'mp4'
VIDEO_CODEC = 'libx264'
VIDEO_PIXEL_FORMAT = 'yuv420p'


import subprocess
import json

def cacheMissHit():
    try:
        api = json.loads(subprocess.check_output("varnishstat --json", shell=True, text=True))
    except:
        return {"cacheHits": 0, "cacheMiss": 0, "hitRatio": 0, "backendFetches": 0, "backendFailures": 0, "backendFailRatio": 0}
    hit = api["counters"]["MAIN.cache_hit"]["value"]
    miss = api["counters"]["MAIN.cache_miss"]["value"]

    backendFetch = api["counters"]["MAIN.backend_req"]["value"]
    backendFails = api["counters"]["MAIN.backend_fail"]["value"]

    if miss == 0 and hit == 0:
        ratio = 0
    else:
        ratio = hit / (miss + hit)

    if backendFails == 0 or backendFetch == 0:
        backendFailRatio = 0
    else:
        backendFailRatio = backendFails / (backendFails + backendFetch)
    return {"cacheHits": hit, "cacheMiss": miss, "hitRatio": round(ratio, 3), "backendFetches": backendFetch, "backendFailures": backendFails, "backendFailRatio": round(backendFailRatio, 3)}

def space():
    try:
        api = json.loads(subprocess.check_output("varnishstat --json", shell=True, text=True))
    except:
        return {"memoryUsedInBytes": 0}

    # Experimental, not sure if I'm understanding the Varnish API correctly
    memUsed = api["counters"]["MAIN.s_resp_bodybytes"]["value"] + api["counters"]["MAIN.s_resp_hdrbytes"]["value"]
    return {"memoryUsedInBytes": memUsed}

print(cacheMissHit())


#Escribe un programa que pida dos números y que conteste cuál es el menor y
#cuál el mayor o que escriba que son iguales.

n1= int(input("Da el primer numero: "))
n2= int(input("Da el segundo numero: "))

if n1>n2:
    print("Mayor: ",n1, "Menor: ", n2)
elif n1<n2:
     print("Mayor: ",n2, "Menor: ", n1)
else:
    print("Los dos son iguales")


from zope.interface import Attribute, Interface
from zope.interface.interfaces import IObjectEvent
from zope.lifecycleevent import IObjectCreatedEvent
from zope.schema import ASCIILine, Bool, Choice, Dict, Field, Object, Text, TextLine, Tuple, URI

from pyams_form.interfaces import DISPLAY_MODE, IContentProviders, IFields, INPUT_MODE
from pyams_form.interfaces.button import IActions, IButtonHandlers, IButtons
from pyams_form.interfaces.widget import IWidgets

__docformat__ = 'restructuredtext'

from pyams_form import _

class IHandlerForm(Interface):
    """A form that stores the handlers locally."""

    handlers = Object(title=_('Handlers'),
                      description=_('A list of action handlers defined on the form.'),
                      schema=IButtonHandlers,
                      required=True)

class IActionForm(Interface):
    """A form that stores executable actions"""

    actions = Object(title=_('Actions'),
                     description=_('A list of actions defined on the form'),
                     schema=IActions,
                     required=True)

    refresh_actions = Bool(title=_('Refresh actions'),
                           description=_('A flag, when set, causes form actions to be '
                                         'updated again after their execution.'),
                           default=False,
                           required=True)

class IContextAware(Interface):
    """Offers a context attribute.

    For advanced uses, the widget will make decisions based on the context
    it is rendered in.
    """

    context = Field(title=_('Context'),
                    description=_('The context in which the widget is displayed.'),
                    required=True)

    ignore_context = Bool(title=_('Ignore Context'),
                          description=_('A flag, when set, forces the widget not to look at '
                                        'the context for a value.'),
                          default=False,
                          required=False)

class IFormAware(Interface):
    """Offers a form attribute.

    For advanced uses the widget will make decisions based on the form
    it is rendered in.
    """

    form = Field()

class IForm(Interface):
    """Form interface"""

    fields = Attribute("Form fields")

    mode = Choice(title=_('Mode'),
                  description=_('The mode in which to render the widgets.'),
                  values=(INPUT_MODE, DISPLAY_MODE),
                  required=True)

    ignore_context = Bool(title=_('Ignore Context'),
                          description=_('If set the context is ignored to retrieve a value.'),
                          default=False,
                          required=True)

    ignore_request = Bool(title=_('Ignore Request'),
                          description=_('If set the request is ignored to retrieve a value.'),
                          default=False,
                          required=True)

    ignore_readonly = Bool(title=_('Ignore Readonly'),
                           description=_('If set then readonly fields will also be shown.'),
                           default=False,
                           required=True)

    ignore_required_on_extract = Bool(
        title=_('Ignore Required validation on extract'),
        description=_("If set then required fields will pass validation "
                      "on extract regardless whether they're filled in or not"),
        default=False,
        required=True)

    widgets = Object(title=_('Widgets'),
                     description=_('A widget manager containing the widgets to be used in '
                                   'the form.'),
                     schema=IWidgets)

    title = TextLine(title=_('Title'),
                     description=_('Main form title'),
                     required=False)

    legend = TextLine(title=_('Legend'),
                      description=_('A human readable text describing the form that can be '
                                    'used in the UI.'),
                      required=False)

    required_label = TextLine(title=_('Required label'),
                              description=_('A human readable text describing the form that can '
                                            'be used in the UI for rendering a required info '
                                            'legend.'),
                              required=False)

    prefix = ASCIILine(title=_('Prefix'),
                       description=_('The prefix of the form used to uniquely identify it.'),
                       default='form.')

    status = Text(title=_('Status'),
                  description=_('The status message of the form.'),
                  default=None,
                  required=False)

    def get_content(self):
        """Return the content to be displayed and/or edited."""

    def update_widgets(self, prefix=None):
        """Update the widgets for the form.

        This method is commonly called from the ``update()`` method and is
        mainly meant to be a hook for subclasses.

        Note that you can pass an argument for ``prefix`` to override
        the default value of ``"widgets."``.
        """

    def extract_data(self, set_errors=True, notify=True):
        """Extract the data of the form.

        set_errors: needs to be passed to extract() and to sub-widgets
        notify: set to False when you don't want to notify IDataExtractedEvent"""

    def update(self):
        """Update the form."""

    def render(self):
        """Render the form."""

    def json(self):
        """Returns the form in json format"""

class IAJAXForm(IForm):
    """A form interface for handling AJAX calls"""

    def get_ajax_handler(self):
        """Get absolute URL of AJAX handler"""

    def get_form_options(self):
        """Get form options in JSON format"""

    def get_ajax_errors(self):
        """Get AJAX status"""

    def get_ajax_output(self, changes):
        """Get AJAX POST output in JSON"""

class IAJAXFormRenderer(Interface):
    """AJAX form JSON renderer"""

    def render(self, changes):
        """Render changes in JSON"""

class ISubForm(IForm):
    """A subform."""

    parent_form = Attribute("Parent form")

class IInnerForm(Interface):
    """Inner form marker interface"""

class IInnerSubForm(IInnerForm, ISubForm):
    """Inner sub-form interface

    Inner sub-forms are standard sub-forms, but which may be included dynamically
    into a given form by using named adapters.
    """

class IInnerTabForm(IInnerForm, ISubForm):
    """Inner tab-form interface

    Inner tab-forms are standard sub-forms, but which may be included dynamically
    into a given form by using named adapters.
    """

class IDisplayForm(IForm):
    """Mark a form as display form, used for templates."""

class IInputForm(Interface):
    """A form that is meant to process the input of the form controls."""

    action = URI(title=_('Action'),
                 description=_('The action defines the URI to which the form data are '
                               'sent.'),
                 required=True)

    name = TextLine(title=_('Name'),
                    description=_('The name of the form used to identify it.'),
                    required=False)

    # pylint: disable=invalid-name
    id = TextLine(title=_('Id'),
                  description=_('The id of the form used to identify it.'),
                  required=False)

    method = Choice(title=_('Method'),
                    description=_('The HTTP method used to submit the form.'),
                    values=('get', 'post'),
                    default='post',
                    required=False)

    enctype = ASCIILine(title=_('Encoding Type'),
                        description=_('The data encoding used to submit the data safely.'),
                        default='multipart/form-data',
                        required=False)

    accept_charset = ASCIILine(title=_('Accepted Character Sets'),
                               description=_('This is a list of character sets the server '
                                             'accepts. By default this is unknown.'),
                               required=False)

    accept = ASCIILine(title=_('Accepted Content Types'),
                       description=_('This is a list of content types the server can '
                                     'safely handle.'),
                       required=False)

    autocomplete = Choice(title=_("Form autocomplete"),
                          description=_("Enable or disable global form autocomplete"),
                          values=('on', 'off', 'new-password'),
                          required=False)

    # AJAX related form settings

    ajax_form_handler = TextLine(title="Name of AJAX form handler",
                                 required=False)

    ajax_form_options = Dict(title="AJAX form submit's data options",
                             required=False)

    ajax_form_target = TextLine(title="Form submit target",
                                description="Form content target, used for HTML and text content "
                                            "types",
                                required=False)

    ajax_form_callback = TextLine(title="AJAX submit callback",
                                  description="Name of a custom form submit callback",
                                  required=False)

    def get_ajax_handler(self):
        """Get absolute URL of AJAX handler"""

    def get_form_options(self):
        """Get form options in JSON format"""

class IAddForm(IForm):
    """A form to create and add a new component."""

    def create_and_add(self, data):
        """Call create and add.

        This method can be used for keep all attributes internal during create
        and add calls. On sucess we return the new created and added object.
        If something fails, we return None. The default handleAdd method will
        only set the _finished_add marker on sucess.
        """

    def create(self, data):
        """Create the new object using the given data.

        Returns the newly created object.
        """

    def add(self, obj):
        """Add the object somewhere."""

    def update_content(self, obj, data):
        """Update content after creation

        This is actually used to apply updates in subforms to newly created content.
        """

class IEditForm(IForm):
    """A form to edit data of a component."""

    def apply_changes(self, data):
        """Apply the changes to the content component."""

class IFieldsForm(IForm):
    """A form that is based upon defined fields."""

    fields = Object(title=_('Fields'),
                    description=_('A field manager describing the fields to be used for '
                                  'the form.'),
                    schema=IFields)

class IFieldsAndContentProvidersForm(IForm):
    """A form that is based upon defined fields and content providers"""

    content_providers = Object(title=_('Content providers'),
                               description=_(
                                   'A manager describing the content providers to be used for '
                                   'the form.'),
                               schema=IContentProviders)

class IButtonForm(IForm):
    """A form that is based upon defined buttons."""

    buttons = Object(title=_('Buttons'),
                     description=_('A button manager describing the buttons to be used for '
                                   'the form.'),
                     schema=IButtons)

class IGroupManager(IForm):
    """Groups manager interface"""

    groups = Tuple(title='Groups',
                   description=('Initially a collection of group classes, which are '
                                'converted to group instances when the form is '
                                'updated.'))

class IGroup(IGroupManager):
    """A group of fields/widgets within a form."""

    parent_form = Attribute("Parent form")

class IGroupForm(IGroupManager):
    """A form that supports groups."""

class IFormCreatedEvent(IObjectCreatedEvent):
    """Form created event interface"""

    request = Attribute("Form request")

class IFormUpdatedEvent(IObjectEvent):
    """Form updated event interface"""

    form = Attribute("Form")
    request = Attribute("Form request")

class IFormContent(Interface):
    """Optional adapter interface used to get form content"""

class IFormFields(Interface):
    """Optional adapter interface used to get form fields"""

class IDataExtractedEvent(Interface):
    """Event sent after data and status are extracted from widgets.
    """
    data = Attribute("Extracted form data. Usually, the widgets extract field names from "
                     "the request and return a dictionary of field names and field values.")
    errors = Attribute("Tuple of status providing IErrorViewSnippet.")
    form = Attribute("Form instance.")


import sys
from collections import deque
input = sys.stdin.readline

n = int(input())
lst = []
for _ in range(n):
    lst.append(list(input().strip()))

visited = []
count = 0
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]

for i in range(n):
    for j in range(n):
        if (i, j) not in visited and lst[i][j] != '0':
            count += 1

        root = (i, j)
        stack = deque([root])

        while stack:
            a = stack.popleft()
            x, y = a
            if lst[x][y] != '0':
                if a not in visited:
                    lst[x][y] = str(count)
                    visited.append(a)
                    for l in range(4): ###### l -> i 는 틀린다.
                        nx = x + dx[l]
                        ny = y + dy[l]

                        if nx < 0 or ny <0 or nx >= n or ny >= n:
                            continue
                        if lst[nx][ny] == '0':
                            continue

                        if lst[nx][ny] == '1':
                            stack.append((nx, ny))
                            lst[nx][ny] == str(count)

print(count)

houseCount = []
for k in range(1, count+1):
    temp = 0
    for i in range(n):
        for j in range(n):
            if lst[i][j] == str(k):
                temp += 1
    houseCount.append(temp)

houseCount.sort()
for i in range(count):
    print(houseCount[i])

    # for문 i, j, k 다 다르게 쓰기.


import numpy as np

FIGURE_STYLE = {"rows": 720, "cols": 1280, "fontsize": 1.0}
AX_SPAN = [0.2, 0.2, 0.75, 0.75]
AX_SPAN_WITH_COLORBAR_PAYLOAD = [0.2, 0.2, 0.55, 0.75]
AX_SPAN_WITH_COLORBAR_COLORBAR = [0.8, 0.2, 0.025, 0.75]

SOURCES = {
    "diffuse": {
        "label": "area $\\times$ solid angle",
        "unit": "m$^{2}$ sr",
        "limits": {
            "passed_trigger": [1e-1, 1e5],
            "passed_all_cuts": [1e-1, 1e5],
        },
    },
    "point": {
        "label": "area",
        "unit": "m$^{2}$",
        "limits": {
            "passed_trigger": [1e1, 1e6],
            "passed_all_cuts": [1e1, 1e6],
        },
    },
}

PARTICLE_COLORS = {
    "gamma": "black",
    "electron": "blue",
    "proton": "red",
    "helium": "orange",
}

MATPLOTLIB_RCPARAMS_LATEX = {
    "mathtext.fontset": "cm",
    "font.family": "STIXGeneral",
}

COLOR_PHOTO_SENSOR_RGBA = np.array([192, 0, 0]) / 255
COLOR_BEAM_RGBA = np.array([0, 128, 255]) / 255
COLOR_EYE_WALLS_RGBA = np.array([0, 192, 0]) / 255

def mark_ax_airshower_spectrum(ax, x=0.93, y=0.93, fontsize=42):
    ax.text(
        x=x,
        y=y,
        s=r"$\star$",
        color="k",
        transform=ax.transAxes,
        fontsize=fontsize,
    )

def mark_ax_thrown_spectrum(ax, x=0.93, y=0.93, fontsize=42):
    ax.text(
        x=x,
        y=y,
        s=r"$\bullet$",
        color="k",
        transform=ax.transAxes,
        fontsize=fontsize,
    )

def add_aperture_plane_to_ax(ax, **kwargs):
    ax.plot([-1, 1], [0, 0], **kwargs)

def add_rays_to_ax(ax, object_distance, N=4, **kwargs):
    x_starts = np.linspace(-0.9, 0.9, N)
    y_starts = np.zeros(N)

    x_ends = -x_starts * 100
    y_ends = 2 * object_distance * np.ones(N) * 100

    for i in range(N):
        ax.plot(
            [x_starts[i], x_ends[i]], [y_starts[i], y_ends[i]], **kwargs,
        )

def is_in_roi(x, y, roi, margin=0.1):
    x0 = roi["x"][0] - margin
    x1 = roi["x"][1] + margin
    y0 = roi["y"][0] - margin
    y1 = roi["y"][1] + margin
    if x0 <= x < x1 and y0 <= y < y1:
        return True
    else:
        return False

def position_of_eye(light_field_geometry, eye_id):
    num_pax = light_field_geometry.number_paxel
    start = eye_id * num_pax
    stop = (eye_id + 1) * num_pax
    poly = light_field_geometry.lixel_polygons[start:stop]
    poly = np.array(poly)
    pp = []
    for pol in poly:
        x = np.mean(pol[:, 0])
        y = np.mean(pol[:, 1])
        pp.append([x, y])
    pp = np.array(pp)
    x_mean = np.mean(pp[:, 0])
    y_mean = np.mean(pp[:, 1])
    return np.array([x_mean, y_mean])

def positions_of_eyes_in_roi(light_field_geometry, roi, margin=0.1):
    positions_of_eyes = {}
    for eye_id in range(light_field_geometry.number_pixel):
        pos = position_of_eye(
            light_field_geometry=light_field_geometry, eye_id=eye_id
        )
        if is_in_roi(x=pos[0], y=pos[1], roi=roi, margin=margin):
            positions_of_eyes[eye_id] = pos
    return positions_of_eyes


from poly.polygon import Polygon
from poly.point import Point
from poly.util import value,computeAngleSign
from math import degrees, acos, sqrt

"""
Implement Convex Polygon Intersection algorithm
[O'Rourke, Chien, Olson, Naddor, 1982]
https://pdfs.semanticscholar.org/3a68/0593c409eb0d86a9c436113581df970554ba.pdf

Note that this algorithm only works on convex polygons.

In general assumes that whenever two edges intersect, they intersect
in a single point that is not a vertex of exither polygon. Might not
handle some really special cases, as described in the above paper.
"""

def inhalfplane(pt, q):
    """Return True if point pt is in half-plane defined by q."""
    signTail = computeAngleSign(pt.x(), pt.y(),
                                q.head().x(), q.head().y(),
                                q.tail().x(), q.tail().y())
    return signTail >= 0

def aim (p, q):
    """Return true if p is "aiming towards" q's half-plane edge."""
    # First check if p.tail is in the half-plane of q
    inside = inhalfplane(p.tail(), q)

    # compute cross product of q x p to determine orientation
    # en.wikipedia.org/wiki/Cross_product#Computational_geometry
    # normalize p and q
    pnorm = Point(p.tail().x() - p.head().x(),
                  p.tail().y() - p.head().y())
    qnorm = Point(q.tail().x() - q.head().x(),
                  q.tail().y() - q.head().y())

    cross = qnorm.x()*pnorm.y() - qnorm.y()*pnorm.x()
    if inside:
        # in half-plane, so now check orientation
        return cross < 0
    else:
        # not in half-plane.
        return cross >= 0

def dist(p, q):
    """Compute Euclidean distance between two points."""
    return sqrt((p.x()-q.x())**2 + (p.y()-q.y())**2)

def containedWithin(pt, p):
    """
    Determine if pt is fully contained within p. Do so by
    summing angles with each edge in the convex polygon p.
    """
    sum = 0
    for e in p.edges():
        C = dist(e.head(), e.tail())
        A = dist(pt, e.head())
        B = dist(pt, e.tail())
        sum += degrees(acos((A*A+B*B-C*C)/(2*A*B)))
    return value(sum-360) == 0

def convexIntersect(p, q):
    """
    Compute and return polygon resulting from the intersection of
    two convext polygons, p and q.
    """
    intersection = Polygon()
    pn = p.numEdges()
    qn = q.numEdges()
    k = 1
    inside = None              # can't know inside until intersection
    first = None               # remember 1st intersection to know when to stop
    firstp = pe = p.edges()[0] # get first edge of p and q
    firstq = qe = q.edges()[0]
    while k < 2*(pn + qn):
        pt = pe.intersect(qe)
        if pt is not None:
            if first == None:
                first = pt
            elif pt == first:
                # stop when find first intersection again
                break

            intersection.add(pt.x(), pt.y())
            if inhalfplane(pe.tail(), qe):
                inside = p
            else:
                inside = q

        # Identify relationship between edges; either we advance
        # p or we advance q, based on whether p's current edge
        # is aiming at qe (or vice versa).
        advancep = advanceq = False

        if (aim(pe,qe) and aim(qe,pe)) or (not aim(pe,qe) and not aim(qe,pe)):
            if inside is p:
                advanceq = True
            elif inside is q:
                advancep = True
            else:
                # no intersection yet. Choose based on
                # which one is "outside"
                if inhalfplane(pe.tail(), qe):
                    advanceq = True
                else:
                    advancep = True
        elif aim(pe, qe):
            advancep = True
        elif aim(qe, pe):
            advanceq = True

##        if aim(pe, qe):
##            if aim(qe, pe):
##                if inside is p:
##                    advanceq = True
##                elif inside is q:
##                    advancep = True
##                else:
##                    advancep = True    # arbitrary pick
##            else:
##                advancep = True
##        else:
##            if aim(qe, pe):
##                advanceq = True
##            else:
##                if inside is p:
##                    advanceq = True
##                elif inside is q:
##                    advancep = True
##                else:
##                    advancep = True    # arbitrary pick

        if advancep:
            if inside is p:
                intersection.add(pe.tail().x(), pe.tail().y())
            pe = pe.next()
        elif advanceq:
            if inside is q:
                intersection.add(qe.tail().x(), qe.tail().y())
            qe = qe.next()

        k += 1

    if intersection.numPoints() == 0:
        if containedWithin(firstp.tail(), q):
            return p
        elif containedWithin(firstq.tail(), p):
            return q
        else:
            return None

    # Return computed intersection
    return intersection


# -*- coding: UTF-8 -*-
"""
@Project : leetcode
@File    : 17-迭代构造二叉树.py
@IDE     : PyCharm
@Author  : Peter
@Date    : 06/12/2021 11:52
@Brief   : 使用前序和中序遍历结构构造二叉树
"""

from typing import List

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if not preorder:
            return None

        root = TreeNode(preorder[0])
        stack = [root]
        inorderIndex = 0
        for i in range(1, len(preorder)):
            preorderVal = preorder[i]
            node = stack[-1]
            if node.val != inorder[inorderIndex]:
                node.left = TreeNode(preorderVal)
                stack.append(node.left)
            else:
                while stack and stack[-1].val == inorder[inorderIndex]:
                    node = stack.pop()
                    inorderIndex += 1
                node.right = TreeNode(preorderVal)
                stack.append(node.right)

        return root

if __name__ == '__main__':
    """
            3
           / \
          9  20
         /  /  \
        8  15   7
       / \
      5  10
     /
    4
    """
    preorder = [3, 9, 8, 5, 4, 10, 20, 15, 7]
    inorder = [4, 5, 8, 10, 9, 3, 15, 20, 7]

    Solution().buildTree(preorder, inorder)

17-迭代构造二叉树.py


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)

url = "https://www.wikipedia.org/"
driver.get(url)
search_bar = driver.find_element(By.ID, "searchInput")
# Typing on searchbar
search_bar.send_keys("python programming")
icon_button = driver.find_element(By.CSS_SELECTOR, ".pure-button .svg-search-icon")
search_bar.send_keys(Keys.ENTER)
# icon_button.click()

# url = "https://www.python.org/"
# driver.get(url)
# python_docs = driver.find_element(By.LINK_TEXT, "Docs")
# Clicking an anchor tag/button
# python_docs.click()

# driver.quit()