# 77. Write a Python program to decode a run-length encoded given list. Go to the editor
# Original encoded list:
# [[2, 1], 2, 3, [2, 4], 5, 1]
a=[[2,1],2,3,[2,4],5]
i=0
b=[]
while i<len(a):
    if type(a[i])==list:
        j=1
        while j>=0:
            b.append(a[i][1])
            j=j-1
    else:
        b.append(a[i])
    i=i+1
print(b)

# a=[0,1,0,1,1,0]
# i=0
# k=[]
# while i<len(a):
#     j=0
#     c=0
#     b=a[:i]
#     while j<len(b):
#         if a[j]==0:
#             c=c+1
#         j=j+1
#         print(c)
#     k.append(c)
#     i=i+1
# print(k)


# Single Number II
# Given 3*n + 1 numbers, every numbers occurs triple times except one, find it.
#
# Example
# Given [1,1,2,3,3,3,2,2,4,1] return 4
#
# Challenge
# One-pass, constant extra space.
#

class Solution:
    """
	@param A : An integer array
	@return : An integer
    """
    def singleNumberII(self, A):
        # write your code here
        if A == None or len(A) == 0: return -1

        # Get a list of all powers of 3.
        # 20 should be enough for any number less than 2^32
        power3 = [1 for i in range(20)]
        for i in range(1, 20):
            power3[i] = 3 * power3[i - 1]

        # Convert any in A into ternary mode
        bit = [0 for i in range(20)]
        for i in range(20):
            for j in range(len(A)):
                bit[i] = bit[i] + ((A[j] / power3[i]) % 3)

        # The number left is what we want
        result = 0
        for i in range(20):
            result += (bit[i] % 3) * power3[i]

        return result

09-High-Frequency/06 Single Number II.py


import sys

class DemoWidth:

    def __init__(self, filename: str, mode: str):
        """DemoWidth Class Constructor to initialize the object.

        Input Arguments: filename must be str, filename must be str
        """
        self.filename = filename
        self.mode = mode

    def __enter__(self):
        print('Inside __enter__')
        self.file_rd = open(self.filename, self.mode)
        return self.file_rd

    def __exit__(self, exception_type, exception_value, traceback):
        print('Inside __enter__')
        print(exception_value)
        self.file_rd.close()

with DemoWidth("random.txt", 'w' ) as dw:
    for increment in range(1,11):
        dw.write(f'Counter = {increment}\n')


from bottle import template, route, run, request, get, post
from tinydb import TinyDB, Query
import backend
from datetime import datetime

db = TinyDB('./database.json')
players = db.table("players")
matches = db.table('matches')

@route('/classifica')
def classifica():
    page = ''
    page += ''
    page += ''
    page += '
Classifica

'
    for voice in players.all()[0].keys():
        header = '' + voice + '	'
        page += header
    page += '
'
    for player in players:
        element = '
' + player['name'] + '	' + str(player['elo']) + '
'
        page += element
    page += '
'
    return page

@get('/newmatch')
def newmatch():
    page = '<form action="/newmatch" method="POST">'

    date = '
<input type="date" name="date" value='+datetime.now().strftime("%Y-%m-%d") + '></input>
'
    page += date

    player1 = '
<select name="player1">'
    for player in players.all():
        option = '<option value=' + player['name'] + '>' + player['name'] + '</option>'
        player1 += option
    player1 += '</select>'
    page += player1

    player2 = '<select name="player2">'
    for player in players.all():
        option = '<option value=' + player['name'] + '>' + player['name'] + '</option>'
        player2 += option
    player2 += '</select>
'
    page += player2

    win1 = '
<input type="radio" name="res1" value=1 label="giocatore 1"/>'
    win2 = '<input type="radio" name="res1" value=0 label="giocatore 2"/>
'
    page += win1 + win2
    page += '<input type="submit" value="INVIA">'
    page += '</form>'

    page += matches_table()

    return (page)

