name = "徐国彩"
money = 5000000

# 查询余额函数
def Show_money():
    print(f"尊敬的{name}，您账号的余额为:{money}")

    return None

def Save_money():

    global money

    money_temp = int(input("请输入你要存款的数额:"))
    money += money_temp
    print(f"{name}账号存款{money_temp}成功!")

    return None

def Take_money():

    global money

    money_temp = int(input("请输入你要取款的数额:"))
    num = money - money_temp
    if num <= 0:
        print("取款失败！账户余额不足！")
    else:
        money -= money_temp
        print(f"{name}账号取款{money_temp}成功!还剩{money}!")
    return None

print("欢迎使用ATM机!")
while True:

    name_temp = input("请输入你的名字查询账号:")

    if name_temp == name:
        while True:
            print()
            print("1.查询余额")
            print("2.存款")
            print("3.取款")

            Cmd = int(input("请输入你要选择的操作:"))
            if Cmd == 1:
                Show_money()
            elif Cmd == 2:
                Save_money()
            elif Cmd == 3:
                Take_money()
            else:
                print("操作有误!")
    else:
        print("账号不存在请重新输入!")


#!/bin/env python
# installation: pip install keybert

from keybert import KeyBERT

kw_model = KeyBERT(model='all-mpnet-base-v2')

with open('S5.txt', 'r') as file:
    full_text = file.read()

    keywords = kw_model.extract_keywords(full_text,
                                         keyphrase_ngram_range=(1, 3),
                                         stop_words='english',
                                         highlight=False,
                                         top_n=20)
    for kw,v in list(keywords):
        # print("%.4f %s" % (v,kw))
        print(kw)


#a = 5
#b = 4
#print(a, b)

#num = (input('Введите число: '))
#numb = (input('Введите другое число: '))
#print(f'Вы ввели {num}, {numb}')
#c = input('Введите ваше имя: ')
#print(c,', рад знакомству!')

#t = int(input('Введите секунды:'))
#hours = t//3600
#hours_r = (hours) if hours > 10 else ('0' + str(hours))
#minute = (t % 3600)//60
#minute_r = (minute) if minute > 10 else ('0' + str(minute))
#second = (t % 3600) % 60
#second_r = (second) if second > 10 else ('0' + str(second))
#if hours > 24:
#    print('Количество полученных часов превышает количество часов в сутка, скоректируйте ввод.')
#else:
#    print(f'Московское время: {hours_r}:{minute_r}:{second_r}')

#n = input('Введите число: ')
#nn = int(n + n)
#nnn = int(n + n + n)
#n = int(n)
#result = n + nn + nnn
#print(result)

#n = int(input('Write a number: '))
#max = n % 10
#while True:
#    n = n // 10
#    if n % 10 > max:
#        max = n % 10
#    elif n > 9:
#        continue
#    else:
#        print(f'Максимальное число: {max}')
#        break

#prib = int(input('Введите данные по выручке: '))
#izd = int(input('Введите данные по рассходу: '))

#profit = prib - izd
#if profit < 0:
#    print(f'Ваша работа не удволитворительна, ваша выручка состовляет: {profit} руб.')
#elif profit > 0:
#    print(f'Хорошая работа, ваша выручка состовляет: {profit} руб.')
#elif profit == 0:
#    print(f'Вам надо поднапречься, ваша выручка составляет: {profit}  руб.')

#rab = int(input('Введите число работников работающих в вашей фирме: '))
#print(f'Прибыль {profit / rab} руб., составляет в расчёте на одного работника.')

a = int(input('В первый день пробежал бегун: '))
b = int(input('Километраж который должен достигнуть бегун: '))
day = 1
while a <= b:
    if a == b:
        break
    a += a / 10
    day += 1
print(f'На {day} день бегун достигнет своей цели.')


S = input()
S = S[::-1]
for i in range(len(S)):
    if S[i] == '6':
        print('9', end = "")
    elif S[i] == '9':
        print('6', end = "")
    else:
        print(S[i], end = "")
print()


import logging
import thread

from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtCore import QCoreApplication

from ui import mainwindow
from ui import submitdialog
import rnghelpers as rng
import debianbts as bts
from rngsettingsdialog import RngSettingsDialog
import bug

def chunks(l, n):
    for i in range(0, len(l), n):
        yield l[i:i+n]

