from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QTreeWidgetItem
# Initialize Qt resources from file resources.py
from .resources import *

# Import the code for the DockWidget
from .plugin_compiler_dockwidget import PluginCompilerDockWidget

# Import necessary module
import glob
import os
import subprocess
import datetime
from qgis.utils import plugins, pluginDirectory
from pyplugin_installer import installer as plugin_installer
from qgis.core import Qgis

class PluginCompiler:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'PluginCompiler_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Plugin Compiler')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'PluginCompiler')
        self.toolbar.setObjectName(u'PluginCompiler')

        # print "** INITIALIZING PluginCompiler"

        self.pluginIsActive = False
        self.dockwidget = None

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('PluginCompiler', message)

    def add_action(
            self,
            icon_path,
            text,
            callback,
            enabled_flag=True,
            add_to_menu=True,
            add_to_toolbar=True,
            status_tip=None,
            whats_this=None,
            parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/plugin_compiler/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Plugin Compiler'),
            callback=self.run,
            parent=self.iface.mainWindow())

    # --------------------------------------------------------------------------

    def onClosePlugin(self):
        """Cleanup necessary items here when plugin dockwidget is closed"""

        # print "** CLOSING PluginCompiler"

        # disconnects
        self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)

        # remove this statement if dockwidget is to remain
        # for reuse if plugin is reopened
        # Commented next statement since it causes QGIS crashe
        # when closing the docked window:
        # self.dockwidget = None

        self.pluginIsActive = False

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""

        # print "** UNLOAD PluginCompiler"

        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&Plugin Compiler'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    # --------------------------------------------------------------------------

    def run(self):
        """Run method that loads and starts the plugin"""

        if not self.pluginIsActive:
            self.pluginIsActive = True

            # print "** STARTING PluginCompiler"

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget is None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = PluginCompilerDockWidget()

            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # show the dockwidget
            # TODO: fix to allow choice of dock location
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget)
            self.dockwidget.show()

            self.cmbPluginList = self.dockwidget.cmbPluginList
            self.twGraphFile = self.dockwidget.twGraphFile
            self.ckbQrc = self.dockwidget.ckbQrc
            self.ckbUi = self.dockwidget.ckbUi
            self.ckbResources = self.dockwidget.ckbResources
            self.ckbPro = self.dockwidget.ckbPro
            self.ckbQm = self.dockwidget.ckbQm
            self.ckbTs = self.dockwidget.ckbTs
            self.ckbFilter = self.dockwidget.ckbFilter
            self.mCmbLanguage = self.dockwidget.mCmbLanguage

            self.lblLang = self.dockwidget.lblLang

            process = self.dockwidget.btnExec
            process.clicked.connect(self.get_selected_leaves)

            self.ckbQrc.stateChanged.connect(self.current_plugin)
            self.ckbUi.stateChanged.connect(self.current_plugin)
            self.ckbResources.stateChanged.connect(self.current_plugin)
            self.ckbPro.stateChanged.connect(self.current_plugin)
            self.ckbQm.stateChanged.connect(self.current_plugin)
            self.ckbTs.stateChanged.connect(self.current_plugin)
            self.ckbFilter.stateChanged.connect(self.current_plugin)

            dict_trad = {"Allemand": "de"
                         , "Anglais": "en"
                         , "Espagnol": "es"
                         , "Français": "fr"
                         , "Italien": "it"
                         }
            for langue, lg in dict_trad.items():
                self.mCmbLanguage.addItemWithCheckState(langue, False, lg)

            plugins_list = sorted(plugins.keys(), key=str.casefold)
            for plugin in plugins_list:
                try:
                    icon = QIcon(plugin_installer.plugins.all()[plugin]['icon'])
                except KeyError:
                    icon = QIcon()
                self.cmbPluginList.addItem(icon, plugin)

            self.cmbPluginList.currentTextChanged.connect(self.current_plugin)
            self.current_plugin()

    def current_plugin(self):
        """
        Prepare the dockwidget for the select plugin
        """
        if self.ckbPro.isChecked():
            self.lblLang.show()
            self.mCmbLanguage.show()
        else:
            self.lblLang.hide()
            self.mCmbLanguage.hide()

        current_plugin = self.cmbPluginList.currentText()
        startpath = pluginDirectory(current_plugin)

        self.twGraphFile.clear()

        check_format = {".qrc": self.ckbQrc.isChecked()
                        , ".ui": self.ckbUi.isChecked()
                        , ".png": self.ckbResources.isChecked()
                        , ".jpg": self.ckbResources.isChecked()
                        , ".pro": self.ckbPro.isChecked()
                        , ".qm": self.ckbQm.isChecked()
                        , ".ts": self.ckbTs.isChecked()
                        }
        sorting = self.ckbFilter.isChecked()
        self.load_project_structure(startpath, self.twGraphFile, check_format, sorting)

    def load_project_structure(self, startpath, tree, check_format, sorting):
        """
        Load Project tree structure in TreeWidget
        Based on solution of Softmixt : https://stackoverflow.com/questions/5144830/how-to-create-folder-view-in-pyqt-inside-main-window

        :param startpath: Path of the plugin
        :type startpath: str

        :param tree: QTreeWidget element where to display the folder and file architecture
        :type tree: QTreeWidget

        :param check_format: Dict of extension user choose to see
        :type check_format: dict
        """

        # List of ignore file or folder to make the tree
        list_ignore = ["__pycache__"]

        # Process all file and folder of startpath
        for element in os.listdir(startpath):

            # Add element to the list_ignore - exemple folder .git or file .gitignore
            if element.startswith("."):
                list_ignore.append(element)
            if element in list_ignore:
                pass

            else:
                # Make the system path
                path_info = startpath + "/" + element

                # Avoid add folder in tree if it already exist
                already_pass = []

                # If current element is detected as folder
                if os.path.isdir(path_info):
                    # If checkbox of file extension is check (shape = True) we display folder if it's extension format
                    if sorting:
                        for extension, shape in check_format.items():
                            if shape:
                                text = glob.glob(path_info + "/**/*{}".format(extension), recursive=True)
                                if len(text) > 0 and path_info not in already_pass:
                                    already_pass.append(path_info)
                                    # Call is_folder function
                                    self.is_folder(tree, [os.path.basename(element)], path_info, check_format, sorting)

                    # If no checkbox are check then we display all folder
                    if not any(check_format.values()) or sorting is False:
                        # Call is_folder function
                        self.is_folder(tree, [os.path.basename(element)], path_info, check_format, sorting)

                else:
                    value = os.path.basename(element)

                    # If checkbox of file extension is check (shape = True) we display file if it's extension format
                    if sorting:
                        for extension, shape in check_format.items():
                            if shape:
                                if value.endswith(extension):
                                    # Call is_file function
                                    self.is_file(tree, [value, path_info], check_format)

                    # If no checkbox are check then we display all file
                    if not any(check_format.values()) or sorting is False:
                        # Call is_file function
                        self.is_file(tree, [value, path_info], check_format)

    def is_folder(self, tree, tree_element, path_info, check_format, sorting):
        """
        Add folder to the tree structure in QTreeWidget

        :param tree: QTreeWidget element where to display the folder and file architecture
        :type tree: QTreeWidget

        :param tree_element: Current element in the os.listdir(startpath)
        :type tree_element: list

        :param path_info: Path of the current element in the os.listdir(startpath)
        :type path_info: str

        :param check_format: Dict of extension user choose to see
        :type check_format: dict
        """

        parent_itm = QTreeWidgetItem(tree, tree_element)
        self.load_project_structure(path_info, parent_itm, check_format, sorting)
        parent_itm.setIcon(0, QIcon(':/plugins/plugin_compiler/icons/mIconFolder.png'))

    def is_file(self, tree, tree_element, check_format):
        """
        Add file to the tree structure in QTreeWidget

        :param tree: QTreeWidget element where to display the folder and file architecture
        :type tree: QTreeWidget

        :param tree_element: Current element in the os.listdir(startpath)
        :type tree_element: list

        :param check_format: Dict of extension user choose to see
        :type check_format: dict
        """
        extension = ".{}".format(tree_element[0].rpartition('.')[-1])
        if extension in check_format.keys() and check_format[extension]:
            parent_itm = QTreeWidgetItem(tree, tree_element)
            parent_itm.setCheckState(0, Qt.Unchecked)
            # parent_itm.setIcon(0, QIcon(':/plugins/plugin_compiler/icons/mIconFile.png'))
        else:
            parent_itm = QTreeWidgetItem(tree, tree_element)
            # parent_itm.setIcon(0, QIcon(':/plugins/plugin_compiler/icons/mIconFile.png'))

    def get_selected_leaves(self):
        """
        Get the list of selected files in the QTreeWidget
        Based on solution of hollebread : https://stackoverflow.com/questions/26963786/pyqt-get-list-of-all-checked-in-qtreewidget
        """

        process_qrc = []
        process_ui = []
        process_resources = []
        process_pro = []
        process_qm = []
        process_ts = []
        langdata = self.mCmbLanguage.checkedItemsData()
        lang = self.mCmbLanguage.checkedItems()

        dict_process = {".qrc": process_qrc
                        , ".ui": process_ui
                        , ".png": process_resources
                        , ".jpg": process_resources
                        , ".pro": process_pro
                        , ".qm": process_qm
                        , ".ts": process_ts
                        }

        def recurse(parent_item):
            for i in range(parent_item.childCount()):
                child = parent_item.child(i)
                grand_children = child.childCount()
                if grand_children > 0:
                    recurse(child)
                else:
                    if child.checkState(0) == Qt.Checked:
                        extension = ".{}".format(child.text(1).rpartition('.')[-1])
                        if extension in dict_process.keys():
                            dict_process[extension].append(child.text(1))

        recurse(self.twGraphFile.invisibleRootItem())

        list_function = [[process_qrc
                         , self.ckbQrc.isChecked()
                         , compile_qrc
                         , "qrc : Vous n'avez pas sélectionné de fichier"]

                         , [process_ui
                             , self.ckbUi.isChecked()
                             , compile_ui
                             , "ui : Vous n'avez pas sélectionné de fichier"]

                         , [process_resources
                             , self.ckbResources.isChecked()
                             , add_resource
                             , "resources : Vous n'avez pas sélectionné de fichier"]

                         # , [process_pro
                         #     , self.ckbPro.isChecked()
                         #     , create_pro
                         #     , "pro : Vous n'avez pas sélectionné de fichier"
                         #     , langdata
                         #     , "pro : Pas de langue choisi"]

                         , [process_ts
                             , self.ckbTs.isChecked()
                             , compile_ts
                             , "ts : Vous n'avez pas sélectionné de fichier"]

                         , [process_qm
                             , self.ckbQm.isChecked()
                             , compile_qm
                             , "qm : Vous n'avez pas sélectionné de fichier"]
                         ]

        process = False

        for val in list_function:
            if val[1]:
                process = True
                if val[0]:
                    print(val[2])
                else:
                    self.iface.messageBar().pushMessage("Warning : ",
                                                        val[3],
                                                        level=Qgis.Warning, duration=5)

        if self.ckbPro.isChecked():
            process = True
            if process_pro:
                if langdata:
                    print("process_pro: ", process_pro, "-", langdata)
                else:
                    self.iface.messageBar().pushMessage("Warning : ",
                                                        "Pas de langue choisi",
                                                        level=Qgis.Warning, duration=5)
            else:
                self.iface.messageBar().pushMessage("Warning : ",
                                                    "Pas de fichier choisi",
                                                    level=Qgis.Warning, duration=5)

        if not process:
            print("Aucune opération")

        self.current_plugin()