@post('/newmatch')
def newmatch():
    date = request.forms.get('date')
    player1 = request.forms.get('player1')
    player2 = request.forms.get('player2')
    elo1 = players.search(Query().name == player1)[0]['elo']
    elo2 = players.search(Query().name == player2)[0]['elo']
    exp1 = backend.expected_result(elo1, elo2)
    exp2 = backend.expected_result(elo2, elo1)
    res1 = int(request.forms.get('res1'))
    # res2 should be 1 when res1 is 0 and viceversa
    res2 = 1 - res1
    backend.new_match(date, player1, player2,elo1,elo2,exp1,exp2,res1,res2)
    page = ('
Match added
New match')
    page += matches_table()
    return page

@route('/hello/<name>')
def saluto(name='Stranger'):
    return template('Hello {{name}}, how are you?', name=name)

def matches_table():
    today = datetime.now().strftime("%Y-%m-%d")
    today_matches = backend.get_today_matches(today)
    table = '

Giocatore 1	Giocatore 2	Risultato
'
    for match in today_matches:
        row = '
' + match['player1'] + '	' + match['player2'] + '	' + str(match['res1']) + ' - ' + str(match['res2']) + '
'
        table += row
    table += '
'
    return table

run(host='localhost',port=1990, debug=True)

### https://bottlepy.org/docs/dev/tutorial.html#installation


# mais listas

lista = ['glauber']

def cadastra(variavel):
    continua = True
    while continua:
        nome = input('Informe o nome: ')
        variavel.insert(0,nome)
        if (input('Deseja continuar?: ') == 'sim'):
            continua = True
        else: continua = False

cadastra(lista)


def sum(list):
    total=0
    for i in range(len(list)):
        print(list[i],'+')
        total+=list[i]
    print('=',total)

list=[15,25,35,65]
sum(list)

a=100
def setNumber():
    a=10
    print(a)

setNumber()
print(a)


# Advent of Code: Day 17
__author__ = "Matteo Golin"

from typing import Literal, TypeAlias, Iterable

# All rocks relative to bottom leftmost edge
Coordinate: TypeAlias = tuple[int, int]
Rock: TypeAlias = set[Coordinate]
JetStream: TypeAlias = list[Literal[1, -1]]

HORIZONTAL: Rock = {(0, 0), (1, 0), (2, 0), (3, 0)}
PLUS: Rock = {(0, 1), (1, 0), (1, 1), (1, 2), (2, 1)}
L: Rock = {(0, 0), (1, 0), (2, 0), (2, 1), (2, 2)}
VERTICAL: Rock = {(0, 0), (0, 1), (0, 2), (0, 3)}
CUBE: Rock = {(0, 0), (0, 1), (1, 0), (1, 1)}
ROCKS: list[Rock] = [HORIZONTAL, PLUS, L, VERTICAL, CUBE]

CHAMBER_WIDTH: int = 7
LFT_OFF: int = 2
BTM_OFF: int = 3
ROCKS_TO_FALL_1: int = 2022
ROCKS_TO_FALL_2: int = 1000000000000

def translate_coord(coord: Coordinate, offset: Coordinate) -> Coordinate:
    """Returns the translated coordinate."""
    return (coord[0] + offset[0], coord[1] + offset[1])

def translate(rock: Iterable[Coordinate], offset: Coordinate) -> Rock:
    """Returns the translated rock."""
    return set(translate_coord(c, offset) for c in rock)

def height(occupied: set[Coordinate]) -> int:
    """Returns the height of the rock tower so far."""
    return max(occupied, key=lambda x: x[1])[1]

def drop_rock(
    cur_rock: int, cur_jet: int, jet_stream: JetStream, occupied: set[Coordinate], fallen: dict[str, int]
) -> int:
    """
    Does one dropped rock cycle and returns the current jet index. If a cycle is detected, then -1 is returned.
    """

    # Translate rock away from side and highest rock to start
    rock = translate(ROCKS[cur_rock % len(ROCKS)], (LFT_OFF, height(occupied) + BTM_OFF + 1))
    fall_pattern = f"{cur_rock % len(ROCKS)}"
    while True:
        # Push rock first
        push = jet_stream[cur_jet]
        translated_rock = translate(rock, (push, 0))

        # Only push rock if it does not hit another rock and does not exceed walls
        if not occupied & translated_rock and all(0 <= x < CHAMBER_WIDTH for x, _ in translated_rock):
            fall_pattern += ">" if push == 1 else "<"
            rock = translated_rock
        else:
            fall_pattern += "x"

        # Translate rock downward
        translated_rock = translate(rock, (0, -1))
        if occupied & translated_rock:  # If the rock will intersect with another...
            occupied.update(rock)  # Record rock spaces as occupied
            if fall_pattern in fallen:
                print(fall_pattern)
                fallen["cycle start"] = fallen[fall_pattern]
                return -1

            fallen[fall_pattern] = cur_rock
            return (cur_jet + 1) % len(jet_stream)  # Return next jet

        fall_pattern += "v"
        rock = translated_rock

        cur_jet = (cur_jet + 1) % len(jet_stream)

def draw_image(occupied: set[Coordinate]) -> None:
    """Prints out a visualization of the rock tower."""
    max_height = height(occupied)
    image = [["." for _ in range(CHAMBER_WIDTH)] for _ in range(max_height + BTM_OFF)]

    for x, y in occupied:
        image[y][x] = "#"

    print("-" * (CHAMBER_WIDTH + 2))
    for row in reversed(image):
        print("|", end="")
        for col in row:
            print(col, end="")
        print("|", end="")
        print()
    print("-" * (CHAMBER_WIDTH + 2))

def height_after(rocks: int) -> int:
    """Returns the height of the rock tower after the passed number of rocks have fallen."""
    cur_jet = 0
    total_rocks = 0
    occupied: set[Coordinate] = set((_, 0) for _ in range(CHAMBER_WIDTH))
    fall_patterns = dict()

    while total_rocks < rocks:
        cur_jet = drop_rock(total_rocks, cur_jet, jet_stream, occupied, fall_patterns)
        if cur_jet == -1:  # Cycle detected
            break
        total_rocks += 1

    if rocks == 5 or rocks == 20:
        draw_image(occupied)

    if cur_jet == -1:
        period_len = total_rocks - fall_patterns["cycle start"]
        print(f"Cycle detected from rock {fall_patterns['cycle start']} to rock {total_rocks}.")
        height_after(fall_patterns["cycle start"])
        height_after(total_rocks)
        print(f"Cycle has period of {period_len}")
        current_height = height(occupied)
        print(f"The current height is {current_height}")
        period_height = current_height - height_after(fall_patterns["cycle start"])
        print(f"The height of each period is {period_height}")
        periods, remainder = divmod(rocks - total_rocks, period_len)

        print(periods, remainder)
        return current_height + (periods * period_height) + height_after(remainder)

    return height(occupied)

# Main
if __name__ == "__main__":
    # Parse input
    jet_stream: JetStream = []
    with open("./example.txt") as file:
        jet_stream = list(map(lambda x: 1 if x == ">" else -1, file.read().strip()))

    # Part 1: How tall is the tower after 2022 rocks have fallen?
    h = height_after(ROCKS_TO_FALL_1)
    print(f"The tower of rocks will be {h} units tall after {ROCKS_TO_FALL_1} rocks have stopped falling.")

    # Part 2: How tall is the tower after 1000000000000 rocks have fallen.
    print(f"The tower of rocks will be {h} units tall after {ROCKS_TO_FALL_2} rocks have stopped falling.")


from django.conf.urls import url
from apps.crud_perins.views import periodoCreate, periodoList, periodoDelete, periodoUpdate, periodoShow, search, \
    inscripCreate, inscripList, inscripDelete, inscripUpdate, inscripShow, searchT

from apps.crud_perins.views import alumnosCreate, alumnosList, alumnosDelete, alumnosUpdate, alumnoShow, searchI, \
    estadoCreate,estadoDelete,estadoList,estadoShow,estadoUpdate, search_I

from apps.crud_perins.views import usuarioCreate, usuarioList, usuarioDelete, usuarioUpdate, usuarioShow, searchJ, \
    areaCreate,areaList,areaDelete,areaUpdate,areaShow, search_J

from apps.crud_perins.views import organigramaCreate, organigramaList, organigrmaDelete, organigramaUpdate, organigramaShow, searchV, \
    puestoCreate, puestoList, puestoDelete, puestoUpdate, puestoShow, search_V

from apps.crud_perins.views import grupoCreate, grupoList, grupoDelete, grupoUpdate, grupoShow, gruposearch, \
    muniCreate, muniList, muniDelete, muniUpdate, muniShow, munisearch

from apps.crud_perins.views import actividadCreate, actividadList, actividadDelete, actividadUpdate, actividadShow, \
    rolCreate, rolList, rolDelete, rolUpdate, rolShow, searchL, search_L

from apps.crud_perins.views import carreraCreate, carreraList, carreraDelete, carreraUpdate, carreraShow, searchM, \
    localidadCreate, localidadList, localidadDelete, localidadShow, localidadUpdate, buscarM

from apps.crud_perins.views import coordinadorCreate, coordinadorList, coordinadorDelete, coordinadorUpdate, coordinadorShow, \
    search_c, instructorCreate, instructorList, instructorDelete, instructorUpdate, instructorShow, search_i
urlpatterns = [
#-----------------------------tablas de joan-------------------------------------------
    url(r'^nuevo/', periodoCreate.as_view(), name='periodo_crear'),
    url(r'^listar/', periodoList.as_view(), name='periodos_listar'),
    url(r'^eliminar/(?P<pk>\d+)/$', periodoDelete.as_view(), name='periodo_eliminar'),
    url(r'^editar/(?P<pk>\d+)/$', periodoUpdate.as_view(), name='periodo_editar'),
    url(r'^mostrar/(?P<pk>\d+)/$', periodoShow.as_view(), name='periodo_mostrar'),
    url(r'^buscar/$', search, name='periodo_buscar'),

    url(r'^Nuevo/', inscripCreate.as_view(), name='inscrip_Crear'),
    url(r'^Listar/', inscripList.as_view(), name='inscrips_Listar'),
    url(r'^Eliminar/(?P<pk>\d+)/$', inscripDelete.as_view(), name='inscrip_Eliminar'),
    url(r'^Editar/(?P<pk>\d+)/$', inscripUpdate.as_view(), name='inscrip_Editar'),
    url(r'^Mostrar/(?P<pk>\d+)/$', inscripShow.as_view(), name='inscrip_Mostrar'),
    url(r'^Buscar/$', searchT, name='inscrip_Buscar'),
#--------------------------Tablas de Ismael--------------------------------------------
    url(r'^nuevoI/', alumnosCreate.as_view(), name='alumno_crear'),
    url(r'^listarI/', alumnosList.as_view(), name='alumnos_listar'),
    url(r'^eliminarI/(?P<pk>\d+)/$', alumnosDelete.as_view(), name='alumno_eliminar'),
    url(r'^modificarI/(?P<pk>\d+)/$', alumnosUpdate.as_view(), name='alumno_editar'),
    url(r'^mostrarI/(?P<pk>\d+)/$', alumnoShow.as_view(), name='alumno_mostrar'),
    url(r'^buscarI/$', searchI, name='alumno_buscar'),
    #aqui inician las urls de estado
    url(r'^nuevo_e/', estadoCreate.as_view(), name='estado_crea'),
    url(r'^listar_e/', estadoList.as_view(), name='estado_lista'),
    url(r'^editar_e/(?P<pk>\d+)/$', estadoUpdate.as_view(), name='estado_edita'),
    url(r'^borrar_e/(?P<pk>\d+)/$', estadoDelete.as_view(), name='estado_borrar'),
    url(r'^ver_e/(?P<pk>\d+)/$', estadoShow.as_view(), name='estado_ver'),
    url(r'^buscar_e/$', search_I, name='estado_busca'),
#----------------------url javier-----------------------------------------------------
    url(r'^nuevoJ/', usuarioCreate.as_view(), name='usuario_crear'),
    url(r'^listarJ/', usuarioList.as_view(), name='usuario_listar'),
    url(r'^eliminarJ/(?P<pk>\d+)/$', usuarioDelete.as_view(), name='usuario_eliminar'),
    url(r'^editarJ/(?P<pk>\d+)/$', usuarioUpdate.as_view(), name='usuario_editar'),
    url(r'^mostrarJ/(?P<pk>\d+)/$', usuarioShow.as_view(), name='usuario_mostrar'),
    url(r'^buscarJ/$', searchJ, name='usuario_buscar'),

    url(r'^nuevos_J/', areaCreate.as_view(), name='area_crea'),
    url(r'^lista_J/', areaList.as_view(), name='area_lista'),
    url(r'^elimina_J/(?P<pk>\d+)/$', areaDelete.as_view(), name='area_elimina'),
    url(r'^edita_J/(?P<pk>\d+)/$', areaUpdate.as_view(), name='area_edita'),
    url(r'^muestra_J/(?P<pk>\d+)/$', areaShow.as_view(), name='area_muestra'),
    url(r'^buscador_J/$', search_J, name='area_busca'),

#------------------------url de ivan--------------------------------
    url(r'^nuevoV/', organigramaCreate.as_view(), name='organigrama_crear'),
    url(r'^listarV/', organigramaList.as_view(), name='organigrama_listar'),
    url(r'^eliminarV/(?P<pk>\d+)/$', organigrmaDelete.as_view(), name='organigrama_eliminar'),
    url(r'^modificarV/(?P<pk>\d+)/$', organigramaUpdate.as_view(), name='organigrama_editar'),
    url(r'^mostrarV/(?P<pk>\d+)/$', organigramaShow.as_view(), name='organigrama_mostrar'),
    url(r'^buscarV/', searchV, name='organigrama_buscar'),

    url(r'^nuevos_V/', puestoCreate.as_view(), name='puesto_crear'),
    url(r'^listarr_V/', puestoList.as_view(), name='puesto_listar'),
    url(r'^eliminarr_V/(?P<pk>\d+)/$', puestoDelete.as_view(), name='puesto_eliminar'),
    url(r'^modificarr_V/(?P<pk>\d+)/$', puestoUpdate.as_view(), name='puesto_editar'),
    url(r'^mostrarr_V/(?P<pk>\d+)/$', puestoShow.as_view(), name='puesto_mostrar'),
    url(r'^search_V/$', search_V, name='puesto_search'),

#-------------------------url karyn-----------------------------------------
    url(r'^nuevok/', grupoCreate.as_view(), name='grupo_crear'),
    url(r'^listark/', grupoList.as_view(), name='grupo_listar'),
    url(r'^eliminark/(?P<pk>\d+)/$', grupoDelete.as_view(), name='grupo_eliminar'),
    url(r'^editark/(?P<pk>\d+)/$', grupoUpdate.as_view(), name='grupo_editar'),
    url(r'^mostrark/(?P<pk>\d+)/$', grupoShow.as_view(), name='grupo_mostrar'),
    url(r'^buscark/$', gruposearch, name='grupo_buscar'),

    url(r'^Nuevo_k/', muniCreate.as_view(), name='muni_crear'),
    url(r'^Listar_k/', muniList.as_view(), name='muni_listar'),
    url(r'^Eliminar_k/(?P<pk>\d+)/$', muniDelete.as_view(), name='muni_eliminar'),
    url(r'^Editar_k/(?P<pk>\d+)/$', muniUpdate.as_view(), name='muni_editar'),
    url(r'^Mostrar_k/(?P<pk>\d+)/$', muniShow.as_view(), name='muni_mostrar'),
    url(r'^Buscar_k/$', munisearch, name='muni_buscar'),

#--------------------url litzy---------------------------------------------
    url(r'^nuevoL/', actividadCreate.as_view(), name='actividad_crear'),
    url(r'^listarL/', actividadList.as_view(), name='actividad_listar'),
    url(r'^eliminarL/(?P<pk>\d+)/$', actividadDelete.as_view(), name='actividad_eliminar'),
    url(r'^modificarL/(?P<pk>\d+)/$', actividadUpdate.as_view(), name='actividad_editar'),
    url(r'^mostrarL/(?P<pk>\d+)/$', actividadShow.as_view(), name='actividad_mostrar'),
    url(r'^buscarL/', searchL, name='actividad_buscar'),

    url(r'^nuevos_L/', rolCreate.as_view(), name='rol_crear'),
    url(r'^listarr_L/', rolList.as_view(), name='rol_listar'),
    url(r'^eliminarr_L/(?P<pk>\d+)/$', rolDelete.as_view(), name='rol_eliminar'),
    url(r'^modificarr_L/(?P<pk>\d+)/$', rolUpdate.as_view(), name='rol_editar'),
    url(r'^mostrarr_L/(?P<pk>\d+)/$', rolShow.as_view(), name='rol_mostrar'),
    url(r'^search_L/$', search_L, name='rol_search'),

#--------------------url may----------------------------
    url(r'^nuevoM/', carreraCreate.as_view(), name='carrera_crear'),
    url(r'^listarM/', carreraList.as_view(), name='carrera_listar'),
    url(r'^eliminarM/(?P<pk>\d+)/$', carreraDelete.as_view(), name='carrera_eliminar'),
    url(r'^modificarM/(?P<pk>\d+)/$', carreraUpdate.as_view(), name='carrera_editar'),
    url(r'^mostrarM/(?P<pk>\d+)/$', carreraShow.as_view(), name='carrera_mostrar'),
    url(r'^searchM/$', searchM, name='carrera_buscar'),

    url(r'^nuevosM/', localidadCreate.as_view(), name='localidad_crear'),
    url(r'^listasM/', localidadList.as_view(), name='localidad_listar'),
    url(r'^eliminasM/(?P<pk>\d+)/$', localidadDelete.as_view(), name='localidad_eliminar'),
    url(r'^modificasM/(?P<pk>\d+)/$', localidadUpdate.as_view(), name='localidad_editar'),
    url(r'^muestrasM/(?P<pk>\d+)/$', localidadShow.as_view(), name='localidad_mostrar'),
    url(r'^buscasM/$', buscarM, name='localidad_buscar'),

#--------------------url nubia-------------------------------
  url(r'^nuevoN/', coordinadorCreate.as_view(), name='coordina_crear'),
    url(r'^listarN/', coordinadorList.as_view(), name='coordinar_listar'),
    url(r'^eliminarN/(?P<pk>\d+)/$', coordinadorDelete.as_view(), name='coordina_eliminar'),
    url(r'^editarN/(?P<pk>\d+)/$', coordinadorUpdate.as_view(), name='coordina_editar'),
    url(r'^mostrarN/(?P<pk>\d+)/$', coordinadorShow.as_view(), name='coordina_mostrar'),
    url (r'^buscarN/$', search_c, name='coordina_buscar'),
#aqui inician las urls del crud instructor
    url(r'^nuevosN/', instructorCreate.as_view(), name='instruccion_crear'),
    url(r'^listaN/', instructorList.as_view(), name='instrucciones_listar'),
    url(r'^eliminaN/(?P<pk>\d+)/$', instructorDelete.as_view(), name='instruccion_eliminar'),
    url(r'^editaN/(?P<pk>\d+)/$', instructorUpdate.as_view(), name='instruccion_editar'),
    url(r'^verN/(?P<pk>\d+)/$', instructorShow.as_view(), name='instruccion_mostrar'),
    url(r'^buscaN/$', search_i, name='instruccion_buscar'),
]


# -*- coding: utf-8 -*-
### 爆后台路径补充版：通过yourdomain/data/mysql_error_trace.inc猜测类似后台地址。
import re
import os
import requests
from common import utils

is_ip = False
interval = 3600

def my_requests(url, method='get', timeout=15, try_count=3, **args):
    for n in range(try_count):
        try:
            global is_ip, proxies
            if (is_ip):
                response = requests.request(method=method, url=url, headers=utils.get_headers(), proxies=proxies,timeout=timeout,**args)
            else:
                response = requests.request(method=method, url=url, headers=utils.get_headers(), timeout=timeout, **args)
            response.encoding = 'utf-8'
            if response.status_code == 200:
                if "antispider" in response.url:
                    #is_ip = True
                    proxies = getip()
                    print("需要切换IP自动验证:",proxies)
                    continue
                if "passport" in response.url:
                    #baidu_img.识别百度验证码()
                    continue
                return response
            else:
                print(url+'---request err:'+ str(response.status_code))
                return None
        except Exception as e:
            print(e)
            #is_ip = True
            proxies = getip()
            print("IP自动验证:", proxies)
            continue
        print("请求url:%s失败，剩余重试次数：%d" % (url, n))

def getip(method='get', timeout=15, try_count=3, **args):
    url = ""
    response = requests.request(method=method, url=url, headers=utils.get_headers(), timeout=timeout, **args)
    if response.status_code == 200:
        proxies = {'https': response.text.replace('\r\n', '')}
        return proxies

class Unit(object):
    def getfilelist(self, filepath):
        try:
            #parentDirPath = os.path.abspath(os.path.dirname(os.path.split(os.path.realpath(__file__))[0]))
            #path = parentDirPath + filepath
            with open(filepath, "r", encoding='UTF-8') as f:  # 打开文件
                data = f.read().split('\n')
                if len(data) > 0:
                    print('导入数据:'+str(len(data)))
                    return data
                else:
                    print('load txt err')
                    return None
        except Exception as e:
            print('not fond file or err')
            return None

    def create_str_to_txt(self,date, str_data):
        try:
            path_file_name = date
            if not os.path.exists(path_file_name):
                with open(path_file_name, "w") as f:
                    print(f)
            with open(path_file_name, "a") as f:
                f.write(str_data)
        except:
            print('e')

if __name__ == '__main__':
    try:
        filename = "注册扫描结果"
        WordList = Unit().getfilelist('./res/' + filename)
        for txt in WordList:
            try:
                arrary =[]
                words = ['member','plus','m']
                domain_url = txt.replace('\r','')
                select_url = domain_url+"/data/mysql_error_trace.inc"
                response = my_requests(url=select_url)
                if response:
                    response_txt = response.text
                    utl_list = re.findall('(?=Page:).*', response_txt)
                    for last_url in utl_list:
                        last_url = last_url.replace('\r','').replace('Page:','').replace(' ','')
                        last_url = last_url[0:last_url.rfind('?')]
                        if last_url.count('/') >= 2:
                            s = last_url.split('/')[1]
                            if s not in words and s not in arrary and s !='':
                                arrary.append(s)
                                s_url = domain_url + '/' + s + '/'
                                print('try:'+ s_url)
                                response2 = my_requests(url=s_url)
                                if response2:
                                    try:
                                        response2.encoding = response2.apparent_encoding
                                        response2_txt = response2.text
                                        title = re.findall('<title>.*</title>', response2_txt)[0]
                                        if '页面未找到' in title:
                                            continue
                                        Unit().create_str_to_txt('./res/批量爆破织梦后台_成功_补充版.txt',domain_url + '\n' + s_url + '\n'+title + '\n\n')
                                        print(title+'  :  '+ s_url)
                                    except:
                                        continue
                    if len(arrary) == 0:
                        print(domain_url + '未找到相对于目录')
            except:
                continue

    except Exception as e:
        print(e)
        pass

织梦/爆路径补充版.py


import sys
import os
import importlib

import bpy

from .. import blender_time as b_time
from .. import caption as c
importlib.reload(b_time)
importlib.reload(c)

def import_cc(context, text, accent, pitch, language):
    print(".txt file detected")
    captions = []
    line_counter = 0
    cc_text = ""
    cc_type = 1

    for line in text:
        if len(line) > 0:
            if line[0:2].find('>>') != -1: # person
                cc_type = 1
                cc_name = line[2:len(line)].split(":")[0]
                text_tmp = line[2:len(line)].split(":")[1]
                cc_text = text_tmp[1:len(text_tmp)]

            elif line[0] == '[': # event
                cc_type = 2
                cc_name = ''
                cc_text = line.split('[')[1].split(']')[0]

            else: # plain text line

                if len(cc_text) == 0: # no previous line
                    cc_name = "noname"
                    cc_type = 0
                    cc_text = line

                else: # second line
                    cc_text += " " + line

        else: # len(line == 0) equivalent of '\n'
            captions.append(c.Caption(context, cc_type, cc_name, cc_text, b_time.Time(-1, -1, -1, -1), b_time.Time(-1, -1, -1, -1), accent, 1, pitch, language))
            cc_text = ""

        line_counter += 1
        if line_counter == len(text): # on exit
            if len(cc_text) > 0:
                captions.append(c.Caption(context, cc_type, cc_name, cc_text, b_time.Time(-1, -1, -1, -1), b_time.Time(-1, -1, -1, -1), accent, 1, pitch, language))

    return(captions)


class Board:

    """
    Representation of a bingo board

    :param id: The board id
    :param str input: The raw board data
    """

    def __init__(self, id, input: str) -> None:
        self.id = id
        self.input = input
        self.lines = self.get_lines()
        self.columns = [self.get_column(i) for i in range(len(self.lines[0]))]

    def __getitem__(self, key: int) -> list[int]:
        return self.lines[key]

    def get_lines(self) -> list[list[int]]:
        """
        Extracts lines from the raw board data and converts values to integers

        :return: The board lines
        """
        lines = []
        for line in self.input.split("\n"):
            tab = []
            for i in range(0, len(line), 3):
                tab.append(int(line[i:i+3]))
            lines.append(tab)
        return lines

    def get_column(self, index: int) -> list[list[int]]:
        """
        Extracts columns from the board lines

        :return: The board columns
        """
        return [line[index] for line in self.lines]

    def is_winner(self, numbers: list[int], turn: int) -> bool:
        """
        Computes wether or not the board is a winner at a specific turn according to problem description

        :return: True if the board is a winner
        """
        res = False
        numbers_at_turn = numbers[:turn]

        for line in self.lines:
            in_numbers = [n in numbers_at_turn for n in line]
            if all(in_numbers):
                res = True
        for column in self.columns:
            in_numbers = [n in numbers_at_turn for n in column]
            if all(in_numbers):
                res = True

        return res

    def get_score(self, numbers: list[int], turn: int) -> int:
        """
        Computes the board score at a specific turn

        :return: The board score
        """
        sum_unmarked = 0
        numbers_at_turn = numbers[:turn]

        for line in self.lines:
            sum_unmarked += sum([n for n in line if n not in numbers_at_turn])

        return sum_unmarked * numbers[turn - 1]

class Bingo:
    """
    Representation of a bingo game

    :param str input: The bingo game data, including boards and drawn numbers in order
    """

    def __init__(self, input: str) -> None:
        self.input = input
        self.numbers = self.get_numbers()
        self.boards = self.get_boards()

    def __getitem__(self, key: int) -> Board:
        return self.boards[key]

    def get_numbers(self) -> list[int]:
        """
        Extracts drawn numbers from the game data

        :return: The drawn numbers in order
        """
        return [int(x) for x in self.input.split("\n\n")[0].split(",")]

    def get_boards(self) -> list[Board]:
        """
        Extracts bingo boards from the game data

        :return: The bingo boards
        """
        boards = self.input.split("\n\n")[1:]
        return [Board(i, board) for i, board in enumerate(boards)]

    def get_winners(self) -> list[tuple[int, int, int]]:
        """
        Simulates the bingo game and computes the winners in order

        :return: The winners in order, along with the turn which they won at and their final score
        """
        turns = len(self.numbers)
        winners = []

        for turn in range(1, turns):
            nums = self.numbers[:turn]
            boards = [board for board in self.boards if board.id not in [
                w[1] for w in winners]]

            for board in boards:
                if board.is_winner(self.numbers, turn):
                    winner = (self.numbers[turn-1], board.id,
                              board.get_score(self.numbers, turn))
                    winners.append(winner)

        return winners

def main():
    INPUT_TEXT = open("input.txt").read()
    bingo_subsystem = Bingo(INPUT_TEXT)
    winners = bingo_subsystem.get_winners()

    print("Part1:", winners[0])
    print("Part2:", winners[-1])

if __name__ == "__main__":
    main()


import numpy as np
import talib as TA
import pandas as pd
import copy

class QuantCenter():
    def __init__(self, exchange):
        self.init_timestamp = time.time()
        self.exchange = exchange
        self.name = self.exchange.GetName()
        self.currency = self.exchange.GetCurrency()

    def update_account(self):
        self.Balance = None
        self.Amount = None
        self.FrozenBalance = None
        self.FrozenStocks = None

        try:
            self.account = self.exchange.GetAccount()

            self.Balance = self.account['Balance']
            self.Amount = self.account['Stocks']
            self.FrozenBalance = self.account['FrozenBalance']
            self.FrozenStocks = self.account['FrozenStocks']
            return True
        except:
            return False

    def update_ticker(self):

        self.High = None
        self.Low = None
        self.Sell = None
        self.Buy = None
        self.Last = None
        self.Volume = None

        try:
            self.ticker = self.exchange.GetTicker()

            self.High = self.ticker['High']
            self.Low = self.ticker['Low']
            self.Sell = self.ticker['Sell']
            self.Buy = self.ticker['Buy']
            self.Last = self.ticker['Last']
            self.Volume = self.ticker['Volume']
            return True
        except:
            return False

    def update_depth(self):
        self.Asks = None
        self.Bids = None
        self.Asks_Price1 = None
        self.Asks_Amount1 = None
        self.Bids_Price1 = None
        self.Bids_Amount1 = None
        try:
            self.Depth = self.exchange.GetDepth()
            self.Asks = self.Depth['Asks']
            self.Bids = self.Depth['Bids']
            self.Asks_Price1 = self.Asks[0]["Price"]
            self.Asks_Amount1 = self.Asks[0]["Amount"]
            self.Bids_Price1 = self.Bids[0]["Price"]
            self.Bids_Amount1 = self.Bids[0]["Amount"]
            return True
        except:
            return False

    def update_kline(self, period=PERIOD_M5):
        try:
            self.Kline = exchange.GetRecords(period)
            return True
        except:
            return False

    def create_order(self, order_type, price, amount):
        if order_type == 'buy':
            try:
                order_id = self.exchange.Buy(price, amount)
            except:
                return False

        elif order_type == 'sell':
            try:
                order_id = self.exchange.Sell(price, amount)
            except:
                return False

        return order_id

    def fetch_order(self, id):
        ##    Log("Id:", order["Id"], "Price:", order["Price"], "Amount:", order["Amount"], "DealAmount:",
        ##    order["DealAmount"], "Status:", order["Status"], "Type:", order["Type"])
        return self.exchange.GetOrder(id)

    def fetch_uncomplete_orders(self):
        # 获取所有未完成的订单
        return self.exchange.GetOrders()

    def cancel_order(self, order_id):
        ## return True or False
        return self.exchange.CancelOrder(order_id)

    def refresh_data(self, period=PERIOD_M5):

        if not self.update_account():
            return 'false_get_account'

        if not self.update_ticker():
            return 'false_get_ticker'
        if not self.update_depth():
            return 'false_get_depth'
        try:
            self.update_kline(period)
        except:
            return 'false_get_K_line_info'

        return 'refresh_data_finish!'

    def fetch_kline(self, period=PERIOD_M5):
        return self.exchange.GetRecords(period)

    def fetch_ticker(self):
        return self.exchange.GetTicker()

    def fetch_depth(self):
        return self.exchange.GetDepth()

## define Stragety
class Strategy():
    def __init__(self, args):
        self.args = args
        self.quantcenter = args.quantcenter

        self.init_time = time.time()
        self.last_time = time.time()

        self.amount_N = args.amount_N
        self.price_N = args.price_N

        self.min_buy_money = args.min_buy_money
        self.min_sell_money = args.min_sell_money
        self.quantcenter.update_kline(args.kline_period)
        self.kline = pd.DataFrame(self.quantcenter.Kline)
        ##record orders
        self.buy_orders = []
        self.sell_orders = []
        self.trend_orders = []
        ## strategy params
        self.price_threshold = args.price_threshold
        self.position_max_percent = args.position_max_percent
        self.price_percent_period = args.price_percent_period
        self.user_price_period = int(self.price_percent_period / len(self.kline) * 24 * 3600)
        self.price_gap = args.price_gap
        self.max_orders = args.max_orders
        self.order_max_wait_time = args.order_max_wait_time
        ##moving average
        self.price_slip = args.price_slip

    def refresh_data(self, period):

        self.quantcenter.refresh_data(period)
        self.Amount = self.quantcenter.Amount
        self.Balance = self.quantcenter.Balance
        self.Buy_price = self.quantcenter.Buy
        self.Sell_price = self.quantcenter.Sell
        self.potential_buy_amount = round(self.Balance / self.Sell_price, self.amount_N)
        self.potential_sell_amount = round(self.Amount, self.amount_N)

        ##update arr will be used in indicator
        self.kline = pd.DataFrame(self.quantcenter.Kline)
        self.close_Arr = self.kline["Close"].to_numpy()
        self.high_Arr = self.kline["High"].to_numpy()
        self.low_Arr = self.kline["Low"].to_numpy()
        ##update user_define_price_percent
        self.user_dataset = pd.DataFrame(self.quantcenter.fetch_kline(self.user_price_period))
        self.user_Max_price = self.user_dataset.High.max()
        self.user_Min_price = self.user_dataset.Low.min()

    def trade_amount_compute(self, price, trade_side):
        price_percent = (price - self.user_Min_price) / (self.user_Max_price - self.user_Min_price)
        if trade_side == "buy":
            ##高估区间不买入
            if price > self.user_Max_price * self.price_threshold["buy"]:
                return False
                ##percent =1 amount =0  percent = 0 amount =1
            self.min_buy_amount = self.position_max_percent * self.Balance / price * (1.0 - price_percent)
            self.min_buy_amount = max(self.min_buy_amount, 0.0)
            self.min_buy_amount = min(self.min_buy_amount, self.Balance / price)
            self.min_buy_amount = round(self.min_buy_amount, self.amount_N)
            self.min_buy_balance = self.min_buy_amount * price
            if self.min_buy_balance < self.min_buy_money:
                return False
            else:
                return True

        elif trade_side == "sell":
            ##低估不卖出
            if price < self.user_Min_price * self.price_threshold["sell"]:
                return False
                ##percent =1 amount =1  percent = 0 amount =0
            self.min_sell_amount = self.position_max_percent * self.Amount * price_percent
            self.min_sell_amount = max(self.min_sell_amount, 0.0)
            self.min_sell_amount = min(self.min_sell_amount, self.Amount)
            self.min_sell_amount = round(self.min_sell_amount, self.amount_N)
            self.min_sell_balance = self.min_sell_amount * price
            if self.min_sell_balance < self.min_sell_money:
                return False
            else:
                return True

    def double_moving_average(self):
        fast_arr = TA.EMA(self.close_Arr, self.args.short_period)
        slow_arr = TA.EMA(self.close_Arr, self.args.long_period)

        cross_over = fast_arr[-1] > slow_arr[-1] and fast_arr[-2] < slow_arr[-2]
        cross_below = fast_arr[-1] < slow_arr[-1] and fast_arr[-2] > slow_arr[-2]
        RSX = self.rsx()
        if cross_over and RSX[-1] > 50 +self.args.rsx_threshold:
            trade_price = round(self.quantcenter.Bids_Price1 * (1.0 + self.price_slip), self.price_N)
            will_trade = self.trade_amount_compute(trade_price, "buy")
            if will_trade:
                trade_id = self.quantcenter.create_order("buy", trade_price, self.min_buy_amount)
                if trade_id:
                    self.refresh_data(self.args.kline_period)
                    self.trend_orders.append({
                        "side": "buy",
                        "price": trade_price,
                        "amount": self.min_buy_amount,
                        "id": trade_id,
                        "timestamp": Unix()})
        if cross_below and RSX[-1] < 50 - self.args.rsx_threshold :
            trade_price = round(self.quantcenter.Asks_Price1 * (1.0 - self.price_slip), self.price_N)
            will_trade = self.trade_amount_compute(trade_price, "sell")
            if will_trade:
                trade_id = self.quantcenter.create_order("sell", trade_price, self.min_sell_amount)
                if trade_id:
                    self.refresh_data(self.args.kline_period)
                    self.trend_orders.append({
                        "side": "sell",
                        "price": trade_price,
                        "amount": self.min_sell_amount,
                        "id": trade_id,
                        "timestamp": Unix()})
##rsx indicator
    def rsx(self):
        length= int(self.args.rsx_period)  if self.args.rsx_period > 0 else 14
        if self.close_Arr is None:
            return 0
        # variables
        vC, v1C = 0, 0
        v4, v8, v10, v14, v18, v20 = 0, 0, 0, 0, 0, 0
        f0, f8, f10, f18, f20, f28, f30, f38 = 0, 0, 0, 0, 0, 0, 0, 0
        f40, f48, f50, f58, f60, f68, f70, f78 = 0, 0, 0, 0, 0, 0, 0, 0
        f80, f88, f90 = 0, 0, 0

        m = len(self.close_Arr)
        result = [np.nan for _ in range(0, length - 1)] + [0]
        for i in range(length, m):
            if f90 == 0:
                f90 = 1.0
                f0 = 0.0
                if length - 1.0 >= 5:
                    f88 = length - 1.0
                else:
                    f88 = 5.0
                f8 = 100.0 * self.close_Arr[i]
                f18 = 3.0 / (length + 2.0)
                f20 = 1.0 - f18
            else:
                if f88 <= f90:
                    f90 = f88 + 1
                else:
                    f90 = f90 + 1
                f10 = f8
                f8 = 100 * self.close_Arr[i]
                v8 = f8 - f10
                f28 = f20 * f28 + f18 * v8
                f30 = f18 * f28 + f20 * f30
                vC = 1.5 * f28 - 0.5 * f30
                f38 = f20 * f38 + f18 * vC
                f40 = f18 * f38 + f20 * f40
                v10 = 1.5 * f38 - 0.5 * f40
                f48 = f20 * f48 + f18 * v10
                f50 = f18 * f48 + f20 * f50
                v14 = 1.5 * f48 - 0.5 * f50
                f58 = f20 * f58 + f18 * abs(v8)
                f60 = f18 * f58 + f20 * f60
                v18 = 1.5 * f58 - 0.5 * f60
                f68 = f20 * f68 + f18 * v18
                f70 = f18 * f68 + f20 * f70
                v1C = 1.5 * f68 - 0.5 * f70
                f78 = f20 * f78 + f18 * v1C
                f80 = f18 * f78 + f20 * f80
                v20 = 1.5 * f78 - 0.5 * f80

                if f88 >= f90 and f8 != f10:
                    f0 = 1.0
                if f88 == f90 and f0 == 0.0:
                    f90 = 0.0

            if f88 < f90 and v20 > 0.0000000001:
                v4 = (v14 / v20 + 1.0) * 50.0
                if v4 > 100.0:
                    v4 = 100.0
                if v4 < 0.0:
                    v4 = 0.0
            else:
                v4 = 50.0
            result.append(v4)
        return np.array(result)

    def next(self):
        self.double_moving_average()

## main
## define args
class Args():
    amount_N = 4
    price_N = 4
    min_buy_money = 5
    min_sell_money = 5

    kline_period = PERIOD_M5
    position_max_percent = 0.1
    price_threshold = {"buy": 0.999,
                       "sell": 1.001}
    ## true_period (Days)
    price_percent_period = 21
    price_gap = 0.005
    max_orders = 5
    order_max_wait_time = 3600 * 4
    ##Moing average
    short_period = 100
    long_period =169
    price_slip = 2.5e-5
    ##ADX
    ADX_period = 14
    ADX_threshold = 30
    ##RSX
    rsx_period = 14
    rsx_threshold = 15
    quantcenter = QuantCenter(exchange)

def main():
    args = Args()
    strategy = Strategy(args)
    strategy.refresh_data(args.kline_period)
    Log("refresh_data ok")
    while (True):
        Sleep(1000 * 60 * 5)
        # time.sleep(60)
        try:
            ## refresh_data and indicator
            strategy.refresh_data(args.kline_period)
            strategy.next()
        except:
            pass


import numpy as np

def frame_selector(data, xi, yi, gap_target, N_range_encode):
    '''
    Selecting [gap_target*N_range_encode] sized patches from 3-km model run
    '''
    assert N_range_encode % 2 == 1
    N_range_half = (N_range_encode - 1) // 2 # half of the encoded target grids
    gap_encode_left = gap_target*N_range_half # left side of the encoded target grids converted to model grids
    gap_encode_right = gap_target*N_range_half+gap_target # right side of the encoded target grids converted to model grids
    return data[xi*gap_target-gap_encode_left:xi*gap_target+gap_encode_right, yi*gap_target-gap_encode_left:yi*gap_target+gap_encode_right]


import requests
import re
import json
from github import Github

def get_browser_download_url(assets, ending):
    for a in assets:
        if a.name.endswith(ending):
            return a.browser_download_url

    raise ValueError("Could not find asset with ending '{}'.".format(ending))

def get_sig(assets, ending):
    for a in assets:
        if a.name.endswith(ending + ".sig"):
            resp = requests.get(a.browser_download_url)
            resp.raise_for_status()
            return resp.text

    raise ValueError("Could not find asset with ending '{}.sig'.".format(ending))

if __name__ == '__main__':
    repo = Github().get_repo("trawls-app/trawls")
    release = repo.get_latest_release()
    version_str = re.search(r"\d+\.\d+\.\d+.*", release.tag_name).group()

    if release.draft:
        raise Exception("Release is still a draft")

    release_assets = release.get_assets()
    data = {
        "name": version_str,
        "notes": release.body,
        "pub_date": release.published_at.isoformat() + "Z",
        "platforms": {
            "darwin-universal": {
                "signature": get_sig(release_assets, ".app.tar.gz"),
                "url": get_browser_download_url(release_assets, ".app.tar.gz")
            },
            "linux-x86_64": {
                "signature": get_sig(release_assets, ".AppImage.tar.gz"),
                "url": get_browser_download_url(release_assets, ".AppImage.tar.gz")
            },
            "windows-x86_64": {
                "signature": get_sig(release_assets, ".msi.zip"),
                "url": get_browser_download_url(release_assets, ".msi.zip")
            }
        }
    }

    with open("../static_api/releases/current.json", "w") as fp:
        json.dump(data, fp, indent=4)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 27 23:07:41 2018

@author: kilingcheung
"""

def isPrime(num):
    if (num == 2):
        return True
    elif (num %2 == 0):
        return False
    else:
        for i in range(3,num-1):
            if (num % i == 0):
                return False
        return True

def getPrimes():
    num = 2
    while True:
        if isPrime(num):
            yield num
        num += 1

def genPrimes():
    p = []
    x = 2
    isPrime = True
    while True:
        for known in p:
            if (x % known == 0):
                isPrime = False
                break
            else:
                isPrime = True
        if (isPrime):
            p.append(x)
            yield x
        x += 1


def add():
    x = int(input('Enter first number: '))
    y = int(input('Enter second: '))
    try:
        result = x + y

    except ValueError:
        print('Enter number not str')

    return result

if __name__ == "__main__":
    with open("task5.txt", "w") as f:
        f.write(f"{str(sum_two_numbers())}\n")


from milvus import *

class MilvusConnector:
    """A class that manages all the operations related to milvus"""
    def __init__(self, host, port, collection_name):

        self.collection_name = collection_name
        self.client = self.milvus_client(host, port)

    def milvus_client(self, host, port):
        try:
            milvus = Milvus(host=host, port=port)
            return milvus
        except Exception as e:
            print("Milvus client error:", e)
            raise e

    def create_collection(self):
        try:
            collection_param = {
                'collection_name': self.collection_name,
                'dimension': 768,
                'index_file_size':2048,
                'metric_type':  MetricType.IP
            }
            status = self.client.create_collection(collection_param)
            return status
        except Exception as e:
            print("Milvus create table error:", e)

    def create_index(self):
        param = {'nlist': 16384}
        try:
            status = self.client.create_index(self.collection_name, IndexType.IVF_FLAT, param)
            return status
        except Exception as e:
            print("Milvus create index error:", e)

    def insert(self, vectors):
        "can insert either single or multiple vectors; in any case the vectors must be a list"
        try:
            status, ids = self.client.insert(collection_name=self.collection_name, records=vectors)
            return status, ids
        except Exception as e:
            print("Milvus insert error:", e)

    def delete(self, ids):
        "either delete single or multiple entities by id or ids, in any case the ids must be a list"
        self.client.delete_entity_by_id('demo_films', ids)

    def get_similar_question(self, question_query, top_k, search_parm):
        status, results = self.search(question_query, top_k, search_parm)

        return results

    def search(self, vec, top_k, search_params):
        try:
            status, results = self.client.search(collection_name=self.collection_name, query_records=vec, top_k=top_k, params=search_params)
            return status, results
        except Exception as e:
            print("Milvus search error:", e)

    def drop_milvus_collection(self):
        try:
            status = self.client.drop_collection(collection_name=self.collection_name)
        except Exception as e:
            print("Milvus drop table error:", e)


with open("medium.in") as f:
	lines = f.readlines()
	#print lines
	for line in lines:
		words = line.split()
		#print words

		ing1 = 'M'
		ing2 = 'T'
		slicesize = 12
		mininum = 4

		def split_line(text):
			words = text.split()
			for word in words:

				len('t')
				words[word:]
				print(word)


# -*- coding: utf-8

import re

from docutils import nodes, statemachine
from docutils.parsers import rst

class Event(rst.Directive):
	has_content = True
	required_arguments = 1
	optional_arguments = 0
	final_argument_whitespace = False
	option_spec = {
		'type':    rst.directives.unchanged_required,
		'in':      rst.directives.unchanged_required,
		'subject': rst.directives.unchanged_required,
		'out':     rst.directives.unchanged,
		'since':   rst.directives.unchanged,
		'params':  rst.directives.unchanged
	}

	def _parseInline(self, text):
		string = statemachine.StringList([text])
		para   = nodes.container()

		self.state.nested_parse(string, 0, para)

		return para

	def _buildParamList(self, ul, params):
		for paramline in params.split("\n"):
			match = re.match('^([^ ]+) +\((.*?)\)(?:\s*(.*?))$', paramline)
			item  = nodes.list_item()
			text  = '``%s`` (%s)' % (match.group(1), match.group(2))

			if len(match.groups()) == 3 and len(match.group(3)) > 0:
				text = text + ' (' + match.group(3) + ')'

			children = self._parseInline(text).children

			for child in children:
				if isinstance(child, nodes.paragraph):
					[item.append(t) for t in child.children]
				else:
					item.append(child)

			ul.append(item)

		return ul

	def run(self):
		event   = self.arguments[0]
		anchor  = event.lower().replace('_', '-')
		kind    = self.options.get('type')
		inType  = self.options.get('in')
		outType = self.options.get('out') or 'void'
		subject = self.options.get('subject')
		params  = self.options.get('params') or ''
		since   = self.options.get('since') or ''
		desc    = u'\n'.join(self.content)

		# create section

		# optionally insert zero-width breaks:
		# event.replace('_', u"_\u200B")

		sec = nodes.section()
		sec.append(nodes.title('', event))
		sec['names'].append(anchor)

		self.state.document.note_implicit_target(sec, sec)

		# the signature

		sig = '%s %s(%s)' % (outType, event, inType)

		if kind == 'until':
			sig += ' BREAKS'

		# additional params for this event

		paramlist = None

		if len(params) > 0:
			paramlist = self._buildParamList(nodes.bullet_list(), params)

		# create actual definition list

		dl = nodes.definition_list('',
			nodes.definition_list_item('',
				nodes.term('', '', nodes.strong('', 'Signatur:')),
				nodes.definition('', nodes.literal('', sig))
			),
			nodes.definition_list_item('',
				nodes.term('', '', nodes.strong('', 'Beschreibung:')),
				nodes.definition('', self._parseInline(desc))
			),
			nodes.definition_list_item('',
				nodes.term('', '', nodes.strong('', 'Subject:')),
				nodes.definition('', self._parseInline(subject))
			)
		)

		if paramlist:
			dl.append(nodes.definition_list_item('',
				nodes.term('', '', nodes.strong('', 'Weitere Parameter:')),
				nodes.definition('', paramlist)
			))

		if len(since) > 0:
			since = 'v%s' % since

			dl.append(nodes.definition_list_item('',
				nodes.term('', '', nodes.strong('', u'Hinzugefügt in:')),
				nodes.definition('', self._parseInline(since))
			))

		sec.append(dl)

		return [sec]

def setup(app):
	app.add_directive('slyevent', Event)


import logging

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QFileDialog, QFrame, QHBoxLayout, QLabel, QLineEdit, QPushButton, QWidget, QTableWidget, \
    QTableWidgetItem, QAbstractItemView

from wannadb_parsql.parsql import Parser
from wannadb_parsql.rewrite import update_query_attribute_list, rewrite_query
from wannadb_ui.common import BUTTON_FONT, CODE_FONT, CODE_FONT_BOLD, LABEL_FONT, MainWindowContent, \
    MainWindowContentSection, CustomScrollableListItem, CustomScrollableList, RED, CODE_FONT_SMALLER, \
    INPUT_DOCS_COLUMN_NAME

logger = logging.getLogger(__name__)

class DocumentBaseViewerWidget(MainWindowContent):
    def __init__(self, main_window):
        super(DocumentBaseViewerWidget, self).__init__(main_window, "Document Base Viewer")

        self.everything_populated = False

        # Stats
        self.num_documents_nuggets = QLabel("0 documents | 0 nuggets")
        self.num_documents_nuggets.setFont(LABEL_FONT)
        self.controls_widget_layout.addWidget(self.num_documents_nuggets)

        self.export_table_button = QPushButton("Export Structured Data to CSV")
        self.export_table_button.setFont(BUTTON_FONT)
        self.export_table_button.setIcon(QIcon("wannadb_ui/resources/table.svg"))
        self.export_table_button.clicked.connect(self.main_window.save_table_to_csv_task)
        self.controls_widget_layout.addWidget(self.export_table_button)

        # query
        self.query = MainWindowContentSection(self, "Query")
        self.layout.addWidget(self.query)

        self.query_input_box = QWidget()
        self.query_input_box_layout = QHBoxLayout(self.query_input_box)
        self.query_input_box_layout.setContentsMargins(0, 0, 0, 0)

        self.query_box = QLineEdit()
        self.query_box.setPlaceholderText("Enter a SQL query or manually specify the target attributes below")
        self.query_box.setFont(CODE_FONT)
        self.query_box.setStyleSheet("border: none")
        self.query_input_box_layout.addWidget(self.query_box, stretch=1)

        self.enter_query_button = QPushButton("Run Query")
        self.enter_query_button.setFont(BUTTON_FONT)
        self.enter_query_button.setIcon(QIcon("wannadb_ui/resources/text_cursor.svg"))
        self.enter_query_button.setAutoDefault(True)
        self.enter_query_button.clicked.connect(self._parse_query)
        self.query_input_box_layout.addWidget(self.enter_query_button, alignment=Qt.AlignmentFlag.AlignRight)

        self.query.layout.addWidget(self.query_input_box)

        # attributes
        self.attributes = MainWindowContentSection(self, "Attributes")
        self.layout.addWidget(self.attributes)

        self.attributes_controls = QWidget()
        self.attributes_controls_layout = QHBoxLayout(self.attributes_controls)
        self.attributes_controls_layout.setContentsMargins(0, 0, 0, 0)

        self.add_attribute_button = QPushButton("Add Attribute")
        self.add_attribute_button.setFont(BUTTON_FONT)
        self.add_attribute_button.setIcon(QIcon("wannadb_ui/resources/plus.svg"))
        self.add_attribute_button.clicked.connect(self.main_window.add_attribute_task)
        self.attributes_controls_layout.addWidget(self.add_attribute_button, stretch=1)

        self.populate_remaining_attributes_button = QPushButton("Populate Remaining Attributes")
        self.populate_remaining_attributes_button.setFont(BUTTON_FONT)
        self.populate_remaining_attributes_button.setIcon(QIcon("wannadb_ui/resources/run_run.svg"))
        self.populate_remaining_attributes_button.clicked.connect(self.main_window.interactive_table_population_task)
        self.attributes_controls_layout.addWidget(self.populate_remaining_attributes_button, stretch=1)

        self.attributes_list = CustomScrollableList(self, AttributeWidget, self.attributes_controls)
        self.attributes.layout.addWidget(self.attributes_list)

        # result visualization
        self.results = MainWindowContentSection(self, "Results")
        self.layout.addWidget(self.results)
        self.results_table = QTableWidget()
        self.results_table.setFont(CODE_FONT_SMALLER)
        self.results_table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self.results.layout.addWidget(self.results_table)

    def update_document_base(self, document_base):
        def _attr_populated(a: str):
            return all(a in d.attribute_mappings.keys() for d in document_base.documents)

        # update documents & nuggets counts
        self.num_documents_nuggets.setText(f"{len(document_base.documents)} documents | {len(document_base.nuggets)} nuggets")

        # update attributes
        self.attributes_list.update_item_list(document_base.attributes, document_base)

        # Everything already populated?
        # Will be used to enable or disable populate and export buttons depending on the completeness of matching
        self.everything_populated = all(_attr_populated(a.name) for a in document_base.attributes)

        # update query
        attributes = [str(a).replace("'", "") for a in document_base.attributes]
        # Take existing query and add manually added attributes if needed
        original_query = self.query_box.text()
        if original_query == "":
            original_query = "SELECT *"
        columns, original_query_parsed = Parser().parse(original_query)
        query = update_query_attribute_list(original_query_parsed, attributes)

        if len(attributes) > 0:
            self.query_box.setText(query)
        else:
            self.query_box.setText("")

        # update cache db
        if self.main_window.cache_db is not None:
            attribute_names = [INPUT_DOCS_COLUMN_NAME]
            attribute_names.extend(attributes)
            query = update_query_attribute_list(original_query_parsed, attribute_names)
            columns, parsed = Parser().parse(query)

            def _get_values_for_column(column):
                for i, document in enumerate(document_base.documents):
                    value = ""
                    if column.name in document.attribute_mappings.keys() and len(
                            document.attribute_mappings[column.name]) > 0:
                        value = document.attribute_mappings[column.name][0].text
                    if value == "":
                        continue
                    yield i, value

            for column in columns:
                if column.name != INPUT_DOCS_COLUMN_NAME and self.main_window.cache_db.table_empty(column.name):
                    logger.info(f"Populating cache table for attribute '{column.name}'")
                    self.main_window.cache_db.store_many(column, _get_values_for_column(column))

            logger.info(f"Columns: {columns}")

            _, rewritten_query = rewrite_query(columns, original_query_parsed)
            logger.info(f"Executing query: '{rewritten_query}'")
            results = self.main_window.cache_db.execute_queries(rewritten_query)[0]

            # update results
            self.results_table.setRowCount(len(results))
            attribute_count = len(attribute_names)
            self.results_table.setColumnCount(attribute_count)
            self.results_table.setHorizontalHeaderLabels(attribute_names)

            for index, row in results.iterrows():
                for c, attribute_name in enumerate(attribute_names):
                    a = row[attribute_name]
                    if a is not None:
                        self.results_table.setItem(index, c, QTableWidgetItem(str(a)))
                    else:
                        self.results_table.setItem(index, c, QTableWidgetItem(""))

            self.results_table.resizeColumnsToContents()

    def enable_input(self):
        self.enter_query_button.setEnabled(True)
        # Enable buttons only conditionally (if needed/possible)
        self.populate_remaining_attributes_button.setEnabled(not self.everything_populated)
        self.export_table_button.setEnabled(self.everything_populated)
        # TODO Apply this to menu entries, too
        self.add_attribute_button.setEnabled(True)
        self.attributes_list.enable_input()

    def disable_input(self):
        self.enter_query_button.setDisabled(True)
        self.populate_remaining_attributes_button.setDisabled(True)
        self.export_table_button.setDisabled(True)
        self.add_attribute_button.setDisabled(True)
        self.attributes_list.disable_input()

    def _parse_query(self):
        if self.main_window.document_base is not None:
            query = self.query_box.text()
            try:
                attributes, parsed = Parser().parse(query)

                attribute_names = [str(attribute) for attribute in attributes]
                logger.info(f"Derived attribute names: {attribute_names}")

                self.main_window.to_busy_state()
                # noinspection PyUnresolvedReferences
                self.main_window.add_attributes.emit(attribute_names, self.main_window.document_base)
            except Exception as e:
                logger.error(str(e))
                self.main_window.status_widget_message.setText(str(e))
                self.main_window.status_widget_progress.setRange(0, 100)
                self.main_window.status_widget_progress.setValue(0)

class AttributeWidget(CustomScrollableListItem):
    def __init__(self, document_base_viewer):
        super(AttributeWidget, self).__init__(document_base_viewer)
        self.document_base_viewer = document_base_viewer
        self.attribute = None

        self.setFixedHeight(40)
        self.setObjectName("attributeWidget")
        self.setStyleSheet("QWidget#attributeWidget { background-color: white}")

        self.layout = QHBoxLayout(self)
        self.layout.setContentsMargins(20, 0, 20, 0)
        self.layout.setSpacing(40)

        self.attribute_name = QLabel()
        self.attribute_name.setFont(CODE_FONT_BOLD)
        self.layout.addWidget(self.attribute_name, alignment=Qt.AlignmentFlag.AlignLeft)

        self.num_matched = QLabel("matches: -")
        self.num_matched.setFont(CODE_FONT)
        self.layout.addWidget(self.num_matched, alignment=Qt.AlignmentFlag.AlignLeft)

        self.buttons_widget = QWidget()
        self.buttons_layout = QHBoxLayout(self.buttons_widget)
        self.buttons_layout.setContentsMargins(0, 0, 0, 0)
        self.buttons_layout.setSpacing(10)
        self.layout.addWidget(self.buttons_widget, alignment=Qt.AlignmentFlag.AlignRight)

        self.start_matching_button = QPushButton()
        self.start_matching_button.setIcon(QIcon("wannadb_ui/resources/run.svg"))
        self.start_matching_button.setToolTip("Populate the cells of this attribute..")
        self.start_matching_button.clicked.connect(self._start_matching_button_clicked)
        self.start_matching_button.hide()
        self.buttons_layout.addWidget(self.start_matching_button)

        self.forget_matches_button = QPushButton()
        self.forget_matches_button.setIcon(QIcon("wannadb_ui/resources/redo.svg"))
        self.forget_matches_button.setToolTip("Clear the cells of this attribute.")
        self.forget_matches_button.clicked.connect(self._forget_matches_button_clicked)
        self.buttons_layout.addWidget(self.forget_matches_button)

        self.remove_button = QPushButton()
        self.remove_button.setIcon(QIcon("wannadb_ui/resources/trash.svg"))
        self.remove_button.setToolTip("Remove this attribute.")
        self.remove_button.clicked.connect(self._remove_button_clicked)
        self.buttons_layout.addWidget(self.remove_button)

    def update_item(self, item, params=None):
        self.attribute = item

        if len(params.attributes) == 0:
            max_attribute_name_len = 10
        else:
            max_attribute_name_len = max(len(attribute.name) for attribute in params.attributes)
        self.attribute_name.setText(self.attribute.name + (" " * (max_attribute_name_len - len(self.attribute.name))))

        mappings_in_some_documents = False
        no_mappings_in_some_documents = False
        num_matches = 0
        for document in params.documents:
            if self.attribute.name in document.attribute_mappings.keys():
                mappings_in_some_documents = True
                if document.attribute_mappings[self.attribute.name] != []:
                    num_matches += 1
            else:
                no_mappings_in_some_documents = True

        if not mappings_in_some_documents and no_mappings_in_some_documents:
            self.num_matched.setStyleSheet(f"color: {RED}")
            self.num_matched.setText("not yet populated")
            self.forget_matches_button.hide()
            self.start_matching_button.show()
        elif mappings_in_some_documents and no_mappings_in_some_documents:
            self.num_matched.setText("only partly populated!")
            self.num_matched.setStyleSheet(f"color: {RED}")
            self.start_matching_button.hide()
            self.forget_matches_button.show()
        else:
            self.num_matched.setText(f"{num_matches} populated cells")
            self.num_matched.setStyleSheet(f"color: black")
            self.start_matching_button.hide()
            self.forget_matches_button.show()

    def enable_input(self):
        self.forget_matches_button.setEnabled(True)
        self.remove_button.setEnabled(True)
        self.start_matching_button.setEnabled(True)

    def disable_input(self):
        self.forget_matches_button.setDisabled(True)
        self.remove_button.setDisabled(True)
        self.start_matching_button.setDisabled(True)

    def _forget_matches_button_clicked(self):
        self.document_base_viewer.main_window.forget_matches_for_attribute_with_given_name_task(self.attribute.name)

    def _start_matching_button_clicked(self):
        self.document_base_viewer.main_window.match_attribute_task(self.attribute.name)

    def _remove_button_clicked(self):
        self.document_base_viewer.main_window.remove_attribute_with_given_name_task(self.attribute.name)

class DocumentBaseCreatorWidget(MainWindowContent):
    def __init__(self, main_window) -> None:
        super(DocumentBaseCreatorWidget, self).__init__(main_window, "Create Document Base")

        self.documents = MainWindowContentSection(self, "Documents:")
        self.layout.addWidget(self.documents)

        self.documents_explanation = QLabel(
            "Enter the path of the directory that contains the documents as .txt files."
        )
        self.documents_explanation.setFont(LABEL_FONT)
        self.documents.layout.addWidget(self.documents_explanation)

        self.path_widget = QFrame()
        self.path_layout = QHBoxLayout(self.path_widget)
        self.path_layout.setContentsMargins(20, 0, 20, 0)
        self.path_layout.setSpacing(10)
        self.path_widget.setObjectName("pathWidget")
        self.path_widget.setStyleSheet("QFrame#pathWidget { background-color: white }")
        self.path_widget.setFixedHeight(40)
        self.documents.layout.addWidget(self.path_widget)

        self.path = QLineEdit()
        self.path.setFont(CODE_FONT_BOLD)
        self.path.setStyleSheet("border: none")
        self.path_layout.addWidget(self.path)

        self.edit_path_button = QPushButton()
        self.edit_path_button.setIcon(QIcon("wannadb_ui/resources/folder.svg"))
        self.edit_path_button.clicked.connect(self._edit_path_button_clicked)
        self.path_layout.addWidget(self.edit_path_button)

        self.attributes = MainWindowContentSection(self, "Attributes:")
        self.layout.addWidget(self.attributes)

        self.labels_explanation = QLabel("Enter the attribute names.")
        self.labels_explanation.setFont(LABEL_FONT)
        self.attributes.layout.addWidget(self.labels_explanation)

        self.create_attribute_button = QPushButton("New Attribute")
        self.create_attribute_button.setFont(BUTTON_FONT)
        self.create_attribute_button.clicked.connect(self._create_attribute_button_clicked)

        self.attribute_names = []
        self.attributes_list = CustomScrollableList(self, AttributeCreatorWidget, self.create_attribute_button)
        self.attributes.layout.addWidget(self.attributes_list)

        self.buttons_widget = QWidget()
        self.buttons_layout = QHBoxLayout(self.buttons_widget)
        self.buttons_layout.setContentsMargins(0, 0, 0, 0)
        self.buttons_layout.setSpacing(10)
        self.buttons_layout.setAlignment(Qt.AlignmentFlag.AlignRight)
        self.attributes.layout.addWidget(self.buttons_widget)

        self.cancel_button = QPushButton("Cancel")
        self.cancel_button.setFont(BUTTON_FONT)
        self.cancel_button.clicked.connect(self._cancel_button_clicked)
        self.buttons_layout.addWidget(self.cancel_button)

        self.create_document_base_button = QPushButton("Create Document Base")
        self.create_document_base_button.setFont(BUTTON_FONT)
        self.create_document_base_button.clicked.connect(self._create_document_base_button_clicked)
        self.buttons_layout.addWidget(self.create_document_base_button)

    def enable_input(self):
        self.edit_path_button.setEnabled(True)
        self.create_attribute_button.setEnabled(True)
        self.cancel_button.setEnabled(True)
        self.create_document_base_button.setEnabled(True)
        self.attributes_list.enable_input()

    def disable_input(self):
        self.edit_path_button.setDisabled(True)
        self.create_attribute_button.setDisabled(True)
        self.cancel_button.setDisabled(True)
        self.create_document_base_button.setDisabled(True)
        self.attributes_list.disable_input()

    def initialize_for_new_document_base(self):
        self.path.setText("")
        self.path.setFocus()
        self.attribute_names = []
        self.attributes_list.update_item_list([])

    def delete_attribute(self, attribute_name):
        self.attribute_names = []
        for attribute_widget in self.attributes_list.item_widgets[:self.attributes_list.num_visible_item_widgets]:
            self.attribute_names.append(attribute_widget.name.text())
        self.attribute_names.remove(attribute_name)
        self.attributes_list.update_item_list(self.attribute_names)
        self.attributes_list.last_item_widget().name.setFocus()

    def _edit_path_button_clicked(self):
        path = str(QFileDialog.getExistingDirectory(self, "Choose a directory of text files."))
        if path != "":
            path = f"{path}/*.txt"
            self.path.setText(path)

    def _create_attribute_button_clicked(self):
        self.attribute_names = []
        for attribute_widget in self.attributes_list.item_widgets[:self.attributes_list.num_visible_item_widgets]:
            self.attribute_names.append(attribute_widget.name.text())
        self.attribute_names.append("")
        self.attributes_list.update_item_list(self.attribute_names)
        self.attributes_list.last_item_widget().name.setFocus()

    def _cancel_button_clicked(self):
        self.main_window.to_start_state()

    def _create_document_base_button_clicked(self):
        self.attribute_names = []
        for attribute_widget in self.attributes_list.item_widgets[:self.attributes_list.num_visible_item_widgets]:
            self.attribute_names.append(attribute_widget.name.text())
        self.main_window.create_document_base_task(self.path.text(), self.attribute_names)

class AttributeCreatorWidget(CustomScrollableListItem):
    def __init__(self, document_base_creator_widget) -> None:
        super(AttributeCreatorWidget, self).__init__(document_base_creator_widget)
        self.document_base_creator_widget = document_base_creator_widget

        self.setFixedHeight(40)
        self.setObjectName("attributeCreatorWidget")
        self.setStyleSheet("QWidget#attributeCreatorWidget { background-color: white}")

        self.layout = QHBoxLayout(self)
        self.layout.setContentsMargins(20, 0, 20, 0)
        self.layout.setSpacing(10)

        self.name = QLineEdit()
        self.name.setFont(CODE_FONT_BOLD)
        self.name.setStyleSheet("border: none")
        self.layout.addWidget(self.name)

        self.delete_button = QPushButton()
        self.delete_button.setIcon(QIcon("wannadb_ui/resources/trash.svg"))
        self.delete_button.clicked.connect(self._delete_button_clicked)
        self.layout.addWidget(self.delete_button)

    def update_item(self, item, params=None):
        self.name.setText(item)

    def _delete_button_clicked(self):
        self.document_base_creator_widget.delete_attribute(self.name.text())

    def enable_input(self):
        self.delete_button.setEnabled(True)

    def disable_input(self):
        self.delete_button.setEnabled(False)

class DocumentBaseCreatingWidget(MainWindowContent):
    def __init__(self, main_window) -> None:
        super(DocumentBaseCreatingWidget, self).__init__(main_window, "Creating the Document Base")

        self.steps = MainWindowContentSection(self, "Please wait while WannaDB prepares the document base.")
        self.layout.addWidget(self.steps)

    def enable_input(self):
        pass

    def disable_input(self):
        pass


from lcd import LCD
import glob
from time import sleep

def lcd_serial_port():
  '''
  Paramter: None
  Function: Looks for the port used by the 16x2 LCD screen
  Returns: port used 16x2 screen port
  '''
  port =  glob.glob('/dev/ttyACM*')
  #port = glob.glob('/dev/tty.usb*')
  if len(port) != 0:
    return port[0]
  else:
    return None

def main():
    port = lcd_serial_port()
    if port != None:
        lcd = LCD(port, 9600)
        while True:
                  lcd.welcome_message()
##      lcd.complete_message()
##      sleep(5)
##      lcd.missed_message()
##      sleep(5)
##      lcd.holding_restart(3)
##      sleep(5)
##      lcd.restart_message()
##      sleep(5)
##      lcd.display_voltage(12.0,30,'complete',False)
##      sleep(5)
##      lcd.send_command('CLEAR')
##      lcd.display_voltage(12.0,12,'missed',False)
##      sleep(5)
##      lcd.send_command('CLEAR')
##      lcd.display_voltage(12.0,'None','None',False)
##      sleep(5)
##      lcd.send_command('CLEAR')
##      lcd.display_voltage(2.0,30,'complete',True)
##      sleep(5)
##      lcd.send_command('CLEAR')
##      lcd.display_voltage(2.0,12,'missed',True)
##      sleep(5)
##      lcd.send_command('CLEAR')
##      lcd.display_voltage(2.0,'None','None',True)
##      sleep(5)
##      lcd.send_command('CLEAR')
    else:
        print("Missing LCD screen")

if __name__ == "__main__":
    main()


# -*- encoding: utf-8 -*-

import random
import math
import sys

if sys.version_info.major < 3:
    import Tkinter
else:
    import tkinter as Tkinter

from GA import GA

class TSP_WIN(object):
    def __init__(self, aRoot, aLifeCount=100, aWidth=560, aHeight=330):
        self.root = aRoot
        self.lifeCount = aLifeCount
        self.width = aWidth
        self.height = aHeight
        self.canvas = Tkinter.Canvas(
                self.root,
                width=self.width,
                height=self.height,
        )
        self.canvas.pack(expand=Tkinter.YES, fill=Tkinter.BOTH)
        self.bindEvents()
        self.initCitys()
        self.new()
        self.title("TSP")

    def initCitys(self):
        self.citys = []

        # 中国34城市经纬度
        self.citys.append((116.46, 39.92))
        self.citys.append((117.2, 39.13))
        self.citys.append((121.48, 31.22))
        self.citys.append((106.54, 29.59))
        self.citys.append((91.11, 29.97))
        self.citys.append((87.68, 43.77))
        self.citys.append((106.27, 38.47))
        self.citys.append((111.65, 40.82))
        self.citys.append((108.33, 22.84))
        self.citys.append((126.63, 45.75))
        self.citys.append((125.35, 43.88))
        self.citys.append((123.38, 41.8))
        self.citys.append((114.48, 38.03))
        self.citys.append((112.53, 37.87))
        self.citys.append((101.74, 36.56))
        self.citys.append((117, 36.65))
        self.citys.append((113.6, 34.76))
        self.citys.append((118.78, 32.04))
        self.citys.append((117.27, 31.86))
        self.citys.append((120.19, 30.26))
        self.citys.append((119.3, 26.08))
        self.citys.append((115.89, 28.68))
        self.citys.append((113, 28.21))
        self.citys.append((114.31, 30.52))
        self.citys.append((113.23, 23.16))
        self.citys.append((121.5, 25.05))
        self.citys.append((110.35, 20.02))
        self.citys.append((103.73, 36.03))
        self.citys.append((108.95, 34.27))
        self.citys.append((104.06, 30.67))
        self.citys.append((106.71, 26.57))
        self.citys.append((102.73, 25.04))
        self.citys.append((114.1, 22.2))
        self.citys.append((113.33, 22.13))

        # 坐标变换
        minX, minY = self.citys[0][0], self.citys[0][1]
        maxX, maxY = minX, minY
        for city in self.citys[1:]:
            if minX > city[0]:
                minX = city[0]
            if minY > city[1]:
                minY = city[1]
            if maxX < city[0]:
                maxX = city[0]
            if maxY < city[1]:
                maxY = city[1]

        w = maxX - minX
        h = maxY - minY
        xoffset = 30
        yoffset = 30
        ww = self.width - 2 * xoffset
        hh = self.height - 2 * yoffset
        xx = ww / float(w)
        yy = hh / float(h)
        r = 5
        self.nodes = []
        self.nodes2 = []
        for city in self.citys:
            x = (city[0] - minX) * xx + xoffset
            y = hh - (city[1] - minY) * yy + yoffset
            self.nodes.append((x, y))
            node = self.canvas.create_oval(x - r, y - r, x + r, y + r,
                                           fill="#ff0000",
                                           outline="#000000",
                                           tags="node", )
            self.nodes2.append(node)

    def distance(self, order):
        distance = 0.0
        for i in range(-1, len(self.citys) - 1):
            index1, index2 = order[i], order[i + 1]
            city1, city2 = self.citys[index1], self.citys[index2]
            distance += math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2)
        return distance

    def matchFun(self):
        return lambda life: 1.0 / self.distance(life.gene)

    def title(self, text):
        self.root.title(text)

    def line(self, order):
        self.canvas.delete("line")
        for i in range(-1, len(order) - 1):
            p1 = self.nodes[order[i]]
            p2 = self.nodes[order[i + 1]]
            self.canvas.create_line(p1, p2, fill="#000000", tags="line")

    def bindEvents(self):
        self.root.bind("n", self.new)
        self.root.bind("g", self.start)
        self.root.bind("s", self.stop)

    def new(self, evt=None):
        self.isRunning = False
        order = range(len(self.citys))
        self.line(order)
        self.ga = GA(aCrossRate=0.7,
                     aMutationRage=0.02,
                     aLifeCount=self.lifeCount,
                     aGeneLenght=len(self.citys),
                     aMatchFun=self.matchFun())

    def start(self, evt=None):
        if evt:
            for i in range(evt):
                if i < evt:
                    self.ga.next()
                    distance = self.distance(self.ga.best.gene)
                    self.line(self.ga.best.gene)
                    self.title("TSP-gen: Modify by Aoxue.sun  第%d次优化" % (self.ga.generation-1))
                    self.canvas.update()
                else:
                    self.stop()
        else:
            self.stop()

    def stop(self, evt=None):
        self.isRunning = False

    def mainloop(self):
        self.root.mainloop()

    @classmethod
    def main(cls):
        # tsp = TSP()
        # tsp.run(10000)
        try:
            number=raw_input('请输入需要优化的次数：')
            assert number is not int
            tsp = TSP_WIN(Tkinter.Tk())
            tsp.start(evt=int(number))
            tsp.mainloop()
        except AssertionError as e:
            raise AssertionError(e.message)
        except Exception as e:
            raise Exception(e.message)
        else:
            print ('程序执行完毕')

if __name__ == '__main__':
    TSP_WIN.main()


"""Information that should be available to the python library.
"""
from os import environ
from pathlib import Path

# The root of the qmk_firmware tree.
QMK_FIRMWARE = Path.cwd()

# This is the number of directories under `qmk_firmware/keyboards` that will be traversed. This is currently a limitation of our make system.
MAX_KEYBOARD_SUBFOLDERS = 5

# Supported processor types
CHIBIOS_PROCESSORS = 'cortex-m0', 'cortex-m0plus', 'cortex-m3', 'cortex-m4', 'MKL26Z64', 'MK20DX128', 'MK20DX256', 'STM32F042', 'STM32F072', 'STM32F103', 'STM32F303', 'STM32F401', 'STM32F411', 'STM32G431', 'STM32G474'
LUFA_PROCESSORS = 'at90usb162', 'atmega16u2', 'atmega32u2', 'atmega16u4', 'atmega32u4', 'at90usb646', 'at90usb647', 'at90usb1286', 'at90usb1287', None
VUSB_PROCESSORS = 'atmega32a', 'atmega328p', 'atmega328', 'attiny85'

# Common format strings
DATE_FORMAT = '%Y-%m-%d'
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S %Z'
TIME_FORMAT = '%H:%M:%S'

# Used when generating matrix locations
COL_LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijilmnopqrstuvwxyz'
ROW_LETTERS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop'

# Mapping between info.json and config.h keys
LED_INDICATORS = {
    'caps_lock': 'LED_CAPS_LOCK_PIN',
    'num_lock': 'LED_NUM_LOCK_PIN',
    'scroll_lock': 'LED_SCROLL_LOCK_PIN',
}

# Constants that should match their counterparts in make
BUILD_DIR = environ.get('BUILD_DIR', '.build')
KEYBOARD_OUTPUT_PREFIX = f'{BUILD_DIR}/obj_'


import os
import numpy as np
from delft.sequenceLabelling import Sequence
from delft.utilities.Tokenizer import tokenizeAndFilter
from delft.utilities.Embeddings import Embeddings,test
from delft.utilities.Utilities import stats
from delft.sequenceLabelling.reader import load_data_and_labels_xml_file, load_data_and_labels_conll, load_data_and_labels_lemonde, load_data_and_labels_ontonotes
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_fscore_support, f1_score
from numpy import nditer, mean
import keras.backend as K
import argparse
import time
from NERDA.datasets import get_conll_data
from NERDA.models import NERDA

tag_scheme = [            'B_NE001',
                            'B_NE003',
                            'B_NE005',
                            'B_NE006',
                            'B_NE007',
                            'B_NE008',
                            'B_NE009',
                            'I_NE001',
                            'I_NE003',
                            'I_NE005',
                            'I_NE006',
                            'I_NE009',
]
tag_outside='O'
# hyperparameters for network
dropout = 0.1
# hyperparameters for training camembert
training_hyperparameters = {
'epochs' : 14,
'warmup_steps' : 700,
'train_batch_size': 32,
'learning_rate': 0.0001
}
def voting(ys=[],coeffs=[],coef_alltime=False):
    unique_ys = list(set(ys))#no001, noo1, noo2, n002
    # no001,noo2
    if len(unique_ys) > 1:
        maximum = ''
        max_occ = 1
        for unique_y in unique_ys:
            temp_occ = ys.count(unique_y)
            if temp_occ > max_occ:
                max_occ = temp_occ
                maximum = unique_y
        if max_occ > len(ys)//2:
            if not coef_alltime:
                return maximum
            else:
                max_coefs = [0 for x in range(len(unique_ys))]
                for i,unique_y in enumerate(unique_ys):
                    indices = [i for i, x in enumerate(ys) if x == unique_y]
                    for j in indices:
                        max_coefs[i] += coeffs[j]
                max_coef_index = max_coefs.index(max(max_coefs))
                return unique_ys[max_coef_index]
        else:
            max_coefs = [0 for x in range(len(unique_ys))]
            for i,unique_y in enumerate(unique_ys):
                indices = [i for i, x in enumerate(ys) if x == unique_y]
                for j in indices:
                    max_coefs[i] += coeffs[j]
            max_coef_index = max_coefs.index(max(max_coefs))
            print(f'conflict max(max_coefs):{max(max_coefs)}\n{*ys,}\t{unique_ys[max_coef_index]}')
            return unique_ys[max_coef_index]
    else : return ys[0]

# usual eval on CoNLL 2003 eng.testb
def eval(model,
         dataset_type='conll2003',
         lang='en',
         architecture='BidLSTM_CRF',
         use_ELMo=False,
         use_BERT=False,
         data_path=None,):

    print('Loading CoNLL-2003 NER data...')
    x_test, y_test = load_data_and_labels_conll('data/sequenceLabelling/CoNLL-2003/eng.testb')
    x_test_list, y_test_list = x_test.tolist(), y_test.tolist()

    new_y_test = []
    for y in y_test_list:
        temp = []
        for p_y in y:
            temp.append(p_y.replace('E_', 'I_'))
        new_y_test.append(temp)

    print(f'x_test shape {x_test.shape}\n \
            y_test shape {y_test.shape}')
    stats(x_eval=x_test, y_eval=y_test)

    coeffs = []
    y_predecteds = []
    print(f'======== {model}')
    model_name1 = 'ner-en-conll2003-BidLSTM_CRF-wiki.fr'
    model_name2 = 'ner-en-conll2003-BidLSTM_CRF-elmo-fr-embeddings-11epocs_3rd-run_2-folds'
    model_name3 = 'ner-en-conll2003-BidLSTM_CRF-bert-base-en-emebddings-11epocs'
    model_name4 = 'ner-en-conll2003-BidLSTM_CRF-glove-840B-embeddings-11epocs'
    model_name5 = 'ner-en-conll2003-BidLSTM_CRF-word2vec-embeddings-25epocs'
    # model_name2 = 'ner-en-conll2003-BidLSTM_CRF-elmo-fr-embeddings-11epocs'
    # model_name4 = 'ner-en-conll2003-BidLSTM_CRF-wiki.fr-embeddings-11epocs'
    if model == 'camembert':
        camembert_model = NERDA(device="cuda:0",
                            tag_scheme = tag_scheme,
                            tag_outside = tag_outside,
                            transformer = '../camembert/camembert_jurica_512/',
                            )
        start_time = time.time()
        print("\nEvaluation on test set:")
        y_predecteds.append(camembert_model.predict(x_test_list))
    elif model == 'w2vec':
        model = Sequence(model_name5)
        model.load()
        start_time = time.time()
        print("\nEvaluation on test set:")
        y_predecteds.append(model.eval(x_test, y_test))
        coeffs.append(1)
    elif model == 'fasttext':
        model = Sequence(model_name1)
        model.load()
        start_time = time.time()
        print("\nEvaluation on test set:")
        y_predecteds.append(model.eval(x_test, y_test))
        coeffs.append(1)
    elif model == 'elmo':
        model = Sequence(model_name2)
        model.load()
        start_time = time.time()
        print("\nEvaluation on test set:")
        y_predecteds.append(model.eval(x_test, y_test))
        coeffs.append(1)
    elif model == 'bert':
        model = Sequence(model_name3)
        model.load()
        start_time = time.time()
        print("\nEvaluation on test set:")
        y_predecteds.append(model.eval(x_test, y_test))
        coeffs.append(1)
    elif model == 'e0':
        model5 = Sequence(model_name5)
        model1 = Sequence(model_name1)
        model1.load()
        model5.load()
        start_time = time.time()
        print("\nEvaluation on test set:")
        y_predecteds.append(model1.eval(x_test, y_test))
        y_predecteds.append(model5.eval(x_test, y_test))
        coeffs = [.4,.6]
    elif model == 'e1':
        model2 = Sequence(model_name2)
        model3 = Sequence(model_name3)
        model2.load()
        model3.load()
        start_time = time.time()
        print("\nEvaluation on test set:")
        y_predecteds.append(model2.eval(x_test, y_test))
        y_predecteds.append(model3.eval(x_test, y_test))
        coeffs = [.6,.4]
    elif model == 'e2':
        model1 = Sequence(model_name1)
        model5 = Sequence(model_name5)
        model2 = Sequence(model_name2)
        model3 = Sequence(model_name3)
        model1.load()
        model5.load()
        model2.load()
        model3.load()
        start_time = time.time()
        print("\nEvaluation on test set:")
        y_predecteds.append(model1.eval(x_test, y_test))
        y_predecteds.append(model5.eval(x_test, y_test))
        y_predecteds.append(model2.eval(x_test, y_test))
        y_predecteds.append(model3.eval(x_test, y_test))
        coeffs = [.3,.3, .2,.2]
    else:
        print('unknown model')
        return
    print(f'coeffs {coeffs}')

    with open('y.txt', 'w') as f:
        y_voted = []
        ys = []
        if len(y_predecteds) == 1:
            f.write(f'X_test\t\tY_test\t\tModel\n')#\t\tGlove
            for x, y, y1 in \
            zip(x_test, y_test, \
            y_predecteds[0]):
                for p_x, p_y, p_y1 in zip(x, y,y1):
                    ys_transformed = []
                    for tr in [ p_y1]:
                        if tr == '<PAD>' or tr == 'O':
                            ys_transformed.append('NE000')
                        else:
                            ys_transformed.append(tr)
                    #[p_y1, p_y2, p_y3, p_y4, p_y5],\
                    y_v = p_y1
                    if y_v == '<PAD>':
                        y_v= 'NE000'
                    y_voted.append(y_v)
                    ys.append(p_y)
                    f.write(f'{p_x}\t\t{p_y}\t\t{p_y1}\t\t{y_v}\n')
        elif len(y_predecteds) == 2:
            f.write(f'X_test\t\tY_test\t\tModel1\t\tModel2\n')#\t\tGlove
            for x, y, y1,y5 in \
            zip(x_test, y_test, \
            y_predecteds[0], y_predecteds[1]):
                for p_x, p_y, p_y1,p_y5 in zip(x, y,y1,y5):
                    ys_transformed = []
                    for tr in [ p_y1,p_y5]:
                        if tr == '<PAD>' or tr == 'O':
                            ys_transformed.append('NE000')
                        else:
                            ys_transformed.append(tr)
                    #[p_y1, p_y2, p_y3, p_y4, p_y5],\
                    y_v = voting(  ys=ys_transformed, \
                                            coeffs=coeffs )
                    if y_v == '<PAD>':
                        y_v= 'NE000'
                    y_voted.append(y_v)
                    ys.append(p_y)
                    f.write(f'{p_x}\t\t{p_y}\t\t{p_y1}\t\t{p_y5}\t\t{y_v}\n')
        elif len(y_predecteds) == 4:
            f.write(f'X_test\t\tY_test\t\tModel1\t\tModel2\t\tModel3\t\tModel4\n')#\t\tGlove
            for x, y, y1,y2,y3,y5 in \
            zip(x_test, y_test, \
            y_predecteds[0], y_predecteds[1], y_predecteds[2], y_predecteds[3]):
                for p_x, p_y, p_y1, p_y2, p_y3,p_y5 in zip(x, y,y1, y2, y3,y5):
                    ys_transformed = []
                    for tr in [ p_y1, p_y2, p_y3,p_y5]:
                        if tr == '<PAD>' or tr == 'O':
                            ys_transformed.append('NE000')
                        else:
                            ys_transformed.append(tr)
                    #[p_y1, p_y2, p_y3, p_y4, p_y5],\
                    y_v = voting(  ys=ys_transformed, \
                                            coeffs=coeffs )
                    if y_v == '<PAD>':
                        y_v= 'NE000'
                    y_voted.append(y_v)
                    ys.append(p_y)
                    f.write(f'{p_x}\t\t{p_y}\t\t{p_y1}\t\t{p_y2}\t\t{p_y3}\t\t{p_y5}\t\t{y_v}\n')

    runtime = round(time.time() - start_time, 3)
    # print(f'Diasappear {set(ys) - set(y_voted)}')
    metrics = precision_recall_fscore_support(ys, y_voted, average=None,)
    metrics2 = f1_score(ys, y_voted, average=None,)
    # print(f'\nmetrics all in one {metrics}\n\n')
    print('============== Voting scores =============\n\tprecision\trecall\tfscore\tsupport\n')
    for label, precision, recall, fscore, support in zip(list(set(ys)),
                                                        nditer(metrics[0]),\
                                                        nditer(metrics[1]), \
                                                        nditer(metrics[2]), \
                                                        nditer(metrics[3]),):
        print(f'{label}\t\t{round(float(precision),4)*100}\t\t{round(float(recall),4)*100}\t\t{round(float(fscore),4)*100}\t\t{support}')
    print('==========================================')
    print(f'AVG:\t{mean(metrics[0])}\t{mean(metrics[1])}\t{mean(metrics[2])}\t{mean(metrics[3])}')

    print('============== Voting scores (2) =============\n\tf1_score\n')
    for label, fscore in zip(list(set(ys)), \
                            nditer(metrics[0]),):
        print(f'{label}\t\t{round(float(fscore),4)*100}')
    print('==========================================')
    print(f'AVG:\t{mean(metrics[0])}')

    print("runtime: %s seconds " % (runtime))

if __name__ == "__main__":

    architectures = ['BidLSTM_CRF', 'BidLSTM_CNN_CRF', 'BidLSTM_CNN_CRF', 'BidGRU_CRF', 'BidLSTM_CNN', 'BidLSTM_CRF_CASING',
                     'bert-base-en', 'bert-large-en', 'scibert', 'biobert']

    parser = argparse.ArgumentParser(
        description = "Neural Named Entity Recognizers")

    parser.add_argument("action", help="one of [train, train_eval, eval, tag]")
    parser.add_argument("--fold-count", type=int, default=1, help="number of folds or re-runs to be used when training")
    parser.add_argument("--lang", default='en', help="language of the model as ISO 639-1 code")
    parser.add_argument("--dataset-type",default='conll2003', help="dataset to be used for training the model")
    parser.add_argument("--train-with-validation-set", action="store_true", help="Use the validation set for training together with the training set")
    parser.add_argument("--architecture",default='BidLSTM_CRF', help="type of model architecture to be used, one of "+str(architectures))
    parser.add_argument("--use-ELMo", action="store_true", help="Use ELMo contextual embeddings")
    parser.add_argument("--use-BERT", action="store_true", help="Use BERT extracted features (embeddings)")
    parser.add_argument("--data-path", default=None, help="path to the corpus of documents for training (only use currently with Ontonotes corpus in orginal XML format)")
    parser.add_argument("--file-in", default=None, help="path to a text file to annotate")
    parser.add_argument("--file-out", default=None, help="path for outputting the resulting JSON NER anotations")
    parser.add_argument("--model", default=None, help="model or ensemble you want to use")
    parser.add_argument(
        "--embedding", default=None,
        help=(
            "The desired pre-trained word embeddings using their descriptions in the file"
            " embedding-registry.json."
            " Be sure to use here the same name as in the registry ('glove-840B', 'fasttext-crawl', 'word2vec'),"
            " and that the path in the registry to the embedding file is correct on your system."
        )
    )

    args = parser.parse_args()

    action = args.action
    model = args.model
    if action not in ('train', 'tag', 'eval', 'train_eval'):
        print('action not specifed, must be one of [train, train_eval, eval, tag]')
    lang = args.lang
    dataset_type = args.dataset_type
    train_with_validation_set = args.train_with_validation_set
    use_ELMo = args.use_ELMo
    use_BERT = args.use_BERT
    architecture = args.architecture
    if architecture not in architectures and architecture.lower().find("bert") == -1:
        print('unknown model architecture, must be one of', architectures)
    data_path = args.data_path
    file_in = args.file_in
    file_out = args.file_out

    # name of embeddings refers to the file embedding-registry.json
    # be sure to use here the same name as in the registry ('glove-840B', 'fasttext-crawl', 'word2vec'),
    # and that the path in the registry to the embedding file is correct on your system
    # below we set the default embeddings value
    if args.embedding is None:
        embeddings_name = 'glove-840B'
        if lang == 'en':
            if dataset_type == 'conll2012':
                embeddings_name = 'fasttext-crawl'
        elif lang == 'fr':
            embeddings_name = 'wiki.fr'
    else:
        embeddings_name = args.embedding

    if action == 'train':
        train(embeddings_name,
            dataset_type,
            lang,
            architecture=architecture,
            use_ELMo=use_ELMo,
            use_BERT=use_BERT,
            data_path=data_path)

    if action == 'train_eval':
        import tensorflow as tf
        strategy = tf.distribute.MirroredStrategy( ["GPU:0", "GPU:1"] )
        with strategy.scope():
            if args.fold_count < 1:
                raise ValueError("fold-count should be equal or more than 1")
            train_eval(embeddings_name,
                dataset_type,
                lang,
                architecture=architecture,
                fold_count=args.fold_count,
                train_with_validation_set=train_with_validation_set,
                use_ELMo=use_ELMo,
                use_BERT=use_BERT,
                data_path=data_path)

    if action == 'eval':
        eval(model, dataset_type, lang, architecture=architecture, use_ELMo=use_ELMo, use_BERT=use_BERT)

    if action == 'tag':
        if lang is not 'en' and lang is not 'fr':
            print("Language not supported:", lang)
        else:
            print(file_in)
            result = annotate("json",
                            dataset_type,
                            lang,
                            architecture=architecture,
                            use_ELMo=use_ELMo,
                            use_BERT=use_BERT,
                            file_in=file_in,
                            file_out=file_out)
            """if result is not None:
                if file_out is None:
                    print(json.dumps(result, sort_keys=False, indent=4, ensure_ascii=False))
            """

    try:
        # see https://github.com/tensorflow/tensorflow/issues/3388
        K.clear_session()
    except:
        # TF could complain in some case
        print("\nLeaving TensorFlow...")