# -*- coding: utf-8 -*-
"""
http://blog.csdn.net/chenghit
"""
import wx
import os
# class MainWindow(wx.Frame):
#     """We simply derive a new class of Frame."""
#     def __init__(self, parent, title):
#         wx.Frame.__init__(self, parent, title = title, size = (200, 100))
#         self.control = wx.TextCtrl(self, style = wx.TE_MULTILINE)
#         self.CreateStatusBar()    #创建位于窗口的底部的状态栏
#
#         #设置菜单
#         filemenu = wx.Menu()
#         filemenu1 = wx.Menu()
#
#         #wx.ID_ABOUT和wx.ID_EXIT是wxWidgets提供的标准ID
#         filemenu.Append(wx.ID_ABOUT, u"关于", u"关于程序的信息")
#         filemenu.AppendSeparator()
#         filemenu.Append(wx.ID_EXIT, u"退出", u"终止应用程序")
#         menuItem = filemenu1.Append(wx.ID_SAVE, u"保存", u"保存文本")
#
#         #创建菜单栏
#         menuBar = wx.MenuBar()
#         menuBar.Append(filemenu, u"文件")
#         menuBar.Append(filemenu1, u"选项")
#
#         self.SetMenuBar(menuBar)
#         self.Show(True)
#         self.Bind(wx.EVT_MENU, self.OnAbout, menuItem)
#
#
# app = wx.App(False)
# frame = MainWindow(None, title = u"记事本")
# app.MainLoop()

# -*- coding: utf-8 -*-
"""
http://blog.csdn.net/chenghit
"""

class MainWindow(wx.Frame):
    """We simply derive a new class of Frame."""
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title = title, size = (600, 400))
        self.control = wx.TextCtrl(self, style = wx.TE_MULTILINE)
        self.CreateStatusBar()    # 创建位于窗口的底部的状态栏

        # 设置菜单
        filemenu = wx.Menu()
        filemenu1 = wx.Menu()

        # wx.ID_ABOUT和wx.ID_EXIT是wxWidgets提供的标准ID
        menuAbout = filemenu.Append(wx.ID_ABOUT, "&About", \
            " Information about this program")    # (ID, 项目名称, 状态栏信息)
        filemenu.AppendSeparator()
        menuExit = filemenu.Append(wx.ID_EXIT, "E&xit", \
            " Terminate the program")    # (ID, 项目名称, 状态栏信息)
        menuOpen = filemenu1.Append(wx.ID_OPEN, "&Open", \
                                   " Open a file")  # (ID, 项目名称, 状态栏信息)
        # 创建菜单栏
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu, "&File")    # 在菜单栏中添加filemenu菜单

        menuBar.Append(filemenu1, "&Choose")
        self.SetMenuBar(menuBar)    # 在frame中添加菜单栏

        panel = wx.Panel(self)
        self.quote = wx.StaticText(panel, label="Hello!",pos=(10,10) ,size=(40,40))
        self.quote1 = wx.StaticText(panel, label="World!", pos=(10,50) ,size=(40, 40))
        # 设置events
        self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)
        self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
        self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)

        # 设置sizers
        self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)  #水平方向布置boxsizer
        self.buttons = []
        for i in range(0, 6):
            self.buttons.append(wx.Button(self,-1, "Button &" + str(i)))
            self.sizer2.Add(self.buttons[i], 1, wx.GROW)

        self.sizer = wx.BoxSizer(wx.VERTICAL)    #垂直方向布置boxsizer
        self.sizer.Add(panel,0, wx.GROW)
        self.sizer.Add(self.control, 1, wx.EXPAND)
        self.sizer.Add(self.sizer2, 0, wx.GROW)
        self.Bind(wx.EVT_BUTTON, self.OnOpen, self.buttons[1])

        # 激活sizer
        self.SetSizer(self.sizer)
        self.SetAutoLayout(True)
        self.sizer.Fit(self)
        self.Show(True)

    def OnAbout(self, e):
        # 创建一个带"OK"按钮的对话框。wx.OK是wxWidgets提供的标准ID
        dlg = wx.MessageDialog(self, "A small text editor.", \
            "About Sample Editor", wx.OK)    # 语法是(self, 内容, 标题, ID)
        dlg.ShowModal()    # 显示对话框
        dlg.Destroy()    # 当结束之后关闭对话框

    def OnExit(self, e):
        self.Close(True)    # 关闭整个frame

    def OnOpen(self,e):
        """ Open a file"""
        self.dirname = ''
        dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*",wx.ID_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            f = open(os.path.join(self.dirname, self.filename), 'r')
            self.control.SetValue(f.read())
            f.close()
        dlg.Destroy()

app = wx.App(False)
frame = MainWindow(None, title = "Small editor")
app.MainLoop()


import pathlib
import datetime
import natsort
from typing import List, Optional

class LogFolder:
    folder = pathlib.Path.cwd()
    friendly_time = None
    friendly_name = None
    start_time = datetime.datetime.now()
    latest_log_folder: pathlib.Path = None
    latest_log_folder_checked = False

    @classmethod
    def set_path(cls, root: pathlib.Path, friendly_name: str):
        # Setup target log folder
        the_date = cls.start_time.date()
        cls.friendly_time = str(datetime.datetime.now()).replace(':', "-").replace(" ", "_")
        cls.friendly_name = friendly_name
        cls.folder = pathlib.Path(root) / cls.friendly_name / str(the_date) / cls.friendly_time

        # Create the folders
        cls.folder.mkdir(parents=True, exist_ok=True)

    @classmethod
    def _get_date_folders(cls, log_folder: pathlib.Path) -> List[str]:
        return natsort.natsorted(list(log_folder.iterdir()))

    @classmethod
    def get_recent_date_folder(cls, log_folder: pathlib.Path) -> Optional[pathlib.Path]:
        date_folders = cls._get_date_folders(log_folder)
        if not date_folders:
            raise FileNotFoundError
        return log_folder / date_folders[-1]

    @classmethod
    def get_datetime_folders(cls, log_folder: pathlib.Path) -> List[pathlib.Path]:
        recent_date_folder = cls.get_recent_date_folder(log_folder)
        if not recent_date_folder:
            raise FileNotFoundError
        return natsort.natsorted(list(recent_date_folder.iterdir()))

    @classmethod
    def get_recent_datetime_folder(cls, log_folder: pathlib.Path) -> Optional[pathlib.Path]:
        datetime_folders = cls.get_datetime_folders(log_folder)
        if not datetime_folders:
            raise FileNotFoundError
        return datetime_folders[-1]

    @classmethod
    def get_latest_log_folder(cls, log_folder: pathlib.Path) -> pathlib.Path:
        """
        Accessor for the latest log folder. Recommended to call this early in execution
        (that is, before a new log folder is created)
        """
        # Cache the latest log folder
        if not cls.latest_log_folder_checked:
            cls.latest_log_folder_checked = True
            cls.latest_log_folder = cls.get_recent_datetime_folder(log_folder)

        return cls.latest_log_folder


#!/usr/bin/python3

from __future__ import print_function
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from os import listdir
from os.path import isfile, join
from googleapiclient.http import MediaFileUpload
from datetime import datetime
import argparse
import pickle
import os.path
import ruamel.yaml
import sys

print()
print("Upload at: " + str(datetime.now()))
# os.chdir(r"/home/pcadmin/upload_script/")

# setup cli argparser interface for more flexibility
parser = argparse.ArgumentParser(description=(
    "This python script uploads files into the drive storage of a google account. For this to work, that account must "
    "activate the drive api (under step 1 here: https://developers.google.com/drive/api/v3/quickstart/python). There "
    "we obtain the file credentials.json, which is used to generate the token.pickle file from the browser that will "
    "pop up the first time this script is executed"))

parser.add_argument("-cf", "--config", type=str, help="The path to the config.yaml file")

args = parser.parse_args()

# read the config file passed as argument
yaml = ruamel.yaml.YAML()
with open(args.config) as f:
    config = yaml.load(f)

class Synchronizer:

    def __init__(self):
        self.service = None
        self.auth_run = False

        # Controls what the app is allowed to do in the cloud storage
        # If modifying these scopes, delete the file token.pickle. A new authentication process will be started that
        self.scopes = ['https://www.googleapis.com/auth/drive.file',
                       'https://www.googleapis.com/auth/drive.install']

        # Starts the authentication process of the client-side script
        self.authorize_app()

    def authorize_app(self):
        """
        Shows basic usage of the Drive v3 API.
        Prints the names and ids of the first 10 files the user has access to.
        """

        creds = None
        # The file token.pickle stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists(config["token_path"]):
            with open(config["token_path"], 'rb') as token:
                creds = pickle.load(token)

        # If there are no (valid) credentials available, let the user log in.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                self.auth_run = True
                flow = InstalledAppFlow.from_client_secrets_file(config["credtials_path"], self.scopes)
                creds = flow.run_local_server()

            # Save the credentials for the next run
            with open(config["token_path"], 'wb') as token:
                pickle.dump(creds, token)

        self.service = build('drive', 'v3', credentials=creds)

    def get_folder_id(self, folder_name):
        """
        Returns the id of the given folder that exists in the cloud storage.
        :param folder_name: The name of the folder from which the ID is wanted
        :return:  The ID of the folder
        """
        page_token = None
        folder_id = ""
        while True:
            response = self.service.files().list(q=str("name='" + folder_name + "'"),
                                                 spaces='drive',
                                                 fields='nextPageToken, files(id, name)',
                                                 pageToken=page_token).execute()
            for file in response.get('files', []):
                # Process change
                folder_id = file.get('id')
            page_token = response.get('nextPageToken', None)
            if page_token is None:

                # if the remote folder does not exist
                if not folder_id:
                    print("Creating folder {} in GoogleDrive storage...".format(folder_name))
                    file_metadata = {
                        'name': folder_name,
                        'mimeType': 'application/vnd.google-apps.folder'
                    }
                    file = self.service.files().create(body=file_metadata,
                                                       fields='id').execute()

                    folder_id = file.get('id')
                else:
                    break

        return folder_id

    def get_remote_files(self, contain_query):
        """
        find all files in drive whose names containes the querry
        :param contain_query: the search querry which is checked for each files name
        :return: a list containing the file names of matches
        """
        page_token = None
        files_in_drive = []
        while True:
            print("Searching for files in Cloud storage...")
            # this gives us all files where the name contains .pdf (use this for .sql
            response = self.service.files().list(q="name contains '" + str(contain_query) + "'",
                                                 spaces='drive',
                                                 # fields='nextPageToken, files(id, name)',
                                                 fields='nextPageToken, files(*)',
                                                 pageToken=page_token).execute()

            for file in response.get('files', []):
                # only use file's that are not delete (this is probably only relevant for development)
                if not file["trashed"]:
                    files_in_drive.append(file.get('name'))

            page_token = response.get('nextPageToken', None)
            if page_token is None:
                break

        print("Found {} files in cloud storage containing the querry: {}".format(len(files_in_drive), contain_query))
        return files_in_drive

    @staticmethod
    def get_local_files(local_path, contain_query):
        """
        lists all files in the folder whose name contains the contain_query
        :param local_path: the path of the folder in which to search
        :param contain_query: the querry each files name in the folder must contain
        :return: a list of (full) file paths of the matches
        """
        print("Searching for files in local folder...")
        if os.path.exists(local_path):
            local_files = [join(local_path, f) for f in listdir(local_path) if
                           isfile(join(local_path, f)) and contain_query in f]

            print("Found {} files in {} containing the querry {}".format(len(local_files), local_path, contain_query))
            return local_files

        else:
            raise Exception("Path {0} does not exist".format(local_path))

    def upload_file(self, file, drive_folder=None):
        """
        Uploads a file into a folder on the cloud
        :param file: The file that is uploaded
        :param drive_folder: The target folder into which the file should be upload. If None uploads into root
        """
        if drive_folder is not None:
            # get id for parent folder, to save file in folder in cloud
            parent_id = self.get_folder_id(folder_name=drive_folder)
            file_metadata = {'name': str(os.path.basename(file)), 'parents': [parent_id]}
        else:
            file_metadata = {'name': str(os.path.basename(file))}

        # get file type for metadata and mimetype
        filename, file_extension = os.path.splitext(os.path.basename(file))
        if file_extension == '.sql':
            mimetype = 'application/sql'
        else:
            # default case
            mimetype = 'plain/text'

        media = MediaFileUpload(str(file),
                                mimetype=mimetype)

        file = self.service.files().create(body=file_metadata,
                                           media_body=media,
                                           fields='id').execute()

        print("File {} has been uploaded into the cloud folder {}".format(file_metadata["name"], drive_folder))