def compile_qrc(list_files):
    # Compile .qrc ressources file
    rc_files = glob.glob('*.qrc')
    for rc in rc_files:
        (name, ext) = os.path.splitext(rc)
        print("pyrcc5.bat -o {}.py {}".format(name, rc))
        subprocess.call(["pyrcc5.bat", "-o", "{}.py".format(name), rc])

def add_resource(list_files):
    pass

def compile_ui(list_files):
    # Compile .ui files
    ui_files = glob.glob('*.ui')
    for ui in ui_files:
        (name, ext) = os.path.splitext(ui)
        print("pyuic5.bat -o {}.py {}".format(name, ui))
        subprocess.call(["pyuic5.bat", "-o", "{}.py".format(name), ui])

def create_pro(list_files, language):
    # Creation of .ts files from .pro file
    if not glob.glob('*.pro'):
        # Find the plugin class name
        plugin_dir = os.getcwd()
        f = open("{}/__init__.py".format(plugin_dir), "r")
        init_file = f.read()
        f.close()
        class_name = ""
        for line in init_file.split("\n"):
            if "return" in line:
                start = line.find("return") + len("return")
                end = line.find("(iface)")
                class_name = line[start + 1:end]

        # Find all .ui files
        ui_files = glob.glob("{}/**/*.ui".format(plugin_dir), recursive=True)
        str_pro_ui = ""
        for ui in ui_files:
            pro_ui = ui.replace(plugin_dir, " ..")
            str_pro_ui += pro_ui

        # Find all .py files
        py_files = glob.glob("{}/**/*.py".format(plugin_dir), recursive=True)
        str_pro_py = ""
        list_ignore_py = [" ..\\compile.py", " ..\\resources.py", " ..\\__init__.py"]
        for py in py_files:
            pro_py = py.replace(plugin_dir, " ..")
            str_pro_py += pro_py
            if "_dialog.py" in pro_py:
                list_ignore_py.append(pro_py)

        for ignore in list_ignore_py:
            str_pro_py = str_pro_py.replace(ignore, "")

        if str_pro_ui != "" and str_pro_py != "" and class_name != "":
            pro_string = "FORMS ={} \nSOURCES ={} \nTRANSLATIONS = {}_fr.ts".format(str_pro_ui, str_pro_py, class_name)
            f = open("{}/i18n/{}.pro".format(plugin_dir, class_name), "w")
            f.write(pro_string)
            f.close()
        else:
            print("Error")
    else:
        pass

def compile_ts(list_files):
    pro_files = glob.glob('i18n/*.pro')
    for pro in pro_files:
        print("pylupdate5.bat {}".format(pro))
        subprocess.call(["pylupdate5.bat"])
        subprocess.call(["pylupdate5.bat", "{}".format(pro)])

def compile_qm(list_files):
    # If translation is done, create .qm files from the .ts files
    pro_files = glob.glob('i18n/*.pro')
    ts_files = glob.glob('i18n/*.ts')
    pro_mtime = os.path.getmtime(pro_files[0])
    ts_mtime = os.path.getmtime(ts_files[0])
    print(ts_mtime - pro_mtime)
    print(datetime.datetime.fromtimestamp(pro_mtime))

    qm_files = glob.glob('i18n/*.ts')
    for qm in qm_files:
        print("lrelease {}".format(qm))
        subprocess.call(["lrelease", "{}".format(qm)])


from random import randint
class Point:
    id = 0
    def __init__(self):
        self.id = Point.id
        self.color = "sus-2nd-imp"
        self.bridge = []
        Point.id += 1

    def to_string(self):
        text = "Id : " + str(self.id )+ "\n" + "Bridge :"
        for i in range(len(self.bridge)):
            text += " Id : " + str(self.bridge[i].id) + " , "
        text += "\n" "Color :" + self.color
        return text

def make_bridge(point1,point2):
    point1.bridge.append(point2)
    point2.bridge.append(point1)

def get_player_by_id(id,players):
    for i in range(len(players)):
        if(players[i].id == id):
            return players[i]

def dead(id,players):
    players.remove(get_player_by_id(id,players))
    return players

def make_connexions(co_per_player,players):
    for p in players:
        for i in range(co_per_player):
            make_bridge(p,(players[randint(0,len(players)-1)]))
    return players

def suspicious (dead_player,players):
    sus = []
    safe = []
    for p in dead_player.bridge:
        sus.append(p)
    for p in sus:
        for b in p.bridge:
            safe.append(b)
    for p in safe:
        p.color = "safe"
    for p in sus :
        p.color = "sus-killer"
    dead_player.color = "dead"

def print_players(players):
    for p in players :
        print(p.to_string())
        print()

def impostors(players):
    impostors=[]
    for p in players:
        if(p.color!="safe" and p.color!="dead"):
            impostors.append(p)
    return impostors

if __name__ == "__main__":
    #initilisation
    players=[]
    for i in range(10):
        players.append(Point())

    #connexion
    make_connexions(2, players)
    dead_player = get_player_by_id(0,players)
    suspicious(dead_player, players)
    print_players(players)

    print("possible impostors : ")
    print_players(impostors(players))


from model.group import Group

# см урок 6_3_ddt.mp4
testdata = [
    Group(name="name111", header="header111", footer="footer111"),
    Group(name="name222", header="header222", footer="footer222")
]

# убрали этот код в уроке 6_5_dynamic_test_generation.mp4
# def random_string(prefix, maxlen):
#     symbols = string.ascii_letters + string.digits + " " # *10 убрал генерацию лишних пробелов так как с ними некоторые тесты падают, а еще не создается группа со знаком ' (string.punctuation + )
#     return prefix + "".join([random.choice(symbols) for i in range(random.randrange(maxlen))])
#
# # первый вариант
# testdata = [Group(name="", header="", footer="")] + [
#     Group(name=random_string("name", 10), header=random_string("header", 20), footer=random_string("footer", 20))
#     for i in range(2)
# ]

# второй вариант
# testdata = [
#     Group(name=name, header=header, footer=footer)
#     for name in ["", random_string("name", 10)]
#     for header in ["", random_string("header", 20)]
#     for footer in ["", random_string("footer", 20)]
# ]


import socket
import threading
import pickle

PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
DISCONNECT_MSSG = "!DISCONNECT"

temp_header = {
    "size" : 64,
    "type" : "get"
}
HEADER_SIZE = len(pickle.dumps(temp_header))

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)

def starting_position():
    pieces = []
    for i in range(8):
        pieces.append((0,0, (1, i)))
        pieces.append((1,0, (6, i)))

    pieces.extend([ (0, type, (0, i)) for i, type in enumerate([3,2,1,4,5,1,2,3])])
    pieces.extend([ (1, type, (7, i)) for i, type in enumerate([3,2,1,4,5,1,2,3])])
    print(pieces)

    return pieces

def update_state(move):
    pass

def handle_client(conn : socket.socket, addr):
    state = {
        "player" : 0,
        "pieces" : starting_position(),
        "turn" : 0,
    }

    print(f"[CONNECTED] the addr {addr} connected")
    connected = True

    while connected:
        bytes_header = conn.recv(HEADER_SIZE)
        header = pickle.loads(bytes_header)

        if header["type"] == "get":
            state_bytes = pickle.dumps(state)
            conn.send(int.to_bytes(len(state_bytes), 64, "little"))
            conn.send(pickle.dumps(state))

        elif header["type"] == "set":
            # piece
            assert False, f"set is not implemented"
        elif header["type"] == "end":
            connected = False
            print(f"[ENDING] {addr} closed")
        else:
            assert False, f"{header['type']} is not implemented"
    conn.close()

def start():
    server.listen()
    print(f"[LISTENING] Server is listening on {SERVER}")
    while 1:
        conn, addr = server.accept()
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()

print("[STARTING] server is starting...")
start()


#!/usr/bin/env python
 # -*- coding: utf-8 -*-
from easyExcel import easyExcel
def parseExcelToLua(src_path,des_path):
	book = easyExcel.easyExcel(src_path)
	sheet = book.getSheet(1)
	info = sheet.UsedRange
	column = info.Columns.Count
	row =info.Rows.Count
	file_path = des_path
	header_row = 1
	type_row =2
	header_list = []
	'''number string '''
	type_list = []
	value_list = []
	for i in range(1,row+1):
		single_value_list = []
		is_wrong = False
		for j in range(1,column+1):
			temp_value = sheet.Cells(i,j).Value
			if i==header_row :
				header_list.append(temp_value)
			elif i==type_row:
				if temp_value !="number" and temp_value !="string" :
					print("类型错误")
					is_wrong = True
					break
				type_list.append(temp_value)
			else:
				single_value_list.append(temp_value)
		if is_wrong :
			break
		if i>=3 :
			value_list.append(single_value_list)

	book.close()
	if len(type_list) != len(header_list):
		print("格式错误")
		return

	fo = open(file_path,"w")
	fo.write('local t ={\n')
	for i in range(0,len(value_list)):
		fo.write('\t[%d]={\n'%(i))
		for j in range(0,len(header_list)):
			content = parseType(type_list[j],value_list[i][j])
			fo.write('\t\t{0}={1},'.format(header_list[j],content))
			fo.write('\n')
		fo.write('\t},\n')
	fo.write('}\nreturn t')
	fo.close()

def parseType(type,value):
	if type=="number" :
		if value =='None' :
			return '0'
		template = '{0}'
	else :
		if value =='None':
			value =''
		template ='\"{0}\"'
	return template.format(value)