class RngGui(QtWidgets.QMainWindow, mainwindow.Ui_MainWindow):

    def __init__(self, args):
        QtWidgets.QMainWindow.__init__(self)
        self.setupUi(self)

        self.logger = logging.getLogger("RngGui")
        self.logger.info("Logger initialized.")

        # Since this is not possible withon qtcreator
        self.toolButton.setDefaultAction(self.actionClearLineEdit)

        #
        self.progressbar = QtWidgets.QProgressBar(self.statusbar)
        self.progressbar.setFixedHeight(20)
        self.progressbar.setFixedWidth(100)
        self.progressbar.hide()
        self.statusbar.addPermanentWidget(self.progressbar)

        self.actionNewBugreport.triggered.connect(self.new_bugreport)
        self.actionAdditionalInfo.triggered.connect(self.additional_info)
        self.actionCloseBugreport.triggered.connect(self.close_bugreport)
        self.actionNewWnpp.triggered.connect(self.new_wnpp)
        self.actionClearLineEdit.triggered.connect(self.clear_lineedit)
        self.actionSettings.triggered.connect(self.settings_diag)
        self.actionAbout.triggered.connect(self.about)
        self.actionAboutQt.triggered.connect(self.about_qt)
        self.lineEdit.textChanged.connect(self.lineedit_text_changed)
        self.lineEdit.returnPressed.connect(self.lineedit_return_pressed)
        self.tableView.activated.connect(self.activated)
        self.webView.loadProgress.connect(self.load_progress)
        self.webView.loadStarted.connect(self.load_started)
        self.webView.loadFinished.connect(self.load_finished)
        self.checkBox.clicked.connect(self.checkbox_clicked)

        # setup the table
        self.model = TableModel(self)
        self.proxymodel = MySortFilterProxyModel(self)
        self.proxymodel.setFilterKeyColumn(-1)
        self.proxymodel.setDynamicSortFilter(True)
        self.proxymodel.setSourceModel(self.model)
        self.tableView.setModel(self.proxymodel)
        self.tableView.horizontalHeader().setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
        self.tableView.verticalHeader().setVisible(False)

        # setup the settings
        self.settings = rng.Settings(rng.Settings.CONFIGFILE)
        self.settings.load()
        self._apply_settings()
        self.webView.setHtml(rng.getRngInstructions())

        # setup the finite state machine
        self._stateChanged(None, None)

        if args:
            self.lineEdit.setText(unicode(args[0]))
            self.lineedit_return_pressed()

    def closeEvent(self, ce):
        """Save the settings and close the GUI."""
        self.logger.info("Catched close event.")
        self._get_settings()
        self.settings.save()
        ce.accept()

    def activated(self, index):
        """React on click in table."""
        self.logger.info("Row %s activated." % str(index.row()))
        realrow = self.proxymodel.mapToSource(index).row()
        bugnr = self.model.elements[realrow].bug_num
        # find the bug in our list, and get the package and nr
        for i in self.bugs:
            if i.bug_num == bugnr:
                self.currentBug = i
                break
        self._stateChanged(self.currentBug.package, self.currentBug)
        url = bts.BTS_URL + str(bugnr)
        self._show_url(url)

    def new_bugreport(self):
        self.logger.info("New Bugreport.")
        self.__submit_dialog("newbug")

    def additional_info(self):
        self.logger.info("Additional Info.")
        self.__submit_dialog("moreinfo")

    def close_bugreport(self):
        self.logger.info("Close Bugreport.")
        self.__submit_dialog("close")

    def new_wnpp(self):
        self.logger.info("New WNPP.")
        self.__submit_dialog("wnpp")

    def clear_lineedit(self):
        self.logger.info("Clear Lineedit.")
        self.lineEdit.clear()

    def lineedit_text_changed(self, text):
        self.logger.info("Text changed: %s" % text)
        text = unicode(text)
        self.proxymodel.setFilterRegExp(\
            QtCore.QRegExp(text,
                           QtCore.Qt.CaseInsensitive,
                           QtCore.QRegExp.FixedString)
            )
        self.tableView.resizeRowsToContents()

    def lineedit_return_pressed(self):
        #
        # just in case ;)
        #
        text = unicode(self.lineEdit.text())
        if text.startswith("http://"):
            self._show_url(text)
            return
        if len(text) == 0:
            return

        self.logger.info("Return pressed.")
        self.lineEdit.clear()
        # TODO: self.lineEdit.clear() does not always work, why?
        #QtCore.QTimer.singleShot(0,self.lineEdit,QtCore.SLOT("clear()"))
        query = rng.translate_query(text)
        self.logger.debug("Query: %s" % str(query))

        # test if there is a submit-as field available and rename the packages
        # if nececesairy
        for i in range(0, len(query), 2):
            if query[i] == 'package':
                realname = bug.submit_as(query[i+1])
                if query[i+1] != realname:
                    self.logger.debug("Using %s as package name as requested by developer." % str(realname))
                    query[i+1] = realname
        # Single bug or list of bugs?
        if query[0]:
            buglist = bts.get_bugs(query)
        else:
            buglist = [query[1]]
        # ok, we know the package, so enable some buttons which don't depend
        # on the existence of the acutal packe (wnpp) or bugreports for that
        # package.
        if query[0] in ("src", "package"):
            self._stateChanged(query[1], None)
        # if we got a bugnumber we'd like to select it and enable some more
        # buttons. unfortunately we don't know if the bugnumber actually exists
        # for now, so we have to wait a bit until the bug is fetched.
        else:
            self._stateChanged(None, None)
        self.logger.debug("Buglist matching the query: %s" % str(buglist))
        chunksize = 50
        if len(buglist) > chunksize:
            self.load_started()
            self.logger.debug("Buglist longer than %i, splitting in chunks." % chunksize)
            self.bugs = []
            i = 0
            for chunk in chunks(buglist, chunksize):
                i += 1
                progress = int(100. * i * chunksize / len(buglist))
                if progress > 100:
                    progress = 100
                self.load_progress(progress)
                bl = bts.get_status(chunk)
                if len(bl) == 0:
                    self.logger.error("One of the following bugs caused the BTS to hickup: %s" % str(bl))
                self.bugs.extend(bl)
            self.load_finished(True)
        else:
            self.bugs = bts.get_status(buglist)
        # ok, we fetched the bugs. see if the list isn't empty
        if query[0] in (None,) and len(self.bugs) > 0:
            self.currentBug = self.bugs[0]
            self.currentPackage = self.currentBug.package
            self._stateChanged(self.currentPackage, self.currentBug)
        self.model.set_elements(self.bugs)
        self.tableView.resizeRowsToContents()

    def settings_diag(self):
        """Spawn settings dialog and get settings."""
        s = RngSettingsDialog(self.settings)
        if s.exec_() == s.Accepted:
            self.logger.debug("Accepted settings change, applying.")
            self.settings = s.settings

    def about(self):
        """Shows the about box."""
        # TODO: copyright string below should be a constant
        QtWidgets.QMessageBox.about(\
            self,
            self.tr("About Reportbug-NG"),"""Reportbug-NG """ +
                rng.getInstalledPackageVersion("reportbug-ng") + """\n""" +
            self.tr(\
"""Reportbug-NG is a graphical interface for searching, filtering, reporting
or manipulating bugs in Debian's Bug Tracking System.""") + """\n""" +
            self.tr(\
"""Copyright (C) 2007-2014 Bastian Venthur <venthur at debian org>

Homepage: http://reportbug-ng.alioth.debian.org

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version."""))

    def about_qt(self):
        QtWidgets.QMessageBox.aboutQt(self, self.tr("About Qt"))

    def _stateChanged(self, package, bug):
        """Transition for our finite state machine logic"""
        if package:
            self.currentPackage = package
            self.actionNewBugreport.setEnabled(1)
        else:
            self.currentPackage = ""
            self.actionNewBugreport.setEnabled(0)

        if bug:
            self.currentBug = bug
            self.actionAdditionalInfo.setEnabled(1)
            self.actionCloseBugreport.setEnabled(1)
        else:
            self.currentBug = bts.Bugreport()
            self.actionAdditionalInfo.setEnabled(0)
            self.actionCloseBugreport.setEnabled(0)

    def __submit_dialog(self, type):
        """Setup and spawn the submit dialog."""
        dialog = SubmitDialog()
        dialog.checkBox_script.setChecked(self.settings.script)
        dialog.checkBox_presubj.setChecked(self.settings.presubj)

        if type == 'wnpp':
            dialog.wnpp_groupBox.setEnabled(1)
            dialog.wnpp_groupBox.setChecked(1)
            dialog.groupBox_other.setEnabled(0)
            package = self.currentPackage
            to = "submit@bugs.debian.org"
        elif type == 'newbug':
            dialog.wnpp_groupBox.setEnabled(1)
            dialog.wnpp_groupBox.setChecked(0)
            package = self.currentPackage
            to = "submit@bugs.debian.org"
        elif type == 'moreinfo':
            dialog.wnpp_groupBox.setEnabled(0)
            dialog.comboBoxSeverity.setEnabled(0)
            dialog.checkBoxSecurity.setEnabled(0)
            dialog.checkBoxPatch.setEnabled(0)
            dialog.checkBoxL10n.setEnabled(0)
            package = self.currentBug.package
            to = "%s@bugs.debian.org" % self.currentBug.bug_num
        elif type == 'close':
            dialog.groupBox_other.setEnabled(0)
            dialog.wnpp_groupBox.setEnabled(0)
            dialog.comboBoxSeverity.setEnabled(0)
            dialog.checkBoxSecurity.setEnabled(0)
            dialog.checkBoxPatch.setEnabled(0)
            dialog.checkBoxL10n.setEnabled(0)
            dialog.lineEditSummary.setText("Done: %s" % self.currentBug.subject)
            package = self.currentBug.package
            to = "%s-done@bugs.debian.org" % self.currentBug.bug_num
        else:
            self.logger.critical("Received unknown submit dialog type!")

        version = rng.getInstalledPackageVersion(package)
        dialog.lineEditPackage.setText(package)
        dialog.lineEditVersion.setText(version)
        for action in rng.WNPP_ACTIONS:
            dialog.wnpp_comboBox.addItem(action)
        for sev in rng.SEVERITY:
            dialog.comboBoxSeverity.addItem(sev)
        # Set default severity to 'normal'
        dialog.comboBoxSeverity.setCurrentIndex(4)

        # Run the dialog
        if dialog.exec_() == dialog.Accepted:
            package = dialog.lineEditPackage.text()
            version = dialog.lineEditVersion.text()
            severity = unicode(dialog.comboBoxSeverity.currentText()).lower()
            tags = []
            cc = []
            if dialog.checkBoxL10n.isChecked():
                tags.append("l10n")
            if dialog.checkBoxPatch.isChecked():
                tags.append("patch")
            if dialog.checkBoxSecurity.isChecked():
                tags.append("security")
                cc.append("secure-testing-team@lists.alioth.debian.org")
            mua = self.settings.lastmua
            script = dialog.checkBox_script.isChecked()
            presubj = dialog.checkBox_presubj.isChecked()

            body, subject = '', ''
            # WNPP Bugreport
            if dialog.wnpp_comboBox.isEnabled():
                action = dialog.wnpp_comboBox.currentText()
                descr = dialog.wnpp_lineEdit.text()
                body = rng.prepare_wnpp_body(action, package, version)
                subject = rng.prepare_wnpp_subject(action, package, descr)
            # Closing a bug
            elif type == 'close':
                severity = ""
                subject = unicode(dialog.lineEditSummary.text())
                body = rng.prepare_minimal_body(package, version, severity, tags, cc)
            # New or moreinfo
            else:
                if type == 'moreinfo':
                    severity = ""
                subject = unicode("[%s] %s" % (package, dialog.lineEditSummary.text()))
                body = rng.prepareBody(package, version, severity, tags, cc, script)

            if len(subject) == 0:
                subject = "Please enter a subject before submitting the report."

            if presubj:
                txt = rng.get_presubj(package)
                if txt:
                    QtWidgets.QMessageBox.information(self, "Information", txt)
            thread.start_new_thread(rng.prepareMail, (mua, to, subject, body))

    def _apply_settings(self):
        """Apply settings."""
        self.resize(self.settings.width, self.settings.height)
        self.move(self.settings.x, self.settings.y)
        self.tableView.horizontalHeader().resizeSection(0, self.settings.bugnrWidth)
        self.tableView.horizontalHeader().resizeSection(1, self.settings.packageWidth)
        self.tableView.horizontalHeader().resizeSection(2, self.settings.summaryWidth)
        self.tableView.horizontalHeader().resizeSection(3, self.settings.statusWidth)
        self.tableView.horizontalHeader().resizeSection(4, self.settings.severityWidth)
        self.tableView.horizontalHeader().resizeSection(5, self.settings.lastactionWidth)
        order = QtCore.Qt.DescendingOrder
        if self.settings.sortAsc:
            order = QtCore.Qt.AscendingOrder
        self.tableView.setSortingEnabled(True)
        self.tableView.sortByColumn(self.settings.sortByCol, order)
        self.checkBox.setChecked(self.settings.hideClosedBugs)

    def _get_settings(self):
        """Get current settings."""
        p = self.pos()
        s = self.size()
        self.settings.x = p.x()
        self.settings.y = p.y()
        self.settings.width = s.width()
        self.settings.height = s.height()
        self.settings.sortByCol = self.tableView.horizontalHeader().sortIndicatorSection()
        self.settings.sortAsc = {QtCore.Qt.AscendingOrder : True,
                                 QtCore.Qt.DescendingOrder : False}[self.tableView.horizontalHeader().sortIndicatorOrder()]
        self.settings.bugnrWidth = self.tableView.columnWidth(0)
        self.settings.packageWidth = self.tableView.columnWidth(1)
        self.settings.summaryWidth = self.tableView.columnWidth(2)
        self.settings.statusWidth = self.tableView.columnWidth(3)
        self.settings.severityWidth = self.tableView.columnWidth(4)
        self.settings.lastactionWidth = self.tableView.columnWidth(5)
        self.settings.hideClosedBugs = self.checkBox.isChecked()

    def _show_url(self, url):
        url = QtCore.QUrl(url)
        self.webView.setUrl(url)

    def load_started(self):
        """Webwiew started to load a page."""
        self.progressbar.show()

    def load_progress(self, progress):
        """Webwiew progress advanced."""
        self.progressbar.setValue(progress)

    def load_finished(self, ok):
        """Webview finished do load the page."""
        self.progressbar.reset()
        self.progressbar.hide()

    def checkbox_clicked(self, check):
        """Checkbox to toggle hide/show closed Bugs was changed."""
        self.settings.hideClosedBugs = check
        self.proxymodel.invalidate()