if __name__ == '__main__':
    # init drive api
    Synchronizer = Synchronizer()
    auth_run = Synchronizer.authorize_app()

    # if this was an execution acquiring the token.pickle file, stop further execution
    if Synchronizer.auth_run:
        sys.exit("Token file has been acquired, exiting...")

    # get a list of files that exists in the remote drive folder and contain the query
    remote_sql_files = Synchronizer.get_remote_files(contain_query=config["contain_query"])

    # get a second list of files that exists in the remote folder and contain the query
    local_sql_files = Synchronizer.get_local_files(local_path=config["local_backup_folder"],
                                                   contain_query=config["contain_query"])

    # compare the lists, upload files that exist on local device but not in remote storage
    uploaded_new_file = False
    for local_file in local_sql_files:
        if os.path.basename(local_file) not in remote_sql_files:
            uploaded_new_file = True
            print("Local file {} is not in list of remote files".format(os.path.basename(local_file)))
            Synchronizer.upload_file(file=local_file, drive_folder=config["remote_backup_folder"])

    if not uploaded_new_file:
        print(("No file has been uploaded, because no file was found in the local directory that was not already in "
               "the cloud storage"))


# this is an openapi spec for http://localhost:8100/, create a streamlit config page to let user to read and edit env with nice looking UI components
import streamlit as st
import requests
import pandas as pd
import os
from pages.utils.style import add_style

add_style()

st.title("Configuration")

with st.sidebar:
    add_radio = st.radio(
        "Select Configuration",
        ("Server Status", "Environment Variables", "Tools", "Document Upload")
    )

API_URL = f"http://{os.getenv('INSOURCE_ADMIN_HOST')}"

if add_radio == "Server Status":
    # Create a function to check server status
    def check_server_status(url):
        response = requests.post(f"{API_URL}/chat_server_status", json={"url": url})
        return response.json()

    # Create a function to restart the server
    def restart_server():
        response = requests.get(f"{API_URL}/restart_chat_server")
        return response.json()

    st.header("Check Server Status")
    server_url = st.text_input("Enter chat server URL", f"http://{os.getenv('INSOURCE_CHAT_HOST')}")
    status_button = st.button("Check Status")

    if status_button:
        status = check_server_status(server_url)
        st.write(f"Server status: {status['status']}")

    # Restart server section
    st.header("Restart Chat Server")
    restart_button = st.button("Restart Server")

    if restart_button:
        restart_status = restart_server()
        st.write(f"Server restart status: {restart_status['status']}")

if add_radio == "Environment Variables":
    # Retrieve the available environment variables from the API
    response = requests.get(f"{API_URL}/env")
    env_vars = response.json()

    # Display and edit the environment variables
    st.header("Environment Variables")
    updated_env_vars = {}
    for key, value in env_vars.items():
        new_value = st.text_input(key, value)
        updated_env_vars[key] = new_value

    # Add an update button to submit changes
    if st.button("Update Environment Variables"):
        response = requests.put(f"{API_URL}/env", json=updated_env_vars)
        if response.status_code == 200:
            st.success("Environment variables updated successfully.")
        else:
            st.error("Failed to update environment variables.")

if add_radio == "Tools":

    # Create a function to get all tools
    def get_all_tools():
        response = requests.get(f"{API_URL}/all_tools")
        return response.json()

    # Create a function to get toggle tools
    def get_toggle_tools():
        response = requests.get(f"{API_URL}/toggle_tools")
        return response.json()

    # Create a function to disable all tools
    def disable_all_tools():
        response = requests.get(f"{API_URL}/disable_all_tools")
        return response.json()

    # Create a function to toggle a tool
    def toggle_tool(tool_name):
        response = requests.post(f"{API_URL}/toggle_tools", json={"name": tool_name})
        return response.json()

    # Create Streamlit UI
    st.header("Tools Management")

    tools = get_all_tools()
    toggle_tools = get_toggle_tools()['tools']

    # Create a dictionary to store checkbox states
    checkbox_states = {}

    # Create checkboxes for each tool
    for tool in tools:

        checkbox_states[tool] = st.checkbox(tool, value=tool in toggle_tools, key=tool)

    # Update the toggle_tool function to first disable all tools and then toggle the checked tools
    def toggle_checked_tools():
        disable_all_tools()

        for tool, state in checkbox_states.items():
            if state:
                toggle_tool(tool)

    toggle_button = st.button("Update Tools")

    if toggle_button:
        toggle_checked_tools()
        st.success("Checked tools updated successfully.")

if add_radio == "Document Upload":

    # Create functions for file management
    def read_all():
        response = requests.get(f"{API_URL}/readall/")
        return response.json()

    def upload_file(file, folder, subfolder):
        files = {"file": file}
        response = requests.post(f"{API_URL}/upload/{folder}/{subfolder}", files=files)
        return response.json()

    def delete_file(folder, subfolder, filename):
        response = requests.delete(f"{API_URL}/delete/{folder}/{subfolder}/{filename}")
        return response.json()

    # Create Streamlit UI
    st.header("File Management")

    # Read files section
    st.subheader("Read Files")
    read_button = st.button("Read Files")

    if read_button:
        files = read_all()
        # Create a DataFrame to display files in a user-friendly table format
        file_data = []
        for file in files["files"]:
            for filename in file["files"]:
                file_data.append([file["folder"], file["subfolder"], filename])

        file_df = pd.DataFrame(file_data, columns=["Folder", "Subfolder", "Filename"])
        st.write(file_df)

    # Upload files section
    st.subheader("Upload Files")

    # Folders and subfolders
    col1, col2 = st.columns(2)
    with col1:
        folder_options = ["txts", "pdfs", "words", "csvs", "htmls", "urls", "markdowns", "xmls"]
        folder = st.selectbox("Select a folder", folder_options)
    with col2:
        subfolder = st.text_input("Enter a subfolder")

    uploaded_file = st.file_uploader("Choose a file")

    if uploaded_file:
        file_details = {"FileName": uploaded_file.name, "FileType": uploaded_file.type, "FileSize": uploaded_file.size}
        st.write(file_details)
        upload_button = st.button("Upload File")

        if upload_button:
            upload_status = upload_file(uploaded_file, folder, subfolder)
            if upload_status["filename"]:
                st.success("File uploaded successfully.")

    # Delete files section
    st.subheader("Delete Files")
    delete_expander = st.expander("Delete a file")
    with delete_expander:
        col3, col4 = st.columns(2)
        with col3:
            folder = st.selectbox("Select a folder", folder_options, key="delete_folder")
        with col4:
            subfolder = st.text_input("Enter a subfolder", key="delete_subfolder")
        filename = st.text_input("Enter the filename to delete")

        if filename:
            delete_button = st.button("Delete File")

            if delete_button:
                delete_status = delete_file(folder, subfolder, filename)
                st.write(delete_status)


# -*- coding: utf-8 -*-
# @Time    : 2022/8/20 21:52
# @Author  : lzc
# @Email   : hybpjx@163.com
# @File    : 23线性回归 数据分析.py
# @Software: PyCharm
import matplotlib.pyplot as plt
import pandas as pd
# 科学计算范畴的库
from scipy.stats import linregress

sales = pd.read_excel("source/23Sales.xlsx", dtype={"Month": str})

slope, intercept, r, p, std_err = linregress(sales.index, sales.Revenue)

exp = sales.index * slope + intercept

# x轴 是sales.index y轴是sales.Revenue
# plt.bar(sales.index, sales.Revenue)
print(slope * 35 + intercept)

plt.scatter(sales.index, sales.Revenue)
plt.plot(sales.index, exp, color="orange")

plt.title(f"y={slope}*x+{intercept}")
# 重新铺了一遍x轴
plt.xticks(sales.index, sales.Month, rotation=90)
# 紧凑布局
plt.tight_layout()
plt.show()

23线性回归 数据分析.py


print("Find the minimum amount of coins to make change for a given amount of money.")

money = float(input("How much: "))

# According to https://blog.softhints.com/python-declare-multiple-variables/
total = quarters = dimes = nickels = pennies = 0

quarters = int(money / 0.25)
money = money % 0.25
dimes = int(money / 0.10)
money = money % 0.10
nickels = int(money / 0.05)
money = money % 0.05
pennies = int(money / 0.01)
money = money % 0.01

total = quarters + dimes + nickels + pennies

print("The minimum amount of coins necessary is", total)

print("The necessary coins are ", end="")
if quarters > 0:
    print(quarters, "quarter(s) ", end="")
if dimes > 0:
    print(dimes, "dime(s)" , end="")
if nickels > 0:
    print(nickels, "nickel(s) ", end="")
if pennies > 0:
    print(pennies, "pennies ", end="")


import keyboard
import random
import time

from colorama import init
from termcolor import colored

prod = u"\u2588"u"\u2588"

class Productor:
    pos = 0
    time = 0
    wait = False
    estado = "init" #init, durmiendo, esperando, trabajando
    estado_exp = "init"

def producir(p):
    buffer[p] = prod
    return

class Consumidor:
    pos = 0
    time = 0
    wait = False
    estado = "init" #init, durmiendo, esperando, trabajando
    estado_exp = "init"

def consumir(p):
    buffer[p] = "__"
    return

buffer = []
productor = Productor()
consumidor = Consumidor()

estados = ["Durmiendo", "Trabajando"]
procesos = ["Productor", "Consumidor"]

#Buffer ocupado por cualquiera de los dos
semaforo = False
wait_prod = False
wait_cons = False

def bufferClean():
    i = 0
    while i < 30:
        buffer.append("__")
        i+=1

def coloredNumber(i):
    if(i == productor.pos +1 and productor.pos + 1 == consumidor.pos + 1):
         return colored(i, 'grey', 'on_white')
    elif(i == productor.pos + 1):
        return colored(i, 'grey', 'on_yellow')
    elif(i == consumidor.pos + 1):
        return colored(i, 'grey', 'on_blue')
    else:
        return i