if __name__ == "__main__":
	src_path =r'E:\python_learn_bran\python_learn\excel_to_lua_tool\test.xlsx'
	des_path =r'E:\python_learn_bran\python_learn\excel_to_lua_tool\Sheet1.lua'
	parseExcelToLua(src_path,des_path)


from django.shortcuts import render, redirect
from phones.models import Phone

def index(request):
    return redirect('catalog')

def show_catalog(request):
    template = 'catalog.html'
    sort = request.GET.get("sort", "id")
    if sort == 'max_price':
        sort = "-price"
    elif sort == 'min_price':
        sort = "price"
    phones = Phone.objects.order_by(sort)

    context = {'phones': phones}
    return render(request, template, context)

def show_product(request, slug):
    template = 'product.html'
    tel = Phone.objects.get(slug=slug)
    context = {'slug': tel}
    return render(request, template, context)


#!/usr/bin/python

import sys
import argparse
from netaddr import *

def main(args):
	parser = argparse.ArgumentParser(description='Check if ip(s) in range(s) --- don\'t use -i and -I or -r and -R')
	igroup = parser.add_mutually_exclusive_group(required = True)
	igroup.add_argument('-i', '--ip',  help='ip to test')
	igroup.add_argument('-I', '--ipFile',  help='txt of ips, 1 per line')
	rgroup = parser.add_mutually_exclusive_group(required = True)
	rgroup.add_argument('-r', '--range',  help='range to check')
	rgroup.add_argument('-R', '--rangeFile',  help='file of ranges, csv with 2nd column name of range')
	parser.add_argument('-o', '--outputfile', help='name of file to output, otherwise stdout')

	args = parser.parse_args()

	rangeName = {}

	if args.ip:
		fips = [args.ip]
		try:
			IPAddress(args.ip)
		except:
			print("Not a valid ip address")
			sys.exit(1)

	if args.ipFile:
		try:
			fips = open(args.ipFile, 'r')
		except:
			print(args.ipFile + " does not exist. Please use full path if error persists")
			sys.exit(1)

	if args.range:
		try:
			range = IPNetwork(args.range)
			rangeIPs[range] = list(range)
			rangeName[range] = "N/A"
		except:
			print("Not a valid network range")
			sys.exit(1)

	count = 0
	if args.rangeFile:
		try:
			frange = open(args.rangeFile, 'r')
		except:
			print(args.rangeFile + " does not exist. Please use full path if error persists")
			sys.exit(1)
		print("Processing IP Ranges\n")
		for line in frange:
			line = line.split(",")
			try:
				range = IPNetwork(line[0])
				if len(line) > 1:
					name = line[1]
				else:
					name = "N/A"
				rangeName[range] = name.strip()
			except:
				print(line[0] + " is not a valid CIDR range.  Will not be included in search")
				ans = "Y"
				while ans != "y" and ans != "n":
					ans = input("Would you like to continue anyway? (Y/N) ")
					ans = ans.lower()
				if ans == "n":
					sys.exit(1)
			count = count + 1
			if count % 25 == 0:
				print("Processed " + str(count) + " ranges\n")

	pflag = True
	if args.outputfile:
		fout = open(args.outputfile, 'w+')
		pflag = False

	count = 0
	flag = False
	print ("Checking IPs\n")
	for ip in fips:
		flag = False
		try:
			ip = IPAddress(ip)
			for range in rangeName:
				if ip >= range[0] and ip <= range[-1]:
					s = str(ip) + "," + str(range) + "," + rangeName[range]
					if pflag:
						print(s)
					else:
						fout.write(s + "\n")
					flag = True
					break
			if flag == False:
				s = str(ip) + " not in ranges"
				if pflag:
					print(s)
				else:
					fout.write(s + "\n")
		except:
			print(ip.strip() + " is not a valid IP address.  Will not be included in search")
		count = count + 1
		if count % 100 == 0:
			print("Processed " + str(count) + " IPs\n")

if __name__ == "__main__":
	if sys.version_info < (3,0):
		print("Must use python 3.0 or +")
		sys.exit(1)
	print("netaddr module must be installed for this script to run correctly!\n")
	main(sys.argv)


from models.album import Album
from models.artist import Artist

import repositories.artist_repos as artist_repos
import repositories.album_repos as album_repos
album_repos.delete_all()
artist_repos.delete_all()
artist1 = Artist("Beatles, The")
artist2 = Artist("Doors, The")
artist3 = Artist("Led Zeppelin")
artist4 = Artist("Rolling Stones, The")
artist5 = Artist("David Bowie")
artist6 = Artist("Cure, The")

album1 = Album("Help!", artist1, "Rock")
album2 = Album("Rubber Soul", artist1, "Rock")
album3 = Album("Revolver!", artist1, "Rock")
album4 = Album("Doors, The", artist2, "Rock")
album5 = Album("Strange Days", artist2, "Rock")
album6 = Album("LA Woman", artist2, "Rock")
album7 = Album("I", artist3, "Rock")
album8 = Album("II", artist3, "Rock")
album9 = Album("III", artist3, "Rock")
album10 = Album("Rolling Stones, The", artist4, "Rock")
album11 = Album("Aftermath", artist4, "Rock")
album12 = Album("Between The Buttons", artist4, "Rock")
album13 = Album("Diamond Dogs", artist5, "Rock")
album14 = Album("Spiders from Mars", artist5, "Rock")
album15 = Album("Hunky Dory", artist5, "Rock")
album16 = Album("Boy's Don't Cry", artist6, "Post punk")
album17 = Album("Seventeen Seconds", artist6, "Post punk")
album18 = Album("Faith", artist6, "Post punk")

artist_repos.save(artist1)
artist_repos.save(artist2)
artist_repos.save(artist3)
artist_repos.save(artist4)
artist_repos.save(artist5)
artist_repos.save(artist6)
album_repos.save(album1)
album_repos.save(album2)
album_repos.save(album3)
album_repos.save(album4)
album_repos.save(album5)
album_repos.save(album6)
album_repos.save(album7)
album_repos.save(album8)
album_repos.save(album9)
album_repos.save(album10)
album_repos.save(album11)
album_repos.save(album12)
album_repos.save(album13)
album_repos.save(album14)
album_repos.save(album15)
album_repos.save(album16)
album_repos.save(album17)
album_repos.save(album18)

# album_repos.delete_all()
# artist_repos.delete_all()

artist1 = Artist("Beatles, The")
artist_repos.save(artist1)

album1 = Album("Help!", artist1, "Rock")
album_repos.save(album1)
album2 = Album("Rubber Soul", artist1, "Rock")
album_repos.save(album2)

album1.genre = "Pop"
album_repos.update(album1)

for album in album_repos.select_all():
    print(album.__dict__)


"""
Kriging: choose an arbitrary trend
==================================
"""
# %%
# The goal of this example is to show how to configure an arbitrary trend in a Kriging metamodel.
# In the :doc:`/auto_meta_modeling/kriging_metamodel/plot_kriging_chose_trend`
# and :doc:`/auto_meta_modeling/kriging_metamodel/plot_kriging_beam_trend` examples,
# we show how to configure a polynomial trend.
#
# In general, any collection of multivariate functions can be used as the
# `basis` argument of a :class:`~openturns.KrigingAlgorithm`.
# In practice, it might not be convenient to create a multivariate basis and
# this is why we sometimes create it by tensorization of univariate functions.
# In this example, we first use Legendre polynomials as our univariate functions,
# then we create an orthogonal polynomial basis corresponding to the input marginals.
#
# For this purpose, we use the :ref:`cantilever beam <use-case-cantilever-beam>` example.

# %%
# Definition of the model
# -----------------------

# %%
from openturns.usecases import cantilever_beam
import openturns as ot

ot.RandomGenerator.SetSeed(0)
ot.Log.Show(ot.Log.NONE)

# %%
# We load the cantilever beam use case
cb = cantilever_beam.CantileverBeam()

# %%
# We load the function (model) which evaluates the output Y depending on the inputs.
model = cb.model

# %%
# Then we define the distribution of the input random vector.
dimension = cb.dim  # number of inputs
myDistribution = cb.distribution

# %%
# Create the design of experiments
# --------------------------------

# %%
# We consider a simple Monte-Carlo sampling as a design of experiments.
# This is why we generate an input sample using the `getSample` method of the distribution.
# Then we evaluate the output using the `model` function.

# %%
sampleSize_train = 20
X_train = myDistribution.getSample(sampleSize_train)
Y_train = model(X_train)

# %%
# Create the Legendre basis
# -------------------------
#
# We first create a Legendre basis of univariate polynomials. In order to convert then into multivariate polynomials, we use a linear enumerate function.
#
# The `LegendreFactory` class creates Legendre polynomials.

# %%
univariateFactory = ot.LegendreFactory()

# %%
# This factory corresponds to the `Uniform` distribution in the [-1,1] interval.

# %%
univariateFactory.getMeasure()

# %%
# This interval does not correspond to the interval on which the input marginals are defined (we will come back to this topic later), but this will, anyway, create a consistent trend for the kriging.

# %%
polyColl = [univariateFactory] * dimension

# %%
enumerateFunction = ot.LinearEnumerateFunction(dimension)
productBasis = ot.OrthogonalProductPolynomialFactory(polyColl, enumerateFunction)

# %%
functions = []
numberOfTrendCoefficients = 12
for i in range(numberOfTrendCoefficients):
    multivariatepolynomial = productBasis.build(i)
    print(multivariatepolynomial)
    functions.append(multivariatepolynomial)

# %%
basis = ot.Basis(functions)

# %%
# Create the metamodel
# --------------------

# %%
# In order to create the kriging metamodel, we first select a constant trend
# with the `ConstantBasisFactory` class.
# Then we use a squared exponential covariance model.
# Finally, we use the `KrigingAlgorithm` class to create the kriging metamodel,
# taking the training sample, the covariance model and the trend basis as input arguments.

# %%
covarianceModel = ot.SquaredExponential([1.0] * dimension, [1.0])

# %%
algo = ot.KrigingAlgorithm(X_train, Y_train, covarianceModel, basis)
algo.run()
result = algo.getResult()
krigingWithConstantTrend = result.getMetaModel()

# %%
# The `getTrendCoefficients` method returns the coefficients of the trend.

# %%
result.getTrendCoefficients()

# %%
# We see that the number of coefficients in the trend corresponds to the number of functions in the basis.

# %%
result.getCovarianceModel()

# %%
# The `SquaredExponential` model has one amplitude coefficient and 4 scale coefficients.
# This is because this covariance model is anisotropic : each of the 4 input variables is associated with its own scale coefficient.

# %%
# Create an orthogonal multivariate polynomial factory
# ----------------------------------------------------