class TableModel(QtCore.QAbstractTableModel):

    def __init__(self, parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self.parent = parent
        self.logger = logging.getLogger("TableModel")
        self.elements = []
        self.header = [QCoreApplication.translate('TableModel', "Bugnumber"),
                       QCoreApplication.translate('TableModel', "Package"),
                       QCoreApplication.translate('TableModel', "Summary"),
                       QCoreApplication.translate('TableModel', "Status"),
                       QCoreApplication.translate('TableModel', "Severity"),
                       QCoreApplication.translate('TableModel', "Tags"),
                       QCoreApplication.translate('TableModel', "Last Action")]

    def rowCount(self, parent):
        return len(self.elements)

    def columnCount(self, parent):
        return len(self.header)

    #
    # DAMMIT DONT IGNORE THE DISPLAY ROLE!!
    #
    def data(self, index, role):
        if not index.isValid():
            return QtCore.QVariant()
        if role == QtCore.Qt.ForegroundRole:
            severity = self.elements[index.row()].severity.lower()
            done = self.elements[index.row()].done
            c = self.parent.settings.c_normal
            if severity == "grave":
                c = self.parent.settings.c_grave
            elif severity == "serious":
                c = self.parent.settings.c_serious
            elif severity == "critical":
                c = self.parent.settings.c_critical
            elif severity == "important":
                c = self.parent.settings.c_important
            elif severity == "minor":
                c = self.parent.settings.c_minor
            elif severity == "wishlist":
                c = self.parent.settings.c_wishlist
            if done:
                c = self.parent.settings.c_resolved
            return QtCore.QVariant(QtGui.QColor(c))
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
        bug = self.elements[index.row()]
        if bug.archived:
            status = "Archived"
        elif bug.done:
            status = "Closed"
        else:
            status = "Open"
        data = {0 : bug.bug_num,
                1 : bug.package,
                2 : bug.subject,
                3 : status,
                4 : bug.severity,
                5 : ", ".join(bug.tags),
                6 : QtCore.QDate(bug.log_modified)}[index.column()]
        return QtCore.QVariant(data)

    #
    # DAMMIT DONT IGNORE THE DISPLAY ROLE!!
    #
    def headerData(self, section, orientation, role):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()
        if orientation == QtCore.Qt.Horizontal:
            return QtCore.QVariant(self.header[section])
        else:
            return QtCore.QVariant()

    def set_elements(self, entries):
        self.logger.info("Setting Elements.")
        self.beginRemoveRows(QtCore.QModelIndex(), 0, len(self.elements)-1)
        self.elements = []
        self.endRemoveRows()
        self.beginInsertRows(QtCore.QModelIndex(), 0, len(entries)-1)
        self.elements = entries
        self.endInsertRows()

class MySortFilterProxyModel(QtCore.QSortFilterProxyModel):

    def __init__(self, parent=None):
        QtCore.QSortFilterProxyModel.__init__(self, parent)
        self.logger = logging.getLogger("MySortFilterProxyModel")
        self.parent = parent

    def lessThan(self, left, right):
        if left.column() != 4:
            return QtCore.QSortFilterProxyModel.lessThan(self, left, right)
        l = self.sourceModel().elements[left.row()]
        r = self.sourceModel().elements[right.row()]
        return l < r

    def filterAcceptsRow(self, sourceRow, sourceParent):
        if self.sourceModel().elements[sourceRow].done and self.parent.settings.hideClosedBugs:
            return False
        return QtCore.QSortFilterProxyModel.filterAcceptsRow(self, sourceRow, sourceParent)

class SubmitDialog(QtWidgets.QDialog, submitdialog.Ui_SubmitDialog):

    def __init__(self):
        QtWidgets.QDialog.__init__(self)
        self.setupUi(self)
        self.buttonBox.button(QtWidgets.QDialogButtonBox.Ok).clicked.connect(self.accept)
        self.buttonBox.button(QtWidgets.QDialogButtonBox.Cancel).clicked.connect(self.reject)
        self.comboBoxSeverity.currentIndexChanged.connect(self.severity_changed)

    def severity_changed(self, index):
        self.label_severity.setText(rng.getSeverityExplanation(index))


import pandas as pd
import os.path
import urllib.request
import json
import threading
import numpy as np

# 사용자가 입력한 수 간격만큼 데이터를 가져옵니다.
end=False
def Cycle(second=300):
    global end
    if end:
        return
    #url을 받아와 실시간 비트코인 시세를 확인합니다.
    url = urllib.request.urlopen('https://api.bithumb.com/public/ticker/BTC')
    readJson = url.read()

    # json파일을 받아와 데이터프레임으로 가공합니다.
    json = pd.read_json(readJson)
    p1 = pd.DataFrame(json).T.drop(["status"]).drop(["24H_fluctate"], axis=1).drop(['24H_fluctate_rate'], axis=1) \
        .drop(['average_price'], axis=1).drop(['max_price'], axis=1).drop(['closing_price'], axis=1) \
        .drop(['opening_price'], axis=1).drop(['units_traded'], axis=1).drop(['volume_1day'], axis=1) \
        .drop(['volume_7day'], axis=1).drop(['min_price'], axis=1).drop(["date"], axis=1)

    if(os.path.exists("data.csv")):
        #파일이 있을때 csv파일에 추가합니다.
        print("파일이 있어 기존의 데이터에 추가합니다.")
        p1.to_csv('data.csv',mode='a',header=False,encoding='utf-8',index=False)
    else:
        #파일이 없을때 csv파일을 생성합니다.
        print("파일이 없어 새로운 데이터를 생성합니다.")
        p1.to_csv("data.csv",encoding='utf-8',header=["buy","sell"],index=False)

    #반복 실행
    threading.Timer(second,Cycle,[second]).start()

print("파이썬을 활용한 비트코인 시세구하기 프로그램 입니다.")
num=input("반복될 시간을 정해주세요(초) : ")

if(num.isdigit()):
    Cycle(int(num))
else:
    print("잘못된 값을 입력하여 프로그램을 종료합니다.")


from sentence_transformers import SentenceTransformer, util
# from utils.extract_keywords import extract_keywords

st_model = SentenceTransformer('paraphrase-MiniLM-L6-v2', device='cuda')

def transformerSim(statements, question):
    question_embedding = st_model.encode(question, convert_to_tensor=True)

    statement_embeddings = st_model.encode(statements, convert_to_tensor=True)

    cosine_scores = util.pytorch_cos_sim(
        question_embedding, statement_embeddings)

    ranked_statements = sorted(
        zip(statements, cosine_scores.tolist()[0]), key=lambda x: x[1], reverse=True
    )

    return ranked_statements

def rankPTKBS(PTKBs, Text):
    # print(f"Sample Response: {turn['response']}")
    a = transformerSim(PTKBs, Text)
    return a

"""
a = rankPTKBS([
"I drink milk every day",
"I own a Christy Dawn leather shoe",
"I hold a bachelor's degree in sociology",
"I love formula one races",
"I love Rally races.",
"I enjoy riding bikes.",
"I like to shop.",
"I like sightseeing.",
"I own a black Harley-Davidson motorcycle.",
"My children live in Germany.",
"I live in the UK.",

], "I'm looking for a car, can you help me?")
print(a)
"""


class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        def dfs(i, j):
            if i < 0 or i >= len(grid) or j <0 or j >= len(grid[0]) or grid[i][j] != '1':
                return
            grid[i][j] = 0
            dfs(i, j + 1)
            dfs(i, j - 1)
            dfs(i + 1, j)
            dfs(i - 1, j)

        cnt = 0
        for i in range(len(grid)):
            for j in range(len(grid[i])):
                if grid[i][j] == '1':
                    dfs(i, j)
                    cnt += 1
        return cnt

V. Algorithm/ii. Site/F. LeetCode/0200_number_of_islands.py


# pyright: reportPrivateUsage=false
import json
import time
from pathlib import Path
from types import TracebackType
from typing import Any, Optional, Type, TypeVar

import httpx
from httpx._models import Request, Response

A = TypeVar("A", bound="InterceptTransport")

def json_default(obj: Any):
    if isinstance(obj, (bytes, bytearray)):
        return obj.decode(errors="ignore")
    if isinstance(obj, httpx.URL):
        return str(obj)
    if isinstance(obj, httpx.Headers):
        return dict(obj)
    return str(obj)

class InterceptTransport(httpx.AsyncBaseTransport):
    _client: httpx.AsyncClient
    _original_transport: httpx.AsyncBaseTransport

    def __init__(self, client: httpx.AsyncClient, path: Path):
        self._client = client
        self._path = path.absolute()
        assert self._path.is_dir()
        # Monkey patch the client's transport with this one
        self._original_transport = client._transport
        client._transport = self

    async def __aenter__(self: A) -> A:
        return await self._original_transport.__aenter__() # type: ignore

    async def __aexit__(
        self,
        exc_type: Optional[Type[BaseException]] = None,
        exc_value: Optional[BaseException] = None,
        traceback: Optional[TracebackType] = None,
    ) -> None:
        await self._original_transport.__aexit__(exc_type, exc_value, traceback)

    async def handle_async_request(self, request: Request) -> Response:
        ts = time.monotonic()
        fname = self._path / f"req_{ts}_{request.url.host}.json"
        with fname.open("w") as f:
            data: dict[str, Any] = {'req': {k: v for k, v in vars(request).items() if k not in ('extensions', 'stream')}, 'ts1': ts}
            try:
                response = await self._original_transport.handle_async_request(request)
                await response.aread()
                data['ts2'] = time.monotonic()
                data['resp'] = {k: v for k, v in vars(response).items() if k not in ('stream',)}
            except Exception as exc:
                data['exc'] = exc
                raise exc
            try:
                js = json.dumps(data, indent=2, default=json_default)
            except Exception as exc:
                js = f"{'error': 'Could not serialize request', 'exc': '{exc}'}"
            f.write(js)
        return response

    async def aclose(self) -> None:
        await self._original_transport.aclose()


import os

#special_vocabs = ["PADDING", "MASK", "UNK", "SEQUENCE_START", "SEQUENCE_END"]
special_vocabs = ["PADDING", "UNK", "SEQUENCE_START", "SEQUENCE_END"]

class Lang:
  def __init__(self, path):
    if not os.path.isfile(path):
      raise ValueError("File does not exist: {}".format(path))
    self.path = path
    self.vocab2index = {}
    self.index2vocab = {}
    self.vocab_size = 0
    self.create_vocab()

  def add_word(self, word):
    if word not in self.vocab2index and len(word) > 0:
      self.vocab2index[word] = self.vocab_size
      self.index2vocab[self.vocab_size] = word
      self.vocab_size += 1

  def create_vocab(self):
    for word in special_vocabs:
      self.add_word(word)
    with open(self.path, "r", encoding='utf-8') as file:
      for line in file:
        word = line.split()[0]
        self.add_word(word)

  def sentence2indexes(self, sentence_as_list, reverse=False):
    index_list = [self.vocab2index["SEQUENCE_START"]]
    for each in sentence_as_list:
      index_list.append(self.vocab2index[each] if each in self.vocab2index else self.vocab2index["UNK"])
    index_list.append(self.vocab2index["SEQUENCE_END"])

    if reverse:
      index_list.reverse()

    return index_list

  def indexes2sentence(self, index_list, clean=True, reverse=False):
    sentence_as_list = []
    index_list = list(index_list)

    if reverse:
      index_list.reverse()

    for word_index in index_list:
      word_index = int(word_index)
      if word_index not in self.index2vocab:
        raise ValueError("Vocab index does not exist: {}".format(word_index))
      word = self.index2vocab[word_index]
      if word != "PADDING" or clean == False:
        sentence_as_list.append(word)

    if clean:
      if sentence_as_list[0] == "SEQUENCE_START":
        sentence_as_list.pop(0)
      if len(sentence_as_list) > 0 and sentence_as_list[-1] == "SEQUENCE_END":
        sentence_as_list.pop()

    return sentence_as_list


#!/usr/bin/env python
# coding: utf-8
import numpy as np
from pyrosetta import Pose, pose_from_file, Vector1
from pyrosetta.rosetta.basic.datacache import CacheableStringMap
from pyrosetta.rosetta.core.pose.datacache import CacheableDataType
from scipy.spatial.transform import Rotation as R
from src.individual import Individual
from src.pdb_structure import pdbstructure_from_file
from pyrosetta.rosetta.protocols.symmetry import SetupForSymmetryMover
from pyrosetta.rosetta.core.pose.symmetry import is_symmetric
from pyrosetta.rosetta.core.kinematics import FoldTree
from pyrosetta.rosetta.core.pose import chain_end_res
from pathlib import Path
from symmetryhandler.reference_kinematics import set_jumpdof_str_str
from cubicsym.utilities import get_jumpidentifier
from cubicsym.utilities import get_base_from_pose, add_id_to_pose_w_base
from cubicsym.actors.symdefswapper import SymDefSwapper
from pyrosetta.rosetta.core.pose import append_pose_to_pose
from pyrosetta.rosetta.core.scoring import calpha_superimpose_pose

def set_init_x(pose, config):
    """Sets the initial x for the input pose if an x_transfile is given in the config file"""
    xf = config.syminfo.x_transfile
    if xf is not None:
        init_x = xf[xf["model"] == Path(config.pose_input).name]["x_trans"].values[0]
        set_jumpdof_str_str(pose, f"JUMP{get_jumpidentifier(pose)}fold111", "x", init_x)

def initialize_starting_poses(config):
    """Initialize the starting poses."""
    native = None
    if config.native_input is not None:
        native = Pose()
        pose_from_file(native, config.native_input)
        native.conformation().detect_disulfides()
    # if flexbb we have to merge the receptor and ligand together
    if isinstance(config.pose_input, list):
        receptor = pose_from_file(config.pose_input[0])
        ligand = pose_from_file(config.pose_input[1])
        if config.template is not None:
            input_pose = align_two_chains_to_pose(pose_from_file(config.template), receptor, ligand)
        else:
            append_pose_to_pose(receptor, ligand, True)
            input_pose = receptor.clone()
    else:
        input_pose = Pose()
        pose_from_file(input_pose, config.pose_input)
    input_pose.conformation().detect_disulfides()
    native_symmetric = None
    if config.syminfo:
        # native suff
        SetupForSymmetryMover(config.syminfo.input_symdef).apply(input_pose)
        # symmetrize the native so that it is the same base
        if config.syminfo.native_symmetric_input is not None:
            native_symmetric = pose_from_file(config.syminfo.native_symmetric_input)
            native_symmetric.conformation().detect_disulfides()
            SetupForSymmetryMover(config.syminfo.native_symdef).apply(native_symmetric)
            base = get_base_from_pose(input_pose)
            if base != "HF":
                sds = SymDefSwapper(native_symmetric, config.syminfo.native_symdef)
                if base == "3F":
                    native_symmetric = sds.create_3fold_pose(native_symmetric)
                elif base == "2F":
                    native_symmetric = sds.create_2fold_pose(native_symmetric)
                else:
                    raise ValueError
        set_init_x(input_pose, config)
        config.syminfo.store_info_from_pose(input_pose) # setup cubic boundaries
    else:
        mres = chain_end_res(input_pose, 1)
        ft = FoldTree()
        ft.add_edge(1, mres, -1)
        ft.add_edge(1, mres + 1, 1)
        ft.add_edge(mres + 1, input_pose.total_residue(), -1)
        input_pose.fold_tree(ft)
    if config.pmm:
        input_pose.pdb_info().name("input_pose")
        if config.native_input is not None:
            native.pdb_info().name("native_pose")
        config.pmm.apply(input_pose)
        config.pmm.apply(native)
    return input_pose, native, native_symmetric

def get_pose_from_file(pose_input):
    pose = Pose()
    pose_from_file(pose, pose_input)
    pose.conformation().detect_disulfides()
    return pose

# compute an axis-aligned bounding box for the given pdb structure
def xyz_limits_for_pdb(pdb):
    first = True
    count = 0
    for chain in pdb.chains:
        for res in chain.residues:
            for atom in res.atoms:
                count += 1
                if first:
                    # print "first", count
                    first = False
                    lower_xyz = np.array(atom.xyz).tolist()
                    upper_xyz = np.array(atom.xyz).tolist()
                else:
                    lower_xyz = np.minimum(lower_xyz, np.array(atom.xyz).tolist())
                    upper_xyz = np.maximum(upper_xyz, np.array(atom.xyz).tolist())
    # print "xyz from", count, "atoms"
    return lower_xyz, upper_xyz

def get_translation_max(pose):
    # we just do this on the pose instead
    for resi in range(1, pose.size() + 1):
        if resi == 1:
            for atom in pose.residue(resi).atoms():
                val = np.array(atom.xyz()).tolist()
                lower_xyz = val
                upper_xyz = val
        else:
            for atom in pose.residue(resi).atoms():
                val = np.array(atom.xyz()).tolist()
                lower_xyz = np.minimum(lower_xyz, val)
                upper_xyz = np.maximum(upper_xyz, val)
    # pdb = pdbstructure_from_file(input_pdb)
    max_translation = max(np.maximum(abs(lower_xyz), abs(upper_xyz)))
    return max_translation + 10

def convert_range(OldValue, old_range, new_range):
    OldMin = old_range[0]
    OldMax = old_range[1]
    NewMin = new_range[0]
    NewMax = new_range[1]
    NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
    return NewValue

def convert_translation(OldValue, trans_max_magnitude):
    OldMin = -1
    OldMax = 1
    NewMin = -1 * trans_max_magnitude
    NewMax = trans_max_magnitude
    NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
    return NewValue

def convert_gamma(OldValue):
    return ((OldValue - (-1)) * (180)) / (1 - (-1))

def random_individual(max_value=180):
    ind = []
    for i in range(6):
        if i < 1:
            # ind.append(0)
            ind.append(np.random.random_sample() * max_value)
        else:
            # ind.append(0)
            ind.append(np.random.random_sample() * 1)
    return ind

def get_rotation_euler(flexible_jump):
    rot_matrix = R.from_matrix(np.asarray(flexible_jump.get_rotation()))
    vec = rot_matrix.as_euler("xyz", degrees=True)
    return vec

def get_translation(flexible_jump):
    return np.asarray(flexible_jump.rt().get_translation())

def get_position_info(dock_pose, syminfo=None):
    if is_symmetric(dock_pose):
        assert syminfo is not None, "syminfo should be defined if pose is symmetric!"
        # map the symmetrical info in the right order as specified in syminfo
        return syminfo.get_position_info(dock_pose)
    else:
        flexible_jump = dock_pose.jump(1)
        euler_vec = get_rotation_euler(flexible_jump)
        return list(euler_vec) + list(flexible_jump.get_translation())

def set_new_max_translations(scfxn, popul):
    # 1) get all positions
    # 2) set new max_translations
    # 3) convert genotypes to new translation
    all_x = []
    all_y = []
    all_z = []
    all_positions = []
    for ind in popul:
        pose = scfxn.apply_genotype_to_pose(ind.genotype)
        positions = get_position_info(pose)
        all_x.append(positions[3])
        all_y.append(positions[4])
        all_z.append(positions[5])
        all_positions.append(positions)

    max_x = max([val for val in all_x])
    max_x += max_x * 0.1
    max_y = max([val for val in all_y])
    max_y += max_y * 0.1
    max_z = max([val for val in all_z])
    max_z += max_z * 0.1

    min_x = min([val for val in all_x])
    min_x += min_x * 0.1
    min_y = min([val for val in all_y])
    min_y += min_y * 0.1
    min_z = min([val for val in all_z])
    min_z += min_z * 0.1

    # print("prev max_trans ")
    # print(scfxn.converter.max_trans)
    scfxn.converter.max_trans = [max_x, max_y, max_z]
    scfxn.converter.min_trans = [min_x, min_y, min_z]
    scfxn.converter.bounds = scfxn.converter.define_bounds()
    # print("updated max_trans ")
    # print(scfxn.converter.max_trans)
    # print(scfxn.converter.min_trans)

    for i, ind in enumerate(popul):
        # print("=== before ===")
        # print(all_positions[i])
        ind.genotype = scfxn.convert_positions_to_genotype(all_positions[i])
        # print("==== after ===")
        # print(scfxn.convert_genotype(ind.genotype))

    return popul

def make_trial(idx, genotype, ligand=1, receptor=1, subunit=1, receptor_name="", ligand_name="", subunit_name="", flipped=None, fixed=None):
    return Individual(idx, genotype, score=1000, idx_ligand=ligand, idx_receptor=receptor, idx_subunit=subunit, rmsd=0, i_sc=0, irms=0,
        receptor_name=receptor_name, ligand_name=ligand_name, subunit_name=subunit_name, flipped=flipped, fixed=fixed)

def align_two_chains_to_pose(reference_pose, pose_chainA, pose_chainB):
    """Aligs pose_chainA and pose_chainB onto the chain A and B of the reference_pose respectively."""
    pose_receptor = Pose(reference_pose, 1, chain_end_res(reference_pose, 1))
    pose_ligand = Pose(
        reference_pose,
        chain_end_res(reference_pose, 1) + 1,
        reference_pose.total_residue(),
    )
    calpha_superimpose_pose(pose_chainA, pose_receptor)
    calpha_superimpose_pose(pose_chainB, pose_ligand)
    join_pose = Pose()
    join_pose.assign(pose_chainA)
    append_pose_to_pose(join_pose, pose_chainB, True)
    return join_pose


# Structure
class DisjointSetUnion:
    def __init__(self, n) -> None:
        self.__lenght = n + 1
        self.__parent = [0] * self.__lenght
        self.__size = [1] * self.__lenght
        self.__set_mins = [float('inf')] * self.__lenght

    def make_set(self, value: int) -> None:
        self.__parent[value] = value

    def find_set(self, value: int) -> int:
        if value == self.__parent[value]:
            return value

        self.__parent[value] = self.find_set(self.__parent[value])
        return self.__parent[value]

    def __update_set_mins(self, root: int, w: int) -> None:
        for i in range(self.__lenght):
            if self.__parent[i] == root:
                self.__set_mins[i] = w

    def union_sets(self, set_x: int, set_y: int, w: int) -> None:
        x = self.find_set(set_x)
        y = self.find_set(set_y)

        if x == y:
            if self.__set_mins[x] < w:
                self.__update_set_mins(x, w)
            return

        set_x, set_y = x, y

        if self.__size[set_x] < self.__size[set_y]:
            set_x, set_y = set_y, set_x

        self.__parent[set_y] = set_x

        if self.__set_mins[set_x] > w:
            self.__update_set_mins(set_x, w)

        self.__size[set_x] += self.__size[set_y]

    def __str__(self) -> str:
        return f'{self.__parent}'

    def get_set_mins(self):
        return self.__set_mins

n, m = map(int, input().split())
# dsu = DisjointSetUnion(n)

# for i in range(1, n + 1):
#     dsu.make_set(i)

visited = set()
ribes = {}

for _ in range(m):
    v, u, w = map(int, input().split())
    # dsu.union_sets(v, u, w)
    if v > u:
        v, u = u, v
    key = f'{v}-{u}'

    if v not in visited or u not in visited:
        visited.add(v)
        visited.add(u)
        ribes[key] = w

# print(dsu.get_set_mins())


from tkinter import *
from tkinter import filedialog

root = Tk()
def call():
    name = filedialog.askopenfilename()

    print(name)
    text = Text(width=20,height=1,wrap=WORD)
    text.pack()
    text.insert(0.0,name)
    label =Label(text =name )
    label.pack()
button =Button(text='btn',command = call)

button.pack()

root.mainloop()


import logging
import os
from pathlib import Path

import hydra
import nest_asyncio
from hydra.utils import instantiate
from omegaconf import DictConfig

from nuplan.common.actor_state.vehicle_parameters import VehicleParameters
from nuplan.planning.nuboard.nuboard import NuBoard
from nuplan.planning.script.builders.scenario_building_builder import build_scenario_builder
from nuplan.planning.script.builders.utils.utils_config import update_config_for_nuboard
from nuplan.planning.script.utils import set_default_path

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# If set, use the env. variable to overwrite the default dataset and experiment paths
set_default_path()

# If set, use the env. variable to overwrite the Hydra config
CONFIG_PATH = os.getenv('NUPLAN_HYDRA_CONFIG_PATH', 'config/nuboard')

if os.environ.get('NUPLAN_HYDRA_CONFIG_PATH') is not None:
    CONFIG_PATH = os.path.join('../../../../', CONFIG_PATH)

if os.path.basename(CONFIG_PATH) != 'nuboard':
    CONFIG_PATH = os.path.join(CONFIG_PATH, 'nuboard')
CONFIG_NAME = 'default_nuboard'

nest_asyncio.apply()

def initialize_nuboard(cfg: DictConfig) -> NuBoard:
    """
    Sets up dependencies and instantiates a NuBoard object.
    :param cfg: DictConfig. Configuration that is used to run the experiment.
    :return: NuBoard object.
    """
    # Update and override configs for nuboard
    update_config_for_nuboard(cfg=cfg)

    scenario_builder = build_scenario_builder(cfg)

    # Build vehicle parameters
    vehicle_parameters: VehicleParameters = instantiate(cfg.scenario_builder.vehicle_parameters)
    profiler_path = None
    if cfg.profiler_path:
        profiler_path = Path(cfg.profiler_path)

    nuboard = NuBoard(
        profiler_path=profiler_path,
        nuboard_paths=cfg.simulation_path,
        scenario_builder=scenario_builder,
        port_number=cfg.port_number,
        resource_prefix=cfg.resource_prefix,
        vehicle_parameters=vehicle_parameters,
        async_scenario_rendering=cfg.async_scenario_rendering,
        scenario_rendering_frame_rate_cap_hz=cfg.scenario_rendering_frame_rate_cap_hz,
    )

    return nuboard

@hydra.main(config_path=CONFIG_PATH, config_name=CONFIG_NAME)
def main(cfg: DictConfig) -> None:
    """
    Execute all available challenges simultaneously on the same scenario.
    :param cfg: DictConfig. Configuration that is used to run the experiment.
    """
    nuboard = initialize_nuboard(cfg)
    nuboard.run()

if __name__ == '__main__':
    main()


from utils import *
import time
import sys

FILEPATH = sys.argv[1]
M = sys.argv[2]
m = int(M)
MARKER1 = ""
if (len(sys.argv) >= 4):
    MARKER1 = sys.argv[3]

x, y, data = createMuniField(FILEPATH)

#start = time.time()
isValid, greedyOut, conscripList = getInitConscriptions(x, y, data, m)
#end = time.time()
if MARKER1 == 'p':
	printDists(x, y, greedyOut)
else:
	print(score(greedyOut))
#print("Time ", end - start)


import logging
from datetime import datetime
# now = datetime.now()
# dt_string = now.strftime("%d_%m_%Y_%H_%M_%S")
# logging.basicConfig(filename=f'{dt_string}.log', level=logging.INFO)
# logging.info('something happened')
import openml

import json
import random
import re
import os
import openml
import pandas as pd
import shap
import sklearn
from importlib_resources import files
import pickle
from XAgent.Agent import constraints
import sys

# sys.path.append('/homes/bach/XAGENT/XAgent/Agent/')
# from dtreeviz.trees import *
from openml.tasks import TaskType
import numpy as np
# print the JS visualization code to the notebook
# shap.initjs()

import pandas
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
from XAgent.Agent.answer import Answers
from XAgent.Agent import utils
from anchor import anchor_tabular

from XAgent.Agent.constraints import *
# import the desired library
from XAgent.Agent.nlu import NLU

# import sys
# sys.stdout = sys.__stdout__
# sys.stderr = sys.__stderr__
import tensorflow as tf
from tensorflow.keras.layers import Conv2D, Dense, Dropout, Flatten, MaxPooling2D, Input
from tensorflow.keras.models import Model, load_model
from tensorflow.keras.utils import to_categorical
import PIL

from XAgent.Agent.utils import print_log

# from IPython.display import display
MODE_INPUT = 0
MODE_QUESTION = 1
# MODE_DATASET = 1

# datetime object containing current date and time

PATH = os.path.dirname(__file__)

conversations = []
class Agent:
    def __init__(self):
        self.dataset = "german-credit"
        self.current_instance = None
        self.clf = None
        self.predicted_class = None
        self.mode = None
        self.data = {"X": None, "y": None, "features": None, "classes": None}
        self.nlu_model = NLU()
        self.list_node = []
        self.clf_display = None
        self.l_exist_classes = None
        self.l_exist_features = None
        self.l_instances = None
        self.df_display_instance = None
        self.current_feature = None
        self.dataset_anchor = None
        self.clf_anchor = None
        self.preprocessor = None

    def preprocess_question(self, question):
        for c in self.data['cls_mapping']:
            for v in self.data['cls_mapping'][c]:
                question = question.replace(str(v),str(c))
        l_features = self.data['features']
        l_classes = self.data['classes']
        # extract instance from question
        l_instances = [[], []]
        self.l_instances = l_instances
        if len(l_features) > 0:
            query = ""
            for f in l_features:
                query += ", "
                query += f
                query += " [a-z]*\d+.\d*"
            query = query[2:]
            regex_search_term = re.compile(query)
            question = re.sub(regex_search_term, "<instance>", question)
            self.l_exist_features = []
            for f in l_features:
                regex_search_term = re.compile(f)
                result = regex_search_term.findall(question)
                if len(result) == 1:
                    self.l_exist_features.append(f)
                regex_replacement = "<feature>"
                question = re.sub(regex_search_term, regex_replacement, question)
        self.l_exist_classes = []

        for c in l_classes:
            c = str(c)
            regex_search_term = re.compile(c)
            result = regex_search_term.findall(question)
            if len(result) == 1:
                self.l_exist_classes.append(c)
            regex_replacement = "<class>"
            question = re.sub(c, regex_replacement, question)
        return question
    def request_instance(self):
        if self.mode == MODE_INPUT:
            if self.dataset == "mnist":
                msg = "Give me the image's name, in the folder, I already have an example with 7.png"
                print_log("xagent", msg)
                user_input = print_log("user")
                image = PIL.Image.open(user_input)
                # display(image)
                image_array = np.array(image)
                msg = "This is your input image."
                print_log("xagent", msg)
                plt.figure(figsize=(2, 2))
                plt.imshow(image_array[:,:,0])
                plt.show()
                self.current_instance = image_array[:,:,0].astype('float32') / 255
                self.predicted_class = self.clf.predict(self.current_instance .reshape(1, 28, 28, 1)).argmax()
                self.mode = MODE_QUESTION
                yield "My prediction for this image is number " + str(self.predicted_class) + "."
            for f, fn in zip(self.data["features"], self.data["feature_names"]):
                self.current_feature = f
                # feature_description = self.data['info']['feature_description'][fn] if fn in  self.data['info']['feature_description'] else ""
                msg = random.choice(l_questions) + str(fn)
                if fn in  self.data['info']['feature_description']:
                    msg += f"({self.data['info']['feature_description'][fn]})"
                if f in self.data['map'].keys():
                    if self.dataset == "german-credit" and f == "Job":
                        yield (msg + "? Please choose one of the following numbers:" + " [0 - unskilled and non-resident, 1 - unskilled and resident, 2 - skilled, 3 - highly skilled]")
                    else:
                        features = ",".join(str(x) for x in self.data['map'][f].values())
                        yield (msg + f"? Please choose one of the following values: [{features}]")
                else:
                    yield (msg + "? Please give me a number")
                    # self.current_instance[f] = float(text)
            self.mode = MODE_QUESTION
            self.current_feature = None
            string_convert = [str(v) for v in self.current_instance.values()]
            instance = ",".join(string_convert)
            display_instance = {}
            for k, v in self.current_instance.items():
                display_instance[k] = [v]
            self.df_display_instance = pandas.DataFrame(display_instance)
            predict = self.clf_display.predict(self.df_display_instance)[0]
            self.predicted_class = predict
            ans = self.data['info']['predict_prompt'][predict] + "\n" + question_msg
            yield "I recorded the information: [" + instance + "] " + ans
    def collect_instance(self, text):
        f = self.current_feature

        if f is None:
            return
        if f in self.data['map'].keys():
            features = ",".join(str(x) for x in self.data['map'][f].values())
            # print(self.data['map'][f].values())
            # print(text)
            while(text not in self.data['map'][f].values()):
                msg = constraints.repeat_cat_features.format(features)
                print_log("xagent", msg)
                text = print_log("user")
            if text.isnumeric():
                self.current_instance[f] = int(text)
            else:
                self.current_instance[f] = str(text)
        else:
            self.current_instance[f] = float(text)
    def dataset_response(self, text, conversations = []):
        if "dataset" in text:
            self.mode = None
            self.dataset = None
            self.current_instance = None
            ans = constraints.welcome_msg
            # logging.info(ans)
            return ans
        if self.mode is None:
            if text not in ["iris","adult","titanic", "german-credit","yes"]:
                return constraints.dataset_error_msg
            else:
                if text != "yes":
                    self.dataset = text
                self.mode = MODE_INPUT
                self.get_dataset_info(self.dataset)
                ans = constraints.wait_msg
                print_log("xagent", ans)
                self.train_model()
                self.current_instance = {}
                self.request_iterator = self.request_instance()
                ans = f"Welcome to {self.dataset} dataset. {self.data['info']['dataset_description']} Are you ready to input the instance?"
                # logging.info(ans)
                print_log(None, ans)
                # return ans
        else:
            if self.mode == MODE_INPUT:
                self.collect_instance(text)
                answer = next(self.request_iterator, None)
            else:
                question = self.preprocess_question(text)
                question = self.nlu_model.match(question, self.data["features"], self.predicted_class, self.current_instance, self.data["classes"]),
                # todo
                logging.log(26,f"question = {question}")
                answer = self.answer_question(question)
                logging.log(26, f"answer = {answer}")
            # logging.info(answer)
            return answer

    def _is_not_blank(self, s):
        return bool(s and not s.isspace())

    def answer_question(self, question, conversations=[]):

        answer = Answers(self.list_node, self.clf, self.clf_display, self.current_instance, question,
                         self.l_exist_classes, self.l_exist_features, self.l_instances, self.data,
                         self.df_display_instance, self.predicted_class, self.dataset_anchor, self.clf_anchor, self.preprocessor)
        return answer.answer(question, conversations)

    def get_dataset_info(self, dataset_name: str):

        self.intro = ""
        with open(files('dataset_info').joinpath(dataset_name+".json")) as f_in:
            self.data['info'] = json.load(f_in)
        if dataset_name.lower() == "german-credit":
            self.data["X_display"] = self.data["X"]= pd.read_csv('dataset/german-credit/german_credit_data.csv')
            self.data["y_display"]=  self.data["y"]  = self.data["X_display"]['Risk']
            self.data["X_display"].drop(['Risk'], axis=1, inplace=True)
            self.data["classes"] = ["bad", "good"]
            self.data["cls_mapping"] = {}
            self.data["features"] = self.data["X_display"].columns.tolist()
            self.data["feature_names"] = self.data["features"]
            mapping = {}
            for f in self.data["features"]:
                if f not in self.data['info']["num_features"]:
                    mapping[f] = {str(value) : str(value) for value in self.data["X_display"][f].unique()}
            self.data["map"] = mapping
            return
        if dataset_name.lower() == "mnist":
            (self.data["X"], self.data["y"]),_ = tf.keras.datasets.mnist.load_data()
            self.data["classes"] = list(range(0,10))
            self.data["cls_mapping"] = {"prediction?": ["predicted?"]}
            self.data["features"] = []
            return
        if dataset_name.lower() == "adult":
            self.data["X"], self.data["y"] = shap.datasets.adult()
            self.data["X_display"], self.data["y_display"] = shap.datasets.adult(display=True)
            for col in self.data["X_display"].columns:
                if (type(self.data["X_display"][col].dtype) == pd.core.dtypes.dtypes.CategoricalDtype):
                    self.data["X_display"][col] = self.data["X_display"][col].apply(lambda x: x.strip())
            self.data["classes"] = ["False","True"]
            self.data["cls_mapping"] = {"False": ["<=50K", "less than 50K"],
                                        "K ?": ["K\?"],
                                        "True": [">50K"],
                                        "have": ["get"],
                                        "instance":["profile","information"],
                                        "prediction":["predicted"]}
            self.data["features"] = self.data["X"].columns.tolist()
            self.data["feature_names"] = self.data["features"]

        if dataset_name.lower() == "titanic":
            X_display = pd.read_csv('dataset/titanic/clean_train.csv')
            y_display = X_display['Survived']
            X_display.drop(['Survived'], axis=1, inplace=True)
            self.data["X_display"] = X_display
            self.data["y_display"] = y_display
            self.data["X"] = X_display.copy(deep=True)
            self.data["y"] = y_display.copy(deep=True)
            self.data["classes"] = ["False","True"]
            self.data["cls_mapping"] = {"False": ["die", "to die"],
                                        "True": ["survive","to survive"]}
            self.data["features"] = self.data["X_display"].columns.tolist()
            self.data["feature_names"] = ["Class (1st, 2nd, 3rd)","Gender","Age","Fare","Port of Embarkation(C = Cherbourg, Q = Queenstown, S = Southampton)","Title","Deck","Family size"]
            for f in self.data['info']['cat_features']:
                self.data["X_display"][f] = self.data["X_display"][f].astype(
                    pandas.core.dtypes.dtypes.CategoricalDtype(categories=self.data["X_display"][f].unique(),
                                                               ordered=True))
            self.intro = " I will receive the information of a passenger, then predict whether the passenger will survive or not"

        if dataset_name.lower() == "iris":
            iris = sklearn.datasets.load_iris()
            X_display = iris.data
            y_display = iris.target
            features = ['sepal length', 'sepal width', 'petal length', 'petal width']
            self.data["X_display"] = pd.DataFrame(data = X_display, columns=features)
            self.data["y_display"] = pd.Series(y_display)
            self.data["X"] = self.data["X_display"].copy(deep=True)
            self.data["y"] = self.data["y_display"].copy(deep=True)
            self.data["classes"] = list(iris.target_names)
            self.data["cls_mapping"] = {}
            self.data["features"] = features
            self.data["feature_names"] = self.data["features"]
        mapping = {}
        for f in self.data["X_display"].columns:
            if type(self.data["X_display"][f].dtype) == pandas.core.dtypes.dtypes.CategoricalDtype:
                mapping[f] = dict(zip(self.data["X_display"][f].cat.codes, self.data["X_display"][f]))
                self.data["X"][f] = self.data["X_display"][f].cat.codes
        self.data['map'] = mapping

    def get_model(self, dataset_name, name_clf: str = "sklearn.tree._classes.DecisionTreeClassifier",
                  metric: str = "predictive_accuracy"):
        tasks_df = openml.tasks.list_tasks(
            task_type=TaskType.SUPERVISED_CLASSIFICATION, output_format="dataframe"
        )
        task_id = tasks_df[tasks_df.name == dataset_name].iloc[0]['tid']
        self.clf = sklearn.tree.DecisionTreeClassifier(max_depth=100)
        flow_ids = openml.flows.get_flow_id(name=name_clf)
        evals = openml.evaluations.list_evaluations(
            function=metric, tasks=[task_id], output_format="dataframe"
        )
        run_id = evals[evals['flow_id'].isin(flow_ids)]['run_id'].iloc[-1]
        run_downloaded = openml.runs.get_run(run_id)
        task = openml.tasks.get_task(task_id)
        setup_id = run_downloaded.setup_id

        # after this, we can easily reinstantiate the model
        model_duplicate = openml.setups.initialize_model(setup_id)
        # it will automatically have all the hyperparameters set

        # and run the task again
        self.train_model()

    def _get_relative(self, node_i, ancestor, n_nodes):
        for i in range(self.clf.tree_.node_count):
            if (node_i == self.clf.tree_.children_left[i]) or (node_i == self.clf.tree_.children_right[i]):
                ancestor.append(i)
                self._get_relative(i, ancestor, self.clf.tree_.node_count)

    def model(self):
        x_in = Input(shape=(28, 28, 1))
        x = Conv2D(filters=64, kernel_size=2, padding='same', activation='relu')(x_in)
        x = MaxPooling2D(pool_size=2)(x)
        x = Dropout(0.3)(x)

        x = Conv2D(filters=32, kernel_size=2, padding='same', activation='relu')(x)
        x = MaxPooling2D(pool_size=2)(x)
        x = Dropout(0.3)(x)

        x = Flatten()(x)
        x = Dense(256, activation='relu')(x)
        x = Dropout(0.5)(x)
        x_out = Dense(10, activation='softmax')(x)

        cnn = Model(inputs=x_in, outputs=x_out)
        cnn.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

        return cnn
    def train_model(self):
        #         self.clf = sklearn.tree.DecisionTreeClassifier(max_depth=100)
        dataset_folder = 'dataset'
        if self.dataset == "german-credit":
            self.clf = pickle.load(open(os.path.join("models/german-credit",'rf_german_credit.pkl'), "rb"))
            self.clf_display = self.clf
            self.preprocessor = pickle.load(open(os.path.join("models/german-credit",'preprocessor.pkl'), "rb"))
            self.dataset_anchor = utils.load_dataset('german-credit', balance=True, dataset_folder=dataset_folder,
                                                     discretize=False)
            self.clf_anchor = sklearn.ensemble.RandomForestClassifier(n_estimators=50, n_jobs=5)
            self.clf_anchor.fit(self.dataset_anchor.train, self.dataset_anchor.labels_train)
            return
        if self.dataset == "mnist":
            self.data["X"] = self.data["X"].astype('float32') /255
            self.data["X"] = np.reshape(self.data["X"] , self.data["X"] .shape + (1,))
            self.data['y'] = to_categorical(self.data['y'])
            self.clf = self.model()
            self.clf = load_model(os.path.join(PATH,'mnist_cnn.h5'))
            return
        if self.dataset == "adult":
            self.dataset_anchor = utils.load_dataset('adult', balance=True, dataset_folder=dataset_folder, discretize=False)

            self.clf_anchor = sklearn.ensemble.RandomForestClassifier()
            self.clf_anchor.fit(self.dataset_anchor.train, self.dataset_anchor.labels_train)
        numerical = self.data['info']['num_features']
        categorical = self.data["X_display"].columns.difference(numerical)

        categorical_transformer = Pipeline(steps=[
            ('onehot', OneHotEncoder(handle_unknown='ignore'))])

        transformations = ColumnTransformer(
            transformers=[
                ('cat', categorical_transformer, categorical)])

        # Append classifier to preprocessing pipeline.
        # Now we have a full prediction pipeline.
        self.clf_display = Pipeline(steps=[('preprocessor', transformations),
                                           ('classifier', RandomForestClassifier())])
        self.clf = RandomForestClassifier()
        #         self.clf_display = RandomForestClassifier()
        self.clf.fit(self.data["X"], self.data["y"])
        if len(categorical) > 0:
            self.clf_display.fit(self.data["X_display"], self.data["y_display"])
        else:
            self.clf_display = self.clf


#! /usr/bin/env python3

import numpy as np

def compute(parties):
    evacuation = []
    while True:
        step = ''
        i = np.argmax(parties)
        if parties[i] == 0:
            return evacuation
        parties[i] -= 1
        step += chr(i + ord('A'))
        j = np.argmax(parties)
        parties[j] -= 1
        if len(list(p for p in parties if p != 0)) == 1:
            parties[j] += 1
        else:
            step += chr(j + ord('A'))
        evacuation.append(step)

T=int(input())
for case in range(1, T+1):
    N = int(input())
    parties = [int(p) for p in input().split()]
    assert N==len(parties)
    evacuation = compute(parties)
    print('Case #%d: %s' % (case, ' '.join(evacuation)))


"""For simulating and learning functional MeDIL Causal Models"""
import torch
import torch.nn as nn
import torch.distributions as dist
from pytorch_lightning import LightningModule
from torch.utils.data import DataLoader
import numpy as np
from collections import OrderedDict

def gaussian_mixture_sampler(
    num_latent, num_mixtures=4, weights=None, means=None, cov=None
):
    """

    :param num_latent:
    :param num_mixtures:
    :param weights:
    :param means:
    :param cov:
    :return:
    """

    if weights is None:
        weights = torch.randn(num_latent, num_mixtures).softmax(dim=1)

    if means is None:
        means = torch.randn(num_latent, num_mixtures, 1) * 2

    if cov is None:
        cov = torch.randn(num_latent, num_mixtures, 1)

    mix = dist.Categorical(weights)
    comp = dist.Independent(dist.Normal(means, cov), 1)

    gmm = dist.MixtureSameFamily(mix, comp)

    return lambda n: gmm.sample((n,)).squeeze()

def uniform_sampler(num_latent, low=-1, high=1):
    """

    :param num_latent:
    :param min:
    :param max:
    :return:
    """

    return lambda n: torch.empty((n, num_latent)).uniform_(low, high)

class NNMechanism(nn.Module):
    def __init__(
        self,
        num_causes,
        num_hidden_layers=1,
        num_hidden_units=20,
        non_linearity="tanh",
        output=None,
        noise_function=None,
        noise_coeff=1.0,
    ):
        """

        :param num_causes:
        :param num_hidden_layers:
        :param num_hidden_units:
        :param activation:
        :param output:
        :param noise_function:
        :param noise_apply:
        """

        super().__init__()
        self.num_causes = num_causes

        # Init Layer list.
        layers = []

        # Input Layer
        layers.append(nn.Linear(self.num_causes + 1, num_hidden_units))

        # Select Activation function
        activation = nn.Identity

        if non_linearity is "tanh":
            activation = nn.Tanh
        elif non_linearity is "relu":
            activation = nn.ReLU
        elif non_linearity is "sigmoid":
            activation = nn.Sigmoid
        elif non_linearity is "gelu":
            activation = nn.GELU

        # Initialise Layers
        for idx in range(num_hidden_layers):
            layers.append(activation())
            layers.append(nn.Linear(num_hidden_units, num_hidden_units))

        # Output Layer
        final = nn.Identity
        if output is "tanh":
            final = nn.Tanh
        elif output is "sigmoid":
            final = nn.Sigmoid

        layers.append(activation())
        layers.append(nn.Linear(num_hidden_units, 1))
        layers.append(final())

        # Assign Layers to Causal Function
        self.causal_function = nn.Sequential(*layers)

        # Horrible shameful hack
        # final_layer_var = 5.0
        # nn.init.uniform_(layers[-2].weight, -final_layer_var, final_layer_var)
        # nn.init.uniform_(layers[-2].bias, -final_layer_var, final_layer_var)
        # print('final', layers[-2].weight, 'pre-final',layers[-4].weight)

        # Exogenous Noise function
        self.noise_function = lambda n: dist.Normal(0, 0.1).sample((n, 1))

        if noise_function is not None:
            self.noise_function = noise_function

        # Exogenous Noise Coefficient
        self.noise_coeff = noise_coeff

    def forward(self, x):
        """

        :param x:
        :return:
        """
        # Sample Exogenous noise corresponding to variable.
        noise = self.noise_coeff * self.noise_function(x.shape[0])

        # Concatenate with input
        causes = torch.cat((noise, x), axis=1)

        # Compute Output
        output = self.causal_function(causes)

        return output

class MeDILCausalModel(nn.Module):
    def __init__(
        self,
        biadj_mat,
        num_hidden_layers=1,
        num_hidden_units=20,
        non_linearity="tanh",
        output="none",
        noise_function=None,
        noise_coeff=1.0,
        debug=False,
    ):

        super().__init__()

        self.biadj_mat = biadj_mat
        self.debug = debug

        self.hparams = {
            "num_hidden_layers": num_hidden_layers,
            "num_hidden_units": num_hidden_units,
            "non_linearity": non_linearity,
            "output": output,
            "noise_coeff": noise_coeff,
        }

        self.num_latent = biadj_mat.shape[0]
        self.num_obs = biadj_mat.shape[1]

        self.subset_mask = [
            np.argwhere(self.biadj_mat[:, idx]).squeeze(axis=-1)
            for idx in range(self.num_obs)
        ]

        print(
            "Generator initialised. #latent: {}, #observed: {}".format(
                self.num_latent, self.num_obs
            )
        )

        forward_dict = {}

        for idx in range(self.num_obs):

            num_latent_causes = np.sum(self.biadj_mat[:, idx].astype(int))

            mechanism = NNMechanism(
                num_latent_causes,
                num_hidden_layers,
                num_hidden_units,
                non_linearity,
                output,
                noise_function,
                noise_coeff,
            )

            forward_dict[str(idx)] = mechanism

        if self.debug:
            print("blah")
        self.observed = nn.ModuleDict(forward_dict)

        if self.debug:
            print("blah")

    def forward(self, x):

        output = []

        if self.debug:
            print("input", x.shape)
        for idx in range(self.num_obs):

            if self.debug:
                print("obs" + str(idx))
            input_subset_mask = np.argwhere(self.biadj_mat[:, idx])

            if self.debug:
                print(input_subset_mask.squeeze())
                print("pre", self.subset_mask[idx])
            input_subset = x[:, self.subset_mask[idx]]

            if self.debug:
                print("input_subset", input_subset.shape)
                print(list(self.observed[str(idx)].modules()))
            obs = self.observed[str(idx)](input_subset)

            if self.debug:
                print("obs", obs.shape)
            output.append(obs)

        output = torch.cat(output, axis=1)

        return output

    def sample(self, sampler, num_samples=100):
        """

        :param sampler:
        :param num_samples:
        :return:
        """

        input_sample = sampler(num_samples)

        self.eval()
        with torch.no_grad():
            output_sample = self.forward(input_sample)

        return input_sample, output_sample

    def set_noise_coeff(self, value):
        """

        :param value:
        :return:
        """

        for module in self.observed:
            # print('before',self.observed[module].noise_coeff)
            self.observed[module].noise_coeff = value
            # print('after',self.observed[module].noise_coeff)

    def interpolate(self, num_samples=100):
        """

        :param num_samples:
        :return:
        """

        self.eval()
        self.set_noise_coeff(0.0)

        output_sample_list = list()

        for latent_idx in range(self.num_latent):

            latent_sample = torch.zeros((num_samples, self.num_latent))
            latent_sample[:, latent_idx] = torch.arange(-10.0, 10.0, 20.0 / num_samples)

            output_sample = self.forward(latent_sample)

            output_sample_list.append(output_sample)

        self.set_noise_coeff(1.0)

        return output_sample_list

class GAN(LightningModule):
    def __init__(self, data_filepath, decoder, latent_sampler=None, batch_size=256):
        """

        :param data_filepath:
        :param decoder:
        :param latent_sampler:
        :param batch_size:
        """

        super().__init__()

        self.hparams = decoder.hparams
        self.hparams["batch_size"] = batch_size
        print(self.hparams)

        self.data_filepath = data_filepath
        self.decoder = decoder
        self.latent_sampler = latent_sampler
        self.batch_size = batch_size

        self.num_latent = self.decoder.num_latent
        self.num_obs = self.decoder.num_obs

    def forward(self, z):

        return self.decoder(z)

    def mmd_loss(self, x_hat_batch, x_batch, alpha=1):

        return MMDLoss(x_batch.shape[0])(x_hat_batch, x_batch)

    def train_dataloader(self):

        dataset = np.load(self.data_filepath).astype(np.float32)

        return DataLoader(dataset, batch_size=self.batch_size, shuffle=True)

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters())

    # Train Functions
    def training_step(self, batch, batch_idx):

        sample = batch

        z = self.latent_sampler(batch.shape[0])

        x_hat = self.forward(z)

        loss = self.mmd_loss(x_hat, batch)

        tqdm_dict = {"loss": loss}
        output = OrderedDict(
            {
                "loss": loss,
                # 'progress_bar': tqdm_dict,
                "log": tqdm_dict,
            }
        )

        self.logger.log_metrics({"mmd_loss": loss.item()}, batch_idx)

        return output