def printBuffer():
    i = 0
    while i<30:
        print(buffer[i], " ", end = "")
        i+=1

    print("")

    i = 0
    space = "  "
    while i<30:

        if(i==9):
            space = " "

        print(coloredNumber(i+1), space, end = "")
        i+=1

    print("\n")

def checkProdAvailable():
    #Producir en su posicion
    if(buffer[productor.pos] == "__"):
        return True
    else:
        return False

def checkConsAvailable():
    #Consumir su posicion
    if(buffer[consumidor.pos] == prod):
        return True
    else:
        return False

def printSem():
    if(semaforo):
        return colored(semaforo, 'green')
    else:
        return colored(semaforo, 'red')

def printWait_Prod():
    if(wait_prod):
        return colored(wait_prod, 'green')
    else:
        return colored(wait_prod, 'red')

def printWait_Cons():
    if(wait_cons):
        return colored(wait_cons, 'green')
    else:
        return colored(wait_cons, 'red')

#Llena el buffer de espacios vacios "_"
bufferClean()

ciclo = 0

while True:
    time.sleep(0.25)

    if(keyboard.is_pressed('ESC')):
        print("\n\nTerminando...")
        break

    #

    else:
        print("########################################################################################################################")
        print("\nCiclo: ", ciclo+1, "\n")

        #Si wait activo entonces proceso debe de ESPERAR
        if(wait_prod == False and productor.time > 0): #Si aun tiene tiempo y puede trabajar o dormir
            productor.time -= 1
        elif(productor.estado != "Esperando" and productor.time < 1): #Si terminó su trabajo o sueño
            productor.estado_exp = random.choice(estados)
            #wait_cons = False
            if(productor.estado == "Trabajando"):#Si el estado era trabajando apagamos semaforo
                semaforo = False
            productor.estado = "Eligiendo"

        if(wait_cons == False and consumidor.time > 0):
            consumidor.time -= 1
        elif(consumidor.estado != "Esperando" and consumidor.time < 1):
            consumidor.estado_exp = random.choice(estados)
            #wait_prod = False
            if(consumidor.estado == "Trabajando"):
                semaforo = False
            consumidor.estado = "Eligiendo"

        #Definicion de estados
        if(semaforo == False):
            #Si hay alguien esperando tiene prioridad
            if(productor.estado == "Esperando"):#Si esta esperando tiene prioridad para entrar
                if(checkProdAvailable()):
                    #print("productor - esp a trabaj # 150")
                    productor.estado = "Trabajando"
                    semaforo = True
                    wait_prod = False
                    #wait_cons = True
                    if(consumidor.estado_exp != "!"):#Cuando se esta realizando un proceso se asigna este caracter
                        #Se esta esperando a asignarse un trabajo
                        if(consumidor.estado_exp == "Trabajando" and checkConsAvailable()):
                            #Si el consumidor quiere trabajar y puede trabajar
                            if(semaforo == False):#El productor no pudo entrar
                                #Se pone a trabajar el consumidor
                                consumidor.estado = "Trabajando"
                                consumidor.estado_exp = "!"
                                semaforo = True
                                wait_cons = False
                            else:
                                #Estado esperando True el wait_cons
                                consumidor.estado = "Esperando"
                                consumidor.estado_exp = "!"
                                wait_cons = True
                            consumidor.time = random.randrange(3, 11, 1)#Asignacion de tiempo
                        elif(consumidor.estado_exp == "Durmiendo"):#Para cuando el consumidor quiera dormir
                            consumidor.estado_exp = "!"#Caracter de control
                            consumidor.estado = "Durmiendo"
                            consumidor.time = random.randrange(3, 11, 1)
                elif(checkProdAvailable() == False):#En caso de que el productor no pueda trabajar
                    if(consumidor.estado_exp != "!"):
                        if(consumidor.estado_exp == "Trabajando" and checkConsAvailable()):
                            if(semaforo == False):
                                consumidor.estado = "Trabajando"
                                consumidor.estado_exp = "!"
                                semaforo = True
                                wait_cons = False
                            else:
                                consumidor.estado = "Esperando"
                                consumidor.estado_exp = "!"
                                wait_cons = True
                            consumidor.time = random.randrange(3, 11, 1)

            elif(consumidor.estado == "Esperando"):
                if(checkConsAvailable()):
                    #Analizamos al consumidor
                    consumidor.estado = "Trabajando"
                    semaforo = True
                    wait_cons = False
                    if(productor.estado_exp != "!"):
                        #Trabajamos con el productor
                        if(productor.estado_exp == "Trabajando" and checkProdAvailable()):
                            if(semaforo == False):
                                productor.estado = "Trabajando"
                                productor.estado_exp = "!"
                                semaforo = True
                                wait_cons = True
                            else:
                                productor.estado = "Esperando"
                                productor.estado_exp = "!"
                                wait_prod = True
                            productor.time = random.randrange(3, 11, 1)
                        elif(productor.estado_exp == "Durmiendo"):
                            productor.estado_exp = "!"
                            productor.estado = "Durmiendo"
                            productor.time = random.randrange(3, 11, 1)
                elif(checkConsAvailable() == False):
                    if(productor.estado_exp != "!"):
                        if(productor.estado_exp == "Trabajando" and checkProdAvailable()):
                            if(semaforo == False):
                                productor.estado = "Trabajando"
                                productor.estado_exp = "!"
                                semaforo = True
                                wait_cons = True
                                wait_prod = False
                            else:
                                productor.estado = "Esperando"
                                productor.estado_exp = "!"
                                wait_prod = True
                            productor.time = random.randrange(3, 11, 1)
                        elif(productor.estado_exp == "Durmiendo"):
                            productor.estado_exp = "!"
                            productor.estado = "Durmiendo"
                            productor.time = random.randrange(3, 11, 1)

            #Ambos quieren trabajar
            elif(productor.estado_exp == consumidor.estado_exp == "Trabajando"):#Verificamos
                if(checkProdAvailable()): #Si puede entrar productor
                    productor.estado = "Trabajando"
                    consumidor.estado = "Esperando"
                    wait_cons = True
                    semaforo = True
                    productor.estado_exp = "!"
                    consumidor.estado_exp = "!"
                    productor.time = random.randrange(3, 11, 1)
                    consumidor.time = random.randrange(3, 11, 1)
                elif(checkConsAvailable()): #Si puede entrar consumidor
                    productor.estado = "Esperando"
                    consumidor.estado = "Trabajando"
                    wait_prod = True
                    semaforo = True
                    consumidor.estado_exp = "!"
                    productor.estado_exp = "!"
                    productor.time = random.randrange(3, 11, 1)
                    consumidor.time = random.randrange(3, 11, 1)

            #Uno quiere trabajar, otro dormir
            elif((productor.estado_exp == "Durmiendo" and consumidor.estado_exp == "Trabajando") or (productor.estado_exp == "Trabajando" and consumidor.estado_exp == "Durmiendo")):
                if(productor.estado_exp == "Trabajando"):
                    productor.estado_exp = "!"
                    consumidor.estado_exp = "!"
                    productor.estado = "Trabajando"
                    consumidor.estado = "Durmiendo"
                    semaforo = True
                    productor.time = random.randrange(3, 11, 1)
                    consumidor.time = random.randrange(3, 11, 1)
                elif(consumidor.estado_exp == "Trabajando"):
                    productor.estado_exp = "!"
                    consumidor.estado_exp = "!"
                    productor.estado = "Durmiendo"
                    consumidor.estado = "Trabajando"
                    semaforo = True
                    productor.time = random.randrange(3, 11, 1)
                    consumidor.time = random.randrange(3, 11, 1)

            #Ambos quieren dormir
            elif(productor.estado_exp == "Durmiendo" == consumidor.estado_exp):
                wait_cons = False
                wait_prod = False
                semaforo = False
                productor.estado_exp = "!"
                consumidor.estado_exp = "!"
                productor.estado = "Durmiendo"
                consumidor.estado = "Durmiendo"
                productor.time = random.randrange(3, 11, 1)
                consumidor.time = random.randrange(3, 11, 1)

            #Uno durmiendo, el otro quiere dormir
            elif(productor.estado_exp == "Durmiendo" and consumidor.estado == "Durmiendo") or (productor.estado == "Durmiendo" and consumidor.estado_exp == "Durmiendo"):
                if(productor.estado_exp == "Durmiendo"):
                    productor.estado_exp = "!"
                    productor.estado = "Durmiendo"
                    productor.time = random.randrange(3, 11, 1)
                elif(consumidor.estado_exp == "Durmiendo"):
                    consumidor.estado_exp = "!"
                    consumidor.estado = "Durmiendo"
                    consumidor.time = random.randrange(3, 11, 1)

            #Uno durmiendo, el otro quiere trabajar
            elif(productor.estado_exp == "Trabajando" and consumidor.estado == "Durmiendo") or (productor.estado == "Durmiendo" and consumidor.estado_exp == "Trabajando"):
                if(productor.estado_exp == "Trabajando" and checkProdAvailable()):
                    productor.estado_exp = "!"
                    productor.estado = "Trabajando"
                    semaforo = True
                    productor.time = random.randrange(3, 11, 1)
                elif(consumidor.estado_exp == "Trabajando" and checkConsAvailable()):
                    consumidor.estado_exp = "!"
                    consumidor.estado = "Trabajando"
                    semaforo = True
                    consumidor.time = random.randrange(3, 11, 1)

            #Uno Esperando, el otro quiere trabajar
            elif(productor.estado_exp == "Trabajando" and consumidor.estado == "Esperando") or (productor.estado == "Esperando" and consumidor.estado_exp == "Trabajando"):
                if(productor.estado_exp == "Trabajando" and checkProdAvailable()):
                    productor.estado_exp = "!"
                    productor.estado = "Trabajando"
                    productor.time = random.randrange(3, 11, 1)
                    semaforo = True
                elif(consumidor.estado_exp == "Trabajando" and checkConsAvailable()):
                    consumidor.estado_exp = "!"
                    consumidor.estado = "Trabajando"
                    semaforo = True
                    consumidor.time = random.randrange(3, 11, 1)

            #Uno Esperando, el otro quiere Dormir
            elif(productor.estado_exp == "Durmiendo" and consumidor.estado == "Esperando") or (productor.estado == "Esperando" and consumidor.estado_exp == "Durmiendo"):
                if(productor.estado_exp == "Durmiendo"):
                    productor.estado_exp = "!"
                    productor.estado = "Durmiendo"
                    productor.time = random.randrange(3, 11, 1)
                elif(consumidor.estado_exp == "Durmiendo"):
                    consumidor.estado_exp = "!"
                    consumidor.estado = "Durmiendo"
                    consumidor.time = random.randrange(3, 11, 1)

        elif(semaforo == True):#Semaforo prendido o hay alguien trabajando
            #Uno trabajando, el otro quiere trabajar
            #Uno trabajando, el otro quiere dormir
            if(productor.estado_exp == "Trabajando"): #Poner a esperar, si el productor quiere trabajar
                productor.estado_exp = "!"
                productor.estado = "Esperando"
                wait_prod = True
                productor.time = random.randrange(3, 11, 1)
            elif(productor.estado_exp == "Durmiendo"): #Si quiere dormir se pone durmiendo
                #print("Sem ON - Prod quiere dormir #305")
                productor.estado_exp = "!"
                productor.estado = "Durmiendo"
                wait_prod = False
                productor.time = random.randrange(3, 11, 1)

            if(consumidor.estado_exp == "Trabajando"):
                #print("Sem ON - Cons quiere trabajar #313")
                consumidor.estado_exp = "!"
                consumidor.estado = "Esperando"
                wait_cons = True
                consumidor.time = random.randrange(3, 11, 1)
            elif(consumidor.estado_exp == "Durmiendo"):
                #print("Sem ON - Cons quiere dormir #319")
                consumidor.estado_exp = "!"
                consumidor.estado = "Durmiendo"
                wait_cons = False
                consumidor.time = random.randrange(3, 11, 1)

        #TRABAJANDO - PRINCIPAL
        if(productor.estado == "Trabajando" and checkProdAvailable() == True):
            producir(productor.pos)#Mandamos la posicion de nuestro productor
            if(productor.pos < 29):
                productor.pos += 1
            else:
                productor.pos = 0
        elif(productor.estado == "Trabajando" and checkProdAvailable() == False):
            wait_prod = True
            wait_cons = False
            productor.estado = "Esperando"
            semaforo = False
            if(consumidor.estado == "Esperando" and checkConsAvailable()):
                consumidor.estado = "Trabajando"
                consumidor.time += 1
                semaforo = True

        if(consumidor.estado == "Trabajando" and checkConsAvailable() == True):
            consumir(consumidor.pos)
            if(consumidor.pos < 29):
                consumidor.pos += 1
            else:
                consumidor.pos = 0
        elif(consumidor.estado == "Trabajando" and checkConsAvailable() == False):
            wait_prod = False
            wait_cons = True
            consumidor.estado = "Esperando"
            semaforo = False
            if(productor.estado == "Esperando" and checkProdAvailable()):
                productor.estado = "Trabajando"
                productor.time += 1
                semaforo = True

        print("Semaforo:", printSem(), "\nwait_prod:", printWait_Prod(), "    wait_cons:", printWait_Cons(), "\n\n", colored("Productor: ", 'grey', 'on_yellow'), productor.estado, "[", productor.time,"]", " - Pos:", productor.pos+1, "\n", colored("Consumidor: ", 'grey', 'on_blue'), consumidor.estado, "[", consumidor.time, "]", "- Pos:", consumidor.pos+1,"\n")

        ciclo += 1
        #Main
        printBuffer()