# %%
# In order to create a Legendre basis which better corresponds to the input marginals, we could consider the orthogonal basis which would be associated to uniform marginals.
# To compute the bounds of these uniform distributions, we may consider the 1% and 99% quantiles of each marginal.
#
# There is, however, a simpler way to proceed. We can simply orthogonalize the input marginals and create the orthogonal polynomial basis corresponding to the inputs.
# This corresponds to the method we would use in the polynomial chaos.
#
# We first create the polynomial basis which corresponds to the inputs.

# %%
multivariateBasis = ot.OrthogonalProductPolynomialFactory([cb.E, cb.F, cb.L, cb.II])

# %%
# Then we create the multivariate basis which has maximum degree equal to 2.

# %%
totalDegree = 2
enumerateFunction = multivariateBasis.getEnumerateFunction()
numberOfTrendCoefficients = enumerateFunction.getStrataCumulatedCardinal(totalDegree)
numberOfTrendCoefficients

# %%
functions = []
for i in range(numberOfTrendCoefficients):
    multivariatepolynomial = productBasis.build(i)
    print(multivariatepolynomial)
    functions.append(multivariatepolynomial)

# %%
basis = ot.Basis(functions)

# %%
algo = ot.KrigingAlgorithm(X_train, Y_train, covarianceModel, basis)
algo.run()
result = algo.getResult()
krigingWithConstantTrend = result.getMetaModel()

# %%
# The `getTrendCoefficients` method returns the coefficients of the trend.

# %%
result.getTrendCoefficients()

# %%
# Conclusion
# ----------
#
# The trend that we have configured corresponds to the basis that we would have used in a full polynomial chaos computed with least squares.
#
# Other extensions of this work would be:
#
# * to use a Fourier basis with `FourierSeriesFactory`,
# * wavelets with `HaarWaveletFactory`,
#
# or any other univariate factory.


"""Spotitude.

Get a user's top 25 tracks and return a 5x5 grid visualization.
"""

from config import Config
from data import get_top_tracks
import spotipy
from visualization import make_visualization
import argparse
import gui

if __name__ == "__main__":
    # Parse the input parameters.
    parser = argparse.ArgumentParser(description="Spotitude Customization")
    parser.add_argument(
        "--time_range",
        type=str,
        default="short_term",
        help="Over what time frame the top tracks are computed. "
        + "Valid values: long_term, medium_term and short_term. (default: short_term)",
    )
    args = parser.parse_args()
    if args.time_range not in ["short_term", "medium_term", "long_term"]:
        raise ValueError(
            "Valid values for time_range are: long_term, medium_term and short_term."
        )

    # Get authentication token for Spotify API
    config = Config()
    token = config.get_token()

    if token:
        spotify = spotipy.Spotify(auth=token)
        # Get user's top tracks
        top_tracks_df = get_top_tracks(
            spotify, limit=25, time_range=args.time_range, save=True
        )

        # Create visualization
        make_visualization(top_tracks_df)

        # Open visualization using Eel as interactive GUI
        gui.open_visualization(spotify, top_tracks_df, args.time_range)


from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
    path('home', views.home, name = 'home'),
    path('signup', views.signup, name = 'signup'),
    path('signin', views.signin, name = 'signin'),
    path('signout', views.signout, name = 'signout'),
    path('science', views.science, name = 'science'),
    path('commerce', views.commerce, name = 'commerce'),
    path('arts', views.arts, name = 'arts'),
    path('tenth', views.tenth, name = 'tenth'),
    path('activate/<uidb64>/<token>', views.activate, name = 'activate'),

]


import pandas as pd
from datetime import datetime

df = pd.read_csv('https://query.data.world/s/tt5efa64gl6ruwmxz4wdgmhfwroi4r',
                 usecols=['longitude', 'latitude', 'region', 'admin1', 'location',
                          'event_type', 'fatalities', 'event_date'])

print('Loading in dataset from data.world/makeovermonday/2018w34-visualizing-conflict...')

df['event_type'] = ['Battle' if e[:6] == 'Battle' else e
                    for e in df['event_type']]

df['event_date'] = [datetime.strptime(d, "%d-%b-%y") for d in df['event_date']]
df['year_month'] = [str(d.year) + '_' + str(d.month) for d in df['event_date']]

df['region'] = [r if r == 'Middle East' else r.split()[1] for r in df['region']]

df.to_csv('data/world_conflict.csv', index=False)


# -*- coding: utf-8 -*-
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.views import LoginView
from django.shortcuts import render, redirect
from .models import Contact
from .forms import ContactForm

template = 'core/'

class CustomAuthenticationForm(AuthenticationForm):
    """Definition of a Django-authentication-form-based form.

    Inherits from AuthenticationForm (class), a base class for
    authenticating users.

    Attributes
    ----------
    error_messages : dict
        Error message key-value pair.
    """
    error_messages = {
        'invalid_login': "Dados inválidos. Tente novamente."
    }

class CustomLoginView(LoginView):
    """Definition of a Django-login-view-based class.

    Inherits from LoginView (class), display the login form and
    handle the login action.

    Attributes
    ----------
    template_name : str
        The login view file path.
    authentication_form : class
        Django-authentication-form-based form.
    """
    template_name = 'accounts/login.html'
    authentication_form = CustomAuthenticationForm

def index(request):
    """Definition of the app index view.

    Parameters
    ----------
    request : HttpRequest
        The client request to the server.

    Returns
    -------
    HttpResponse
        The server response to the client.
    """
    form = ContactForm(request.POST or None)
    context = {}
    if form.is_valid():
        form.save()
        request.session['success'] = True
        request.session['was_reloaded'] = False
        return redirect('/#contact')
    else:
        if 'was_reloaded' in request.session:
            if not request.session['was_reloaded']:
                request.session['was_reloaded'] = True
            else:
                request.session['success'] = False
    context['form'] = form
    return render(request, template + 'index.html', context)

def error_500_view(request):
    """Definition of the 500 error view.

    Parameters
    ----------
    request : HttpRequest
        The client request to the server.

    Returns
    -------
    HttpResponse
        The server response to the client.
    """
    return render(request, 'core/500.html')


import tensorflow as tf
from skimage import transform as tr
from skimage import io
import pandas as pd
import numpy as np
import re

import netv2 as net

#fetch data
def datFetch(dat, path, batch_size, iteration = 0, offset = 0, aug_chance = 0.3, load_box = True):
    imgs = []
    bboxes = []
    categories = []
    detection = []

    indexes = np.array(range(batch_size)) + iteration * batch_size + offset
    for index in indexes:

        #Image
        img = io.imread('./%s/%s' % (path, dat.loc[index]['filename'])) / 255
        r = np.random.uniform() #Random float between 0-1
        if r <= aug_chance:
            img = augment(img)
        imgs.append(img.flatten())

        #Category
        onehot = np.identity(3)
        onehot[0, 0] = 0
        onehot = onehot[1 : , 1 : ]
        try:
            categories.append(onehot[int(dat.loc[index]['category']) - 1])
            detection.append(1)
        except:
            detection.append(0)

        #Bounding box
        if load_box:
            bbox = np.array(re.sub(' +', ' ', dat.loc[index]['bounding_box'][1 : -2]).split(' ')[:4], np.float)
            bboxes.append(bbox)

        '''
        try:
            bbox = np.array(re.sub(' +', ' ', dat.loc[index]['bounding_box'][1 : -2]).split(' '), np.float)
            bboxes.append(bbox)
        except:
            pass'''

    return np.array(detection),  np.array(imgs), np.array(bboxes), np.array(categories)

#augment data
def augment(x):
    angle = np.random.uniform() * 30 # max rotation angle
    noise = np.random.uniform(size = x.shape) * np.random.uniform() * 0.5
    return tr.rotate(x, angle, mode = 'edge') + noise

#placeholders
#input
x = tf.placeholder(tf.float32, shape = [None, 64 * 64 * 3])
x_reshaped = tf.reshape(x, shape = [-1, 64, 64, 3])

#obj detection
d = tf.placeholder(tf.float32, shape = [None])
d_reshaped = tf.reshape(d, shape = [-1, 1, 1, 1])

#category
c = tf.placeholder(tf.float32, shape = [None, 2])
c_reshaped = tf.reshape(c, shape = [-1, 1, 1, 2])

#bounding box
b = tf.placeholder(tf.float32, shape = [None, 4])
b_reshaped = tf.reshape(b, shape = [-1, 1, 1, 4])

logit_d, logit_c, out_d, out_c, out_b = net.pred(x_reshaped) # outputs

#Losses

#obj detection
d_loss = tf.nn.sigmoid_cross_entropy_with_logits(labels = d_reshaped, logits = logit_d)
#category
c_loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels = c_reshaped, logits = logit_c)
#bounding box
b_loss = tf.losses.mean_squared_error(labels = b_reshaped, predictions = out_b)

#Learning rate
lr = 0.0001

#Optimizer
opt = tf.train.AdamOptimizer(learning_rate = lr, beta1 = 0.5)
#opt = tf.train.GradientDescentOptimizer(learning_rate = lr)

#Optimize ops
d_opt = opt.minimize(d_loss)
c_opt = opt.minimize(c_loss)
b_opt = opt.minimize(b_loss)


""" openconfig_aft_types

Types related to the OpenConfig Abstract Forwarding
Table (AFT) model

"""
from collections import OrderedDict

from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64
from ydk.filters import YFilter
from ydk.errors import YError, YModelError
from ydk.errors.error_handler import handle_type_error as _handle_type_error

class EncapsulationHeaderType(Enum):
    """
    EncapsulationHeaderType (Enum Class)

    Types of tunnel encapsulation that are supported by systems as either

    head\- or tail\-end.

    .. data:: GRE = 0

    	The encapsulation header is a Generic Routing Encapsulation

    	header.

    .. data:: IPV4 = 1

    	The encapsulation header is an IPv4 packet header

    .. data:: IPV6 = 2

    	The encapsulation header is an IPv6 packet header

    .. data:: MPLS = 3

    	The encapsulation header is one or more MPLS labels indicated

    	by the pushed and popped label stack lists.

    """

    GRE = Enum.YLeaf(0, "GRE")

    IPV4 = Enum.YLeaf(1, "IPV4")

    IPV6 = Enum.YLeaf(2, "IPV6")

    MPLS = Enum.YLeaf(3, "MPLS")