class MMDLoss(nn.Module):
    def __init__(self, input_size, bandwidths=None):
        """Init the model."""
        super(MMDLoss, self).__init__()
        if bandwidths is None:
            bandwidths = torch.Tensor([0.01, 0.1, 1, 10, 100])
        else:
            bandwidths = bandwidths
        s = torch.cat(
            [
                torch.ones([input_size, 1]) / input_size,
                torch.ones([input_size, 1]) / -input_size,
            ],
            0,
        )

        self.register_buffer("bandwidths", bandwidths.unsqueeze(0).unsqueeze(0))
        self.register_buffer("S", (s @ s.t()))

    def forward(self, x, y):

        X = torch.cat([x, y], 0)

        XX = X @ X.t()
        X2 = (X * X).sum(dim=1).unsqueeze(0)

        exponent = -2 * XX + X2.expand_as(XX) + X2.t().expand_as(XX)

        b = (
            exponent.unsqueeze(2).expand(-1, -1, self.bandwidths.shape[2])
            * -self.bandwidths
        )
        lossMMD = torch.sum(self.S.unsqueeze(2) * b.exp()).sqrt()

        return lossMMD


#!/usr/bin/env python

import sys, os, glob, re, math

import argparse
parser = argparse.ArgumentParser(description='calculate histogram distances between a file with observed PValues and a group of files each containing the same number of P values')
parser.add_argument("--in", dest="infile", help="fisher file with P values", required=True)
parser.add_argument("--out", dest="outfile", help="output file",default="")
parser.add_argument("--comp", dest="comps", help="comparisons to retrieve (eg: \"1:4,2:5,3:6\")",required=True)
args = parser.parse_args()
comps = vars(args)['comps'].split(",")
infile = vars(args)['infile']
outfile = vars(args)['outfile']
if (outfile == ""):
    outfile = re.sub(r'\.\w+$','',infile)+".fishcomp"