#!/usr/bin/env Python
from sys import argv
import sys
import numpy

sys.setrecursionlimit(10000)

with open(argv[1],'r') as in_file:
  in_data = in_file.read().splitlines()
in_file.closed

if (len(in_data[0]) > len(in_data[1])):
  str1 = in_data[0]
  str2 = in_data[1]
else:
  str1 = in_data[1]
  str2 = in_data[0]

def LCS(v,w):
  n = len(v)
  m = len(w)
  s = numpy.zeros(shape=(n+1,m+1))
  b = numpy.zeros(shape=(n+1,m+1))
  for i in range(1,n+1):
    for j in range(1,m+1):
      if (v[i-1] == w[j-1]):
        s[i][j] = max(s[i-1][j],s[i][j-1],s[i-1][j-1]+1)
      else:
        s[i][j] = max(s[i-1][j],s[i][j-1])
      if (s[i][j] == s[i-1][j]):
        b[i][j] = 1
      elif (s[i][j] == s[i][j-1]):
        b[i][j] = 2
      elif (s[i][j] == (s[i-1][j-1] + 1)):
        b[i][j] = 3
  return (s[n][m],b,s)

lc_string = []

def PrintLCS(b,v,i,j):
  if (i == 0 or j == 0):
    return
  if (b[i][j] == 3):
    PrintLCS(b,v,i-1,j-1)
    lc_string.append(v[i-1])
  else:
    if (b[i][j] == 1):
      PrintLCS(b,v,i-1,j)
    else:
      PrintLCS(b,v,i,j-1)

PrintLCS(LCS(str1,str2)[1],str1,len(str1),len(str2))
with open("finding_shared_spliced_motif.txt",'w') as out_file:
  out_file.write("".join(lc_string))
out_file.closed


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('slide', '0002_slide_image'),
    ]

    operations = [
        migrations.AlterField(
            model_name='slide',
            name='image',
            field=models.ImageField(height_field=b'height', upload_to=b'', width_field=b'width', verbose_name='\u56fe\u7247\u6587\u4ef6'),
        ),
    ]


import os

__all__ = ["listdir", "opendir", "annotate", "reset"]

cache = {}

def reset():
    """Reset the cache completely."""
    global cache
    cache = {}

def listdir(path):
    """List directory contents, using cache."""
    try:
        cached_mtime, list = cache[path]
        del cache[path]
    except KeyError:
        cached_mtime, list = -1, []
    try:
        mtime = os.stat(path)[8]
    except os.error:
        return []
    if mtime != cached_mtime:
        try:
            list = os.listdir(path)
        except os.error:
            return []
        list.sort()
    cache[path] = mtime, list
    return list

opendir = listdir  # XXX backward compatibility

def annotate(head, list):
    """Add '/' suffixes to directories."""
    for i in range(len(list)):
        if os.path.isdir(os.path.join(head, list[i])):
            list[i] = list[i] + '/'


############################################################
#
# craft_poisons_htbd.py
# Hidden Trigger Backdoor Attack
# June 2020
#
# Reference: A. Saha, A. Subramanya, and H. Pirsiavash. Hidden
#     trigger backdoor attacks. arXiv:1910.00033, 2019.
############################################################
import argparse
import logging
import os
import pickle
import sys

import numpy as np
import torch
import torch.utils.data
import torchvision
import torchvision.transforms as transforms
from PIL import Image

sys.path.append(os.path.realpath("."))
from learning_module import (
    TINYIMAGENET_ROOT,
    load_model_from_checkpoint,
    now,
    get_transform,
    NormalizeByChannelMeanStd,
    data_mean_std_dict,
)
from tinyimagenet_module import TinyImageNet

class LossMeter(object):
    """Computes and stores the average and current loss value"""

    def __init__(self):
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