class AFTADDRESSFAMILY(Identity):
    """
    A base identity that is used for address families that have
    distinct Abstract Forwarding Tables (AFTs).

    """

    _prefix = 'oc-aftt'
    _revision = '2017-01-13'

    def __init__(self):
        super(AFTADDRESSFAMILY, self).__init__("http://openconfig.net/yang/fib-types", "openconfig-aft-types", "openconfig-aft-types:AFT_ADDRESS_FAMILY")

class IPV4UNICAST(Identity):
    """
    The AFT entries within the corresponding table relate to unicast
    IPv4 forwarding entries.

    """

    _prefix = 'oc-aftt'
    _revision = '2017-01-13'

    def __init__(self):
        super(IPV4UNICAST, self).__init__("http://openconfig.net/yang/fib-types", "openconfig-aft-types", "openconfig-aft-types:IPV4_UNICAST")

class IPV6UNICAST(Identity):
    """
    The AFT entries within the corresponding table relate to unicast
    IPv6 forwarding entries.

    """

    _prefix = 'oc-aftt'
    _revision = '2017-01-13'

    def __init__(self):
        super(IPV6UNICAST, self).__init__("http://openconfig.net/yang/fib-types", "openconfig-aft-types", "openconfig-aft-types:IPV6_UNICAST")

class MPLS(Identity):
    """
    The AFT entries within the corresponding table relate to labelled
    forwarding entries using MPLS labels.

    """

    _prefix = 'oc-aftt'
    _revision = '2017-01-13'

    def __init__(self):
        super(MPLS, self).__init__("http://openconfig.net/yang/fib-types", "openconfig-aft-types", "openconfig-aft-types:MPLS")

class L2ETHERNET(Identity):
    """
    The AFT entries within the corresponding table relate to Ethernet
    switched forwarding entries.

    """

    _prefix = 'oc-aftt'
    _revision = '2017-01-13'

    def __init__(self):
        super(L2ETHERNET, self).__init__("http://openconfig.net/yang/fib-types", "openconfig-aft-types", "openconfig-aft-types:L2_ETHERNET")


description = """
You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise).

Try to solve this in-place - in a real interview, you will only be allowed to use O(1) additional memory.

Example

For

a = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

the output should be

rotateImage(a) =
    [[7, 4, 1],
     [8, 5, 2],
     [9, 6, 3]]

Input/Output

    [time limit] 4000ms (py3)

    [input] array.array.integer a

    Guaranteed constraints:
    1 ≤ a.length ≤ 100,
    a[i].length = a.length,
    1 ≤ a[i][j] ≤ 104.

    [output] array.array.integer

"""

def test():
    testeql(rotateImage([[1,2,3],
                         [4,5,6],
                         [7,8,9]]),
            [[7,4,1],
             [8,5,2],
             [9,6,3]])

# 250 xp, 1000 coins

def rotateImageMySolution(a):
    # uses O(n) memory, not ideal
    n = len(a)
    target = [[0 for _ in range(n)] for _ in range(n)]

    for r in range(n):
        for c in range(n):
            target[c][n-r-1] = a[r][c]
    return target

def rotateImage(a):
    # solution by darth_tytus
    return [[row[i] for row in a][::-1]
            for i in range(len(a))]


import pickle
import PIL
from PIL import Image
import numpy as np
import os

# for letter in ['o','p','q','r','s','u']:
for letter in ['a','b','c','e','g']:
	samples = len([f for f in os.listdir('./Letters/'+letter+'/') if f[-5:] == ".jpeg"])
	databasename='./Letters/'+letter+'/'+letter+'_vector.p'
	database=[]
	for i in range(0,samples):
		imagename='./Letters/'+letter+'/img_'+letter+'_'+str(i)
		img = Image.open(imagename+'.jpeg')
		#To create vector:
		img = img.convert('L')
		dat=np.array(img)/255
		database.append(dat)
	pickle.dump(database,open(databasename,'wb'))
	print("Exported vector for letter " + letter)


import config
import hashlib
import app

class Edit:

    def __init__(self):
        pass

    '''
    def GET(self, id_denuncia, **k):
        if app.session.loggedin is True: # validate if the user is logged
            # session_username = app.session.username
            session_privilege = app.session.privilege # get the session_privilege
            if session_privilege == 0: # admin user
                return self.GET_EDIT(id_denuncia) # call GET_EDIT function
            elif session_privilege == 1: # guess user
                raise config.web.seeother('/guess') # render guess.html
        else: # the user dont have logged
            raise config.web.seeother('/login') # render login.html

    def POST(self, id_denuncia, **k):
        if app.session.loggedin is True: # validate if the user is logged
            # session_username = app.session.username
            session_privilege = app.session.privilege # get the session_privilege
            if session_privilege == 0: # admin user
                return self.POST_EDIT(id_denuncia) # call POST_EDIT function
            elif session_privilege == 1: # guess user
                raise config.web.seeother('/guess') # render guess.html
        else: # the user dont have logged
            raise config.web.seeother('/login') # render login.html

    @staticmethod
    def GET_EDIT(id_denuncia, **k):

    @staticmethod
    def POST_EDIT(id_denuncia, **k):

    '''

    def GET(self, id_denuncia, **k):
        message = None # Error message
        id_denuncia = config.check_secure_val(str(id_denuncia)) # HMAC id_denuncia validate
        result = config.model.get_denuncia(int(id_denuncia)) # search for the id_denuncia
        result.id_denuncia = config.make_secure_val(str(result.id_denuncia)) # apply HMAC for id_denuncia
        return config.render.edit(result, message) # render denuncia edit.html

    def POST(self, id_denuncia, **k):
        form = config.web.input()  # get form data
        form['id_denuncia'] = config.check_secure_val(str(form['id_denuncia'])) # HMAC id_denuncia validate
        # edit user with new data
        result = config.model.edit_denuncia(
            form['id_denuncia'],form['descripcion_d'],form['calle_d'],form['municipio_d'],form['colonia_d'],form['longitud'],form['latitud'],
        )
        if result == None: # Error on udpate data
            id_denuncia = config.check_secure_val(str(id_denuncia)) # validate HMAC id_denuncia
            result = config.model.get_denuncia(int(id_denuncia)) # search for id_denuncia data
            result.id_denuncia = config.make_secure_val(str(result.id_denuncia)) # apply HMAC to id_denuncia
            message = "Error al editar el registro" # Error message
            return config.render.edit(result, message) # render edit.html again
        else: # update user data succefully
            raise config.web.seeother('/denuncia') # render denuncia index.html


"""tox-pyenv

Plugin for the tox_get_python_executable using tox's plugin system:

    https://testrun.org/tox/latest/plugins.html#tox.hookspecs.tox_get_python_executable

Modified to instead use `pyenv which` to locate the
appropriate python executable. This takes the place
of the standard behavior in tox. The built-in default
for the tox_get_python_exeucutable function
is the following (for sys.platform != 'win32'):

    @hookimpl
    def tox_get_python_executable(envconfig):
        return py.path.local.sysfind(envconfig.basepython)

which uses the 'py' package's sysfind():

    https://pylib.readthedocs.org/en/latest/path.html#py._path.local.LocalPath.sysfind

If `pyenv`'s shims are not at the very front of your path,
sysfind might lookup the global system version of python
instead of preferring a version specified by using `pyenv local`
or `pyenv global`. This plugin changes the way tox finds
your python executable to exclusively use `pyenv which`.

    https://github.com/yyuu/pyenv/blob/master/COMMANDS.md#pyenv-which

"""

# __about__
__title__ = 'tox-pyenv'
__summary__ = ('tox plugin that makes tox use `pyenv which` '
               'to find python executables')
__url__ = 'https://github.com/samstav/tox-pyenv'
__version__ = '1.1.0'
__author__ = 'Sam Stavinoha'
__email__ = 'smlstvnh@gmail.com'
__keywords__ = ['tox', 'pyenv', 'python']
__license__ = 'Apache License, Version 2.0'
# __about__

import logging
import subprocess

import py
from tox import hookimpl as tox_hookimpl

LOG = logging.getLogger(__name__)

class ToxPyenvException(Exception):

    """Base class for exceptions from this plugin."""

class PyenvMissing(ToxPyenvException, RuntimeError):

    """The pyenv program is not installed."""

class PyenvWhichFailed(ToxPyenvException):

    """Calling `pyenv which` failed."""

@tox_hookimpl
def tox_get_python_executable(envconfig):
    """Return a python executable for the given python base name.

    The first plugin/hook which returns an executable path will determine it.

    ``envconfig`` is the testenv configuration which contains
    per-testenv configuration, notably the ``.envname`` and ``.basepython``
    setting.
    """
    try:
        # pylint: disable=no-member
        pyenv = (getattr(py.path.local.sysfind('pyenv'), 'strpath', 'pyenv')
                 or 'pyenv')
        cmd = [pyenv, 'which', envconfig.basepython]
        pipe = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True
        )
        out, err = pipe.communicate()
    except OSError:
        err = '\'pyenv\': command not found'
        LOG.warning(
            "pyenv doesn't seem to be installed, you probably "
            "don't want this plugin installed either."
        )
    else:
        if pipe.poll() == 0:
            return out.strip()
        else:
            if not envconfig.tox_pyenv_fallback:
                raise PyenvWhichFailed(err)
    LOG.debug("`%s` failed thru tox-pyenv plugin, falling back. "
              "STDERR: \"%s\" | To disable this behavior, set "
              "tox_pyenv_fallback=False in your tox.ini or use "
              " --tox-pyenv-no-fallback on the command line.",
              ' '.join([str(x) for x in cmd]), err)

def _setup_no_fallback(parser):
    """Add the option, --tox-pyenv-no-fallback.

    If this option is set, do not allow fallback to tox's built-in
    strategy for looking up python executables if the call to `pyenv which`
    by this plugin fails. This will allow the error to raise instead
    of falling back to tox's default behavior.
    """

    cli_dest = 'tox_pyenv_fallback'
    halp = ('If `pyenv which {basepython}` exits non-zero when looking '
            'up the python executable, do not allow fallback to tox\'s '
            'built-in default logic.')
    # Add a command-line option.
    tox_pyenv_group = parser.argparser.add_argument_group(
        title='{0} plugin options'.format(__title__),
    )
    tox_pyenv_group.add_argument(
        '--tox-pyenv-no-fallback', '-F',
        dest=cli_dest,
        default=True,
        action='store_false',
        help=halp
    )

    def _pyenv_fallback(testenv_config, value):
        cli_says = getattr(testenv_config.config.option, cli_dest)
        return cli_says or value

    # Add an equivalent tox.ini [testenv] section option.
    parser.add_testenv_attribute(
        name=cli_dest,
        type="bool",
        postprocess=_pyenv_fallback,
        default=False,
        help=('If `pyenv which {basepython}` exits non-zero when looking '
              'up the python executable, allow fallback to tox\'s '
              'built-in default logic.'),
    )

