from flask import render_template, flash, redirect, url_for, request
from app import app
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import DataRequired, Email
import auxFunctions as aux

# SELECT_MANAGERS_SQL = "SELECT managerName AS `Manager`, emailAddress AS `Email` FROM Manager ORDER BY managerName;"
# INSERT_NEW_MANAGER_SQL = "INSERT INTO Manager(emailAddress, managerName) VALUES (%s,%s);"
# UPDATE_MANAGER_SQL = "UPDATE Manager SET managerName = %s WHERE emailAddress = %s;"
# DEACTIVATE_MANAGER_SQL = "DELETE FROM Manages WHERE emailAddress = %s;"
# FIND_MANAGER_ASSIGNMENTS_SQL = "SELECT storeNumber, emailAddress FROM Manages WHERE emailAddress= %s;"
# REMOVE_MANAGER_ASSIGNMENTS_SQL = "DELETE FROM Manager WHERE emailAddress = %s;"
# COUNT_MANAGER_ASSIGNMENTS_SQL = "SELECT COUNT(emailAddress) FROM Manages WHERE emailAddress= %s;"
# DELETE_MANAGER_SQL = "DELETE FROM Manager WHERE emailAddress = %s;"

@app.route('/managers', methods=['GET', 'POST'])
def managers():
    managerForm = ManagerForm(request.form)

    ret = aux.getSqlSplit('03. Edit Manager Profile.sql')
    if not ret[0]:
        flash(ret[1])
        return render_template('managers.html', form=managerForm, title='Managers', table='')
    manager_sql = ret[1]
    SELECT_MANAGERS_SQL = manager_sql[0]
    INSERT_NEW_MANAGER_SQL = manager_sql[1]
    UPDATE_MANAGER_SQL = manager_sql[2]
    DEACTIVATE_MANAGER_SQL = manager_sql[3]
    FIND_MANAGER_ASSIGNMENTS_SQL = manager_sql[4]
    REMOVE_MANAGER_ASSIGNMENTS_SQL = manager_sql[5]
    COUNT_MANAGER_ASSIGNMENTS_SQL = manager_sql[6]
    DELETE_MANAGER_SQL = manager_sql[7]

    resultGet = aux.get_table_rl(SELECT_MANAGERS_SQL)
    if resultGet[0]:
        sqlOutput = resultGet[1]
        managerForm.managersDDL.choices = [(email, "%s (%s)" % (name, email)) for (name, email) in sqlOutput]
        if request.method == 'POST':
            if managerForm.deactivateManager.data:
                # deactivate manager
                flash("Deactivating manager %s" % dict(managerForm.managersDDL.choices).get(managerForm.managersDDL.data))
                resultWrite = aux.writeQuery(DEACTIVATE_MANAGER_SQL, paramList=[managerForm.managersDDL.data])
                if resultWrite[0]:
                    flash("Successfully deactivated manager %s" % dict(managerForm.managersDDL.choices).get(
                        managerForm.managersDDL.data))
                    return redirect(url_for('managers'))
                else:
                    flash(resultWrite[1])
                    return redirect(url_for('managers'))
            elif managerForm.deleteManager.data:
                # delete manager
                flash("Deleting manager %s" % dict(managerForm.managersDDL.choices).get(managerForm.managersDDL.data))
                resultGet = aux.get_scalar(COUNT_MANAGER_ASSIGNMENTS_SQL, paramList=managerForm.managersDDL.data)
                if resultGet[0]:
                    if resultGet[1][0] == 0:
                        resultWrite = aux.writeQuery(DELETE_MANAGER_SQL, paramList=managerForm.managersDDL.data)
                        if resultWrite[0]:
                            flash("Successfully deleted manager %s" % dict(managerForm.managersDDL.choices).get(
                                managerForm.managersDDL.data))
                            return redirect(url_for('managers'))
                        else:
                            flash(resultWrite[1])
                            return redirect(url_for('managers'))
                    else:
                        flash("Manager %s, must be deactivated before being deleted." % dict(managerForm.managersDDL.choices).get(managerForm.managersDDL.data))
                        return redirect(url_for('managers'))
                else:
                    flash(resultGet[1])
                    return redirect(url_for('managers'))
            elif managerForm.addChange.data and \
                    managerForm.managerEmail.validate(managerForm, extra_validators=[DataRequired("Please enter manager's email address"), Email("Please enter a valid email address")]) and \
                    managerForm.managerName.validate(managerForm, extra_validators=[DataRequired("Please enter manager's name")]):
                    emails = [email for (name, email) in sqlOutput]
                    if (managerForm.managerEmail.data in emails):
                        # existing manager email
                        flash("Updating existing manager: %s (%s)" % (managerForm.managerName.data, managerForm.managerEmail.data))
                        resultWrite = aux.writeQuery(UPDATE_MANAGER_SQL, paramList=[managerForm.managerName.data, managerForm.managerEmail.data])
                        if resultWrite[0]:
                            flash("Updated existing manager: %s (%s)" % (managerForm.managerName.data, managerForm.managerEmail.data))
                            return redirect(url_for('managers'))
                        else:
                            flash(resultWrite[1])
                            return redirect(url_for('managers'))
                    else:
                        # new manager
                        flash("Inserting new manager: %s (%s)" % (managerForm.managerName.data, managerForm.managerEmail.data))
                        resultWrite = aux.writeQuery(INSERT_NEW_MANAGER_SQL, paramList=[managerForm.managerEmail.data, managerForm.managerName.data])
                        if resultWrite[0]:
                            flash("Successfully inserted new manager: %s (%s)" % (managerForm.managerName.data, managerForm.managerEmail.data))
                            return redirect(url_for('managers'))
                        else:
                            flash(resultWrite[1])
                            return redirect(url_for('managers'))
            else:
                return render_template('managers.html', form=managerForm, title='Managers', table=sqlOutput)
        else:
            # todo: FLASH: if an existing one is added , flash a warning message within form.validate_on_submit as illustrated here: https://learning.oreilly.com/library/view/flask-web-development/9781491991725/ch04.html#ch_forms
            # todo  check manager email syntax to match email address if not, flash
            # todo: add logic for deactivate manager
            # todo: add logic for delete manager
            return render_template('managers.html', form=managerForm, title='Managers', table=sqlOutput)
    else:
        flash(resultGet[1])
        # return render_template('managers.html', form=managerForm, title='Managers', table='')
        return redirect(url_for('managers'))