inf = open(infile,"r")
f_pos={}
out = open(outfile,"w")
for line in inf:
    line.rstrip()
    fields=line.split()
    if (len(f_pos) == 0):
        for i in range(0,len(fields)):
            for j in comps:
                if (re.match(j+"=",fields[i])):
                    f_pos[j]=i
        diff_xor = set(f_pos) ^ set(comps)
        if (len(diff_xor) > 0):
            sys.exit("Field"+str(diff_xor)+" not found")
        print >>out,"\#"+"\t".join(comps)
        pos=[ f_pos[x] for x in comps]
    out_array=[ fields[x].split("=")[1] for x in pos]
    for i in range(0,len(out_array)):
        if (out_array[i] != "na"):
            out_array[i] = str(10**(-1*float( out_array[i])))
    print >>out,"\t".join(out_array)
inf.close()
out.close()


# User function Template for python3

class Solution:
    def findEmptyLocation(self, grid, l):
        for row in range(9):
            for col in range(9):
                if grid[row][col] == 0:
                    l[0] = row
                    l[1] = col
                    return True
        return False

    def usedInRow(self, grid, row, num):
        for x in range(9):
            if grid[row][x] == num:
                return True
        return False

    def usedInCol(self, grid, col, num):
        for x in range(9):
            if grid[x][col] == num:
                return True
        return False

    def usedInBox(self, grid, row, col, num):
        for i in range(3):
            for j in range(3):
                if grid[i+row][j+col] == num:
                    return True
        return False

    def isLocationSafe(self, grid, row, col, num):
        return not self.usedInRow(grid, row, num) and not self.usedInCol(grid, col, num) and not self.usedInBox(grid, row - row % 3, col-col % 3, num)
    # Function to find a solved Sudoku.

    def SolveSudoku(self, grid):
        l = [0, 0]
        if not self.findEmptyLocation(grid, l):
            return True
        row = l[0]
        col = l[1]

        for num in range(1, 10):
            if self.isLocationSafe(grid, row, col, num):
                grid[row][col] = num
                if self.SolveSudoku(grid):
                    return True
                grid[row][col] = 0
        return False
    # Function to print grids of the Sudoku.

    def printGrid(self, arr):
        for i in range(9):
            for j in range(9):
                print(arr[i][j], sep=' ', end=' ')