@tox_hookimpl
def tox_addoption(parser):
    """Add command line option to the argparse-style parser object."""
    _setup_no_fallback(parser)


import toml

def parse_toml_to_venv_script(file_path: str, python_version="3.10.12", env_name="myenv") -> str:
    """
    Convert a TOML configuration to a bash script that sets up a python environment using venv and performs actions based on the TOML.

    Parameters:
    - file_path: The path to the TOML file.
    - python_version: The desired Python version (unused, but kept for function signature compatibility).
    - env_name: Name of the virtual environment using venv.

    Returns:
    - Bash script as a string.
    """

    def check_command_availability(commands: list) -> list:
        """Generate bash snippets to check if each command in the provided list is available."""
        checks = [f"""
if [[ $IS_COLAB -eq 0 ]] && ! command -v {cmd} >/dev/null; then
  echo "{cmd} not found. Please install {cmd}."
  exit 1
fi
        """.strip() for cmd in commands]
        return checks

    # Load TOML configuration
    with open(file_path, 'r') as f:
        config = toml.load(f)

    model_name = config["environment"].get("model_name")
    if not model_name:
        raise ValueError("Missing model_name in flatpack.toml")

    script = ["#!/bin/bash"]

    # Check if running in Google Colab
    colab_check = """
if [[ "${COLAB_GPU}" == "1" ]]; then
  echo "Running in Google Colab environment"
  IS_COLAB=1
else
  echo "Not running in Google Colab environment"
  IS_COLAB=0
fi
    """.strip()
    script.append(colab_check)

    # Bash check for directory existence
    script.append(f"""
if [[ $IS_COLAB -eq 1 ]]; then
    if [ ! -d "{model_name}" ]; then
        mkdir -p {model_name}
    else
        echo 'Directory {model_name} already exists in Google Colab. Moving on.'
    fi
fi
    """)

    # Ensure required commands are available
    script.extend(check_command_availability(["curl", "wget", "git"]))

    # Install required Unix packages using apt, but only if not in Google Colab and on a Debian-based system
    unix_packages = config.get("packages", {}).get("unix", {})
    package_list_unix = [package for package in unix_packages.keys()]
    if package_list_unix:
        apt_install = f"""
OS=$(uname)
if [[ $IS_COLAB -eq 0 && "$OS" = "Linux" && -f /etc/debian_version ]]; then
    echo "Installing required Unix packages..."
    sudo apt update
    sudo apt install -y {' '.join(package_list_unix)}
fi
        """.strip()
        script.append(apt_install)

    # Setup venv environment
    venv_setup = f"""
handle_error() {{
    echo "ðŸ˜Ÿ Oops! Something went wrong."
    exit 1
}}

if [[ $IS_COLAB -eq 0 ]]; then
    # Check if python3 is available
    if command -v python3 &>/dev/null; then
        PYTHON_CMD=python3
    else
        PYTHON_CMD=python
    fi

    if [ ! -d "{env_name}" ]; then
        $PYTHON_CMD -m venv {env_name} || handle_error
    fi

    export VENV_PYTHON={env_name}/bin/python
fi
    """.strip()
    script.append(venv_setup)

    # Create other directories as per the TOML configuration
    directories_map = config.get("directories")
    if directories_map:
        for directory_path in directories_map.values():
            formatted_path = directory_path.lstrip('/').replace("home/content/", "")
            script.append(f"mkdir -p ./{model_name}/{formatted_path}")

    # Set model name as an environment variable
    script.append(f"export model_name={model_name}")

    # Install python packages
    packages = config.get("packages", {}).get("python", {})
    package_list = [f"{package}=={version}" if version != "*" and version else package for package, version in
                    packages.items()]
    if package_list:
        script.append(f"$VENV_PYTHON -m pip install {' '.join(package_list)}")

    # Clone required git repositories
    for git in config.get("git", []):
        from_source, to_destination, branch = git.get("from_source"), git.get("to_destination"), git.get("branch")
        if from_source and to_destination and branch:
            repo_path = f"./{model_name}/{to_destination.replace('/home/content/', '')}"
            git_clone = f"""
echo "Cloning repository from: {from_source}"
git clone -b {branch} {from_source} {repo_path}
if [ $? -eq 0 ]; then
    echo "Git clone was successful."
    flatpack callback git-success
else
    echo "Git clone failed."
    exit 1
fi
if [ -f {repo_path}/requirements.txt ]; then
    echo "pwd: $(pwd)"
    echo "repo_path: {repo_path}"
    echo "Found requirements.txt, installing dependencies..."
    ${{VENV_PYTHON}} pip install -r {repo_path}/requirements.txt
else
    echo "No requirements.txt found."
fi
            """.strip()
            script.append(git_clone)

    # Download datasets or files
    for item_type in ["dataset", "file"]:
        for item in config.get(item_type, []):
            from_source, to_destination = item.get("from_source"), item.get("to_destination")
            if from_source and to_destination:
                script.append(f"curl -L {from_source} -o ./{model_name}/{to_destination.replace('/home/content/', '')}")

    # Execute specified run commands
    run_vec = config.get("run", [])
    for run in run_vec:
        command, args = run.get("command"), run.get("args")
        if command and args:
            replaced_args = args.replace("/home/content/", f"./{model_name}/")
            script.append(f"{command} {replaced_args}")

    return "\n".join(script)


from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'agilecar.views.index', name='index'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^jobposting/', include('jobposting.urls')),
    url(r'^application/', include('application.urls')),
    url(r'^screeners/', include('screener.urls')),

    #auth urls
    url(r'^account/login/$', 'agilecar.views.login'),
    url(r'^account/register/$', 'agilecar.views.register'),
    url(r'^account/logout/$', 'agilecar.views.logout'),
    #url(r'^account/loggedin/$', 'agilecar.views.loggedin'),
    #url(r'^account/invalid/$', 'agilecar.views.invalid_login'),
)


from typing import Any, Union

from prometheus_client import Counter, Histogram

from metrics.event import Event

class SampleEvent(Event):
    LABELS = ["error"]
    METRICS = {
        "result": Counter("sample_result", "sample result", LABELS),
        "latency": Histogram(
            "sample_latency",
            "sample latency",
            LABELS,
            buckets=[1000, 2000, 3000, 5000, 10000],  # 1s to 10s
        ),
    }

    # protected

    def _transform_result_to_labels(self, result: Union[dict, Any]) -> dict:
        if isinstance(result, dict) and "error" in result:
            return {"error": result["error"]}
        else:
            return {"error": None}


from datetime import datetime, timedelta
from typing import List

from fastapi import Depends, HTTPException, status, Path, APIRouter
from sqlalchemy.orm import Session

from src.database.db import get_db
from src.database.model import Contact
from src.schemas import ContactResponse, ContactModel

router = APIRouter(prefix="/contacts", tags=["contacts"])

@router.get("/", response_model=List[ContactResponse], name="Get contacts")
async def get_contacts(db: Session = Depends(get_db)):
    contacts = db.query(Contact).all()
    return contacts

@router.post("/", response_model=ContactResponse, status_code=status.HTTP_201_CREATED)
async def create_contact(body: ContactModel, db: Session = Depends(get_db)):
    contact = db.query(Contact).filter_by(email=body.email).first()
    if contact:
        raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Email is exists")
    contact = Contact(**body.dict())
    db.add(contact)
    db.commit()
    db.refresh(contact)
    return contact

@router.get("/{contact_id}", response_model=ContactResponse, name="Get contact by id")
async def get_contact_by_id(contact_id: int = Path(ge=1), db: Session = Depends(get_db)):
    contact = db.query(Contact).filter_by(id=contact_id).first()
    if contact is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
    return contact

@router.put("/{contact_id}", response_model=ContactResponse, name="Update contact by id")
async def update_contact_by_id(body: ContactModel, contact_id: int = Path(ge=1), db: Session = Depends(get_db)):
    contact = db.query(Contact).filter_by(id=contact_id).first()
    if contact is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
    contact.first_name = body.first_name
    contact.last_name = body.last_name
    contact.email = body.email
    contact.phone = body.phone
    contact.born_date = body.born_date
    contact.add_data = body.add_data
    db.commit()
    return contact

@router.delete("/{contact_id}", status_code=status.HTTP_204_NO_CONTENT, name="Remove contact by id")
async def remove_contact_by_id(contact_id: int = Path(ge=1), db: Session = Depends(get_db)):
    contact = db.query(Contact).filter_by(id=contact_id).first()
    if contact is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
    db.delete(contact)
    db.commit()
    return contact

@router.get("/search/{find_item}",
            response_model=List[ContactResponse],
            name="Find contact by first_name, last_name, email")
async def get_search(find_item: str, db: Session = Depends(get_db)):
    result = []
    if find_item:
        contacts_f_name = db.query(Contact).filter(Contact.first_name.like(f'%{find_item}%')).all()
        if contacts_f_name:
            result.extend(contacts_f_name)
        contacts_l_name = db.query(Contact).filter(Contact.last_name.like(f'%{find_item}%')).all()
        if contacts_l_name:
            result.extend(contacts_l_name)
        contacts_email = db.query(Contact).filter(Contact.email.like(f'%{find_item}%')).all()
        if contacts_email:
            result.extend(contacts_email)
        result = list(set(result))
    if not result:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
    return result

@router.get("/birthday/", response_model=List[ContactResponse], name="Birthday in 7 days")
async def birthday_7(db: Session = Depends(get_db)):
    contacts = db.query(Contact).all()
    result = []
    today = datetime.now()
    for contact in contacts:
        if contact.born_date.month > today.month:
            contact_birthday = datetime(year=today.year, month=contact.born_date.month, day=contact.born_date.day)
        elif contact.born_date.month < today.month:
            contact_birthday = datetime(year=today.year+1, month=contact.born_date.month, day=contact.born_date.day)
        else:
            if contact.born_date.day > today.day:
                contact_birthday = datetime(year=today.year, month=contact.born_date.month, day=contact.born_date.day)
            else:
                contact_birthday = datetime(year=today.year+1, month=contact.born_date.month, day=contact.born_date.day)
        delta = contact_birthday - today
        if delta <= timedelta(days=7):
            result.append(contact)
    if not result:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
    return result


def row_number(t, e):
    for list in t:
        if e in list:
            return t.index(list)

def flatten(t):
    flattened_list = []
    for list in t:
        for element in list:
            if element == 0:
                continue
            flattened_list.append(element)
    return flattened_list