def adjust_learning_rate(lr, iteration, dataset):
    """Update the learning rate by a factor after certain iterations
    inputs:
        lr:         Current learning rate
        iter:       Current iteration number
        dataset:  Name of the dataset
    return:
        updated learning rate
    """
    if dataset.upper() == "CIFAR10":
        lr = lr * (0.95 ** (iteration // 2000))
        return lr
    else:
        lr = lr * (0.5 ** (iteration // 1000))
        return lr

def main(args):
    """Function to generate the generate the HTBD poison
    inputs:
        args:        Argument Parser object
    return:
        void
    """
    print(now(), "craft_poisons_htbd.py main() running...")
    mean, std = data_mean_std_dict[args.dataset.lower()]
    normalization_net = NormalizeByChannelMeanStd(mean, std)
    device = "cuda" if torch.cuda.is_available() else "cpu"
    net = load_model_from_checkpoint(
        args.model[0], args.model_path[0], args.pretrain_dataset
    )
    net.eval()
    normalization_net = normalization_net.to(device)
    net = net.to(device)

    ####################################################
    #               Dataset
    if args.dataset.lower() == "cifar10":
        transform_test = get_transform(False, False)
        testset = torchvision.datasets.CIFAR10(
            root="./data", train=False, download=True, transform=transform_test
        )
        trainset = torchvision.datasets.CIFAR10(
            root="./data", train=True, download=True, transform=transform_test
        )
        num_per_class = 5000
    elif args.dataset.lower() == "tinyimagenet_first":
        transform_test = get_transform(False, False, dataset=args.dataset)
        trainset = TinyImageNet(
            TINYIMAGENET_ROOT,
            split="train",
            transform=transform_test,
            classes="firsthalf",
        )
        testset = TinyImageNet(
            TINYIMAGENET_ROOT,
            split="val",
            transform=transform_test,
            classes="firsthalf",
        )
        num_per_class = 500
    elif args.dataset.lower() == "tinyimagenet_last":
        transform_test = get_transform(False, False, dataset=args.dataset)
        trainset = TinyImageNet(
            TINYIMAGENET_ROOT,
            split="train",
            transform=transform_test,
            classes="lasthalf",
        )
        testset = TinyImageNet(
            TINYIMAGENET_ROOT,
            split="val",
            transform=transform_test,
            classes="lasthalf",
        )
        num_per_class = 500
    elif args.dataset.lower() == "tinyimagenet_all":
        transform_test = get_transform(False, False, dataset=args.dataset)
        trainset = TinyImageNet(
            TINYIMAGENET_ROOT,
            split="train",
            transform=transform_test,
            classes="all",
        )
        testset = TinyImageNet(
            TINYIMAGENET_ROOT,
            split="val",
            transform=transform_test,
            classes="all",
        )
        num_per_class = 500
    else:
        print("Dataset not yet implemented. Exiting from craft_poisons_htbd.py.")
        sys.exit()
    ###################################################

    with open(args.poison_setups, "rb") as handle:
        setup_dicts = pickle.load(handle)
    setup = setup_dicts[args.setup_idx]

    losses = LossMeter()
    lr = args.lr

    trans_trigger = transforms.Compose(
        [transforms.Resize((args.patch_size, args.patch_size)), transforms.ToTensor()]
    )
    trigger = Image.open(args.trigger_path).convert("RGB")
    trigger = trans_trigger(trigger).unsqueeze(0).to(device)

    target_img_idx = (
        setup["target index"] if args.target_img_idx is None else args.target_img_idx
    )
    base_indices = (
        setup["base indices"] if args.base_indices is None else args.base_indices
    )

    target_img_save, target_label_save = testset[target_img_idx]
    target_class = target_label_save

    # Get target images
    trainset_targets = np.array(trainset.targets)
    target_class = target_class
    tar_idx = np.where(trainset_targets == target_class)[0]
    indexes = np.arange(0, num_per_class)
    indexes = np.random.choice(indexes, len(base_indices), replace=False)
    target_img_idx = np.array(tar_idx[indexes]).astype(int)

    poisoned_tuples = []
    target_tuples = []

    # get multiple bases
    base_imgs = torch.stack([trainset[i][0] for i in base_indices]).to(device)
    base_labels = torch.LongTensor([trainset[i][1] for i in base_indices]).to(device)

    target_imgs = torch.stack([trainset[i][0] for i in target_img_idx]).to(device)

    batch_size = base_imgs.shape[0]

    start_x = args.image_size - args.patch_size - 5
    start_y = args.image_size - args.patch_size - 5

    for i in range(0, len(base_imgs), batch_size):

        remaining = np.min((batch_size, len(base_imgs) - i))
        input_target_imgs = target_imgs[i : i + remaining]
        input_bases = base_imgs[i : i + remaining]
        input_target_imgs = input_target_imgs.to(device)
        input_bases = input_bases.to(device)

        for z in range(input_target_imgs.size(0)):
            # paste the trigger on input_target_imgs
            input_target_imgs[
                z,
                :,
                start_y : start_y + args.patch_size,
                start_x : start_x + args.patch_size,
            ] = trigger

        # get features of input_target_imgs
        if args.normalize:
            input_target_imgs = normalization_net(input_target_imgs)
        feat1 = net(input_target_imgs, penu=True)
        feat1 = feat1.detach().clone()

        for j in range(args.crafting_iters):
            input_bases.requires_grad_()
            lr1 = adjust_learning_rate(lr, j, args.dataset)

            # get features of input_bases
            if args.normalize:
                input_bases_proc = normalization_net(input_bases)
            else:
                input_bases_proc = input_bases

            feat2 = net(input_bases_proc, penu=True)
            feat11 = feat1.clone()
            dist = torch.cdist(feat1, feat2)
            for _ in range(feat2.size(0)):

                dist_min_index = (dist == torch.min(dist)).nonzero().squeeze()
                feat1[dist_min_index[1]] = feat11[dist_min_index[0]]
                dist[dist_min_index[0], dist_min_index[1]] = 1e5

            loss = torch.norm(feat1 - feat2) ** 2
            losses.update(loss.item(), input_target_imgs.size(0))
            loss.backward()

            input_bases = input_bases - lr1 * input_bases.grad
            pert = input_bases - base_imgs[i : i + remaining]
            pert = torch.clamp(pert, -args.epsilon, args.epsilon).detach_()
            input_bases = pert + base_imgs[i : i + remaining]
            input_bases = input_bases.clamp(0, 1)

            if j % 100 == 0:
                logging.info(
                    "Epoch: {:2d} | i: {} | iter: {:5d} | LR: {:2.5f} | Loss Val: {:5.3f} | Loss Avg: {:5.3f}".format(
                        0, i, j, lr1, losses.val, losses.avg
                    )
                )
                print(
                    "Epoch: {:2d} | i: {} | iter: {:5d} | LR: {:2.5f} | Loss Val: {:5.3f} | Loss Avg: {:5.3f}".format(
                        0, i, j, lr1, losses.val, losses.avg
                    )
                )

            if loss.item() < 10 or j == (args.crafting_iters - 1):
                logging.info("Max_Loss: {}".format(loss.item()))
                for k in range(input_bases.size(0)):
                    poisoned_tuples.append(
                        (
                            transforms.ToPILImage()(input_bases[k].cpu()),
                            int(base_labels[i + k]),
                        )
                    )
                    if len(target_tuples) < 1:
                        img = target_img_save.to(device)
                        trigger_ = trigger.cpu()

                        # Tuple for target.pickle
                        target_tuples.append(
                            (
                                transforms.ToPILImage()(img.cpu()),
                                int(target_label_save),
                                trigger_.squeeze(0),
                                [start_x, start_y],
                            )
                        )
                break

    # Creating the directories and saving the poisons
    print(now(), "Saving poisons...")
    if not os.path.isdir(args.poisons_path):
        os.makedirs(args.poisons_path)
    with open(os.path.join(args.poisons_path, "poisons.pickle"), "wb") as handle:
        pickle.dump(poisoned_tuples, handle, protocol=pickle.HIGHEST_PROTOCOL)
    with open(os.path.join(args.poisons_path, "target.pickle"), "wb") as handle:
        pickle.dump(target_tuples[0], handle, protocol=pickle.HIGHEST_PROTOCOL)
    with open(os.path.join(args.poisons_path, "base_indices.pickle"), "wb") as handle:
        pickle.dump(base_indices, handle, protocol=pickle.HIGHEST_PROTOCOL)
    ####################################################

    print(now(), "craft_poisons_htbd.py done.")
    return

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description="Hidden Trigger Backdoor Attack")
    parser.add_argument("--dataset", type=str, default="CIFAR10", help="dataset")
    parser.add_argument("--normalize", dest="normalize", action="store_true")
    parser.add_argument("--no-normalize", dest="normalize", action="store_false")
    parser.set_defaults(normalize=True)
    parser.add_argument(
        "--epsilon", type=int, default=8 / 255, help="poison perturbation allowance"
    )
    parser.add_argument(
        "--model", type=str, default=["resnet18"], nargs="+", help="model name"
    )
    parser.add_argument("--image_size", type=int, default=32, help="Image Size")
    parser.add_argument("--patch_size", type=int, default=5, help="Size of the patch")
    parser.add_argument(
        "--trigger_path",
        type=str,
        default="./poison_crafting/triggers/htbd.png",
        help="Trigger path",
    )
    parser.add_argument("--lr", type=float, default=0.001, help="learning rate")
    parser.add_argument("--batch_size", type=int, default=100, help="Batch Size")
    parser.add_argument(
        "--crafting_iters", type=int, default=5000, help="Number of iterations"
    )
    parser.add_argument(
        "--poison_setups",
        type=str,
        default="./poison_setups/cifar10_transfer_learning.pickle",
        help="poison setup pickle file",
    )
    parser.add_argument("--setup_idx", type=int, default=0, help="Which setup to use")
    parser.add_argument(
        "--poisons_path",
        default="poison_examples/htbd_poisons",
        type=str,
        help="Where to save the poisons?",
    )
    parser.add_argument(
        "--base_indices", nargs="+", default=None, type=int, help="which base images"
    )
    parser.add_argument(
        "--target_img_idx",
        default=None,
        type=int,
        help="Index of the target image in the clean set.",
    )
    parser.add_argument(
        "--model_path",
        type=str,
        nargs="+",
        default=["pretrained_models/ResNet18_CIFAR100_A.pth"],
        help="Checkpoint file",
    )
    parser.add_argument(
        "--pretrain_dataset", default="CIFAR100", type=str, help="dataset"
    )

    args = parser.parse_args()

    if args.dataset.lower() == "cifar10":
        args.image_size = 32
    elif "tinyimagenet" in args.dataset.lower():
        args.image_size = 64

    main(args)


import urllib
from bs4 import BeautifulSoup

def get_data():
	page = "http://www.governing.com/gov-data/gentrification-in-cities-governing-report.html"

	# query the website and return the html to the variable ‘page’
	page = urllib.request.urlopen(page)

	# parse the html using beautiful soup and store in variable `soup`
	soup = BeautifulSoup(page, "html.parser")

	# get table with data
	table = soup.find("table", attrs={"id": "inputdata"})

	data = []
	# get the index price
	for row in table.find_all('tr'):
	    column_marker = 0
	    columns = row.find_all('td')
	    count = 0
	    city = ""
	    index = 0
	    for column in columns:
	    	if count == 0:
	    		city = column.get_text()
	    	elif count == 1:
	    		index = column.get_text()
	    	else:
	    		break;
	    	count += 1
	    data.append([city, index])

	data = data[2:]

	# turn percent to float
	for d in data:
		val = d[1][0:-1]
		d[1] = float(val)

	###########################################
	# get educational attainment on each city #
	###########################################
	page = "https://en.wikipedia.org/wiki/List_of_U.S._states_by_educational_attainment"

	# query the website and return the html to the variable ‘page’
	page = urllib.request.urlopen(page)

	# parse the html using beautiful soup and store in variable `soup`
	soup = BeautifulSoup(page, "html.parser")

	# get table with data
	table = soup.find("table", attrs={"class": "wikitable sortable"})

	edu = {}
	# get the educational attainment
	for row in table.find_all('tr'):
	    column_marker = 0
	    columns = row.find_all('td')
	    count = 0
	    city = ""
	    index = 0
	    for column in columns:
	    	if count == 0:
	    		city = column.get_text()
	    	elif count == 3:
	    		index = column.get_text()
	    	elif count > 3:
	    		break;
	    	count += 1
	    	edu[city] = index

	# abbreviations to states
	states = {
	        'AK': 'Alaska',
	        'AL': 'Alabama',
	        'AR': 'Arkansas',
	        'AS': 'American Samoa',
	        'AZ': 'Arizona',
	        'CA': 'California',
	        'CO': 'Colorado',
	        'CT': 'Connecticut',
	        'DC': 'District of Columbia',
	        'DE': 'Delaware',
	        'FL': 'Florida',
	        'GA': 'Georgia',
	        'GU': 'Guam',
	        'HI': 'Hawaii',
	        'IA': 'Iowa',
	        'ID': 'Idaho',
	        'IL': 'Illinois',
	        'IN': 'Indiana',
	        'KS': 'Kansas',
	        'KY': 'Kentucky',
	        'LA': 'Louisiana',
	        'MA': 'Massachusetts',
	        'MD': 'Maryland',
	        'ME': 'Maine',
	        'MI': 'Michigan',
	        'MN': 'Minnesota',
	        'MO': 'Missouri',
	        'MP': 'Northern Mariana Islands',
	        'MS': 'Mississippi',
	        'MT': 'Montana',
	        'NA': 'National',
	        'NC': 'North Carolina',
	        'ND': 'North Dakota',
	        'NE': 'Nebraska',
	        'NH': 'New Hampshire',
	        'NJ': 'New Jersey',
	        'NM': 'New Mexico',
	        'NV': 'Nevada',
	        'NY': 'New York',
	        'OH': 'Ohio',
	        'OK': 'Oklahoma',
	        'OR': 'Oregon',
	        'PA': 'Pennsylvania',
	        'PR': 'Puerto Rico',
	        'RI': 'Rhode Island',
	        'SC': 'South Carolina',
	        'SD': 'South Dakota',
	        'TN': 'Tennessee',
	        'TX': 'Texas',
	        'UT': 'Utah',
	        'VA': 'Virginia',
	        'VI': 'Virgin Islands',
	        'VT': 'Vermont',
	        'WA': 'Washington',
	        'WI': 'Wisconsin',
	        'WV': 'West Virginia',
	        'WY': 'Wyoming'
	}

	# iterate through data and get educatiuonal attainment
	for node in data:
		city = node[0]
		state = states[city[-2:]]
		node.append(float(edu[state][0:-1]))

	########################
	# get household income #
	########################
	page = "https://en.wikipedia.org/wiki/List_of_U.S._states_by_income"

	# query the website and return the html to the variable ‘page’
	page = urllib.request.urlopen(page)

	# parse the html using beautiful soup and store in variable `soup`
	soup = BeautifulSoup(page, "html.parser")

	# get table with data
	table = soup.find("table", attrs={"class": "wikitable sortable"})

	income = {}
	# get the income
	for row in table.find_all('tr'):
	    column_marker = 0
	    columns = row.find_all('td')
	    count = 0
	    city = ""
	    index = 0
	    for column in columns:
	    	if count == 1:
	    		city = column.get_text()
	    	elif count == 2:
	    		index = column.get_text()
	    	elif count > 2:
	    		break;
	    	count += 1
	    	income[city] = index
	income["District of Columbia"] = "$75,628"

	# iterate through data and get income
	for node in data:
		city = node[0]
		state = states[city[-2:]]
		val = income[state].replace(",","")[1:]
		node.append(float(val))

	return data


import time
from flask import Flask, jsonify, request, render_template, redirect, url_for, flash, session
from datetime import datetime
import hashlib, json

class blockchain:
	def __init__(self):
		self.chain = []
		self.transaction_pendientes = []
		self.transaction(0, 0, 0) # se crea la transaccion genesis
		self.create_block(proof = 1, previous_hash = '0') # se crea el bloque genesis

	def create_block(self, proof, previous_hash):
		block = {
			'index': len(self.chain) + 1,
			'tiempo': str(datetime.now()),
			'transacciones': self.transaction_pendientes,
			'proof': proof,
			'previous_hash': previous_hash
			} # despues de agregar las transacciones, se limpian las transacciones pendientes para que no se repitan en la proxima creacion de bloque
		self.transaction_pendientes = [] #limpiar las transacciones pendientes
		self.chain.append(block) #agregar el bloque a la blockchain
		return block #retornar el bloque creado

	def anterior_bloque(self): #retornar el bloque anterior
		return self.chain[-1]

	def proof_of_work(self, previous_proof):
		new_proof = 1
		check_proof = False
		while check_proof is False:
			hash_operation = hashlib.sha256(str(new_proof**2 + previous_proof**2).encode()).hexdigest()
			if hash_operation[:4] == '4242': #si el hash empieza con 4242, es correcto
				check_proof = True
			else:
				new_proof += 1
		if check_proof is True:
			blockchain.transaction('4c6e7e2a9f2f7f7ff8e7d3d6c8b7c6e8e23a7', '4c6e7e2a9f2f7f7ff8e7d3d6c8b7c6e8e23a7', 42) #transaccion para minar
			print('Se ha minado un bloque con un hash de: ' + hash_operation, 'y se han recompesado al minero: ')
		return new_proof

	def hash(self, block): #funcion para calcular el hash del bloque
		encoded_block = json.dumps(block, sort_keys = True).encode() #se codifica el bloque
		return hashlib.sha256(encoded_block).hexdigest() #se retorna el hash del bloque

	def transaction(self, sender, recipient, amount): #funcion para agregar transacciones a la blockchain
		transaccion = {
			'sender': sender,
			'recipient': recipient,
			'amount': amount
			}
		self.transaction_pendientes.append(transaccion) #se agrega la transacc
		return transaccion #se retorna la transaccion

blockchain = blockchain()

print('El bloque creado es: ')

############################## flask appp web ################################################

app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
	return r'
ft_blockchain is going on!
'

@app.route('/chain', methods=['GET'])
def chain():
	chain = {
		'chain': blockchain.chain,
		'length': len(blockchain.chain)
	}
	return jsonify(chain)

@app.route('/mine', methods=['GET'])
def mine():
	previous_block = blockchain.anterior_bloque()
	previous_proof = previous_block['proof']
	proof = blockchain.proof_of_work(previous_proof)
	previous_hash = blockchain.hash(previous_block)
	block = blockchain.create_block(proof, previous_hash)
	print ('Se ha minado un bloque con un hash de: ' + blockchain.hash(block))
	return jsonify(block), 200

@app.route('/transactions/new', methods=['POST', 'GET'])
def new_transaction():
	if request.method == 'GET':
		a = blockchain.transaction('4c6e7e2a9f2f7f7ff8e7d3d6c8b7c6e8e23a7', '4c6e7e2a9f2f7f7ff8e7d3d6c8b7c6e8e23a7', 1000) #transaccion para mi
		return jsonify(a), 200
	elif request.method == 'POST':
		values = request.get_json()
		required = ['sender', 'recipient', 'amount']
		if not all(k in values for k in required):
			return 'Missing values', 400
		blockchain.transaction(values['sender'], values['recipient'], values['amount'])
		print('Se ha agregado una transaccion a la blockchain' + str(values))
	return 'Transaccion agregada', 201
def main():
	app.run(debug=True)

if __name__ == '__main__':
	main()


import flask
import base64
import io
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_dangerously_set_inner_html as dhtml
import dash_table
from dash.dependencies import Input, Output

import os
import argparse
import numpy as np
from rdkit import Chem
from rdkit.Chem import Descriptors
from rdkit.Chem import AllChem
from rdkit.Chem import DataStructs
from rdkit.Chem import Draw
from rdkit.Chem.Draw import rdDepictor
from sklearn.decomposition import PCA

import plotly.graph_objs as go
descdict = dict(Descriptors._descList)

app = dash.Dash(__name__)

css_directory = os.getcwd()+'/static/'
stylesheets = ['bWLwgP.css']
static_css_route = '/static/'

def smi2svg(smi):
    mol = Chem.MolFromSmiles(smi)
    rdDepictor.Compute2DCoords(mol)
    mc = Chem.Mol(mol.ToBinary())
    Chem.Kekulize(mc)
    drawer = Draw.MolDraw2DSVG(300,300)
    drawer.DrawMolecule(mc)
    drawer.FinishDrawing()
    svg = drawer.GetDrawingText().replace('svg:','')
    return svg

def parse_contents(contents):
    content_type, content_string = contents.split(',')
    decoded = base64.b64decode(content_string)
    with open('./static/temp.sdf', 'w') as f:
        f.write(decoded.decode('utf-8'))
    mols = [mol for mol in Chem.SDMolSupplier('./static/temp.sdf')]
    return mols

@app.server.route('{}<stylesheet>'.format(static_css_route))
def serve_stylesheet(stylesheet):
    if stylesheet not in stylesheets:
        raise Exception()
    return flask.send_from_directory(css_directory, stylesheet)

for stylesheet in stylesheets:
    app.css.append_css({"external_url": "/static/{}".format(stylesheet)})

app.layout = html.Div(children=[
    html.H1(children='Hello Chemoinfo'),
    dcc.Upload(
        id='upload-data',
        children=html.Div(
            ['Drag and Drop SDF or ',
            html.A('Select Files')
            ]),
            style={
                    'width': '80%',
                    'height': '60px',
                    'lineHeight': '60px',
                    'borderWidth': '1px',
                    'borderStyle': 'dashed',
                    'borderRadius': '5px',
                    'textAlign': 'center',
                    'margin': '10px'
            },
            multiple=True
        ),

    html.Div(children='''
    Dash : sample plot
    '''),

    html.Div([dcc.Dropdown(id='x-column',
                           value='MaxEStateIndex',
                           options=[{'label': key, 'value': key} for key in descdict.keys()],
                           style={'width':'48%', 'display':'inline-block'}),
              dcc.Dropdown(id='y-column',
                           value='MaxEStateIndex',
                           options=[{'label': key, 'value': key} for key in descdict.keys()],
                           style={'width':'48%', 'display':'inline-block'}),
                           ]),
    html.Div([
        html.Div([html.Div(id="molimg")], className="four columns"),
        html.Div([dcc.Graph(id='example-graph')], className="eight columns")
        ], className="row"),
    #html.Div([dcc.Graph(id='chemical-space')])
    ])

@app.callback(
    Output('example-graph', 'figure'),

    [Input('upload-data', 'contents'),
     Input('x-column', 'value'),
     Input('y-column', 'value')]
)
def update_graph(contents, x_column_name, y_column_name):
    mols = parse_contents(contents[0])
    for i, mol in enumerate(mols):
        AllChem.Compute2DCoords(mol)
    x = [descdict[x_column_name](mol) for mol in mols]
    y = [descdict[y_column_name](mol) for mol in mols]

    return {'data':[go.Scatter(
        x=x,
        y=y,
        #text=['mol_{}'.format(i) for i in range(len(mols))],
        text=[Chem.MolToSmiles(mol) for mol in mols],
        mode='markers',
        marker={
            'size':15,
            'opacity':0.5
        }
    )],
    'layout':go.Layout(
        xaxis={'title':x_column_name},
        yaxis={'title':y_column_name}
    )}

@app.callback(
    Output('molimg', 'children'),
    [Input('example-graph', 'hoverData'),
    ]
)
def update_img(hoverData1):
    try:
        svg = smi2svg(hoverData1['points'][0]['text'])
    except:
        svg = 'Select molecule'
    return dhtml.DangerouslySetInnerHTML(svg)

if __name__=='__main__':
    app.run_server(debug=True)


from Model import race
from Model.race import Race_History, Race
from Model import res
from Model.horse import Horse_History
import data_exchanger as de
import nosql_connector as nsc
import mysql_connector
from Controller import algorithm

rid = 201605020611
mysql_conn = mysql_connector.MYSQL_connector()

def test_add_extention_info():
    r = race.Race(rid, mysql_conn)
    for hid in r._hids:
        # print(hid
        horse_sr = r.df[ r.df['hid']==hid ]
        # print(horse_sr
        obj = horse_sr['jockey']
        print(obj)
        print(type(obj))

def test__get_df_from_db():
    res = mysql_conn.select_data_by_rid(rid)
    df = de.beautify_data(res)
    print(df)

def test_jockey_time():
    hid = 2013105840
    jockey = 'ルメール'
    times = mysql_conn.get_times_same_jockey(hid, jockey)
    print(times)
    print('time: ' + str( len(times) ))

def test_jockey_time():
    hid = 2013105840
    course_status = "芝"
    times = h.get_times_same_field(course_status)
    print(times)
    print('time: ' + str( len(times) ))

def remove_after_data():
    hid = 2013105840
    jockey = 'ルメール'
    res = mysql_conn.get_times_same_jockey(hid, jockey)
    date = 20160508
    res = de.remove_after_data(res, date)
    print(len(res))

# def test_get_race_result_return():
#     rid = 200401010409
#     nosql_connector = nsc.NOSQL_connector()
#     odds_dict = nosql_connector.get_race_result_return(rid)
#     if odds_dict:
#         print(odds_dict['単勝'])

def test_get_odds_dict():
    """
    Rasult_Oddsで生成されるrtvalがどのようになっているか調べるテスト
    """
    rid = 201605020611
    dict = algorithm.get_odds_dict(rid)
    print('dict[単勝]): '+str(dict['単勝']))
    print('dict[ワイド]): '+str(dict['ワイド']))

def test_race_rist_del():
    rids = [201605020611, 201505020611, 201405020611]
    race_models = []
    for rid in rids:
        r = race.Race(rid, mysql_conn)
        race_models.append(r)
    import copy
    models = copy.deepcopy(race_models)
    for i, race_model in enumerate(models):
        del race_models[i]
        print(race_models)
        break
    print(models)

class Race_History_Test(object):
    def __init__(self):
        self.mysql_conn = mysql_connector.MYSQL_connector()
        self.race_id = '201405020611'
        self.race_History = Race_History(self.race_id, mysql_conn)

    def test_get_old_races(self):
        self.race_History.retrieve_history_race()
        print(self.race_History.history_map)

class Race_Test(object):
    def __init__(self):
        self.mysql_conn = mysql_connector.MYSQL_connector()
        self.race_id = '201405020611'
        self.race = Race(self.race_id, mysql_conn)

    def test_get_rank_by_hid(self):
        hid = '2011105000'
        r = self.race.get_rank_by_hid(hid)
        print(r)

class Horse_History_Test(object):
    # mysql_conn = MYSQL_connector()

    def test_get_previous_race(self):
        hid = '2013106133'
        race_date = 20160508
        h = Horse_History(hourse_id=hid, mysql_conn=mysql_conn)
        history_rids_df = h.get_previous_race(race_date)
        test_df = history_rids_df[['race_id']].apply(lambda x: x % 100000000)
        print(test_df)

def test_get_race_rank():
    import history_race_analyzer as hra
    ranks = [3,4,5,2,3,1,8]
    l = hra.get_race_rank(ranks)
    print(l)

def test_get_race_result_return():
    from nosql_connector import NOSQL_connector
    nc = NOSQL_connector()
    rid = 201509040211
    res = nc.get_race_result_return(rid)
    print(res)

# test__get_df_from_db()
# test_add_extention_info()
# test_jockey_time()
# test__get_df_from_db()
# remove_after_data()
# test_get_race_result_return()
# test_race_rist_del()
# test_Result_Odds_dict()

rht = Race_History_Test()
# rht.test_get_old_races()

rt = Race_Test()
# rt.test_get_rank_by_hid()
# rt.test___2dummy()

# test_get_race_rank()

hht = Horse_History_Test()
# hht.test_get_previous_race()

test_get_race_result_return()


import numpy as np
import itertools

import matplotlib.pyplot as plt
from util.data_process import plot_3d_points

"""
    This class represents a n-dimensional unit cube with a specific number of points embeded.
    Points are distributed uniformly in the initialization. A search can be made using the
    search_point function that returns the k (given) nearest neighbors of the input point.

"""

class Space:

    def __init__(self, low, high, points):

        self._low = np.array(low)
        self._high = np.array(high)
        self._range = self._high - self._low
        self._dimensions = len(low)
        self.__space = init_uniform_space([0] * self._dimensions,
                                          [1] * self._dimensions,
                                          points)

    def search_point(self, point, k):

        pnt = int(np.round(point))
        rng = int(k/2)
        low = pnt - rng
        high = low + k
        if (low < self._low):
            low = self._low
            high = low + k
        elif (high > self._high):
            high = self._high + 1
            low = high - k

        pnts = np.arange(low, high).reshape((k, 1))
        out = np.array([pnts])
        return out

    def import_point(self, point):
        return (point - self._low) / self._range

    def export_point(self, point):
        return self._low + point * self._range

    def get_space(self):
        return self.__space

    def shape(self):
        return self.__space.shape

    def get_number_of_actions(self):
        return self.shape()[0]

    def plot_space(self, additional_points=None):

        dims = self._dimensions

        if dims > 3:
            print(
                'Cannot plot a {}-dimensional space. Max 3 dimensions'.format(dims))
            return

        space = self.get_space()
        if additional_points is not None:
            for i in additional_points:
                space = np.append(space, additional_points, axis=0)

        if dims == 1:
            for x in space:
                plt.plot([x], [0], 'o')

            plt.show()
        elif dims == 2:
            for x, y in space:
                plt.plot([x], [y], 'o')

            plt.show()
        else:
            plot_3d_points(space)

class Discrete_space(Space):
    """
        Discrete action space with n actions (the integers in the range [0, n))
        0, 1, 2, ..., n-2, n-1
    """

    def __init__(self, n):  # n: the number of the discrete actions
        super().__init__([0], [n - 1], n)

    def export_point(self, point):
        return super().export_point(point).astype(int)

def init_uniform_space(low, high, points):
    dims = len(low)
    points_in_each_axis = round(points**(1 / dims))

    axis = []
    for i in range(dims):
        axis.append(list(np.linspace(low[i], high[i], points_in_each_axis)))

    space = []
    for _ in itertools.product(*axis):
        space.append(list(_))

    return np.array(space)


from django.contrib import admin
from django.contrib.auth.models import User
from django.conf import settings
from bookmeeting.models import BookingInfo, MeetingRoom

# Register your models here.

class MeetingRoomBookInline(admin.TabularInline):
    model = BookingInfo

@admin.register(MeetingRoom)
class MeetingRoomAdmin(admin.ModelAdmin):
    list_per_page = 20
    list_display = ('name', 'screen', 'capacity', 'picture', 'comment')
    list_filter = ('name', 'screen')
    inlines = [MeetingRoomBookInline, ]

@admin.register(BookingInfo)
class BookingInfoAdmin(admin.ModelAdmin):
    list_per_page = 20
    list_display = ('user', 'meeting_room', 'start_time', 'end_time',
                    'duration', 'subject', 'abstract', 'member', 'book_time', 'invitation')
    list_filter = ('user', 'meeting_room')

# class UserAdmin(admin.ModelAdmin):
#     list_per_page = 50
#     list_display = ('username', 'first_name', 'email', 'is_active', 'is_staff', 'is_superuser')
#     list_filter = ('is_active', 'username')
#     search_fields = ('username',)
#     actions = ['sync_user_from_oa']
#
#     def sync_user_from_oa(self, request, queryset):
#         from .logic import sync_user
#         sync_user()
#
#     sync_user_from_oa.short_description = '从OA系统同步用户'
#
#
# admin.site.unregister(User)
# admin.site.register(User, UserAdmin)


import re  # regexp
import sys  # open file
import requests
import json

class AndroidLogEntry:

    def __init__(self, date, time, info, msg):
        self.date = date
        self.time = time
        self.info = info
        self.msg = msg

class NotFound(Exception):
    pass

class AndroidLogParser:
    # https://developer.android.com/studio/debug/am-logcat.html
    androidLogRegexp = "([0-9]{2}-[0-9]{2}) ([0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3}) ([^:]*): (.*)"

    def __init__(self):
        self.parser = re.compile(AndroidLogParser.androidLogRegexp)  # prepare regexp

    def parseLine(self, line):
        r = self.parser.match(line)
        if r is None:
            raise NotFound()
        return AndroidLogEntry(date=r.group(1), time=r.group(2), info=r.group(3), msg=r.group(4))

    def parserLogFile(self, fileName):
        headers = {'Content-Type': 'application/json'}
        with open(fileName, 'r') as f:
            for line in f:
                try:
                    tokens = self.parseLine(line)
                    print("date: {0}\ttime: {1}\tinfo: {2}\tmsg: {3}".format(
                        tokens.date,
                        tokens.time,
                        tokens.info,
                        tokens.msg))
                    #data = {"MESSAGE": tokens.msg,
                    #        "timestamp": "2017-%sT%s" % (tokens.date, tokens.time)}
                    #print(requests.post('http://spirana.lille.inria.fr/custom1/logs/',
                    #                    data=json.dumps(data),
                    #                    headers=headers).text)
                except NotFound as inst:
                    print("couldNotParse {}".format(line[:-1]), file=sys.stderr)

if len(sys.argv) == 2:
    AndroidLogParser().parserLogFile(sys.argv[1])
else:
    print("You must specify a fileName")


import json
import logging

import disnake

from cogs5e.initiative.combatant import Combatant, MonsterCombatant, PlayerCombatant
from cogs5e.initiative.utils import create_combatant_id
from cogs5e.models.automation import EffectResult, IEffectResult
from gamedata import Monster, Spell, compendium
from tests.discord_mock_data import DEFAULT_USER_ID
from tests.utils import ContextBotProxy, requires_data
from utils.argparser import argparse

log = logging.getLogger(__name__)

async def run_automation(automation, avrae, combat=None, targets=None, **kwargs):
    """
    Runs the given automation and runs basic assertions on its results.

    If *combat* is given and the automation returns ieffects granting attacks or buttons, those will be tested
    recursively.
    """
    if targets is None:
        targets = []

    default_kwargs = dict(
        ctx=ContextBotProxy(avrae), embed=disnake.Embed(), args=argparse(""), combat=combat, targets=targets
    )
    result = await automation.run(**{**default_kwargs, **kwargs})
    result_dict = result.to_dict()  # AutomationResult must be dict-serializable
    assert json.dumps(result_dict)  # and JSON-serializable

    log.info("Completed root automation")

    async def _recurse_results(result: EffectResult):
        """Recurse over an automation result, and run granted buttons and attacks"""
        for node in result:
            if isinstance(node, IEffectResult) and node.effect.combatant is not None:
                log.info(f"Found IEffect with combatant: {node.effect.name} on {node.effect.combatant.name}")
                for attack_interaction in node.effect.attacks:
                    # simulate running the attack against the same targets
                    attack = attack_interaction.attack
                    log.info(f"Simulating granted action: {attack.name}")
                    await run_automation(
                        attack.automation,
                        avrae,
                        combat=combat,
                        caster=node.effect.combatant,
                        targets=targets,
                        **attack.__run_automation_kwargs__,
                    )
                    log.info(f"Finished simulating granted action: {attack.name}")
                for button in node.effect.buttons:
                    # simulate clicking the button
                    # this is pretty much just copied from cogs5e.initiative.buttons
                    log.info(f"Simulating granted button: {button.label}")
                    if button.granting_spell_id is not None:
                        spell = compendium.lookup_entity(Spell.entity_type, button.granting_spell_id)
                    else:
                        spell = None
                    await run_automation(
                        button.automation,
                        avrae,
                        combat=combat,
                        caster=node.effect.combatant,
                        targets=[],
                        ieffect=node.effect,
                        allow_caster_ieffects=False,
                        # do not allow things like damage-boosting effects to affect dot ticks
                        ab_override=button.override_default_attack_bonus,
                        dc_override=button.override_default_dc,
                        spell_override=button.override_default_casting_mod,
                        spell=spell,
                        spell_level_override=button.granting_spell_cast_level,
                        from_button=True,
                    )
                    log.info(f"Finished simulating granted button: {button.label}")
                log.info(f"Finished IEffect on combatant: {node.effect.name} on {node.effect.combatant.name}")
            await _recurse_results(node)

    if combat is not None:
        await _recurse_results(result)

def create_basic_combatant(combat, avrae):
    """Creates a new minimal basic combatant, adds it to the combat, and returns it"""
    basic_combatant = Combatant(
        id=create_combatant_id(),
        name="Test Combatant",
        controller_id=int(DEFAULT_USER_ID),
        init=0,
        private=False,
        ctx=ContextBotProxy(avrae),
        combat=combat,
    )
    combat.add_combatant(basic_combatant)
    return basic_combatant

@requires_data(fail_if_no_data=True)
def create_monster_combatant(combat, avrae, monster_id=16939):
    """Creates a new monster combatant, adds it to the combat, and returns it. Defaults to using a kobold"""
    mon = compendium.lookup_entity(Monster.entity_type, monster_id)
    return create_monster_combatant_from_monster(combat, avrae, mon)

def create_monster_combatant_from_monster(combat, avrae, monster):
    monster_combatant = MonsterCombatant.from_monster(
        monster,
        ctx=ContextBotProxy(avrae),
        combat=combat,
        name="Test Monster",
        controller_id=int(DEFAULT_USER_ID),
        init=0,
        private=False,
    )
    combat.add_combatant(monster_combatant)
    return monster_combatant

def create_player_combatant(combat, avrae, character):
    """Creates a new player combatant from the given character and adds and returns it"""
    player_combatant = PlayerCombatant.from_character(
        character,
        ctx=ContextBotProxy(avrae),
        combat=combat,
        controller_id=int(DEFAULT_USER_ID),
        init=0,
        private=False,
    )
    combat.add_combatant(player_combatant)
    return player_combatant


from django.shortcuts import render, redirect, reverse, get_object_or_404
from .models import Artworks
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from .forms import ArtworkForm, ArtworkEditForm
from members.models import Members

def all_artworks(request):
    """ A view to show all artworks, including sorting and search queries """

    artworks = Artworks.objects.all()
    qry = None
    sort = None
    direction = None

    if request.GET:
        if 'sort' in request.GET:
            sortkey = request.GET['sort']
            sort = sortkey
            if 'direction' in request.GET:
                direction = request.GET['direction']
                if direction == 'desc':
                    sortkey = f'-{sortkey}'
            artworks = artworks.order_by(sortkey)

        if 'q' in request.GET:
            qry = request.GET['q']
            if not qry:
                messages.error(request, "You didn't enter any search criteria")
                return redirect(reverse('artworks'))

            queries = Q(title__icontains=qry) | Q(description__icontains=qry)
            artworks = artworks.filter(queries)

    current_sorting = f'{sort}_{direction}'

    context = {
        'artworks': artworks,
        'search_term': qry,
        'current_sorting': current_sorting,
    }

    return render(request, 'artworks/artworks.html', context)

def artwork_detail(request, artwork_id):
    """ A view to show individual artwork details """

    artwork = get_object_or_404(Artworks, pk=artwork_id)

    context = {
        'artwork': artwork,
    }

    return render(request, 'artworks/artwork_detail.html', context)

@login_required
def add_artwork(request):
    """ Add an artwork to the club """
    if not request.user.is_superuser:
        messages.error(request, 'Sorry, only club admin can do that.')
        return redirect(reverse('home'))

    if request.method == 'POST':
        form = ArtworkForm(request.POST, request.FILES)
        if form.is_valid():
            artwork = form.save()
            messages.success(request, 'Successfully added artwork')
            return redirect(reverse('artwork_detail', args=[artwork.id]))
        else:
            messages.error(request,
                           'Failed to add artwork.\
                            Please ensure the form is valid.')
    else:
        form = ArtworkForm()

    template = 'artworks/add_artwork.html'
    context = {
        'form': form,
    }

    return render(request, template, context)

@login_required
def edit_artwork(request, artwork_id):
    """ Edit a artwork in the club """
    if not request.user.is_superuser:
        messages.error(request, 'Sorry, only club admin can do that.')
        return redirect(reverse('home'))

    artwork = get_object_or_404(Artworks, pk=artwork_id)
    if request.method == 'POST':
        form = ArtworkEditForm(request.POST, request.FILES, instance=artwork)
        if form.is_valid():
            form.save()
            messages.success(request, 'Successfully updated artwork')
            return redirect(reverse('artwork_detail', args=[artwork.id]))
        else:
            messages.error(request, 'Failed to update artwork. \
                                     Please ensure form is valid.')
    else:
        form = ArtworkEditForm(instance=artwork)
        messages.info(request, f'You are editing {artwork.title}')

    template = 'artworks/edit_artwork.html'
    context = {
        'form': form,
        'artwork': artwork,
    }

    return render(request, template, context)

@login_required
def delete_artwork(request, artwork_id):
    """ Delete an artwork from the club """
    if not request.user.is_superuser:
        messages.error(request, 'Sorry, only club admin can do that.')
        return redirect(reverse('home'))

    artwork = get_object_or_404(Artworks, pk=artwork_id)
    artwork.delete()
    messages.success(request, 'Artwork deleted!')
    return redirect(reverse('artworks'))

@login_required
def sold_artwork(request):
    """ Query on sold artworks """

    sold = Artworks.objects.filter(sold=True)
    sold_count = sold.count()

    template = 'artworks/sold_artwork.html'
    context = {
        'artworks': sold,
        'count': sold_count,
    }

    return render(request, template, context)

@login_required
def my_sales(request):
    """ Query on sold artworks for a logged in member """

    sold = Artworks.objects.filter(sold=True)
    usrnm = request.user.username

    if usrnm:
        try:
            Members.objects.get(username=usrnm)
        except Members.DoesNotExist:
            messages.info(request, 'Sorry, only club members can do that.')
            return redirect(reverse('home'))

    template = 'artworks/my_sales.html'
    context = {
        'artworks': sold,
        'username': usrnm,
    }

    return render(request, template, context)


#!/usr/bin/env python3

import os
from tkinter import *
from tkinter import filedialog

class App:
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.directory = ""
        self.list_of_files = []
        self.image = None

        self.directory_label = Label(frame, text="Directory")
        self.directory_label.grid(row=0, column=0)
        self.directory_entry = Entry(frame, width=90)
        self.directory_entry.grid(row=0, column=1)
        self.directory_btn = Button(frame,
                                    text="Load",
                                    command=self.load_directory)
        self.directory_btn.grid(row=0, column=2)

        self.name_label = Label(frame, text="Filename")
        self.name_label.grid(row=1, column=0)
        self.name_entry = Entry(frame, width=90)
        self.name_entry.grid(row=1, column=1)
        self.rename_btn = Button(frame,
                                 text="Rename",
                                 command=self.rename_file)
        self.rename_btn.grid(row=1, column=2)

        self.file_list = Listbox(frame,
                                 listvariable=self.list_of_files,
                                 selectmode=SINGLE,
                                 height=30,
                                 width=50)
        self.file_list.grid(row=3, column=0, columnspan=1)

        self.canvas = Canvas(frame,
                             bg='white',
                             height=100,
                             width=80)
        self.canvas.grid(row=3, column=1, columnspan=2)

    def load_directory(self):
        self.directory = filedialog.askdirectory()
        self.directory_entry.insert(0, self.directory)
        self.update_file_list()

    def rename_file(self):
        print("Rename file to: " + self.name_entry.get())

    def update_file_list(self):
        if self.directory != "":
            for _, _, self.file in os.walk(self.directory):
                for self.element in self.file:
                    self.file_list.insert(END, self.element)
                    self.list_of_files.append(self.element)

    def create_file_image(self):
        self.image = None

    def show_file_image(self):
        self.canvas.create_image(100, 80, anchow=NW, image=self.image)

root = Tk()
root.title("Scan rename")
root.minsize(width=800, height=640)
app = App(root)
root.mainloop()


# -*- coding: utf-8 -*-
# @Time    : 2021/1/21 8:22 下午
# @Author  : jeffery
# @FileName: data_process.py
# @website : http://www.jeffery.ink/
# @github  : https://github.com/jeffery0628
# @Description:

from base import BaseDataSet
from tqdm import tqdm
import torch
from pathlib import Path
import json
from dataclasses import dataclass
from typing import Optional, List

@dataclass
class InputExample:
    guid: Optional[str]
    text: str
    keyword:str
    location:str
    label: float

@dataclass
class InputFeatures:
    """
    A single set of features of data.
    Property names are the same names as the corresponding inputs to a model.
    """
    guid: Optional[str]
    input_ids: List[int]
    attention_mask: Optional[List[int]]
    label: float
    text: str
    sent_len: int

class DisasterDataset(BaseDataSet):

    def __init__(self, data_dir, file_name, cache_dir, shuffle, transformer_model, overwrite_cache, batch_size,
                 force_download, num_workers):
        self.data_dir = Path(data_dir)
        self.file_name = file_name
        self.shuffle = shuffle
        self.batch_size = batch_size
        self.num_workers = num_workers
        self.transformer_model = transformer_model
        self.feature_cache_file = Path(cache_dir) / self.data_dir.parent.name / (file_name.split('.')[0] + '.cache')
        super(DisasterDataset, self).__init__(transformer_model=transformer_model,
                                             overwrite_cache=overwrite_cache,
                                             force_download=force_download, cache_dir=cache_dir)

    def read_examples_from_file(self):
        input_file = self.data_dir / self.file_name

        with input_file.open('r') as f:
            for line in tqdm(f):
                json_line = json.loads(line)
                yield InputExample(guid=json_line['id'], text=json_line['text'],keyword=json_line['keyword'],
                                   location=json_line['location'],label=float(json_line['label']))

    def convert_examples_to_features(self):
        features = []
        for example in self.read_examples_from_file():
            text = example.text + example.keyword + example.location
            inputs = self.tokenizer.encode_plus(text, return_token_type_ids=False,
                                                return_attention_mask=True, return_length=True)

            features.append(InputFeatures(guid=example.guid, input_ids=inputs.data['input_ids'],
                                          attention_mask=inputs.data['attention_mask'],
                                          sent_len=inputs.data['length'], text=example.text,
                                          label=example.label))
        return features

    def collate_fn(self, datas: List[InputFeatures]):
        max_len = max([data.sent_len for data in datas])
        ids = []
        input_ids = []
        attention_masks = []
        text_lengths = []
        labels = []
        texts = []

        for data in datas:
            ids.append(data.guid)
            texts.append(data.text)
            input_ids.append(data.input_ids + [self.tokenizer.pad_token_id] * (max_len - data.sent_len))
            attention_masks.append(data.attention_mask + [0] * (max_len - data.sent_len))
            text_lengths.append(data.sent_len)
            labels.append(data.label)

        input_ids = torch.LongTensor(input_ids)
        attention_masks = torch.ByteTensor(attention_masks)
        text_lengths = torch.LongTensor(text_lengths)
        labels = torch.LongTensor(labels)
        return ids, texts, input_ids, attention_masks, text_lengths, labels


# -*- coding: utf-8 -*-
"""
Created on Fri May 10 15:46:41 2019

@author: Narayan Devpura
"""

"""
Code Challenge
  Name:
    Word count
  Filename:
    wordcount.py
  Problem Statement:
    Unix systems contain many utility functions.
    One of the most useful to me is wc, the "word count" program.
    If you run wc against a text file, it'll count the characters, words,
    and lines that the file contains.

    The challenge for this exercise is to write a version of wc in Python.
    However, your version of wc will return four different types of information
    about the files:

        Number of characters (including whitespace)
        Number of words (separated by whitespace)
        Number of lines
        Number of unique words

    The program should ask the user for the name of an input file,
    and then produce output for that file.

"""

file = input('Enter filename: ')
with open(file, mode = 'r') as fp:
    c_line = 0
    c_words = 0
    c_char = 0
    c_unique = 0
    w = set()
    for line in fp:
        c_line += 1
        c_char += len(line)
        for item in line.split():
            c_words += 1
            w.add(item)
    c_unique += len(w)
    print('Number of characters: ',c_char)
    print('Number of words: ',c_words)
    print('Number of lines: ',c_line)
    print('Number of unique words: ',c_unique)


import argparse

from dt_shell import DTCommandAbs, dtslogger
from utils.cli_utils import ask_confirmation
from utils.secrets_utils import SecretsManager

class DTCommand(DTCommandAbs):
    help = "Configure GitHub credentials"

    usage = f"""
Usage:

    dts config github credentials set --username <your-github-username> --token <your-github-access-token>
"""

    @staticmethod
    def command(shell, args, **kwargs):
        parser = argparse.ArgumentParser(
            prog="dts config github credentials set",
            description=("Save github logins locally for Duckietown"),
        )
        parser.add_argument(
            "--username",
            help="GitHub username",
            required=True,
        )
        parser.add_argument(
            "--token",
            help="GitHub access token",
            required=True,
        )
        parsed = parser.parse_args(args)

        username = parsed.username
        token = parsed.token

        # ---

        # set secrets
        secret_key: str = "github/credentials/token"
        # - overwrite?
        if SecretsManager.has(secret_key):
            overwrite: bool = ask_confirmation(
                "A set of credentials for GitHub is already stored, if you continue, the "
                "old credentials will be overwritten.",
                default="y",
            )
            if not overwrite:
                dtslogger.info("Leaving credentials untouched")
                return False

        # - store secrets
        secret_value: dict = {"username": username, "secret": token}
        SecretsManager.set(secret_key, secret_value)

        dtslogger.info("GitHub access credentials stored!")


import os

destination = "/Users/Harry.Hextall/Projects/"
total = 0
illegal = ['\\', '/', ':', '*', '?', '"', '<', '>', '|']

def walk_directory():
    global total
    for root, directories, filenames in os.walk(destination):
        for filename in filenames:
            total += 1
            abs_path = os.path.join(root, filename)
            if [e for e in illegal if e in filename]:
                print(abs_path)
        for directory in directories:
            total += 1
            abs_path = os.path.join(root, directory)
            if [e for e in illegal if e in directory]:
                print(abs_path)

walk_directory()
print(total)