from torch import conv_transpose1d
from util.homo_transform import warpPerspectivePts
from stag_decode.fine_grid_matcher import FineGridMatcher
from stag_decode.keypoints import *
import cv2
import time

class StagDecoder:
    def __init__(self, predictor, unit_tag_template, marker_dict, cameraMatrix= None, distCoeffs = None, sigma_keypoints = 5, min_grid_match_ratio = 0.8, batch_size = 8, border_ratio = 0.15, image_rect_size = (256,256), iter_num = 1):

        self.predictor = predictor
        self.features = None
        self.sigma_keypoints = sigma_keypoints
        self.cameraMatrix = cameraMatrix
        self.distCoeffs =distCoeffs
        self.unit_tag_template = unit_tag_template
        self.min_grid_match_ratio = min_grid_match_ratio
        self.batch_size = batch_size
        self.image_rect_size = image_rect_size
        self.roi_in_crop = get_crop_ordered_corners(image_rect_size[0], image_rect_size[1], border_ratio)
        self.iter_num = iter_num
        self.marker_dict = marker_dict

    def detect_tags(self, image, rois):

        batch_size = self.batch_size
        iter_num = self.iter_num
        self.cnn_timing_list = []
        self.prediction_timing_list = []
        self.postprocess_timing_list = []

        rois_curr = rois
        valid_ids = None

        # iteration by updating ROIs
        decoded_tags = [{'is_valid': False} for _ in range(len(rois))]
        t0 = time.time()
        for iter_i in range(iter_num):

            print('>iter #%d'% iter_i)
            crops, H_list, valid_ids = rectify_crops(image, rois_curr, self.roi_in_crop, self.image_rect_size)

            # # visualize crops
            # for ii, crop in enumerate(crops):
            #     cv2.imshow('crop_%d_%d'%(iter_i, ii), crop)
            # cv2.waitKey(0)

            # CNN prediction
            features_pred_list = []
            batch_id = 0
            while batch_id * batch_size < len(crops):
                t1 = time.time()
                features_pred_list += self.predictor.predict(crops[batch_id *batch_size:(batch_id+1)*batch_size])
                self.cnn_timing_list.append(self.predictor.cnn_timing)
                self.prediction_timing_list.append(time.time()-t1)
                batch_id +=1

            # decode from CNN outputs
            for features_pred, H, roi_idx in zip(features_pred_list, H_list, valid_ids):
                # print('--ROI #%d--'% (roi_idx))
                t2 = time.time()
                decoded_tag, roi_updated = self.decode_one_tag(features_pred, H)
                decoded_tag['image_size_crop'] =  self.image_rect_size
                rois_curr[roi_idx] = roi_updated # update roi
                decoded_tags[roi_idx] = decoded_tag # update result
                self.postprocess_timing_list.append(time.time()-t2)
                # print('Valid tag.' if decoded_tag['is_valid'] else 'Invalid.')

        self.total_timing = time.time() -t0
        return decoded_tags

    def decode_one_tag(self, features_pred, H):
        cameraMatrix = self.cameraMatrix
        distCoeffs = self.distCoeffs
        unit_tag_template = self.unit_tag_template
        sigma_keypoints = self.sigma_keypoints
        min_grid_match_ratio = self.min_grid_match_ratio
        marker_dict = self.marker_dict

        confidences_pred_np, grid_pred_np = features_pred['grid_pred'][:2]
        corners_pred_np = features_pred['corners_pred'][1]

        ordered_corners = [corners_pred_np.tolist()[idx] for idx in [0,1,3,2]]

        # detect fine_grid_points from cnn outputs
        fine_grid_points_with_ids_candidates, scores_candidates = detect_keypoints_with_hms(confidences_pred_np, grid_pred_np, sigma3_nms = sigma_keypoints)

        # match fine_grid_points with unit_tag_templates
        fine_grid_matcher = FineGridMatcher(ordered_corners, ordered_corners_in_crop_set = [], cameraMatrix=cameraMatrix, distCoeffs=distCoeffs)
        match_ratio, ordered_fine_grid_points_ids = unit_tag_template.match_fine_grid(fine_grid_points_with_ids_candidates, H, [fine_grid_matcher])

        # refine and get ids
        roi_updated = None
        if match_ratio > min_grid_match_ratio:
            # get id if missing
            ordered_fine_grid_points_ids = fill_empty_ids(ordered_fine_grid_points_ids, fine_grid_points_with_ids_candidates)

            # update roi
            roi_updated = unit_tag_template.update_corners_in_image(ordered_fine_grid_points_ids, H, valid_flag_list= None, cameraMatrix = cameraMatrix, distCoeffs = distCoeffs)

            # get main_idx and reorder
            # _, ordered_kpts_with_ids = unit_tag_template.reorder_points_with_main_idx(ordered_fine_grid_points_ids, 0)
            main_idx, decimal_id = marker_dict.get_main_idx([kpt[2] for kpt in ordered_fine_grid_points_ids])
            if decimal_id < 0:
                main_idx, decimal_id = unit_tag_template.get_main_idx([kpt[2] for kpt in ordered_fine_grid_points_ids])
            ordered_fine_grid_points_ids, ordered_kpts_with_ids = unit_tag_template.reorder_points_with_main_idx(ordered_fine_grid_points_ids, main_idx)
            binary_ids = [kpt[2] for kpt in ordered_kpts_with_ids]

            # get score
            tag_score = sum(scores_candidates)/len(scores_candidates)

            # get unit_tag
            unit_tag = unit_tag_template.get_unit_tag(ordered_fine_grid_points_ids)

            # unwarp keypoints
            H_inv = np.linalg.inv(H)
            ordered_fine_grid_points_in_image = warpPerspectivePts(H_inv, [kpt[:2] for kpt in ordered_fine_grid_points_ids])

            # save results
            decoded_tag = {'is_valid': True,
                        'H_crop': H,
                        'tag_id': decimal_id,
                        'binary_ids': binary_ids,
                        'keypoints_with_ids': ordered_fine_grid_points_ids,
                        'keypoints_in_images': ordered_fine_grid_points_in_image,
                        'score': tag_score,
                        'unit_tag': unit_tag,
                        'main_idx': main_idx,
                        'rotation_idx': 0
                        }

        else:

            decoded_tag = {'is_valid': False}
            roi_updated = None

        return decoded_tag, roi_updated