def inversions(x):
    inversion = 0
    for index in range(len(x)):
        for element in x[index:]:
            if x[index] > element:
                inversion += 1
    return inversion

def solvable(t):
    if len(t) % 2 == 0:
        if inversions(flatten(t)) % 2 == 0:
            if row_number(t, 0) % 2 == 0:
                return False
            else:
                return True
        else:
            if row_number(t, 0) % 2 == 0:
                return True
            else:
                return False
    else:
        if inversions(flatten(t)) % 2 == 0:
            return True
        else:
            return False

exec(input().strip())


# coding: utf-8
"""@brief Module declaring the interface to which must comply all concrete implementations of progress bar handlers
"""
import abc

class ProgressBarInterface(metaclass=abc.ABCMeta):
    """@brief Interface to which must comply all concrete implementations of progress bar handlers"""

    @abc.abstractmethod
    def __init__(self, name: str, min_value: int, max_value: int, show_eta: bool = False, *args, **kwargs):
        """@brief Construct a progressbar object based on its name

        @param name The name of the progress bar
        @param min_value The minimum value for progress display (corresponds to 0% progress)
        @param max_value The maximum value for progress display (corresponds to 100% progress)
        @param show_eta Should we calculate and display an estimated completion time?
        """
        raise NotImplementedError

    @abc.abstractmethod
    def __enter__(self):
        """@brief Ressource acquisition entry point"""
        raise NotImplementedError

    @abc.abstractmethod
    def __exit__(self, type, value, traceback):
        """@brief Ressource release"""
        raise NotImplementedError

    @abc.abstractmethod
    def update(self, value: int, raise_on_out_of_bounds = False):
        """Update the progressbar with a given value

        @param value The updated value
        @param raise_on_outofbounds Should we raise on out of bounds values (stricly lower than min, or strictly higher than max)? If set to no, we will saturate the value to bounds instead.
        """
        raise NotImplementedError

    @abc.abstractmethod
    def start(self):
        """Start displaying the progressbar with 0% completion
        """
        raise NotImplementedError

    @abc.abstractmethod
    def finish(self, value: int, raise_on_out_of_bounds = False):
        """Update the progressbar with 100% completion
        """
        raise NotImplementedError

    @classmethod
    def __subclasshook__(cls, subclass):
        if cls is not ProgressBarInterface:
            return NotImplemented
        return (
            hasattr(subclass, "__enter__")
            and callable(  # pylint: disable=consider-using-ternary
                subclass.__enter__
            )
            and hasattr(subclass, "__exit__")
            and callable(  # pylint: disable=consider-using-ternary
                subclass.__exit__
            )
            and hasattr(subclass, "update")
            and callable(  # pylint: disable=consider-using-ternary
                subclass.update
            )
            and hasattr(subclass, "start")
            and callable(  # pylint: disable=consider-using-ternary
                subclass.start
            )
            and hasattr(subclass, "finish")
            and callable(  # pylint: disable=consider-using-ternary
                subclass.finish
            )
            or NotImplemented
        )

class ProgressBarFactoryInterface(metaclass=abc.ABCMeta):
    """@brief Interface to which must comply all concrete implementations of progress bar handlers"""

    @abc.abstractstaticmethod
    def create(*args, **kwargs):
        """@brief Generate a progressbar instance

        @note All arguments are to be passed as are to the ProgressBar contructor
        """
        raise NotImplementedError

    @classmethod
    def __subclasshook__(cls, subclass):
        if cls is not ProgressBarFactoryInterface:
            return NotImplemented
        return (
            hasattr(subclass, "create")
            and callable(  # pylint: disable=consider-using-ternary
                subclass.create
            )
        )


# -*- coding: utf-8 -*

import re
import argparse

def parse_args():
    parser = argparse.ArgumentParser(
        description="Paddle Fluid word2 vector preprocess")
    parser.add_argument(
        '--data_path',
        type=str,
        required=True,
        help="The path of training dataset")
    parser.add_argument(
        '--dict_path',
        type=str,
        default='./dict',
        help="The path of generated dict")
    parser.add_argument(
        '--freq',
        type=int,
        default=5,
        help="If the word count is less then freq, it will be removed from dict")
    parser.add_argument(
        '--is_local',
        action='store_true',
        required=False,
        default=False,
        help='Local train or not, (default: False)')

    return parser.parse_args()

def text_strip(text):
    return re.sub("[^a-z ]", "", text)

def build_Huffman(word_count, max_code_length):

    MAX_CODE_LENGTH = max_code_length
    sorted_by_freq = sorted(word_count.items(), key=lambda x: x[1])
    count = list()
    vocab_size = len(word_count)
    parent = [-1] * 2 * vocab_size
    code = [-1] * MAX_CODE_LENGTH
    point = [-1] * MAX_CODE_LENGTH
    binary = [-1] * 2 * vocab_size
    word_code_len = dict()
    word_code = dict()
    word_point = dict()
    i = 0
    for a in range(vocab_size):
        count.append(word_count[sorted_by_freq[a][0]])

    for a in range(vocab_size):
        word_point[sorted_by_freq[a][0]] = [-1] * MAX_CODE_LENGTH
        word_code[sorted_by_freq[a][0]] = [-1] * MAX_CODE_LENGTH

    for k in range(vocab_size):
        count.append(1e15)

    pos1 = vocab_size - 1
    pos2 = vocab_size
    min1i = 0
    min2i = 0
    b = 0

    for r in range(vocab_size):
        if pos1 >= 0:
            if count[pos1] < count[pos2]:
                min1i = pos1
                pos1 = pos1 - 1
            else:
                min1i = pos2
                pos2 = pos2 + 1
        else:
            min1i = pos2
            pos2 = pos2 + 1
        if pos1 >= 0:
            if count[pos1] < count[pos2]:
                min2i = pos1
                pos1 = pos1 - 1
            else:
                min2i = pos2
                pos2 = pos2 + 1
        else:
            min2i = pos2
            pos2 = pos2 + 1

        count[vocab_size + r] = count[min1i] + count[min2i]

        #record the parent of left and right child
        parent[min1i] = vocab_size + r
        parent[min2i] = vocab_size + r
        binary[min1i] = 0  #left branch has code 0
        binary[min2i] = 1  #right branch has code 1

    for a in range(vocab_size):
        b = a
        i = 0
        while True:
            code[i] = binary[b]
            point[i] = b
            i = i + 1
            b = parent[b]
            if b == vocab_size * 2 - 2:
                break

        word_code_len[sorted_by_freq[a][0]] = i
        word_point[sorted_by_freq[a][0]][0] = vocab_size - 2

        for k in range(i):
            word_code[sorted_by_freq[a][0]][i - k - 1] = code[k]

            # only non-leaf nodes will be count in
            if point[k] - vocab_size >= 0:
                word_point[sorted_by_freq[a][0]][i - k] = point[k] - vocab_size

    return word_point, word_code, word_code_len

def preprocess(data_path, dict_path, freq, is_local):
    """
    proprocess the data, generate dictionary and save into dict_path.
    :param data_path: the input data path.
    :param dict_path: the generated dict path. the data in dict is "word count"
    :param freq:
    :return:
    """
    # word to count
    word_count = dict()

    if is_local:
        for i in range(1, 100):
            with open(data_path + "/news.en-000{:0>2d}-of-00100".format(
                    i)) as f:
                for line in f:
                    line = line.lower()
                    line = text_strip(line)
                    words = line.split()
                    for item in words:
                        if item in word_count:
                            word_count[item] = word_count[item] + 1
                        else:
                            word_count[item] = 1
    item_to_remove = []
    for item in word_count:
        if word_count[item] <= freq:
            item_to_remove.append(item)
    for item in item_to_remove:
        del word_count[item]

    path_table, path_code, word_code_len = build_Huffman(word_count, 40)

    with open(dict_path, 'w+') as f:
        for k, v in word_count.items():
            f.write(str(k) + " " + str(v) + '\n')

    with open(dict_path + "_ptable", 'w+') as f2:
        for pk, pv in path_table.items():
            f2.write(str(pk) + ":" + ' '.join((str(x) for x in pv)) + '\n')

    with open(dict_path + "_pcode", 'w+') as f3:
        for pck, pcv in path_table.items():
            f3.write(str(pck) + ":" + ' '.join((str(x) for x in pcv)) + '\n')

if __name__ == "__main__":
    args = parse_args()
    preprocess(args.data_path, args.dict_path, args.freq, args.is_local)


from discord.commands import slash_command, SlashCommandGroup, Option
from discord.ext import commands as ext_commands
from discord import Permissions
import discord
import commands
import common
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from BadWolfBot import BadWolfBot

EMPTY_CHAR = '\u200b'

allowed = common.botAdmins | common.OWNERS

# REQUIRED_PERMISSIONS = [CommandPermission(int(id),2,True) for id in allowed]
GUILDS = [] if common.is_prod else common.SLASH_GUILDS