class ManagerForm(FlaskForm):
    managerName = StringField('To Add or Change Manager:
Manager Name: ')
    managerEmail = StringField('Manager Email: ', validators=[Email()])
    addChange = SubmitField('Add or Change')
    managersDDL = SelectField('
Select Manager to Deactivate or Delete:')
    deactivateManager = SubmitField('Deactivate Manager')
    deleteManager = SubmitField('Delete Manager')


import os
import sys
import threading
from contextlib import contextmanager

from pymaid import LifoQueue, PriorityQueue, QueueFull, QueueEmpty
from pymaid.net import dial_stream

class ConnectionPool(object):
    '''Inspired by redis.ConnectionPool'''

    queue_class = LifoQueue
    empty_item = None

    def __init__(
        self,
        name,
        address=None,
        *,
        size=50,
        init_count=0,
        **connection_kwargs,
    ):
        '''Create a blocking connection pool.

        Use ``size`` to increase / decrease the pool size::

        By default, connections will be created by dial_stream.

        Any additional keyword arguments are passed to the dial_stream.
        '''
        if not isinstance(size, int) or size < 0 or size > 100:
            raise ValueError('size must be 0 < size <= 100')

        self.name = name
        self.address = address
        self.size = size
        self.init_count = init_count
        self.connection_kwargs = connection_kwargs
        self.reset()

    def _checkpid(self):
        if self.pid != os.getpid():
            with self._check_lock:
                if self.pid == os.getpid():
                    # another thread already did the work while we waited
                    # on the lock.
                    return
                self.disconnect()
                self.reset()

    def reset(self):
        self.pid = os.getpid()
        self._check_lock = threading.Lock()

        # Create and fill up a thread safe queue with ``empty_item`` values.
        self.pool = self.queue_class(self.size)
        while 1:
            try:
                self.pool.put_nowait(self.empty_item)
            except QueueFull:
                break

        # Keep a list of actual connection instances so that we can
        # disconnect them later.
        self._connections = []
        if self.init_count:
            self.initpool(self.init_count)

    def item_getter(self, item):
        return item

    def item_putter(self, conn):
        return conn

    def initpool(self, init_count):
        if self._connections:
            # do not init pool if there are connections
            return
        if init_count > self.size:
            raise ValueError('init_count should not greater than pool size')
        if not self.address:
            raise ValueError('calling initpool with address is None')
        self.init_count = init_count
        try:
            for _ in range(init_count):
                self.pool.get_nowait()
        except QueueEmpty:
            pass
        try:
            for _ in range(init_count):
                self.pool.put_nowait(self.item_putter(self.make_connection()))
        except QueueFull:
            pass

    def get_connection(self, timeout=None):
        '''
        Get a connection from the pool, blocking for ``timeout`` util
        a connection is available from the pool.
        '''
        self._checkpid()
        # will raise QueueEmpty if timeout is not None
        item = self.pool.get(block=True, timeout=timeout)
        if item is self.empty_item:
            return self.make_connection()
        else:
            return self.item_getter(item)

    @contextmanager
    def get_autorelease_connection(self, timeout=None):
        conn = self.get_connection(timeout)
        try:
            yield conn
        finally:
            self.release(conn)

    def make_connection(self):
        '''Create a new connection'''
        connection = dial_stream(self.address, **self.connection_kwargs)
        connection.pid = os.getpid()

        def close(conn, reason=None, reset=None):
            self._connections.remove(conn)
            item = self.item_putter(conn)
            if item in self.pool.queue:
                self.pool.queue.remove(item)
            del connection.pid
            try:
                self.pool.put_nowait(self.empty_item)
            except QueueFull:
                pass

        connection.add_close_cb(close)
        self._connections.append(connection)
        return connection

    def release(self, connection):
        '''Releases the connection back to the pool'''
        self._checkpid()
        if connection.pid != self.pid:
            return

        if connection.is_closed:
            if connection in self._connections:
                self._connections.remove(connection)
            connection = None
            item = self.empty_item
        else:
            item = self.item_putter(connection)
        try:
            self.pool.put_nowait(item)
        except QueueFull:
            # perhaps the pool has been reset() after a fork? regardless,
            # we don't want this connection
            # should we close this conn?
            if connection:
                connection.close('useless')

    def disconnect(self, reason=None):
        '''Disconnects all connections in the pool'''
        for connection in self._connections[:]:
            connection.close(reason)

    def __repr__(self):
        return '[ConnectionPool|%s][connect_kwargs|%s][max|%d][created|%d]' % (
            self.name, self.connection_kwargs, self.size,
            len(self._connections)
        )
    __str__ = __repr__

class PriorityConnectionPool(ConnectionPool):

    queue_class = PriorityQueue
    empty_item = (sys.maxsize, None)

    def item_getter(self, item):
        return item[1] if item else item

    def item_putter(self, conn):
        return (conn.transmission_id, conn) if conn else conn


import os
import textwrap
from typing import Any, Tuple

import pandas as pd
from utils import clean_html_content, get_root_fpath

"""An implementation for loading leetcode problems from the gym"""

class LeetCodeLoader:
    """Concrete class responsible for loading and providing LeetCode problems."""

    def __init__(self, data_path: str):
        self.data_path = data_path
        self.data = pd.read_csv(self.data_path)
        self.data_full = pd.read_csv(
            os.path.join(
                get_root_fpath(),
                "data",
                "inputs",
                "leetcode_full.csv",
            )
        )

    def get_problem_header(self, idx: int) -> str:
        """Retrieve a problem by its index."""
        row = self.data.iloc[idx]
        return f"Title:{row['question_title']}\n\nDescription:\n{row['description']}"

    def get_problem_context(self, idx: int) -> str:
        """Retrieve a problem by its index."""
        row = self.data.iloc[idx]
        raw_content = self.data_full[
            self.data_full["question_id"] == row["question_id"]
        ]["raw_content"].iloc[0]
        return f"LeetCode Problem #{row['frontend_question_id']}\nTitle: {row['question_title']}\nDescription:\n{clean_html_content(raw_content)}\n\n"

    def get_problem_id_slug(self, idx: int) -> Tuple[int, int, Any]:
        """Retrieve a problem by its index."""
        row = self.data.iloc[idx]
        return (
            int(row["frontend_question_id"]),  # type: ignore
            int(row["question_id"]),  # type: ignore
            row["question_slug"],
        )

    def get_problem_slug(self, idx: int) -> Any:
        """Get the backend problem id for a given problem."""
        row = self.data.iloc[idx]
        return str(row["question_slug"])  # type: ignore

    def get_backend_problem_id(self, idx: int) -> int:
        """Get the backend problem id for a given problem."""
        row = self.data.iloc[idx]
        return int(row["question_id"])  # type: ignore

    def get_frontend_problem_id(self, idx: int) -> int:
        """Get the frontend problem id for a given problem."""
        row = self.data.iloc[idx]
        return int(row["frontend_question_id"])  # type: ignore

    def get_snippet(self, idx: int) -> int:
        """Get the frontend problem id for a given problem."""
        row = self.data.iloc[idx]
        return row["python3_snippet"]  # type: ignore


# The grid size cell dimensions in km
VALID_GRID_SIZES = (6.25, 12.5, 25)

# Valid hemisphere names.
NORTH = 'north'
SOUTH = 'south'
VALID_HEMISPHERES = (NORTH, SOUTH)

# Earth-parameter defualts
TRUE_SCALE_LATITUDE = 70
EARTH_RADIUS_KM = 6378.273
EARTH_ECCENTRICITY = 0.081816153


import matplotlib.pyplot as plt
import pandas as pd
import NaiveDE
import SpatialDE

meta = pd.read_csv('/Volumes/GoogleDrive/My Drive/Marmoset_shared_folder/CS6_sections_246.csv', index_col=0)
counts = pd.read_csv('/Users/christopherpenfold/Desktop/spatialDE/AllExp.csv',index_col=0)

plt.scatter(meta['X'][meta['Loc']==246], meta['Y'][meta['Loc']==246], c='k');
plt.axis('equal');
#plt.show()
plt.savefig('246.png')

norm_expr = NaiveDE.stabilize(counts)
norm_expr2 = norm_expr.T
resid_expr = NaiveDE.regress_out(meta, norm_expr, 'np.log(total_counts)').T

sample_resid_expr = resid_expr.sample(n=15000, axis=1, random_state=1)
X = meta[['X', 'Y']]
results = SpatialDE.run(X, sample_resid_expr)
results.to_csv('/Users/christopherpenfold/Desktop/spatialDE/results.csv') # relative position

plt.scatter(meta['X'], meta['Y'], c=norm_expr2['SOX2']);
plt.title('SOX2')
plt.axis('equal')
plt.savefig('246_SOX2.png')
plt.colorbar(ticks=[]);
plt.show()

plt.scatter(meta['X'], meta['Y'], c=norm_expr2['T']);
plt.title('T')
plt.axis('equal')
plt.savefig('246_T.png')
plt.colorbar(ticks=[]);
plt.show()

plt.scatter(meta['X'], meta['Y'], c=norm_expr2['MIXL1']);
plt.title('MIXL1')
plt.axis('equal')
plt.savefig('246_MIXL1.png')
plt.colorbar(ticks=[]);
plt.show()

X = meta[['X', 'Y', 'Z']]
results = SpatialDE.run(X, sample_resid_expr)
results.to_csv('/Users/christopherpenfold/Desktop/spatialDE/results2.csv') # relative position

plt.scatter(meta['X'], meta['Y'], c=norm_expr2['SOX2']);
plt.title('SOX2')
plt.axis('equal')
plt.savefig('246_SOX2_3d.png')
plt.colorbar(ticks=[]);
plt.show()

plt.scatter(meta['X'], meta['Y'], c=norm_expr2['T']);
plt.title('T')
plt.axis('equal')
plt.savefig('246_T_3d.png')
plt.colorbar(ticks=[]);
plt.show()

plt.scatter(meta['X'], meta['Y'], c=norm_expr2['MIXL1']);
plt.title('MIXL1')
plt.axis('equal')
plt.savefig('246_MIXL1_3d.png')
plt.colorbar(ticks=[]);
plt.show()


class Solution:
    def maximumUniqueSubarray(self, nums: List[int]) -> int:

        '''# A set named check_val is initialized to store unique values from          the given list.
        check_val=set()

        # An empty list named result_temp is initialized to store the                   unique values from the given list.
        result_temp=[]

        # A loop is used to iterate through the values of the given list.

        for i in nums:

            # If a value is not present in the set check_val, then it is                added to the set and the list result_temp.
            if i not in check_val:
                check_val.add(i)
                result_temp.append(i)

        # The prefix sum technique is used to calculate the sum of the              unique values in the list result_temp.
        value=result_temp[0]
        # print(sorted(result_temp))

        for j in range(1,len(result_temp)):

            value+=result_temp[j]

        # The sum of the unique values in the list result_temp is                   returned as the result.
        return value'''

        left=0
        check_val=set()

        # An empty list named result_temp is initialized to store the                   unique values from the given list.
        result_temp=0
        value=0

        # A loop is used to iterate through the values of the given list.

        for i in range(len(nums)):

            while nums[i] in check_val and left<i:

                check_val.remove(nums[left])
                result_temp-=nums[left]
                left+=1

            check_val.add(nums[i])
            result_temp+=nums[i]
            value=max(value,result_temp)
        return value


#!/usr/bin/env python3

if __name__ == "__main__":
    a = 10
    b = "test"
    c = 2 + 4

    str1 = f"hello {a+1} world"
    assert str1 == "hello 11 world"

    str2 = f"hello {b} world {a}"
    assert str2 == "hello test world 10"

    str3 = f"hello {b} world {a} test {c}"
    assert str3 == "hello test world 10 test 6"

    a = 10
    assert f"hello {a+1} world" == "hello 11 world"
    assert f"test {a+1} test {a+20} test {a+30}" == "test 11 test 30 test 40"

    # Rounding test (More complex rounding fails in PyJL)
    a = 1
    str4 = f"hello {a+1} world {0.44444:.3}"
    assert str4 == "hello 2 world 0.444"

    print("OK")


## Quiz5
# Quiz) 당신은 Cocoa 서비스를 이용하는 택시 기사님이다.
# 50명의 승객과 매칭 기회가 있을 때, 총 탑승 승객 수를 구하는 프로그램을 작성하시오.

# 조건1 : 승객별 운행 소요 시간은 5분 ~ 50분 사이의 난수로 정해집니다.
# 조건2 : 당신은 소요 시간 5분 ~ 15분 사이의 승객만 매칭해야 합니다.

# (출력문 예제)
# [O] 1번째 손님 (소요시간 : 15분)
# [ ] 2번째 손님 (소요시간 : 50분)
# [O] 3번째 손님 (소요시간 : 5분)
# ...
# [ ] 50번째 손님 (소요시간 : 16분)

# 총 탑승 승객 : 2분

from random import *
customers = list(range(1, 51))
sum = 0
for customer in customers:
    time = randint(5, 51)
    if 5 <= time <= 15:
        print("[O] {0}번째 손님 (소요시간 : {1}분)".format(customer, time))
        sum += 1
    else:
        print("[ ] {0}번째 손님 (소요시간 : {1}분)".format(customer, time))
print("총 탑승 승객 : {} 분".format(sum))

# 해답
from random import *
cnt = 0 # 총 탑승 승객 수
for i in range(1, 51): # 1 ~ 50 이라는 수 (승객)
    time = randrange(5, 51) # 5분 ~ 50분 소요 시간
    if 5 <= time <= 15: # 5분 ~ 15분 이내의 손님 (매칭 성공), 탑승 승객 수 증가 처리
        print("[O] {0}번째 손님 (소요시간 : {1}분)".format(i, time))
        cnt += 1
    else: # 매칭 실패한 경우
        print("[ ] {0}번째 손님 (소요시간 : {1}분)".format(i, time))

print("총 탑승 승객 : {0} 분".format(cnt))

##
# 퀴즈 #6
# Quiz) 표준 체중응 구하는 프로그램을 작성하시오

# * 표준 체중 : 각 개인의 키에 적당한 체중

# (성별에 따른 공식)
# 남자 : 키(m) X 키(m) x 22
# 여자 : 키(m) x 키(m) x 21

# 조건1 : 표준 체중은 별도의 함수 내에서 계산
#       * 함수명 : std_weight
#       * 전달값 : 키(height), 성별(gender)
# 조건2 : 표준 체중은 소수점 둘째자리까지 표시

# (출력 예제)
# 키 175cm 남자의 표준 체중은 67.38kg 입니다.

def std_weight(height, gender):
    if gender == "남자":
        generate = (height * 0.01) * (height * 0.01) * 22
        print("키 {0}cm 남자의 표준 체중은 {1:.2f}kg 입니다.".format(height, generate))
        return generate
    elif gender == "여자":
        generate = (height * 0.01) * (height * 0.01) * 21
        print("키 {0}cm 여자의 표준 체중은 {1:.2f}kg 입니다.".format(height, generate))
        return generate
gender = input("성별을 입력하세요.")
height = float(input("키(cm)를 입력하세요."))
generate = std_weight(height, gender)
print('출력값: {}'.format(generate))

# 해답
def std_weight(height, gender): # 키 m 단위(실수), 성별 "남자" / "여자"
    if gender == "남자":
        return height * height * 22
    else:
        return height * height * 21

height = 175 # cm 단위
gender = "남자"
weight = round(std_weight(height / 100, gender), 2)
print("키 {0}cm {1}의 표준 체중은 {2}kg 입니다.".format(height, gender, weight))

##
# 퀴즈 #7
# Quiz) 당신의 회사에서는 매주 1회 작성해야 하는 보고서가 있습니다.
# 보고서는 항상 아래와 같은 형태로 출력되어야 합니다.

# - X 주차 주간보고 -
# 부서 :
# 이름 :
# 업무 요약 :

# 1주차부터 50주차까지의 보고서 파일을 만드는 프로그램을 작성하시오.

# 조건 : 파일명은 '1주차.txt', '2주차.txt', ...와 같이 만듭니다.

for week in range(1, 4):
    with open(str(week) + "주차.txt", "w", encoding = "utf8") as file:
        print("- " + str(week) + "주차 주간보고 - ", file = file)
        print('부서 : ', file = file)
        print("이름 : ", file = file)
        print("업무 요약 : ", file = file)

def report(weeks):
    for week in range(1, weeks+1):
        with open(str(week) + "주차.txt", "w", encoding = "utf8") as file:
             print("- " + str(week) + "주차 주간보고 - ", file = file)
             print('부서 : ', file = file)
             print("이름 : ", file = file)
             print("업무 요약 : ", file = file)
report(4)

# 해답
for i in range(1, 51):
    with open(str(i) + "주차.txt", "w", encoding = "utf8") as report_file:
        report_file.write("- {0} 주차 주간보고".format(i))
        report_file.write("\n부서 :")
        report_file.write("\n이름 :")
        report_file.write("\n업무 요약 :")


class Node:
    def __init__(self, data, bottom, up) -> None:
        self.data = data
        self.bottom = bottom
        self.up = up
        self.mid = (bottom+up)//2

class SegTree:
    def __init__(self) -> None:
        self.root = self.init(0, n-1)

    def init(self, bottom, up):
        node = Node(None, bottom, up)
        if bottom == up:
            node.data = arr[up]
            return node
        mid = node.mid
        node.left = self.init(bottom, mid)
        node.right = self.init(mid+1, up)
        node.data = min(node.left.data, node.right.data)
        return node

    def update_ord(self, i, v):
        i -= 1
        self.update(self.root, i, v)

    def update(self, node, i, v):
        if node.bottom == node.up:
            node.data = v
            return v

        if i <= node.mid:
            x = self.update(node.left, i, v)
            y = node.right.data
        else:
            x = self.update(node.right, i, v)
            y = node.left.data
        node.data = min(x, y)
        return node.data

    def find_ord(self, i, j):
        i -= 1
        j -= 1
        return self.find(self.root, i, j)

    def find(self, node, i, j):
        if node.bottom == i and node.up == j:
            return node.data

        left, right = [int(1e9)]*2
        if j <= node.mid:
            left = self.find(node.left, i, j)
        elif i > node.mid:
            right = self.find(node.right, i, j)
        else:
            left = self.find(node.left, i, node.mid)
            right = self.find(node.right, node.mid+1, j)
        return min(left, right)

n = int(input())
arr = [*map(int, input().split())]
tree = SegTree()

for _ in range(int(input())):
    a, b, c = map(int, input().split())
    if a == 1:
        tree.update_ord(b, c)
    else:
        print(tree.find_ord(b, c))


#!/bin python
# -*- coding: utf-8 -*-

import os

import pandas as pd

# 读取单个excel
def read(root, name):
    date = name[0:8]  # 根据文件名, 提取日期
    yxhb_sum = 0  # 当前日期内,圆心惠宝参保人数
    no_yxhb_sum = 0  # 当前日期内,非圆心惠宝参保人数

    excel_file = os.path.join(root, name)  # excel文件地址
    excel_df = pd.read_excel(excel_file)  # pandas读取excel生成DataFrame文件(标题自动转为列名, 真正数据行不包括标题)

    for index, row in excel_df.iterrows():  # 遍历每行数据,index为行号, row为一行数据
        code = str(row['渠道编码'])  # 读取当前行的编码
        num = int(row['参保人数'])  # 读取当前行的参保人数
        if code.startswith('yxhb'):  # 判断编码是否以'yxhb'开头
            yxhb_sum += num  # 等于: yxhb_sum = yxhb_sum + num
        else:
            no_yxhb_sum += num  # 等于: no_yxhb_sum = no_yxhb_sum + num

    return [date, yxhb_sum, no_yxhb_sum]  # 返回一个列表: ['日期', '圆心惠宝参保人数','非圆心惠宝参保人数']

# 保存统计结果到excel
def write(datas, target):
    # 三个标题
    date_title = '日期'
    yxhb_title = 'yxhb_参保人数'
    no_yxhb_title = '非yxhb_参保人数'

    # 新建一个DataFrame数据对象, 用来保存统计结果
    # 结果类似:
    #    日期   | yxhb_参保人数 | 非yxhb_参保人数
    # 20210508 |     5378     |    9317
    # 20210509 |     4621     |    9624
    result = pd.DataFrame(datas, columns=[date_title, yxhb_title, no_yxhb_title])

    yxhb_sum_total = result[yxhb_title].sum()  # 对所有日期的圆心惠宝参保人数进行求和
    no_yxhb_sum_total = result[no_yxhb_title].sum()  # 对所有日期的非圆心惠宝参保人数进行求和

    # 在最后一行之后新增加一行汇总数据
    result = result.append({date_title: "汇总", yxhb_title: yxhb_sum_total, no_yxhb_title: no_yxhb_sum_total},
                           ignore_index=True)

    # print(result)
    # 日期  yxhb_参保人数  非yxhb_参保人数
    # 0  20210508       5378        9317
    # 1  20210509       4621        9624
    # 2       汇总       9999       18941

    # 保存最终结果到excel
    result.to_excel(target, index=False)

if __name__ == '__main__':
    path = "渠道统计数据2"  # 数据地址
    target = "结果.xlsx"  # 保存统计结果的文件名

    datas = []  # 数据列表

    for root, dirs, files in os.walk(path, topdown=False):  # 遍历数据地址
        for name in files:  # 挨个处理文件
            datas.append(read(root, name))  # 合并读取结果
    print(datas)  # 结果模板: [['20210508', 5378, 9317], ['20210509', 4621, 9624]...]
    write(datas, target)  # 保存结果


#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
import os
import re
import io
'''
#import matplotlib
#import matplotlib.pyplot as plt
import turtle
import math
def square(t):
	for i in range(4):
		t.fd(100)
		t.lt(90
			)

def circle(t,r):
	circ=2*math.pi * r
	m=50
	nagasa=circ/m
	ploygon(r,m,nagasa)

masa=turtle.Turtle()

square(masa)


########## Numpy ##########

# Doing the last section (on Numpy) from DataCamp's introductory python for data science

# Numpy provides alternative to Python lists: the Numpy array.

import numpy as np

height = [1.73, 1.68, 1.71, 1.89, 1.79]
weight = [65.4, 59.2, 63.6, 88.4, 68.7]

np_height = np.array(height)
np_weight = np.array(weight)

# print type(np_height)
# print type(np_weight)

# Numpy arrays can perform element-wise calculations (unlike Python lists)
bmi = np_weight / np_height ** 2
# print bmi

# Numpy arrays:
# 	- arrays contain values of all the same type (eg float)
# 	- Numpy arrays have different methods than Python lists (because Numpy arrays are a different data type)
# 		- example: python lists: [1,2,3] + [4,5,6] = [1,2,3,4,5,6] (concatenation)
# 		- example: numpy arrays: [1,2,3] + [4,5,6] = [5,7,9] (element-wise sum)

# Subsetting
# print bmi[1] # returns index 1
# print bmi[bmi > 23] # use booleans to only return elements where bmi > 23. Notice returns datatype array.
# print bmi[1:3] # slicing operator :, takes indexes [1,3)

### 2D Numpy Arrays

np_2d = np.array([[1.73, 1.68, 1.71, 1.89, 1.79],
				[65.4, 59.2, 63.6, 88.4, 68.7]])

# print np_2d
# print type(np_2d)
# print np_2d.shape # returns (2,5) (this is rows, columns)

# Subsetting 2d arrays
# print np_2d[0] # returns just the first row
# print np_2d[0][2] # returns the 0 index row, the 2 index column
# print np_2d[0,2] # another way to get a row and column [row_ind, column_ind]

### Numpy: Basic Statistics

# mean: np.mean(1d-array)
# median: np.median(1d-array)
# np.corrcoef(1d-array1, 1d-array2) returns correlation coefficient
# np.sum(1d-array)
# np.sort(1d-array)

# Generate random data:
height = np.round(np.random.normal(1.75, 0.20, 5000), 2)
weight = np.round(np.random.normal(60.32, 15, 5000), 2)

np_city = np.column_stack((height, weight)) # this is like cbind


import logging
from gnr.core.gnrbag import Bag
from gnr.sql.gnrsql import GnrSqlDb
from gnr.app.gnrapp import GnrApp
import datetime

class ManagerSituazioni(object):
    def __init__(self, db):
        self.db = db

    def situazioniPerPersona(self, persona):
        self.persona = persona
        q = self.queryUnita()
        self.selUnita = q.selection(key='index')
        #self.selUnita.apply(self.preparaUnita)
        #self.selUnita.analyze(group_by=['condominio','gestione','unimm'], distinct=['nomecond','gestione','nomegest'], key='index')
        self.selMovimenti = self.queryMovimenti()
        self.selUnita.extend(self.selMovimenti, merge=True)
        self.preparaMovimenti()

        self.selRate = self.queryRate()
        self.preparaRate()

        u = []
        for c in self.selUnita.analyzeBag:
            cond = list(c.getAttr('dist_nomecond'))[0]
            labels = ['%s-%s' % (cond, gest) for gest in list(c.getAttr('dist_nomegest'))]
            paths = ['%s.%s' % (c.label, g) for g in list(c.getAttr('dist_gestione'))]
            tabs = zip(paths, labels)
            u.extend(tabs)
        www = 0

    def queryUnita(self):
        tp = self.db.table('idea.unita_immob_nominativi')
        q = tp.query(columns=
                     """
                   $id,
                   $unita_immob_xcodice AS unimm,
                   $codice,
                   $tipo,
                   $quota,
                   $spese_ord,
                   $spese_str,
                   $attivo,
                   @codice.nome AS nomeprop,
                   @unita_immob_xcodice.xsumquote AS xsumquote,
                   @unita_immob_xcodice.xflag1 AS xflag1,
                   @unita_immob_xcodice.xflag4 AS xflag4,
                   $condominio,
                   @unita_immob_xcodice.@xcondominio.nome AS nomecond,
                   @unita_immob_xcodice.@xcondominio.@idea_gestioni_condominio.codice AS gestione,
                   @unita_immob_xcodice.@xcondominio.@idea_gestioni_condominio.nome AS nomegest,
                   $tipogest,
                   @unita_immob_xcodice.nome AS nomeunimm,
                   $ordine,
                   @unita_immob_xcodice.intestato AS intestato,
                   @unita_immob_xcodice.@xscala.nome AS nomescala""",
                     relationDict={'ordine': '@unita_immob_xcodice.ordine',
                                   'condominio': '@unita_immob_xcodice.xcondominio',
                                   'chiusa': '@unita_immob_xcodice.@xcondominio.@idea_gestioni_condominio.chiusa',
                                   'tipogest': '@unita_immob_xcodice.@xcondominio.@idea_gestioni_condominio.tipo'},
                     where="""
                            $codice=:indir
                            AND $attivo=:att
                            AND $chiusa=:chiusa""",
                     order_by="""
                            $condominio,
                            $tipogest,
                            $ordine""",
                     indir=self.persona, att=True, chiusa=False)
        return q

    def queryMovimenti(self):
        tm = self.db.table('idea.movimenti')
        q = tm.query(columns="""
                                  sum($importo_euro) AS toteuro,
                                  $condominio,
                                  $gestione,
                                  $saldo,
                                  $unimm,
                                  $proprieta""",
                     where="""
                                  @gestione.chiusa=:chiusa
                                  AND $datab<=:oggi
                                  AND $tipo='2'
                                  AND $codiceprop=:indir
                                  AND $attivo=:att""",
                     group_by="""
                                  $condominio,
                                  $gestione,
                                  $saldo,
                                  $unimm,
                                  $proprieta""",
                     relationDict={'codiceprop': '@unimm.@idea_unita_immob_nominativi_unita_immob_xcodice.codice',
                                   'attivo': '@unimm.@idea_unita_immob_nominativi_unita_immob_xcodice.attivo'},
                     indir=self.persona, att=True, chiusa=False, oggi=datetime.date.today()
                     )
        s = q.selection()
        return s

    def queryRate(self):
        tr = self.db.table('idea.unita_immob_rate')
        return tr.query(columns="""
                                    sum($importo) AS tot_importo,
                                    $condominio,
                                    $gestione,
                                    $unita_immob AS unimm""",
                        where="""
                                    @rata.scadenza<=:oggi
                                    AND $codiceprop=:indir
                                    AND $attivo=:att""",
                        group_by="""
                                    $condominio,
                                    $gestione,
                                    $unita_immob""",
                        relationDict={'condominio': '@rata.condominio', 'gestione': '@rata.gestione',
                                      'codiceprop': '@unita_immob.@idea_unita_immob_nominativi_unita_immob_xcodice.codice'
                                      ,
                                      'attivo': '@unita_immob.@idea_unita_immob_nominativi_unita_immob_xcodice.attivo'},
                        indir=self.persona, att=True, oggi=datetime.date.today()
                        ).selection()

    def preparaMovimenti(self):
        for mov in self.selMovimenti.data:
            path = '%i.%i.%i' % (mov['condominio'], mov['gestione'], mov['unimm'])
            i = list(self.selUnita.analyzeBag.getAttr(path, 'idx'))[0]
            record = self.selUnita.getByKey(i)
            frazione = record['fraz']
            quota = record['quota']
            if mov['saldo']:
                x = 'saldo_prec'
            else:
                x = 'versato'

            if str(mov['proprieta']) == str(self.persona):
                record[x] = record[x] + mov['toteuro']
            elif mov['proprieta'] == 0:
                record[x] = record[x] + mov['toteuro'] * frazione
            elif '*' not in quota:
                quota = '*%s' % quota
                record['quota'] = quota

    def preparaMovimenti2(self, mov):
        result = {}
        path = '%i.%i.%i' % (mov['condominio'], mov['gestione'], mov['unimm'])
        i = list(self.selUnita.analyzeBag.getAttr(path, 'idx'))[0]
        record = self.selUnita.getByKey(i)
        frazione = record['fraz']
        quota = record['quota']
        if mov['saldo']:
            x = 'saldo_prec'
        else:
            x = 'versato'
        result['saldo_prec'] = 0
        result['versato'] = 0
        if str(mov['proprieta']) == str(self.persona):
            result[x] = mov['toteuro']
        elif mov['proprieta'] == 0:
            result[x] = mov['toteuro'] * frazione
        elif '*' not in quota:
            quota = '*%s' % quota
            result['quota'] = quota
        return result

    def preparaRate(self):
        for r in self.selRate.data:
            path = '%i.%i.%i' % (r['condominio'], r['gestione'], r['unimm'])
            i = list(self.selUnita.analyzeBag.getAttr(path, 'idx'))[0]
            record = self.selUnita.data[i]
            frazione = record['fraz']
            quota = record['quota']
            record['scaduto'] = r['tot_importo'] * frazione
            record['saldo'] = record['scaduto'] - record['versato'] - record['saldo_prec']

    def preparaRate2(self, mov):
        result = {}
        path = '%i.%i.%i' % (r['condominio'], r['gestione'], r['unimm'])
        i = list(self.selUnita.analyzeBag.getAttr(path, 'idx'))[0]
        unita = self.selUnita.getByPkey(i)
        m = self.selMovimenti.analyzeBag.getAttr(path)
        versato = m['sum_versato']
        saldo_prec = m['sum_saldo_prec']
        unita = self.selUnita.data[i]
        frazione = unita['fraz']
        quota = unita['quota']
        result['scaduto'] = r['tot_importo'] * frazione
        result['saldo'] = result['scaduto'] - versato - saldo_prec

    def preparaUnita(self, u):
        result = {}
        fraz = 1
        opz = ''
        inq_no_paga = True
        tipo_prop = 'Inquilino'
        tipo_gest = u['tipogest']
        if ((tipo_gest == 'Ordinaria' and u['spese_ord']) or (tipo_gest != 'Ordinaria' and u['spese_str'])):
            if u['tipo'] == 'Inquilino':
                if u['xflag4']:
                    opz = 'I'
                    fraz = 1
                    inq_no_paga = False
                else:
                    fraz = 0

            if u['xflag1']:
                fraz = float(pp['quota']) / u['xsumquote']
                opz = 'D'
        else:
            fraz = 0
        result['quota'] = '%s %i/%i' % (opz, u['quota'], u['xsumquote'])
        result['fraz'] = fraz
        result['scaduto'] = 0
        result['versato'] = 0
        result['saldo_prec'] = 0
        result['saldo'] = 0
        return result

if __name__ == "__main__":
    app = GnrApp('/usr/local/genro/data/instances/idea')
    db = app.db
    sit = ManagerSituazioni(db)
    sit.situazioniPerPersona(299)


from  service_provider import ServiceProvider
from patient import Patient
from doctors_rooms import DoctorsRooms
from time import time
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import datetime
from math import sqrt

def elapse_time(reception, doctors):
    patients = reception.elapse_time()
    doctors.elapse_time()

    return patients

def add_inputs(reception, patient_entry_rate, patient_patience_rate):

    number_of_patients = np.random.poisson(lam=patient_entry_rate)
    if number_of_patients == 0:
        return 0, 0, 0
    corona_tests = np.random.uniform(0, 1, number_of_patients)

    plus = 0
    minus = 0

    for p in range(number_of_patients):
        corona_test = "-" if corona_tests[p] > 0.1 else "+"

        if corona_test == "-":
            minus += 1
        elif corona_test == "+":
            plus += 1
        else:
            raise("Invalid test result")

        reception.add_to_line(Patient(corona_test, patient_patiance_rate))

    return number_of_patients, plus, minus

def test_95_percent(array):
    if len(array) == 0:
        print("array is empty")
        return
    head = (1.96 * sqrt(np.var(array)))
    amount = (sqrt(len(array)) * np.mean(array))
    if amount == 0:
        print("devision by zero")
    else:
        print("precision is : " + str(head/amount))

def compute_doctors_best_rate(x, array, value):
    final = 0
    for a in array:
        final += 1/(a - x)
    final -= value
    return final

if __name__ == "__main__":

    # ====== Begin Initialization From File =====

    file = open("input.txt", "r")
    split_character = ","

    array_inp = file.readline().split(split_character)

    number_of_rooms = int(array_inp[0])
    patient_entry_rate = float(array_inp[1])
    patient_patiance_rate = int(array_inp[2])
    reception_service_rate = int(array_inp[3])
    # print(number_of_rooms, patient_entry_rate, patient_patiance_rate, reception_service_rate)

    reception = ServiceProvider([reception_service_rate], patient_patiance_rate, "reception")
    doctors_rooms = DoctorsRooms(patient_patiance_rate)

    for line in range(number_of_rooms):
        doctors_service_rate = list(map(int, file.readline().split(split_character)))
        doctors_rooms.add_room(doctors_service_rate)

    # doctors_rooms.print_info()

    file.close()

    # ====== End Initialization ======

    time_start = time()

    patient_goal = 100
    flag1 = flag2 = flag3 = flag4 = flag5 = flag5 = flag6 = flag7 = flag8 = flag9 = True
    flag95 = True
    total_number_of_patients = 0
    total_plus = 0
    total_minus = 0

    while True:

        if flag1 and total_number_of_patients >= patient_goal/10:
            print("10% in " + str(round(time() - time_start, 2)) + "s")
            p_wait, m_wait = doctors_rooms.get_waited()
            np_p_wait = np.array(p_wait)
            np_m_wait = np.array(m_wait)
            test_95_percent(np.concatenate(np_m_wait).ravel())
            flag1 = False

        if flag2 and total_number_of_patients >= patient_goal/10 * 2 :
            print("20% in " + str(round(time() - time_start, 2)) + "s")
            p_wait, m_wait = doctors_rooms.get_waited()
            np_p_wait = np.array(p_wait)
            np_m_wait = np.array(m_wait)
            test_95_percent(np.concatenate(np_m_wait).ravel())
            flag2 = False

        if flag3 and total_number_of_patients >= patient_goal/10 * 3 :
            print("30% in " + str(round(time() - time_start, 2)) + "s")
            p_wait, m_wait = doctors_rooms.get_waited()
            np_p_wait = np.array(p_wait)
            np_m_wait = np.array(m_wait)
            test_95_percent(np.concatenate(np_m_wait).ravel())
            flag3 = False

        if flag4 and total_number_of_patients >= patient_goal/10 * 4 :
            print("40% in " + str(round(time() - time_start, 2)) + "s")
            p_wait, m_wait = doctors_rooms.get_waited()
            np_p_wait = np.array(p_wait)
            np_m_wait = np.array(m_wait)
            test_95_percent(np.concatenate(np_m_wait).ravel())
            flag4 = False

        if flag5 and total_number_of_patients >= patient_goal/10 * 5 :
            print("50% in " + str(round(time() - time_start, 2)) + "s")
            p_wait, m_wait = doctors_rooms.get_waited()
            np_p_wait = np.array(p_wait)
            np_m_wait = np.array(m_wait)
            test_95_percent(np.concatenate(np_m_wait).ravel())
            flag5 = False

        if flag6 and total_number_of_patients >= patient_goal/10 * 6 :
            print("60% in " + str(round(time() - time_start, 2)) + "s")
            p_wait, m_wait = doctors_rooms.get_waited()
            np_p_wait = np.array(p_wait)
            np_m_wait = np.array(m_wait)
            test_95_percent(np.concatenate(np_m_wait).ravel())
            flag6 = False

        if flag7 and total_number_of_patients >= patient_goal/10 * 7 :
            print("70% in " + str(round(time() - time_start, 2)) + "s")
            p_wait, m_wait = doctors_rooms.get_waited()
            np_p_wait = np.array(p_wait)
            np_m_wait = np.array(m_wait)
            test_95_percent(np.concatenate(np_m_wait).ravel())
            flag7 = False

        if flag8 and total_number_of_patients >= patient_goal/10 * 8 :
            print("80% in " + str(round(time() - time_start, 2)) + "s")
            p_wait, m_wait = doctors_rooms.get_waited()
            np_p_wait = np.array(p_wait)
            np_m_wait = np.array(m_wait)
            test_95_percent(np.concatenate(np_m_wait).ravel())
            flag8 = False

        if flag9 and total_number_of_patients >= patient_goal/10 * 9 :
            print("90% in " + str(round(time() - time_start, 2)) + "s")
            p_wait, m_wait = doctors_rooms.get_waited()
            np_p_wait = np.array(p_wait)
            np_m_wait = np.array(m_wait)
            test_95_percent(np.concatenate(np_m_wait).ravel())
            print("No more patients are accepted, patients are waiting for service...")
            flag9 = False

        if total_number_of_patients < patient_goal:
            number_of_patients, plus, minus = add_inputs(reception, patient_entry_rate, patient_patiance_rate)
            total_number_of_patients += number_of_patients
            total_plus += plus
            total_minus += minus

        if total_number_of_patients >= patient_goal and reception.patients_line.get_line_length() == 0 and doctors_rooms.get_number_of_patients() == 0:
            break

        patients = elapse_time(reception, doctors_rooms)

        if len(patients) == 0:
            continue

        for patient in patients:
            next_room = doctors_rooms.get_next_room()
            doctors_rooms.add_to_room(next_room, patient)

    array_plus, array_minus, array_line_plus, array_line_minus, left_plus, left_minus = doctors_rooms.get_patients_data()

    array_plus.append(reception.current_plus_patients)
    array_minus.append(reception.current_minus_patients)
    array_line_plus.append(reception.get_fifo_plus_data())
    array_line_minus.append(reception.get_fifo_minus_data())
    left_plus += reception.get_left_plus_patients()
    left_minus += reception.get_left_minus_patients()

    np_plus = np.array(array_plus)
    np_minus = np.array(array_minus)
    np_line_plus = np.array(array_line_plus)
    np_line_minus = np.array(array_line_minus)

    time_end = doctors_rooms.get_time()

    print("Total number of patients : " + str(total_number_of_patients))
    print("Total number of plus patients : " + str(total_plus))
    print("Total number of minus patients : " + str(total_minus))

    #===== task for mean time in system
    print("Mean amount of time spent in system : " + str(round((np.sum(np_plus) + np.sum(np_minus))/total_number_of_patients, 2)))
    print("Mean amount of time spent in system (patients tested plus for corona) : " + str(round(np.sum(np_plus)/total_plus, 2)))
    print("Mean amount of time spent in system (patients not yet tested for corona) : " + str(round(np.sum(np_minus)/total_minus, 2)))

    #===== task for mean time in line
    print("Mean amount of time spent in line : " + str(round((np.sum(np_line_plus) + np.sum(np_line_minus))/total_number_of_patients, 2)))
    print("Mean amount of time spent in line (patients tested plus for corona) : " + str(round(np.sum(np_line_plus)/total_plus, 2)))
    print("Mean amount of time spent in line (patients not yet tested for corona) : " + str(round(np.sum(np_line_minus)/total_minus, 2)))

    #===== task for patients who left
    print("A total amount of " + str(left_plus + left_minus) + " left the hospital. this was a simulation of " + str(time_end) + " minutes. " + str(left_plus) + " of them were tested plus for corona and " + str(left_minus) + " of them were not tested yet.")

    #===== task for mean line length of reception and doctors rooms
    print("reception mean line length was : " + str(round((np.sum(np_line_plus[-1]) + np.sum(np_line_minus[-1])) / time_end, 2)) + " for " + str(time_end) + " minutes.")
    print("and doctors rooms line mean length was according to the following: ")
    for doctor_room_index in range(len(np_line_plus)):
        print(str(round((np.sum(np_line_plus[doctor_room_index]) + np.sum(np_line_minus[doctor_room_index])) / time_end, 2)))

    print("Simulation completed in : " + str(round(time() - time_start, 2)) + "s")

    #===== drawing the graphs
    np_getting_service_cumulutive_plus = np_plus.sum(axis=0)
    np_getting_service_cumulutive_minus = np_minus.sum(axis=0)

    np_waiting_in_line_cumulutive_plus = np_line_plus.sum(axis=0)
    np_waiting_in_line_cumulutive_minus = np_line_minus.sum(axis=0)

    plt.figure(0)
    plt.title("answering to all of the current patients - blue (plus), orange (not tested), green (overall)")
    plt.plot(range(time_end), np_getting_service_cumulutive_plus)
    plt.plot(range(time_end), np_getting_service_cumulutive_minus)
    plt.plot(range(time_end), np.add(np_getting_service_cumulutive_plus, np_getting_service_cumulutive_minus))

    plt.figure(1)
    plt.title("all patients waiting to time  - blue (plus), orange (not tested), green (overall)")
    plt.plot(range(time_end), np_waiting_in_line_cumulutive_plus)
    plt.plot(range(time_end), np_waiting_in_line_cumulutive_minus)
    plt.plot(range(time_end), np.add(np_waiting_in_line_cumulutive_plus, np_waiting_in_line_cumulutive_minus))

    plt.figure(2)
    plt.title("patients in the simulation - blue (plus), orange (not tested), green (overall)")
    plt.plot(range(time_end), np.add(np_waiting_in_line_cumulutive_plus, np_getting_service_cumulutive_plus))
    plt.plot(range(time_end), np.add(np_waiting_in_line_cumulutive_minus, np_getting_service_cumulutive_minus))
    plt.plot(range(time_end), np.add(np_waiting_in_line_cumulutive_minus, np.add(np_waiting_in_line_cumulutive_plus, np.add(np_getting_service_cumulutive_minus, np_getting_service_cumulutive_plus))))

    plt.figure(3)
    plt.title("frequency of patients")
    name_labels = ["plus", "not tested"]
    patients_numbers = [total_plus, total_minus]
    plt.bar(name_labels, patients_numbers)

    plt.show()

    plus_wait, minus_wait = doctors_rooms.get_waited()

    plt.figure(4)
    plt.title("frequency of waitings in line - orange (tested plus), blue (not tested)")
    np_plus_wait = np.array(plus_wait)
    np_minus_wait = np.array(minus_wait)
    unique_plus_wait, unique_plus_count = np.unique(np.concatenate(np_plus_wait).ravel(), return_counts=True)
    unique_minus_wait, unique_minus_count = np.unique(np.concatenate(np_minus_wait).ravel(), return_counts=True)

    plt.bar(unique_plus_wait, unique_plus_count, width=0.2)
    plt.bar(unique_minus_wait - 0.2, unique_minus_count, width=0.2)

    plt.show()

    plus_service, minus_service = doctors_rooms.get_service_time()

    plt.figure(5)
    plt.title("frequency of service - blue (tested plus), orange (not tested)")
    np_plus_service = np.array(plus_service)
    np_minus_service = np.array(minus_service)
    unique_plus_service, unique_plus_service_count = np.unique(np.concatenate(np_plus_service).ravel(), return_counts=True)
    unique_minus_service, unique_minus_service_count = np.unique(np.concatenate(np_minus_service).ravel(), return_counts=True)

    plt.bar(unique_plus_service, unique_plus_service_count, width=0.2)
    plt.bar(unique_minus_service - 0.2, unique_minus_service_count, width=0.2)

    plt.show()

    plt.figure(6)

    plt.title("effect of increasing doctors rate on line length")

    all_means = doctors_rooms.get_doctors_means()
    np_all_means = np.array(all_means)
    flatten_all_mean = np.concatenate(np_all_means).ravel()
    reception_rate = reception.array_of_means[0]

    rr = np.arange(0, max(flatten_all_mean), 0.1)
    f = []
    for r in rr:
        f.append(compute_doctors_best_rate(r, flatten_all_mean, reception_rate))
    f = np.array(f)

    plt.plot(rr, f)
    plt.show()


#!/usr/bin/python

import argparse

from bomara.interface import run
from bomara.utils import clear_output

# Load args ------------------------->

parser = argparse.ArgumentParser()
parser.add_argument('tool', nargs='?')
parser.add_argument('tool_args', nargs='?')

args = parser.parse_args()

if args.tool == 'clear':
    if args.tool_args != None:
        clear_output(output_dir=args.tool_args)
    else:
        # Assume default dir ('output/')
        clear_output()
    exit()

# ----------------------------------->

# Run GUI
if __name__ == '__main__':
	run()


def print_HTP(H, T, P, filename="output.txt"):
    """
    Print matrices to .txt-file (name of file = filename).
    H... overall assembled stiffness matrix
    T... nodal temperature vector
    P... nodal force vector

    Make sure, that your system of equations is sorted by
    ascending node numbers, i.e., N1 N2 ... N100.
    """

    F = open(filename, 'w')

    F.write("Stiffness matrix H: \n")
    for row in H:
        for col in row:
            outline = "{0:+8.4e},".format(col)
            F.write("{0:11s}".format(str(outline)))
        F.write("\n")

    F.write("Temperature T: \n")
    for row in T:
        for col in row:
            outline = "{0:+8.4e},".format(col)
            F.write("{0:11s} \n".format(str(outline)))

    F.write("Force vector P: \n")
    for row in P:
        for col in row:
            outline = "{0:+8.4e},".format(col)
            F.write("{0:11s} \n".format(str(outline)))

    F.close()

    return None


import logging
import sqlite3
import os
import requests
import html
import random
from dotenv import load_dotenv
from db import init_db

from telegram import \
    KeyboardButton, \
    Update, \
    ReplyKeyboardMarkup
from telegram.ext import \
    Updater, \
    CommandHandler, \
    CallbackContext, \
    PicklePersistence

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)

load_dotenv()

TOKEN = os.getenv('TELEGRAM_TOKEN')
api_key = os.getenv('API_KEY')

def start(update: Update, context: CallbackContext) -> None:
    """Sends a message with three inline buttons attached."""
    keyboard = [[
        KeyboardButton(text="/get_info"),
        KeyboardButton(text="/get_key")
    ]]

    reply_markup = ReplyKeyboardMarkup(keyboard, resize_keyboard=True)

    if not context.user_data:
        context.user_data['token'] = 10

    text = f'Hello! Your token count is {context.user_data["token"]}.\n' \
           f'Type /help for more info.'

    update.message.reply_text(text, reply_markup=reply_markup)

def help_command(update: Update, context: CallbackContext) -> None:
    """Displays info on how to use the bot."""
    text = '/get_info - show you your information and available tokens.\n' \
           '/get_key - get xPub key.\n' \
           '/get_data [key] - Search in database. On successful search you lose one token.'
    update.message.reply_text(text)

def get_info_command(update: Update, context: CallbackContext) -> None:
    ret_str = f'Tokens: {context.user_data["token"]}\n'

    res = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
    for cur in ['USD', 'GBP', 'EUR']:

        ret_str += f"{html.unescape(res.json()['bpi'][cur]['symbol'])} " \
                   f"{res.json()['bpi'][cur]['code']}: " \
                   f"{res.json()['bpi'][cur]['rate_float']}\n"

    update.message.reply_text(ret_str)

def payment_check():
    return True if random.randint(0, 1) else False

def payment_check_cycle(context: CallbackContext):
    update, user_data = context.job.context
    if user_data['timer_count'] > 0:
        logger.log(msg=f"Checking ... {user_data['timer_count']}", level=logging.INFO)
        if payment_check():
            user_data['token'] += 10
            update.message.reply_text(f'Payment successful\nTokens: {user_data["token"]}')
            logger.log(msg="Payment successful", level=logging.INFO)
            context.job.schedule_removal()
        user_data['timer_count'] -= 1
    else:
        logger.log(msg="Payment was not complete", level=logging.INFO)
        update.message.reply_text('Payment was not complete')
        context.job.schedule_removal()

def get_key_command(update: Update, context: CallbackContext) -> None:

    context.user_data['timer_count'] = 2

    context.job_queue.run_repeating(payment_check_cycle, context=(update, context.user_data), interval=3, first=1)

    text = f'xPub key: "TEST_KEY"\n'

    text += 'Waiting for payment'
    update.message.reply_text(text)

def get_data_command(update: Update, context: CallbackContext) -> None:
    if context.user_data["token"] < 1:
        update.message.reply_text(f'Not anough tokens ({context.user_data["token"]}) to perform task.')
    else:
        if context.args:
            arg = context.args[0]
            with sqlite3.connect('sqlite3.db') as con:
                cur = con.cursor()

                query = f'''
                    SELECT name, phone_number FROM users
                    WHERE name = "{arg}" or phone_number = "{arg}"
                '''

                cur.execute(query)
                rows = cur.fetchall()

            ret_str = f'Searched:\n\t{arg}\nResults:\n'

            for row in rows:
                ret_str += f'\t{row[0]} {row[1]}\n'

            context.user_data["token"] -= 1

            ret_str += f'Tokens: {context.user_data["token"]}'

            update.message.reply_text(ret_str)
        else:
            update.message.reply_text('Insert search parameters')

def main() -> None:
    """Run the bot."""
    # Create the Updater and pass it your bot's token.

    persistence = PicklePersistence(filename='test_task_bot')
    updater = Updater(TOKEN, persistence=persistence)
    # updater = Updater(TOKEN)

    updater.dispatcher.add_handler(CommandHandler('start', start))
    updater.dispatcher.add_handler(CommandHandler('help', help_command))

    updater.dispatcher.add_handler(CommandHandler('get_info', get_info_command))
    updater.dispatcher.add_handler(CommandHandler('get_key', get_key_command))
    updater.dispatcher.add_handler(CommandHandler('get_data', get_data_command))

    # Start the Bot
    updater.start_polling()

    # Run the bot until the user presses Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT
    updater.idle()

if __name__ == '__main__':
    path_to_db = os.path.join(os.getcwd(), 'sqlite3.db')
    if not os.path.exists(path_to_db):
        logger.log(msg='DB initializing', level=logging.INFO)
        init_db()
    else:
        logger.log(msg='DB exists', level=logging.INFO)

    main()


from typing import List

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """

        # a,b left upper   x,y right bottom
        def rotate(a, x):
            if a == x:
                return

            for t in range(x - a):
                tmp = matrix[a][a]
                # left column
                for i in range(a, x):
                    matrix[i][a] = matrix[i + 1][a]
                # bottom row
                for j in range(a, x):
                    matrix[x][j] = matrix[x][j + 1]
                # right column
                for i in range(a, x):
                    matrix[x - i + a][x] = matrix[x - i + a - 1][x]
                # up row
                for j in range(a, x - 1):
                    matrix[a][x - j + a] = matrix[a][x - j + a - 1]

                matrix[a][a + 1] = tmp

        a, x = 0, len(matrix) - 1
        while a < x:
            rotate(a, x)
            a += 1
            x -= 1

t = Solution()
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
t.rotate(matrix)
print(matrix)


#######################################################
# Author: Nicolas Besson                              #
# TL-OR: Project                                      #
#######################################################

def writeCoordFile(coords, filename):
    coords_string = ""
    for c in coords:
        coords_string = coords_string + str(c[0]) + ", " + str(c[1]) + "\n"
    with open(filename, "w") as f:
        coordString = f.write(coords_string)

def readCoordFile(filename):
    with open(filename, "r") as f:
        coordStringLines = f.readlines()
    coords = []
    for coordStringLine in coordStringLines:
        lineArray = coordStringLine.split(", ")
        x, y = int(lineArray[0]), int(lineArray[1])
        coords.append([x, y])
    return coords

def readSolutionFile(filename):
    with open(filename, "r") as f:
        path_string = f.readlines()
    for line in path_string:
        path = [int(i) for i in line.split(", ")]
    return path

def writeSolutionFile(paths, filename):
    path_string = ""
    for i, path in enumerate(paths):
        for i in path[:-1]:
            path_string = path_string + str(i) + ", "
        path_string = path_string + str(path[-1]) + "\n"
    with open(filename, "w") as f:
        f.write(path_string)

def readDistanceMatrixFile(filename):
    with open(filename, "r") as f:
        matrixString = f.readlines()
    return [[float(i) for i in line.split(", ")] for line in matrixString]

def writeDistanceMatrixFile(distanceMatrix, filename):
    matrixString = ""
    for line in distanceMatrix:
        lineString = ""
        for i in line[:-1]:
            lineString = lineString + str(i) + ", "
        lineString = lineString + str(line[-1]) + "\n"
        matrixString += lineString
    with open(filename, "w") as f:
        f.write(matrixString)

def readDemandMatrixFile(filename):
    with open(filename, "r") as f:
        matrixString = f.readlines()
    demands = []
    currentDemandMatrix = []
    for line in matrixString:
        if line == "#1:":
            continue
        elif line[0] == "#":
            demands.append(currentDemandMatrix)
            currentDemandMatrix = []
        else:
            currentDemandMatrix.append([int(i) for i in line.split(", ")])
    return demands

def writeDemandMatrixFile(demands, filename):
    matrixString = ""
    for day in range(1, len(demands) + 1):
        matrixString = matrixString + "#" + str(day) + ":\n"
        currentDemandMatrix =  demands[day - 1]
        for line in currentDemandMatrix:
            lineString = ""
            for i in line[:-1]:
                lineString = lineString + str(i) + ", "
            lineString = lineString + str(line[-1]) + "\n"
            matrixString += lineString
    with open(filename, "w") as f:
        f.write(matrixString)

def readInfoInstanceFile(filename):
    with open(filename) as f:
        infoString = f.readlines()
    for lineString in infoString:
        line = lineString.split(" ")
        if line[0] == "clients":
            nbClients = int(line[1])
        if line[0] == "farmers":
            nbFarmers = int(line[1])
        if line[0] == "capacity":
            capacity = int(line[1])
        if line[0] == "locationCost":
            locationCost = int(line[1])
        if line[0] == "costPerKm":
            costPerKm = float(line[1])
    return nbClients, nbFarmers, capacity, locationCost, costPerKm

def writeAllocationFile(allocation, filename):
    string_allocation = ""
    for i, a in enumerate(allocation[:-1]):
        string_allocation = string_allocation + str(a) + ", "
    string_allocation += str(allocation[-1])
    with open(filename, "w") as f:
        f.write(string_allocation)

def readAllocationFile(filename):
    with open(filename, "r") as f:
        string_allocation = f.read()
    return [float(i) for i in string_allocation.split(", ")]

def readDepotsFile(filename):
    with open(filename, "r") as f:
        depots_string = f.read()
    return [int(i) for i in depots_string.split(", ")]

def writeDepotsFile(depot_set, filename):
    depots_string = ""
    for i in depot_set[1:]:
        depots_string += str(i)
    depots_string += str(depot_set[-1])
    with open(filename, "w") as f:
        f.write(depots_string)


from django.conf import settings
from django.core.validators import (MaxValueValidator, MinValueValidator,
                                    RegexValidator)
from django.db import models

COLOR_VALIDATOR = RegexValidator(
    r'^#[a-fA-F0-9]{6}$',
    'Используйте RGB-формат для указания цвета (#FFFFFF)',
)

class Subscription(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='subscribing',
        on_delete=models.CASCADE,
    )
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='subscribers',
        on_delete=models.CASCADE,
    )

    class Meta:
        verbose_name = 'Подписка на автора'
        verbose_name_plural = 'Подписки на авторов'
        ordering = ['-author_id']
        constraints = [
            models.UniqueConstraint(
                fields=['user', 'author'],
                name='%(app_label)s_%(class)s_unique_relationships',
            ),
            models.CheckConstraint(
                name='%(app_label)s_%(class)s_prevent_self_follow',
                check=~models.Q(user=models.F('author')),
            ),
        ]

    def __str__(self):
        return f'{self.user} {self.author}'

class Tag(models.Model):
    name = models.CharField(
        verbose_name='Название тэга',
        max_length=200,
        unique=True,
    )
    color = models.CharField(
        verbose_name='Цвет',
        max_length=7,
        validators=[COLOR_VALIDATOR],
        unique=True,
    )
    slug = models.SlugField(
        verbose_name='Slug',
        max_length=200,
        unique=True,
    )

    class Meta:
        verbose_name = 'Тег'
        verbose_name_plural = 'Теги'
        ordering = ['name']

    def __str__(self):
        return f'{self.name}'

class Ingredient(models.Model):
    name = models.CharField(
        verbose_name='Название',
        max_length=200,
        blank=False,
    )
    measurement_unit = models.CharField(
        verbose_name='Единицы измерения',
        max_length=200,
        blank=False,
    )

    class Meta:
        verbose_name = 'Ингредиент'
        verbose_name_plural = 'Ингредиенты'
        ordering = ['name', 'measurement_unit']
        constraints = [
            models.UniqueConstraint(
                fields=['name', 'measurement_unit'],
                name='%(app_label)s_%(class)s_unique_relationships',
            ),
        ]

    def __str__(self):
        return f'{self.name} ({self.measurement_unit})'

class Recipe(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        verbose_name='Автор',
        related_name='recipes',
        on_delete=models.CASCADE,
    )
    name = models.CharField(
        verbose_name='Название',
        max_length=200,
    )
    image = models.ImageField(
        verbose_name='Картинка',
        upload_to='recipes/images',
    )
    text = models.TextField(
        verbose_name='Описание',
    )
    ingredients = models.ManyToManyField(
        Ingredient,
        verbose_name='Ингредиенты',
        through='RecipeIngredient',
    )
    tags = models.ManyToManyField(
        Tag,
        verbose_name='Теги',
    )
    cooking_time = models.PositiveSmallIntegerField(
        verbose_name='Время приготовления',
        validators=[MinValueValidator(1), MaxValueValidator(1440)],
    )
    pub_date = models.DateTimeField(
        verbose_name='Дата публикации',
        auto_now_add=True,
    )

    class Meta:
        verbose_name = 'Рецепт'
        verbose_name_plural = 'Рецепты'
        ordering = ['-pub_date']

    def __str__(self):
        return f'{self.name}'

class RecipeIngredient(models.Model):
    ingredient = models.ForeignKey(
        Ingredient,
        on_delete=models.RESTRICT,
    )
    recipe = models.ForeignKey(
        Recipe,
        on_delete=models.CASCADE,
    )
    amount = models.PositiveIntegerField(
        verbose_name='Количество',
        validators=[
            MinValueValidator(1),
        ],
    )

    class Meta:
        verbose_name = 'Ингредиент рецепта'
        verbose_name_plural = 'Ингредиенты рецепта'
        ordering = ['ingredient', 'recipe']
        constraints = [
            models.UniqueConstraint(
                fields=['ingredient', 'recipe'],
                name='%(app_label)s_%(class)s_unique_relationships',
            ),
        ]

    def __str__(self):
        return f'{self.ingredient} {self.recipe} {self.amount}'

class FavoriteRecipe(models.Model):
    recipe = models.ForeignKey(
        Recipe,
        on_delete=models.CASCADE,
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )

    class Meta:
        verbose_name = 'Рецепт в избранном'
        verbose_name_plural = 'Рецепт в избранном'
        ordering = ['recipe', 'user']
        constraints = [
            models.UniqueConstraint(
                fields=['recipe', 'user'],
                name='%(app_label)s_%(class)s_unique_relationships',
            ),
        ]

    def __str__(self):
        return f'{self.recipe} {self.user}'

class RecipeInShoppingCart(models.Model):
    recipe = models.ForeignKey(
        Recipe,
        on_delete=models.CASCADE,
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )

    class Meta:
        verbose_name = 'Рецепт в корзине'
        verbose_name_plural = 'Рецепт в корзинах'
        ordering = ['recipe', 'user']
        constraints = [
            models.UniqueConstraint(
                fields=['recipe', 'user'],
                name='%(app_label)s_%(class)s_unique_relationships',
            ),
        ]

    def __str__(self):
        return f'{self.recipe} {self.user}'


from django.db import models
from tcs.models import CommentBucket, VotingBucket

class Commentable(models.Model):
	bucket = models.OneToOneField(CommentBucket, blank = True)

	def save(self, *args, **kwargs):
		try:
			self.bucket
		except CommentBucket.DoesNotExist:
			new_bucket = CommentBucket()
			new_bucket.save()
			self.bucket = new_bucket

		return super().save(*args, **kwargs)

	class Meta:
		abstract = True

VOTING = {
	'difficulty': [
			dict(text = 'Very Easy', style = 'badge-warning'),
			dict(text = 'Easy', style = 'badge-info'),
			dict(text = 'Medium', style = 'badge-success'),
			dict(text = 'Hard', style = 'badge-important'),
			dict(text = 'Very Hard', style = 'badge-inverse'),
		],
	'coolness': [
			dict(text = 'Boring', style = 'badge-warning'),
			dict(text = 'Typical', style = 'badge-info'),
			dict(text = 'Not Bad', style = 'badge-success'),
			dict(text = 'Cool', style = 'badge-important'),
			dict(text = 'Awesome', style = 'badge-inverse'),
		],
}

def Voteable(field_name, related = '', category = None):
	if category is None: category = field_name
	assert category in VOTING

	def make_save(obj):
		def save(self, *args, **kwargs):
			try:
				getattr(self, field_name)
			except VotingBucket.DoesNotExist:
				new_bucket = VotingBucket()
				new_bucket.save()
				setattr(self, field_name,  new_bucket)

			return super(obj, self).save(*args, **kwargs)

		return save

	def make_voting(obj):
		@classmethod
		def get_voting(self, arg):
			if arg == category:
				return VOTING[arg]

			return super(obj, self).get_voting(arg)

		return get_voting

	class Meta:
		abstract = True

	_Voteable = type('_Voteable', (models.Model, ), {
			'__module__': Meta.__module__,
			field_name: models.OneToOneField(VotingBucket, blank = True, related_name = related + '_' + category),
			'Meta': Meta
		})

	_Voteable.save = make_save(_Voteable)
	_Voteable.get_voting = make_voting(_Voteable)

	return _Voteable


# SPLIT

import sys

input = sys.argv[1]
if len(sys.argv) <= 2:
    tableau = input.split(' ')
    print('\n'.join(tableau))
else:
    print("Erreur\nCe programme n'accepte qu'un seul argument.\nVotre chaîne de caractères se trouve-t-elle bien entre guillemets ?\n")
    sys.exit()


from typing import List, Any, cast, Optional

from boa3.builtin import public, CreateNewEvent, contract, display_name
from boa3.builtin.interop import storage
from boa3.builtin.interop.contract import update_contract
from boa3.builtin.interop.runtime import check_witness, time
from boa3.builtin.interop.stdlib import serialize, deserialize
from boa3.builtin.interop.storage import get_context, find
from boa3.builtin.interop.storage.findoptions import FindOptions
from boa3.builtin.type import UInt160, ByteString

from smart_contracts.daonators_classes.campaign import Campaign
from smart_contracts.daonators_classes.org import Org
from smart_contracts.daonators_classes.voting import TypeVoting, Voting

# Prefixes
PF_ORG = b'pforg'   # organization
PF_CMP = b'pfcmp'   # campaign
PF_VTN = b'pfvtn'   # voting
PF_ACC = b'pfacc'   # será usada pra indicar qual campanha o usuário irá votar

# Getters constants
PERCENT_VOTES = b'prcvt'
LAST_WINNER = b'lswin'

VTN_COUNT = b'vtcnt'

NewOrgEvent = CreateNewEvent(
    [
        ('script_hash', UInt160),
        ('name', str),
    ],
    'Org added'
)

NewCampaignEvent = CreateNewEvent(
    [
        ('org_script_hash', UInt160),
        ('org_name', str),
    ],
    'Campaign created'
)

NewVoteEvent = CreateNewEvent(
    [
        ('voter_script_hash', UInt160),
        ('org_script_hash', UInt160),
        ('org_name', str),
    ],
    'Vote campaign added'
)

RemoveVoteEvent = CreateNewEvent(
    [
        ('voter_script_hash', UInt160),
        ('org_script_hash', UInt160),
        ('org_name', str),
    ],
    'Vote campaign removed'
)

NewVotingEvent = CreateNewEvent(
    [
        ('voting_id', int),
        ('voting_type', str),
    ],
    'Voting created'
)

AddCampaignToVoting = CreateNewEvent(
    [
        ('campaign_address', UInt160),
        ('voting_id', int),
    ],
    'Campaign added to Voting'
)

@public
def get_campaigns() -> List[Campaign]:
    context = get_context()
    iterator = find(PF_CMP, context, FindOptions.VALUES_ONLY)
    campaigns: List[Campaign] = []

    while iterator.next():
        campaign: Campaign = deserialize(cast(bytes, iterator.value))
        campaigns.append(campaign)

    return campaigns

@public
def get_campaign(org_script_hash: UInt160) -> Optional[Campaign]:
    campaign_bytes = storage.get(_mk_cmp_key(org_script_hash))
    if len(campaign_bytes) == 0:
        return None

    return cast(Campaign, deserialize(campaign_bytes))

@public
def get_orgs() -> List[Org]:
    context = get_context()
    iterator = find(PF_ORG, context, FindOptions.VALUES_ONLY)
    orgs: List[Org] = []

    while iterator.next():
        org: Org = deserialize(cast(bytes, iterator.value))
        orgs.append(org)

    return orgs

@public
def get_account_voting(account_script_hash: UInt160) -> Optional[UInt160]:
    org_bytes = storage.get(_mk_acc_key(account_script_hash))
    if len(org_bytes) == 0:
        return None

    return UInt160(org_bytes)

@public
def get_org(org_script_hash: UInt160) -> Optional[Org]:
    org_bytes = storage.get(_mk_org_key(org_script_hash))
    if len(org_bytes) == 0:
        return None
    return cast(Org, deserialize(org_bytes))

@public
def get_voting(voting_id: int) -> Optional[Voting]:
    voting_bytes = storage.get(_mk_vtn_key(voting_id))
    if len(voting_bytes) == 0:
        return None
    return cast(Voting, deserialize(voting_bytes))

@public
def get_votings() -> List[Voting]:
    context = get_context()
    iterator = find(PF_VTN, context, FindOptions.VALUES_ONLY)
    votings: List[Voting] = []

    while iterator.next():
        voting_bytes = cast(bytes, iterator.value)
        voting: Voting = cast(Voting, deserialize(voting_bytes))
        votings.append(voting)

    return votings

@public
def add_organization(org_script_hash: UInt160, name: Optional[str]) -> bool:
    _org: Optional[Org] = get_org(org_script_hash)

    # check if org exists
    if _org is not None:
        return False

    new_org = Org(org_script_hash, name)
    _save_org(org_script_hash, new_org)

    return True

@public
def create_campaign(org_script_hash: UInt160) -> bool:
    # Pode ser que tenha uma verificação se:
    #   é administrador ou;
    #   se tem x tokens para poder criar a campanha.
    # Mas atualmente qualquer pessoa pode

    _org: Optional[Org] = get_org(org_script_hash)

    if _org is None:
        return False
    else:

        # verifica se ja existe campanha
        check_already_exists = get_campaign(org_script_hash)
        if check_already_exists is not None:
            return False

        # alguns problemas com a compilação se nao fizer esse cast
        org_selected = cast(Org, _org)
        campaign = Campaign(org_selected)

        _save_cmp(org_script_hash, campaign)
        NewCampaignEvent(org_selected.script_hash, org_selected.name)

        return True

@public
def create_voting(voting_type_name: str) -> int:
    type_voting = TypeVoting(voting_type_name, _get_voting_count())
    _inc_voting_count()

    voting_ = Voting(type_voting)
    _save_voting(type_voting.id, voting_)
    NewVotingEvent(type_voting.id, voting_type_name)
    return type_voting.id

@public
def add_campaign_to_voting(voting_id: int, campaing_script_hash: UInt160) -> bool:
    voting_ = get_voting(voting_id)

    if voting_ is None:
        return False

    if get_campaign(campaing_script_hash) is None:
        return False

    voting_selected: Voting = cast(Voting, voting_)
    voting_selected.add_campaign(campaing_script_hash)

    _save_voting(voting_id, voting_selected)
    AddCampaignToVoting(campaing_script_hash, voting_id)
    return True

@public
def vote(org_script_hash: UInt160, voter_script_hash: UInt160) -> bool:
    if not check_witness(voter_script_hash):
        return False

    # se não tiver tokens para votar entao retorna falso
    if Token.balance_of(voter_script_hash) <= 0:
        return False

    # se não existe campanha então não da pra votar
    if get_campaign(org_script_hash) is None:
        return False

    campaign: Campaign = get_campaign(org_script_hash)
    org_voted: Org = campaign.org_full

    voter_added = campaign.add_voter(voter_script_hash)
    # se adicionar o voto falhou, então retorna False
    if not voter_added:
        return False

    verify: Optional[Org] = get_account_voting(voter_script_hash)
    # se o usuário já está votando em alguém então é necessário remover esse voto
    if verify is not None:
        old_org: Org = verify
        old_org_script_hash = old_org.script_hash
        old_campaign: Campaign = get_campaign(old_org_script_hash)
        old_campaign.remove_voter(voter_script_hash)
        _save_cmp(old_org_script_hash, old_campaign)
        RemoveVoteEvent(voter_script_hash, old_org_script_hash, old_org.name)

    # salva as mudanças no storage
    _save_cmp(org_script_hash, campaign)
    _save_account_vote(voter_script_hash, org_script_hash)

    NewVoteEvent(voter_script_hash, org_voted.script_hash, org_voted.name)

    return True

@public
def remove_vote(org_script_hash: UInt160, voter_script_hash: UInt160) -> bool:
    if not check_witness(voter_script_hash):
        return False

    # se não existe campanha então não da para tirar o voto
    if get_campaign(org_script_hash) is None:
        return False

    campaign: Campaign = get_campaign(org_script_hash)
    org_voted: Org = campaign.org_full

    voter_removed = campaign.remove_voter(voter_script_hash)
    if not voter_removed:
        return False

    _save_cmp(org_script_hash, campaign)
    _remove_account_vote(voter_script_hash)
    RemoveVoteEvent(voter_script_hash, org_voted.script_hash, org_voted.name)

    return True

@public
def amount_to_donate() -> int:
    # ta sendo mockado atualmente, futuramente isso seria um balanceOf no NeoBurger desse contrato

    return time // 10000

@public
def _deploy(data: Any, update: bool):
    if not update:
        script_hash1 = UInt160(b'testeScriptHashNovo1')
        script_hash2 = UInt160(b'testeScriptHashNovo2')
        script_hash3 = UInt160(b'testeScriptHashNovo3')
        nome_org1 = 'criança feliz'
        nome_org2 = 'paz do amanhã'
        nome_org3 = 'felicidade do outro'
        test_org1 = Org(script_hash1, nome_org1)
        test_org2 = Org(script_hash2, nome_org2)
        test_org3 = Org(script_hash3, nome_org3)

        _save_org(script_hash1, test_org1)
        NewOrgEvent(script_hash1, nome_org1)

        _save_org(script_hash2, test_org2)
        NewOrgEvent(script_hash2, nome_org2)

        _save_org(script_hash3, test_org3)
        NewOrgEvent(script_hash3, nome_org3)

        create_campaign(script_hash1)
        create_campaign(script_hash2)

        create_voting('Educação')

        add_campaign_to_voting(0, script_hash1)

def _mk_org_key(org_address: UInt160) -> ByteString:
    return PF_ORG + org_address

def _mk_cmp_key(org_address: UInt160) -> ByteString:
    return PF_CMP + org_address

def _mk_vtn_key(voting_id: int) -> ByteString:
    return PF_VTN + voting_id.to_bytes()

def _mk_acc_key(account_address: UInt160) -> ByteString:
    return PF_ACC + account_address

def _save_org(org_script_hash: UInt160, org: Org):
    storage.put(_mk_org_key(org_script_hash), serialize(org))

def _save_cmp(org_script_hash: UInt160, campaign: Campaign):
    storage.put(_mk_cmp_key(org_script_hash), serialize(campaign))

def _save_voting(voting_id: int, voting_: Voting):
    storage.put(_mk_vtn_key(voting_id), serialize(voting_))

def _save_account_vote(account_script_hash: UInt160, org_script_hash: UInt160):
    storage.put(_mk_acc_key(account_script_hash), org_script_hash)

def _remove_account_vote(account_script_hash: UInt160):
    storage.delete(_mk_acc_key(account_script_hash))

def _get_voting_count() -> int:
    return storage.get(VTN_COUNT).to_int()

def _inc_voting_count():
    amount = _get_voting_count()

    storage.put(VTN_COUNT, amount + 1)

@contract(b'ys\x91\xe04\xb3\x01\xe5\n8J\xdc\x96\x98\x92\xc2\xee\x93\xf2\xc7')
class Token:
    # token no teste b'\x9d\x1f0\x89\xc8L\x01\xf9w@\xfa\x1f\xa3!\x01bj\xbf\xd6\x8b'
    # token na TestNet b'ys\x91\xe04\xb3\x01\xe5\n8J\xdc\x96\x98\x92\xc2\xee\x93\xf2\xc7'
    # Tem que fazer o reverse nos dois casos

    @staticmethod
    @display_name('balanceOf')
    def balance_of(account: UInt160) -> int:
        pass

@public
def update(script: bytes, manifest: bytes, data: Any):
    update_contract(script, manifest, data)


import smtplib
from flask_mail import Mail, Message
from flask import current_app
from app.main import mail

# def send_email(to, subject, body):
#     server = smtplib.SMTP_SSL('smtpout.secureserver.net', 465)
#     server.ehlo()
#     server.login("Support@XchangeRate.io", "Support1!")
#     fromaddr = "Support@XchangeRate.io"
#     server.sendmail(fromaddr, to, body)

def send_email(to, subject, body):
    msg = Message(
        subject,
        sender=current_app.config['MAIL_USERNAME'],
        recipients=[to]
    )
    msg.body = body
    mail.send(msg)

def send_email2(to, subject, body):
    msg = Message(
        subject,
        sender='Support@XchangeRate.io ',
        recipients=[to]
    )
    msg.body = body
    mail.send(msg)


import random

import numpy as np
import torch
import torch.nn as nn

import utils
from args import args
from args import args as pargs
from models.modules import ThreeParamConv
from models.modules import TwoParamBN
from models.modules import TwoParamConv

def get_stats(model):
    norms = {}
    numerators = {}
    difs = {}
    cossim = 0
    l2 = 0
    num_points = 2 if args.conv_type is "LinesConv" else 3

    for i in range(num_points):
        norms[f"{i}"] = 0.0
        for j in range(i + 1, num_points):
            numerators[f"{i}-{j}"] = 0.0
            difs[f"{i}-{j}"] = 0.0

    for m in model.modules():
        if isinstance(m, nn.Conv2d):
            for i in range(num_points):
                vi = get_weight(m, i)
                norms[f"{i}"] += vi.pow(2).sum()
                for j in range(i + 1, num_points):
                    vj = get_weight(m, j)
                    numerators[f"{i}-{j}"] += (vi * vj).sum()
                    difs[f"{i}-{j}"] += (vi - vj).pow(2).sum()

    for i in range(num_points):
        for j in range(i + 1, num_points):
            cossim += numerators[f"{i}-{j}"].pow(2) / (
                norms[f"{i}"] * norms[f"{j}"]
            )
            l2 += difs[f"{i}-{j}"]

    l2 = l2.pow(0.5).item()
    cossim = cossim.item()
    return cossim, l2

def get_weight(m, i):
    if i == 0:
        return m.weight
    return getattr(m, f"weight{i}")

def init(models, writer, data_loader):
    pass

def train(models, writer, data_loader, optimizers, criterion, epoch):

    # We consider only a single model here. Multiple models are for ensembles and SWA baselines.
    model = models[0]
    optimizer = optimizers[0]

    if args.num_samples > 1:
        model.apply(lambda m: setattr(m, "return_feats", True))

    model.zero_grad()
    model.train()
    avg_loss = 0.0
    train_loader = data_loader.train_loader

    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(args.device), target.to(args.device)

        # num_samples is the number of samples to draw from the subspace for batch.
        # in all experiments in the main paper it is 1.
        if args.num_samples == 1:

            if args.layerwise:
                for m in model.modules():
                    if isinstance(m, nn.Conv2d) or isinstance(
                        m, nn.BatchNorm2d
                    ):
                        alpha = np.random.uniform(0, 1)
                        setattr(m, f"alpha", alpha)
            else:
                alpha = np.random.uniform(0, 1)
                for m in model.modules():
                    if isinstance(m, nn.Conv2d) or isinstance(
                        m, nn.BatchNorm2d
                    ):
                        setattr(m, f"alpha", alpha)

            optimizer.zero_grad()
            output = model(data)
            loss = criterion(output, target)

        else:
            # Feel free to ignore this part as it is often not used.
            # This corresponds to section B of the appendix, where multiple samples from the subsapce are
            # taken for each batch.
            div = data.size(0) // args.num_samples
            feats = []
            ts = []
            optimizer.zero_grad()

            for sample in range(args.num_samples):

                if args.layerwise:
                    for m in model.modules():
                        if isinstance(m, nn.Conv2d) or isinstance(
                            m, nn.BatchNorm2d
                        ):
                            alpha = np.random.uniform(0, 1)
                            setattr(m, f"alpha", alpha)
                else:
                    alpha = np.random.uniform(0, 1)
                    for m in model.modules():
                        if isinstance(m, nn.Conv2d) or isinstance(
                            m, nn.BatchNorm2d
                        ):
                            setattr(m, f"alpha", alpha)

                output, f = model(data[sample * div : (sample + 1) * div])
                feats.append(f)

                if sample == 0:
                    loss = (
                        criterion(
                            output, target[sample * div : (sample + 1) * div]
                        )
                        / args.num_samples
                    )
                else:
                    loss += (
                        criterion(
                            output, target[sample * div : (sample + 1) * div]
                        )
                        / args.num_samples
                    )

            if args.lamb > 0:
                out = random.sample([i for i in range(args.num_samples)], 2)
                i, j = out[0], out[1]
                fi, fj = feats[i], feats[j]
                ti, tj = ts[i], ts[j]
                loss += (
                    args.fcos_weight
                    * abs(ti - tj)
                    * (
                        (fi * fj).sum().pow(2)
                        / (fi.pow(2).sum() * fj.pow(2).sum())
                    )
                )

        # Application of the regularization term, equation 3.
        num_points = 2 if args.conv_type is "LinesConv" else 3
        if args.beta > 0:
            out = random.sample([i for i in range(num_points)], 2)

            i, j = out[0], out[1]
            num = 0.0
            normi = 0.0
            normj = 0.0
            for m in model.modules():
                if isinstance(m, nn.Conv2d):
                    vi = get_weight(m, i)
                    vj = get_weight(m, j)
                    num += (vi * vj).sum()
                    normi += vi.pow(2).sum()
                    normj += vj.pow(2).sum()
            loss += args.beta * (num.pow(2) / (normi * normj))

        loss.backward()

        optimizer.step()

        avg_loss += loss.item()

        it = len(train_loader) * epoch + batch_idx
        if batch_idx % args.log_interval == 0:
            num_samples = batch_idx * len(data)
            num_epochs = len(train_loader.dataset)
            percent_complete = 100.0 * batch_idx / len(train_loader)
            print(
                f"Train Epoch: {epoch} [{num_samples}/{num_epochs} ({percent_complete:.0f}%)]\t"
                f"Loss: {loss.item():.6f}"
            )

            if args.save:
                writer.add_scalar(f"train/loss", loss.item(), it)
        if args.save and it in args.save_iters:
            utils.save_cpt(epoch, it, models, optimizers, -1, -1)

    model.apply(lambda m: setattr(m, "return_feats", False))

    avg_loss = avg_loss / len(train_loader)
    return avg_loss, optimizers

def test(models, writer, criterion, data_loader, epoch):
    model = models[0]

    model.zero_grad()
    model.eval()
    test_loss = 0
    correct = 0
    val_loader = data_loader.val_loader

    model.apply(lambda m: setattr(m, "alpha", 0.5))

    # optionally update the bn during training to, but note this slows down things.
    if args.train_update_bn:
        utils.update_bn(data_loader.train_loader, model, args.device)

    with torch.no_grad():

        for data, target in val_loader:
            data, target = data.to(args.device), target.to(args.device)

            output = model(data)
            test_loss += criterion(output, target).item()

            # get the index of the max log-probability
            pred = output.argmax(dim=1, keepdim=True)

            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(val_loader)
    test_acc = float(correct) / len(val_loader.dataset)

    print(
        f"\nTest set: Average loss: {test_loss:.4f}, Accuracy: ({test_acc:.4f})\n"
    )
    cossim, l2 = get_stats(model)

    if args.save:
        writer.add_scalar(f"test/loss", test_loss, epoch)
        writer.add_scalar(f"test/acc", test_acc, epoch)
        writer.add_scalar(f"test/norm", l2, epoch)
        writer.add_scalar(f"test/cossim", cossim, epoch)

    metrics = {"norm": l2, "cossim": cossim}

    return test_acc, metrics


#!/usr/bin/env python
# coding: utf-8

# In[1]:

#imports
import os
import csv
import re

import pandas as pd
import numpy as np

import pyLDAvis.sklearn as LDAvis
import pyLDAvis

# https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from nltk.tokenize import word_tokenize
from sklearn.decomposition import NMF, LatentDirichletAllocation

import warnings
warnings.filterwarnings('ignore')

# In[2]:

# functions
def print_topics(model, vectorizer, top_n=10):
    for idx, topic in enumerate(model.components_):
        print("Topic %d:" % (idx))
        print([(vectorizer.get_feature_names()[i], topic[i])
                        for i in topic.argsort()[:-top_n - 1:-1]])

# In[3]:

file_path = "C:\\Users\\dvjr2\\Google Drive\\Documents\\Syracuse\\IST_736_TextMining\\Project\\tables_v2"

file_list = []
essay_list = []
for item in os.listdir(file_path):

    file_list.append(file_path + "\\" + item)
    essay_list.append(item)

# In[4]:

# created files filtering emoji chars

'''
i = essay_list[3]

file = open('v2_'+i, 'w')

print(i)

with open(file_path + '\\' + i, encoding='utf-8', errors='ignore') as csvfile:
    reader = csv.reader(csvfile, delimiter = ',')
    for row in reader:
        #print(row)
        file.write(re.sub('\W+',' ', ''.join(row))+'\n')

file.close()
'''

# In[5]:

# functions
def print_topics(model, vectorizer, top_n=10):
    for idx, topic in enumerate(model.components_):
        print("Topic %d:" % (idx))
        print([(vectorizer.get_feature_names()[i], topic[i])
                        for i in topic.argsort()[:-top_n - 1:-1]])

# In[6]:

no_features = 500

#lda_cv = CountVectorizer(input = 'filename', analyzer = 'word', stop_words = 'english', lowercase = True,
#encoding="ISO-8859-1")
lda_cv = CountVectorizer(input = 'filename', analyzer = 'word', stop_words = 'english', lowercase = True,
                         max_df = 0.95, min_df = 2, max_features = no_features, encoding="ISO-8859-1")
#lda_cv = CountVectorizer(input = 'filename', analyzer = 'word', lowercase = True, encoding="ISO-8859-1")
#lda_cv = CountVectorizer(input = 'filename', encoding="ISO-8859-1")

# In[7]:

CV = lda_cv.fit_transform(file_list)
lda_columns = lda_cv.get_feature_names()
df_corpus_lda = pd.DataFrame(CV.toarray(),columns = lda_columns)
df_corpus_lda.head()

# In[8]:

no_topics = 5
max_iterations = 10
learn_off = 50
random = 0

lda_model = LatentDirichletAllocation(n_components = no_topics, max_iter = max_iterations, learning_method='online',
                                         learning_offset = learn_off,random_state = random)
#lda_model = LatentDirichletAllocation(n_components=NUM_TOPICS, max_iter=10, learning_method='online')
LDA_DH_Model = lda_model.fit_transform(CV)

# In[9]:

print(LDA_DH_Model.shape) # docs | topics
print(LDA_DH_Model[0])

# In[10]:

print_topics(lda_model, lda_cv)

# In[11]:

panel = LDAvis.prepare(lda_model, CV, lda_cv, mds='tsne')
'''
Note: if you're in the IPython notebook, pyLDAvis.show() is not the best command
      to use. Consider using pyLDAvis.display(), or pyLDAvis.enable_notebook().
'''
pyLDAvis.show(panel)
#pyLDAvis.display(panel)
#pyLDAvis.enable_notebook(panel, sort=True)

# In[ ]:


from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, Optional
from mchy.common.com_loc import ComLoc
from mchy.common.com_types import ComType, InertType, StructType
from mchy.errors import ConversionError

if TYPE_CHECKING:
    from mchy.contextual.struct.stmnt import MarkerDeclVar

@dataclass(eq=True)
class CtxVar:
    name: str
    var_type: ComType
    read_only: bool
    declaration_marker: 'MarkerDeclVar'

    def render(self) -> str:
        """Renders in a human readable way"""
        return ("let" if self.read_only else "var") + f" {self.name}: {self.var_type.render()}"

class VarScope:

    def __init__(self) -> None:
        self._vars: Dict[str, CtxVar] = {}

    def var_defined(self, name: str) -> bool:
        return name in self._vars.keys()

    def get_var(self, name: str) -> Optional[CtxVar]:
        if name in self._vars.keys():
            return self._vars[name]
        return None

    def get_var_oerr(self, name: str) -> CtxVar:
        var = self.get_var(name)
        if var is None:
            raise TypeError("Variable unexpectedly doesn't exist")
        return var

    def register_new_var(self, name: str, type: ComType, read_only: bool, declaration_marker: 'MarkerDeclVar', var_loc: ComLoc) -> CtxVar:
        if self.var_defined(name):
            raise ConversionError(f"A Variable of name `{name}` is already defined in this scope").with_loc(var_loc)
        new_var = CtxVar(name, type, read_only, declaration_marker)
        self._vars[name] = new_var
        return new_var


"""comments

Revision ID: b94fb79e6463
Revises: 65e496d0fe3c
Create Date: 2022-10-14 21:35:19.347570

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'b94fb79e6463'
down_revision = '65e496d0fe3c'
branch_labels = None
depends_on = None

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('comments',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('user_id', sa.Integer(), nullable=True),
    sa.Column('created_time', sa.DateTime(), nullable=True),
    sa.Column('comment', sa.String(), nullable=True),
    sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_comments_id'), 'comments', ['id'], unique=False)
    op.add_column('users', sa.Column('anonymous_name', sa.String(), nullable=True, server_default=''))
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('users', 'anonymous_name')
    op.drop_index(op.f('ix_comments_id'), table_name='comments')
    op.drop_table('comments')
    # ### end Alembic commands ###


n , target = map(int,input().split())
arr = list(map(int,input().split()))
def mergeSort(arr,left,right,target):
    if left == right:
        return [left]
    mid = left + (right- left)//2
    left_half = mergeSort(arr,left , mid ,target)
    right_half = mergeSort(arr,mid + 1 , right,target)
    return merge(arr , left_half , right_half ,target)
def merge( arr ,left , right,target):
    sizel = len(left)
    sizer = len(right)
    r = 0
    l = 0
    while l<sizel and r < sizer:
        if abs(arr[left[l]] - arr[right[r]]) > target:
            if arr[left[l]] > arr[right[r]]:
                r += 1
            else:
                l += 1
        else:
            break

    temp = []
    while l < sizel and r<sizer:
        if arr[left[l]] >=arr[right[r]]:
            temp.append(right[r])
            r += 1
        else:
            temp.append(left[l])
            l += 1
    while l < sizel:
        temp.append(left[l])
        l += 1
    while r < sizer:
        temp.append(right[r])
        r += 1

    return temp

ans = mergeSort(arr , 0 , 2**n - 1,target)
ans.sort()
print(*[num +1 for num in ans])


# swea 1486 장훈이의 높은 선반
#함수 인자 조심, 포함여부 조심

T = int(input())

def check(idx,height): #자꾸 lst를 통쨰로 주려고 하는데 그러지 말고 인덱스를 줘라
    global ans

    if B<=height<ans: #최소값 갱신
        ans = height
    if idx==N: #종료 (끝까지 왔으면 안되는거) #얘가 갱신 위에 있어도 안됨. 가지치기가 아니라서
        return

    #해당 인덱스의 키를 포함시키지 않는 경우
    check(idx+1, height)
    #포함시키는 경우
    check(idx+1, height+lst[idx])

for tc in range(1, T+1):
    N,B = map(int, input().split())
    lst = list(map(int, input().split()))

    # 높이가 B 이상인 탑 중에서 높이가 가장 낮은 탑
    ans = 20*10000 #N최대20, B최대10000 # 최소값을 찾아야 되기 땜에 . ..
    check(0, 0) #0번째 인덱스부터, 시작의 height은 0이니까

    print(f'#{tc} {ans-B}')