def rectify_crops(image, rois, roi_in_crop, image_rect_size):

    crops = []
    H_list = []
    valid_ids = []
    th, tw = image_rect_size

    for ii, roi in enumerate(rois):
        if roi is not None:
            H, _ = cv2.findHomography(np.float32(roi), np.float32(roi_in_crop))
            image_rect = cv2.warpPerspective(image, H, (tw,th))
            crops.append(image_rect)
            H_list.append(H)
            valid_ids.append(ii)

    return crops, H_list, valid_ids

def get_crop_ordered_corners(h, w, border_ratio):
    # border_ratio is in [0,0.3]
    bw = max(h,w) * border_ratio
    ordered_corners_in_crop = [[bw-0.5, bw-0.5], [w-bw-0.5, bw-0.5], [w-bw-0.5, h-bw-0.5], [bw-0.5, h-bw-0.5] ]
    return ordered_corners_in_crop


from collections import defaultdict
from openerp.addons.account_financial_report_webkit.report.webkit_parser_header_fix \
    import HeaderFooterTextWebKitParser
from openerp.addons.account_financial_report_webkit.report.open_invoices \
    import PartnersOpenInvoicesWebkit
import time

class PartnersOpenInvoicesWebkitExt(PartnersOpenInvoicesWebkit):

    def set_context(self, objects, data, ids, report_type=None):
        self.localcontext.update({
            'only_residual_amount': data['form']['only_residual_amount'],
            'filter_currency_id': data['form']['filter_currency_id'] and data['form']['filter_currency_id'][0] or False,
        })
        return super(PartnersOpenInvoicesWebkitExt, self).set_context(objects, data, ids, report_type=report_type)

    def _get_partners_move_line_ids(self, filter_from, account_id, start, stop,
                                    target_move,
                                    opening_mode='exclude_opening',
                                    exclude_reconcile=False,
                                    partner_filter=None):
        if self.localcontext.get('filter_currency_id', False):
            final_res = defaultdict(list)

            sql_select = "SELECT account_move_line.id, \
                            account_move_line.partner_id FROM account_move_line"
            sql_joins = ''
            sql_where = " WHERE account_move_line.account_id = %(account_ids)s " \
                        " AND account_move_line.state = 'valid' "

            method = getattr(self, '_get_query_params_from_' + filter_from + 's')
            sql_conditions, search_params = method(start, stop)

            sql_where += sql_conditions

            if exclude_reconcile:
                sql_where += ("  AND ((account_move_line.reconcile_id IS NULL)"
                              "   OR (account_move_line.reconcile_id IS NOT NULL \
                                  AND account_move_line.last_rec_date > \
                                                          date(%(date_stop)s)))")

            if partner_filter:
                sql_where += "   AND account_move_line.partner_id \
                                                                in %(partner_ids)s"

            if target_move == 'posted':
                sql_joins += "INNER JOIN account_move \
                                    ON account_move_line.move_id = account_move.id"
                sql_where += " AND account_move.state = %(target_move)s"
                search_params.update({'target_move': target_move})

            sql_where += " AND account_move_line.transaction_curr_id = %(currency_id)s"
            search_params.update({
                'account_ids': account_id,
                'partner_ids': tuple(partner_filter),
                'currency_id': self.localcontext['filter_currency_id'],
            })

            sql = ' '.join((sql_select, sql_joins, sql_where))
            self.cursor.execute(sql, search_params)
            res = self.cursor.dictfetchall()
            if res:
                for row in res:
                    final_res[row['partner_id']].append(row['id'])
            return final_res

        return super(PartnersOpenInvoicesWebkitExt, self)._get_partners_move_line_ids(filter_from, account_id, start, stop,
                    target_move, opening_mode=opening_mode, exclude_reconcile=exclude_reconcile, partner_filter=partner_filter)

    def _partners_initial_balance_line_ids(self, account_ids, start_period,
                                           partner_filter,
                                           exclude_reconcile=False,
                                           force_period_ids=False,
                                           date_stop=None):
        if self.localcontext.get('filter_currency_id', False):
            period_ids = force_period_ids \
                if force_period_ids \
                else self._get_period_range_from_start_period(
                    start_period, fiscalyear=False, include_opening=False)

            if not period_ids:
                period_ids = [-1]
            search_param = {
                'date_start': start_period.date_start,
                'period_ids': tuple(period_ids),
                'account_ids': tuple(account_ids),
                'currency_id': self.localcontext['filter_currency_id'],
            }
            sql = ("SELECT ml.id, ml.account_id, ml.partner_id "
                   "FROM account_move_line ml "
                   "INNER JOIN account_account a "
                   "ON a.id = ml.account_id "
                   "WHERE ml.period_id in %(period_ids)s "
                   "AND ml.account_id in %(account_ids)s "
                   "AND ml.transaction_curr_id = %(currency_id)s ")
            if exclude_reconcile:
                if not date_stop:
                    raise Exception(
                        "Missing \"date_stop\" to compute the open invoices.")
                search_param.update({'date_stop': date_stop})
                sql += ("AND ((ml.reconcile_id IS NULL) "
                        "OR (ml.reconcile_id IS NOT NULL \
                        AND ml.last_rec_date > date(%(date_stop)s))) ")
            if partner_filter:
                sql += "AND ml.partner_id in %(partner_ids)s "
                search_param.update({'partner_ids': tuple(partner_filter)})

            self.cursor.execute(sql, search_param)
            return self.cursor.dictfetchall()

        return super(PartnersOpenInvoicesWebkitExt, self)._partners_initial_balance_line_ids(account_ids, start_period,
                    partner_filter, exclude_reconcile=exclude_reconcile, force_period_ids=force_period_ids, date_stop=date_stop)

    def _compute_open_transactions_lines(self, accounts_ids, main_filter,
                                         target_move, start, stop,
                                         date_until=False,
                                         partner_filter=False):
        res = super(PartnersOpenInvoicesWebkitExt, self)._compute_open_transactions_lines(accounts_ids,
                    main_filter, target_move, start, stop, date_until=date_until, partner_filter=partner_filter)
        if self.localcontext.get('only_residual_amount', False):
            #date_stop = time.strftime('%Y-%m-%d')
            #if main_filter in ('filter_period', 'filter_no'):
            #    date_stop = stop.date_stop
            #elif main_filter == 'filter_date':
            #    date_stop = stop
            invoice_obj = self.pool.get('account.invoice')
            all_line_ids = [ l['id'] for vals in res.values() for lines in vals.values() for l in lines ]
            for account_id, vals in res.items():
                for partner_id, lines in vals.items():
                    del_line_ids = []
                    for line in lines:
                        if line['id'] in del_line_ids:
                            res[account_id][partner_id].remove(line)
                            del_line_ids.remove(line['id'])
                            continue
                        if not line.get('invoice_id', False):
                            continue
                        if line.get('invoice_type') in ('out_invoice', 'in_invoice'):
                            invoice = invoice_obj.browse(self.cursor, self.uid, line['invoice_id'])
                            debit_total = line.get('debit') or 0.0
                            credit_total = line.get('credit') or 0.0
                            for pl in invoice.payment_ids:
                                #if pl.state == 'valid' and pl.account_id.id in accounts_ids and \
                                #   (not pl.reconcile_id or (pl.reconcile_id and pl.last_rec_date > date_stop)):
                                if pl.id in all_line_ids:
                                    debit_total += pl.debit
                                    credit_total += pl.credit
                                    del_line_ids.append(pl.id)
                            if hasattr(invoice, 'refund_ref_ids'): # notas de crédito asociadas
                                for refund in invoice.refund_ref_ids:
                                    for refund_line in refund.move_lines:
                                        #if refund_line.state == 'valid' and refund_line.account_id.id in accounts_ids and \
                                        #   (not refund_line.reconcile_id or (refund_line.reconcile_id and refund_line.last_rec_date > date_stop)):
                                        if refund_line.account_id.id in accounts_ids and refund_line.id in all_line_ids:
                                            debit_total += refund_line.debit
                                            credit_total += refund_line.credit
                                            del_line_ids.append(refund_line.id)
                                    for refund_pline in refund.payment_ids:
                                        if refund_pline.id in all_line_ids:
                                            debit_total += refund_pline.debit
                                            credit_total += refund_pline.credit
                                            del_line_ids.append(refund_pline.id)
                            line['debit'] = (debit_total - credit_total) if (debit_total - credit_total) > 0 else 0.0
                            line['credit'] = (credit_total - debit_total) if (credit_total - debit_total) > 0 else 0.0
                    if del_line_ids:
                        for line in lines:
                            if line['id'] in del_line_ids:
                                res[account_id][partner_id].remove(line)
                                del_line_ids.remove(line['id'])
                                if not del_line_ids:
                                    break
        return res

    def _group_lines_by_currency(self, account_br):
        # Fix a bug when grouping by currency. By irabaza
        if not hasattr(account_br, 'ledger_lines'):
            return
        super(PartnersOpenInvoicesWebkitExt, self)._group_lines_by_currency(account_br)

HeaderFooterTextWebKitParser(
    'report.account.account_report_open_invoices_webkit_ext',
    'account.account',
    'addons/account_financial_report_webkit/report/templates/account_report_open_invoices.mako',
    parser=PartnersOpenInvoicesWebkitExt)


"""Django rest client serializers"""
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from .models import Customer, CustomerFavoriteProduct

class CustomerBaseSerializer(serializers.ModelSerializer):
    """Serializer for user"""

    class Meta:
        model = Customer
        fields = ("id", "name", "email")

class CustomerCreateSerializer(CustomerBaseSerializer):
    """Serializer for create user"""

    email = serializers.EmailField(
        validators=[
            UniqueValidator(
                queryset=Customer.objects.all(),
                message="There is already an account with this email",
            )
        ]
    )

    class Meta:
        model = Customer
        fields = ("id", "name", "email", "password")

class CustomerUpdateSerializer(CustomerBaseSerializer):
    """Serializer for user"""

    email = serializers.ReadOnlyField()

class CustomerFavoriteProductSerializer(serializers.ModelSerializer):
    """Serializer for customer product favorite"""

    created_at = serializers.ReadOnlyField()

    class Meta:
        model = CustomerFavoriteProduct
        fields = ("product", "price", "created_at",)