class AdminSlash(ext_commands.Cog):
    def __init__(self, bot: 'BadWolfBot'):
        self.bot = bot

    sha = SlashCommandGroup("sha", "Configure Table Bot's SHA-track mappings", guild_ids=GUILDS)

    @sha.command(name="add",
    description="Add a SHA-track mapping",
    )
    async def _add_sha(
        self,
        ctx: discord.ApplicationContext,
        sha: Option(str, "SHA to add"),
        track: Option(str, "Track name (paste the track name exactly as it appears)")
    ):
        command, message, this_bot, server_prefix, is_lounge = await self.bot.slash_interaction_pre_invoke(ctx)
        args = [command, sha, track]

        await commands.BotAdminCommands.add_sha_track(message, args)

    @sha.command(name="remove",
    description="Remove a SHA-track mapping",
    )
    async def _remove_sha(
        self,
        ctx: discord.ApplicationContext,
        sha: Option(str, "SHA to remove")
    ):
        command, message, this_bot, server_prefix, is_lounge = await self.bot.slash_interaction_pre_invoke(ctx)
        args = [command, sha]

        await commands.BotAdminCommands.remove_sha_track(message, args)

    blacklist = SlashCommandGroup("blacklist", "Configure Table Bot's blacklists", guild_ids=GUILDS)
    blacklist_user = blacklist.create_subgroup("user", "Configure Table Bot's blacklisted users", guild_ids=GUILDS)
    blacklist_word = blacklist.create_subgroup("word", "Configure Table Bot's blacklisted words", guild_ids=GUILDS)

    @blacklist_user.command(name="add",
    description="Blacklist a user from using Table Bot",
    )
    async def _add_user_blacklist(
        self,
        ctx: discord.ApplicationContext,
        user: Option(int, "User's Discord ID"),
        reason: Option(str, "Reason for blacklist")
    ):
        command, message, this_bot, server_prefix, is_lounge = await self.bot.slash_interaction_pre_invoke(ctx)
        args = [command, user, reason]

        await commands.BotAdminCommands.blacklist_user_command(message, args)

    @blacklist_user.command(name="remove",
    description="Remove a user from Table Bot's blacklisted users",
    )
    async def _remove_user_blacklist(
        self,
        ctx: discord.ApplicationContext,
        user: Option(int, "User's Discord ID")
    ):
        command, message, this_bot, server_prefix, is_lounge = await self.bot.slash_interaction_pre_invoke(ctx)
        args = [command, user]

        await commands.BotAdminCommands.blacklist_user_command(message, args)

    @blacklist_word.command(name="add",
    description="Blacklist a word from being used with Table Bot",
    )
    async def _add_word_blacklist(
        self,
        ctx: discord.ApplicationContext,
        word: Option(str, "Word to blacklist")
    ):
        command, message, _, _, _ = await self.bot.slash_interaction_pre_invoke(ctx)
        args = [command, word]

        await commands.BotAdminCommands.add_blacklisted_word_command(message, args)

    @blacklist_word.command(name="remove",
    description="Remove a blacklisted word",
    )
    async def _remove_word_blacklist(
        self,
        ctx: discord.ApplicationContext,
        word: Option(str, "Word to remove from blacklist")
    ):
        command, message, _, _, _ = await self.bot.slash_interaction_pre_invoke(ctx)
        args = [command, word]

        await commands.BotAdminCommands.remove_blacklisted_word_command(message, args)

    @slash_command(name='global_vr',
    description="Turn the /vr command on or off",
    guild_ids=GUILDS,
    )
    async def _global_vr(
        self,
        ctx: discord.ApplicationContext,
        status: Option(str, "on/off", choices=["on", "off"])
    ):
        command, message, _, _, _ = await self.bot.slash_interaction_pre_invoke(ctx)
        status = True if status == 'on' else False

        await commands.BotAdminCommands.global_vr_command(message, on=status)

def setup(bot):
    bot.add_cog(AdminSlash(bot))


from django.http import HttpResponse
from django.core.serializers import serialize
import json
from django.shortcuts import render
class HttpResponseMixin(object):
    def render_to_Http_response(self,json_data,status=200):
        return HttpResponse(json_data,content_type='application/json',status=status)

class SerializerMixin(object):
    def serializermix(self,dataval):
        json_data = serialize('json', [dataval,], fields={'emp_name',"emp_address" ,'emp_salary'})
        print("Ye json_data hai serializemixin se :",type(json_data))

        p_dict = json.loads(json_data)
        print(p_dict)
        print("Ye p_dict ka type :",type(p_dict))
        final_view = []
        for obj in p_dict:
            emp_dataview = obj['fields']
            print("Ye bahinchod hai :",emp_dataview)
            final_view.append(emp_dataview)
        json_data = json.dumps(final_view)
        return json_data


#!/usr/bin/env python3
import os
import base64
from keystore import save, load, config_reader

def test_keystore():
  compare_dir = './test/compare'

  print('Testing keystore saving...')

  save.save(keystorerc='.keystorerc', verbose=True)

  if not os.path.exists(compare_dir):
    os.makedirs(compare_dir)

  print('Testing keystore loading...')

  load.load(keystore='testkeystore', copyto='./test/compare', verbose=True)

  print('Comparing before and after...')

  cf = config_reader.read('.keystorerc')
  for f in cf['files']:
    if os.path.isdir(f):
      for dirpath, dirnames, filenames in os.walk(os.path.expanduser(f)):
        original_dir = dirpath
        for filename in filenames:
          original_path = os.path.join(original_dir, os.path.basename(filename))
          copied_path = os.path.join('./test/compare', os.path.basename(filename))
          with open(original_path, 'rb') as original, open(copied_path, 'rb') as copy:
            assert(original.read() == copy.read())

    elif os.path.isfile(f):
      original_path = os.path.join(original_dir, os.path.basename(f))
      copied_path = os.path.join('./test/compare', os.path.basename(f))
      with open(original_path, 'rb') as original, open(copied_path, 'rb') as copy:
        assert(original.read() == copy.read())

  print('Test successful.')

if __name__ == '__main__':
  test_keystore()


"""
N layers optimistic neural network
"""

import torch

class ThreeLayersNN(torch.nn.Module):

    def __init__(self, in_dim, out_dim, h_dim, activation='relu'):
        """
        :param in_dim: (int) input dimension
        :param out_dim: (int) output dimension
        """
        super(ThreeLayersNN, self).__init__()
        self.activation = activation

        # Initialize layers
        self.h_dim = h_dim
        self.linear1 = torch.nn.Linear(in_dim, h_dim[0])
        self.linear2 = torch.nn.Linear(h_dim[0], h_dim[1])
        self.linear3 = torch.nn.Linear(h_dim[1], out_dim)

    def forward(self, x):
        if self.activation == 'sigmoid':
            h = torch.sigmoid(self.linear1(x))
            h = torch.sigmoid(self.linear2(h))
            return self.linear3(h)
        elif self.activation == 'relu':
            h = self.linear1(x).clamp(min=0)
            h = self.linear2(h).clamp(min=0)
            return self.linear3(h)


from ast import literal_eval

from src.data_classes.data_class import DataClass
from src.data_classes.member import Member
from src.utils.constants import data_path

class Group(DataClass):
    def __init__(self):
        super().__init__()
        self.id: int = None
        self.name: str = None
        self.description: str = None
        self.participants: list[Member] = None

        self.data_table = data_path / "group.csv"
        self.converters = {
            'participants_ids': literal_eval
        }

    def from_dict(self, dictionary, count_of_recurs=5):
        self.name = dictionary['name']
        self.description = dictionary['description']

        self.participants = []
        if count_of_recurs > 0:
            for i in dictionary['participants_ids']:
                self.participants.append(Member().get_by_id(i, count_of_recurs - 1))

    def to_dict(self) -> dict:
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description,
            'participants_ids': [i.id for i in self.participants]
        }


# This code have been programmed by Christian Blad, Sajuran and Søren Koch aka. Group VT4103A
# The reinforcement learning framework is based on the original code from udemy course https://www.udemy.com/artificial-intelligence-az/
# From Aalborg University

# Importing the libraries
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import os
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

# Making the body
class SoftmaxBody(nn.Module):

    def __init__(self, T):
        super(SoftmaxBody, self).__init__()
        self.T = T

    def forward(self, outputs):
        """Returns action randomly drawn from a distribution of Q-values where
        state is send through Q-network"""
        probs = F.softmax(outputs * self.T)
        actions = probs.multinomial()
        return actions

# Making the AI
class AI:

    def __init__(self, brain, body):
        self.brain = brain
        self.body = body

    def __call__(self, inputs):
        input = Variable(torch.from_numpy(np.array(inputs, dtype = np.float32)))
        output = self.brain(input)
        actions = self.body(output)
        return actions.data.numpy()

class Training:
    def __init__(self, params, ai, eligibility_memory, n_steps, dqn):
        self.params = params
        self.nb_epochs = 0
        self.optimizer = optim.Adam(ai.brain.parameters(), params.lr)
        self.loss = nn.MSELoss()
        self.eligibility_memory = eligibility_memory
        self.ai = ai
        self.n_steps = n_steps
        self.reward_window = []
        self.scores = []

    def update(self):
        """This function update/links the learning, experience list, action selector, Q-network and the reward window"""
        # Run steps
        self.eligibility_memory.run_steps(1)

        # Learn when it have enough in buffer and every 20 times inorder not to have a to high execution time of iteration
        if  len(self.eligibility_memory.buffer) > self.params.ER_batch_size and  len(self.eligibility_memory.buffer) % 100 == 0 and self.params.learning_mode == 1:
            self.learn()

        # Make window for brain plot
        self.reward_window.append(self.n_steps.rewardski)
        if len(self.reward_window) > 1000:
            del self.reward_window[0]

        #update score
        self.scores.append(self.score())

    def score(self):
        """Returns sum of rewards"""
        return sum(self.reward_window)/(len(self.reward_window)+1.)

	# Saving experience
    def save_plot(self, path, name):
        """Saving training curves tracking the agent score to the path 'saves/plot' with the specified name specified in parse argument in main"""
        plt.plot(self.scores, color='red')
        plt.ylabel('reward score per iterations')
        plt.xlabel('Training iterations')
        plt.title('Training curves tracking the agent score')
        plt.savefig(os.path.join(path, str(name) + '.pdf'), format='pdf')

    def eligibility_trace(self, batch):
        """Perform eligibility trace"""
        inputs = []
        targets = []
        for series in batch:
            input = Variable(torch.from_numpy(np.array([series[0].state, series[-1].state], dtype = np.float32)))
            output = self.ai.brain(input)
            cumul_reward = output[1].data.max()
            for step in reversed(series[:-1]):
                cumul_reward = step.reward + self.params.gamma * cumul_reward
            state = series[0].state
            target = output[0].data
            target[series[0].action] = cumul_reward
            inputs.append(state)
            targets.append(target)
        return torch.from_numpy(np.array(inputs, dtype = np.float32)), torch.stack(targets)

    def learn(self):
        """Updating weights of Q-network depending on the loss calculated from the predicted Q-values
        from the Q-network and the target Q-values(gamma*Qp + r)"""
        for batch in self.eligibility_memory.sample_batch(self.params.ER_batch_size):
            inputs, targets = self.eligibility_trace(batch)
            inputs, targets = Variable(inputs), Variable(targets)
            predictions = self.ai.brain(inputs)
            loss_error = self.loss(predictions, targets)
            self.optimizer.zero_grad()
            loss_error.backward()
            self.optimizer.step()
        rewards_steps = self.n_steps.rewards_steps()

    def save_brain(self, path, name):
        torch.save({'state_dict': self.ai.brain.state_dict(),
                    'optimizer' : self.optimizer.state_dict(),
                   }, os.path.join(path, str(name) + '.pth'))

    def load_brain(self, path, name):
        if os.path.isfile(os.path.join(path, str(name) + '.pth')):
            print("=> loading brain... ")
            checkpoint = torch.load(os.path.join(path, str(name) + '.pth'))
            self.ai.brain.load_state_dict(checkpoint['state_dict'])
            self.optimizer.load_state_dict(checkpoint['optimizer'])
            print("Loading is complete !")
        else:
            print("no brain found...")
            exit(1)