import os
import shutil
import time

import deezloader
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from telethon.tl.types import DocumentAttributeAudio

from userbot import CMD_HELP, DEEZER_ARL_TOKEN, TEMP_DOWNLOAD_DIRECTORY
from userbot.events import register

# LORD USERBOT
@register(outgoing=True, pattern=r"^\.deez (.+?|) (FLAC|MP3\_320|MP3\_256|MP3\_128)")
async def _(event):
    """DeezLoader by @An0nimia
    Ported for UniBorg by @SpEcHlDe"""
    if event.fwd_from:
        return

    strings = {
        "name": "DeezLoad",
        "arl_token_cfg_doc": "ARL Token untuk Deezer",
        "invalid_arl_token": "tolong setel variabel yang dibutuhkan untuk modul ini",
        "wrong_cmd_syntax": "bruh, sekarang saya pikir seberapa jauh kita harus melangkah. tolong hentikan Sesi saya!",
        "server_error": "Terjadi kesalahan teknis.",
        "processing": "`Sedang Mendownload..`",
        "uploading": "`Sedang Mengunggah...`",
    }

    ARL_TOKEN = DEEZER_ARL_TOKEN

    if ARL_TOKEN is None:
        await event.edit(strings["invalid_arl_token"])
        return

    try:
        loader = deezloader.Login(ARL_TOKEN)
    except Exception as er:
        await event.edit(str(er))
        return

    temp_dl_path = os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(time.time()))
    if not os.path.exists(temp_dl_path):
        os.makedirs(temp_dl_path)

    required_link = event.pattern_match.group(1)
    required_qty = event.pattern_match.group(2)

    await event.edit(strings["processing"])

    if "spotify" in required_link:
        if "track" in required_link:
            required_track = loader.download_trackspo(
                required_link,
                output=temp_dl_path,
                quality=required_qty,
                recursive_quality=True,
                recursive_download=True,
                not_interface=True,
            )
            await event.edit(strings["uploading"])
            await upload_track(required_track, event)
            shutil.rmtree(temp_dl_path)
            await event.delete()

        elif "album" in required_link:
            reqd_albums = loader.download_albumspo(
                required_link,
                output=temp_dl_path,
                quality=required_qty,
                recursive_quality=True,
                recursive_download=True,
                not_interface=True,
                zips=False,
            )
            await event.edit(strings["uploading"])
            for required_track in reqd_albums:
                await upload_track(required_track, event)
            shutil.rmtree(temp_dl_path)
            await event.delete()

    elif "deezer" in required_link:
        if "track" in required_link:
            required_track = loader.download_trackdee(
                required_link,
                output=temp_dl_path,
                quality=required_qty,
                recursive_quality=True,
                recursive_download=True,
                not_interface=True,
            )
            await event.edit(strings["uploading"])
            await upload_track(required_track, event)
            shutil.rmtree(temp_dl_path)
            await event.delete()

        elif "album" in required_link:
            reqd_albums = loader.download_albumdee(
                required_link,
                output=temp_dl_path,
                quality=required_qty,
                recursive_quality=True,
                recursive_download=True,
                not_interface=True,
                zips=False,
            )
            await event.edit(strings["uploading"])
            for required_track in reqd_albums:
                await upload_track(required_track, event)
            shutil.rmtree(temp_dl_path)
            await event.delete()

    else:
        await event.edit(strings["wrong_cmd_syntax"])

# LORD - USERBOT
async def upload_track(track_location, message):
    metadata = extractMetadata(createParser(track_location))
    duration = 0
    title = ""
    performer = ""
    if metadata.has("duration"):
        duration = metadata.get("duration").seconds
    if metadata.has("title"):
        title = metadata.get("title")
    if metadata.has("artist"):
        performer = metadata.get("artist")
    document_attributes = [
        DocumentAttributeAudio(
            duration=duration,
            voice=False,
            title=title,
            performer=performer,
            waveform=None,
        )
    ]
    supports_streaming = True
    force_document = False
    caption_rts = os.path.basename(track_location)
    await message.client.send_file(
        message.chat_id,
        track_location,
        caption=caption_rts,
        force_document=force_document,
        supports_streaming=supports_streaming,
        allow_cache=False,
        attributes=document_attributes,
    )
    os.remove(track_location)

# LORD USERBOT
# @LORDUSERBOT_GROUP
CMD_HELP.update(
    {
        "deezload": "**Modules:** __Deezload__\n\n**Perintah:** `.deez <spotify/deezer link> <Format>`"
        "\n**Penjelasan:** Unduh musik dari deezer."
        "\n\n *Format= `FLAC`, `MP3_320`, `MP3_256`, `MP3_128`."
    }
)


import os
import fnmatch
import json
import sys
import subprocess
import multiprocessing

def run_cmd(cmd):
  print(cmd)
  return subprocess.call(cmd, shell=True)

def get_bounds(coords):
  x = []
  y = []
  for coord in coords:
    x.append(coord[0])
    y.append(coord[1])
  return [min(x), max(y), max(x), min(y)]

"""
# get the arguments
arg = sys.argv
chunkDir = arg[1]
outDir = arg[2]
clipFile = arg[3]
clipFeature = arg[4]
name = arg[5]
indexID = arg[6]
nVert = int(arg[7])
startYear = int(arg[8])
endYear = int(arg[9])
proj = arg[10]
delete = arg[11]
"""

chunkDir = '/vol/v1/proj/nccn/gee_idl_lt_compare/raster/noca'
outDir = '/vol/v1/proj/nccn/gee_idl_lt_compare/raster/noca'
clipFile = '/vol/v1/proj/nccn/gee_idl_lt_compare/vector/LPa01_LEWI_MORA_NOCA_OLYM.geojson'
clipAttribute = 'PARK_CODE'
clipFeature = 'NOCA'
name = 'nccn_gee_vs_idl_noca'
indexID = 'nbr'
nVert = 7
startYear = 1984
endYear = 2012
proj = 'EPSG:5070'
delete = 'keep'

# make sure path parts are right
if chunkDir[-1] != '/':
  chunkDir += '/'
if outDir[-1] != '/':
  outDir += '/'

# find the tif chunks
tifs = []
for root, dirnames, filenames in os.walk(chunkDir):
  for filename in fnmatch.filter(filenames, '*.tif'):
    tifs.append(os.path.join(root, filename))

# make a list of tile tifs
vrtFile = chunkDir+name+'.vrt'
tileListFile = vrtFile.replace('.vrt', '_filelist.txt')
tileList = open(tileListFile, 'w')
for tif in tifs:
  tileList.write(tif+'\n')
tileList.close()

# create vrt
cmd = 'gdalbuildvrt -input_file_list '+tileListFile+' '+vrtFile
subprocess.call(cmd, shell=True)

# define the list of replacement types in the new out images
outTypes = ['vert_yrs.bsq',
            'vert_src.bsq',
            'vert_fit.bsq',
            'ftv_'+indexID+'.bsq',
            'ftv_tcb.bsq',
            'ftv_tcg.bsq',
            'ftv_tcw.bsq']

# make a list of band ranges for each out type
vertStops = []
for vertType in range(4):
  vertStops.append(vertType*nVert+1)

nYears = (endYear - startYear) + 1
ftvStops = []
for ftvType in range(1,5):
  ftvStops.append(ftvType*nYears+vertStops[-1])

bandStops = vertStops+ftvStops
bandRanges = [range(bandStops[i],bandStops[i+1]) for i in range(len(bandStops)-1)]

# load the tile features
with open(clipFile) as f:
  features = json.load(f)

coords = []
for i in range(len(features['features'])):
  if features['features'][i]['properties'][clipAttribute] == clipFeature:
    coords = coords+features['features'][i]['geometry']['coordinates'][0]

#features['features'][1]['properties']['PARK_CODE'] == 'LEWI'
bounds = get_bounds(coords)
projwin = ' '.join([str(coord) for coord in bounds])

# make a list of all the gdal_translate commands needed for the ee conus chunk
cmdList = []
if not os.path.isdir(outDir):
  os.mkdir(outDir)

for i in range(len(outTypes)):
  outFile = outDir+name+'_'+outTypes[i]
  bands = ' -b '+' -b '.join([str(band) for band in bandRanges[i]])
  cmd = 'gdal_translate -q --config GDAL_DATA "/usr/lib/anaconda/share/gdal" -of ENVI -a_srs ' + proj + bands + ' -projwin '+projwin+' '+ vrtFile + ' ' + outFile
  cmdList.append(cmd)

# run the commands in parallel
pool = multiprocessing.Pool(processes=len(cmdList))
pool.map(run_cmd, cmdList)
pool.close()


import numpy as np
import networkx as nx
import trimesh
from Proj_edge.SketchP import *
from utils import *
import scipy.sparse
import time
import copy
#----------------hierarchy------------
'''Application
    -main을 call (input: mesh) output: 바뀐 mesh
        -sketchP (input: mesh, viewM, draw_line), output: mesh 위의 patch
            -edge_extraction output: mesh의 edge (윤곽선)'''

def Laplac(mm, View):
    print(View['Detail'])
    mes=copy.deepcopy(mm)
    mes.compute_vertex_normals()
    mes.remove_unreferenced_vertices()
    mesh = trimesh.Trimesh(np.asarray(mes.vertices), np.asarray(mes.triangles),
                           vertex_normals=np.asarray(mes.vertex_normals))  #Trimesh로 변환예정

    print(len(mesh.vertices), len(mes.vertices))
    g = mesh_to_graph(mesh)

    M=easyMesh(mes)
    TempZip=Sketch2Patch(M, View)
    if TempZip==None:
        return None
    else:
        handle, _, _, Patch, _ = TempZip

    '''handles = {
        24092 : [-0.01134 ,  0.151374 , -0.0242688]  # 점.
    }
    boundary_ctrl_points = [15617, 24120, 30216, 11236, 6973] #boundary 점들
    '''
    TTT={}
    for hand in handle:
        TTT[hand[1]] = hand[0]
    handles = TTT
    '''mesh = trimesh.load('./meshes/00288_symmetric_2k.ply', process=False)'''
    export_fn = './exports/chair_%s.ply' % (time.strftime("%Y%m%d%H%M%S", time.localtime()))

    print("---------------Edge start--------")
    Edged=[]
    for Pointz in Patch:
        A = 0
        B = 0
        for i, connection in enumerate(M.connected[Pointz]):
            if connection==1:
                A+=1
                if i in Patch:
                    B+=1
                if i not in Patch:
                    print("thisis Edge")
                    Edged.append(Pointz)
        print(f"{A}/{B}")

    print("------------------Edge extracted")
    boundary_ctrl_points=list(set(Edged))
    print(handles, boundary_ctrl_points)

    #-------------------------------- Build Graph ------------------------------- #
    for point in boundary_ctrl_points:
        A=0
        for point2 in boundary_ctrl_points:
            if M.connected[point][point2] == 1 or M.connected[point2][point] == 1:
                A+=1
        print(A)

    '''orderedboundary=[]
    ttz = 0
    def Boundaryorder(cur):
        orderedboundary.append(cur)
        A = None
        for i in boundary_ctrl_points:
            if M.connected[i][cur] == 1 or M.connected[cur][i] == 1:
                if i ==orderedboundary[0] and len(orderedboundary)!=2:
                    print("routed")
                    break
                if i not in orderedboundary:
                    A = Boundaryorder(i)'''

    def Boundaryorder(cur, path):
        print(f"----{path}----")
        A = []
        for i in boundary_ctrl_points:
            if i not in path and (M.connected[i][cur] == 1 or M.connected[cur][i] == 1):
                A.append(Boundaryorder(i, path+[i]))

        if len(A)==0:
            return path
        else:
            Rank = sorted(A, key=lambda B: len(B))
            print(Rank)
            return Rank[-1]
    '''orderedboundary=[]'''
    '''ttz=0
    while 1:
        def Boundaryorder(cur, path):
            orderedboundary.append(cur)
            A=None
            for i in boundary_ctrl_points:
                if M.connected[i][cur]==1 or M.connected[cur][i]==1:
                    if i == boundary_ctrl_points[ttz] and len(path)!=2:
                        print("route")
                        print(path)
                        print(len(path), len(boundary_ctrl_points))
                        return path
                    elif i not in path:
                        A = Boundaryorder(i, path+[i])

            if A==None:
                return path
            return A

        orderedboundary= Boundaryorder(boundary_ctrl_points[ttz], [boundary_ctrl_points[ttz]])
        if len(boundary_ctrl_points)!=len(orderedboundary):
            ttz+=1

        print(boundary_ctrl_points, orderedboundary)
        print(len(boundary_ctrl_points), len(orderedboundary))'''

    orderedboundary=Boundaryorder(boundary_ctrl_points[0], [boundary_ctrl_points[0]])

    print(len(boundary_ctrl_points), len(orderedboundary))

    if len(boundary_ctrl_points) != len(orderedboundary):
        print("irrelevancy error")
        return None

    boundary_ctrl_points=orderedboundary

    g = mesh_to_graph(mesh)

    print("----------------------------좁은간격------------------------------")
    print(nx.shortest_path(g, boundary_ctrl_points[0], boundary_ctrl_points[1]))

    '''boundary = get_boundary(g, boundary_ctrl_points)'''

    boundary=boundary_ctrl_points  #test

    print("-----compare boundary---------")
    print(len(boundary), len(boundary_ctrl_points))

    editable_verts = get_editable_vertices(g, boundary, list(handles.keys())[int(len(handles)/2)])

    # --------------------- Subgraph of the Editiable Region --------------------- #
    subgraph = g.subgraph(boundary + editable_verts)

    print(f"---------{len(subgraph.nodes)}----------{len(Patch)}-----")
    g2l = {}
    for n in subgraph.nodes:
        g2l[n] = len(g2l)
    l2g = list(subgraph.nodes)

    def get_local_neighbor(subgraph, n, l2g, g2l):
        nb = []
        for i in subgraph.neighbors(l2g[n]):
            nb.append(g2l[i])
        return nb

    # -------------------------- Build the Linear System ------------------------- #
    L = rw_laplacian_matrix(subgraph).todense()
    V = np.matrix([subgraph.nodes[i]['pos'] for i in subgraph.nodes])
    Delta = L.dot(V)
    n = L.shape[0]

    LS = np.zeros([3*n, 3*n])
    LS[0*n:1*n, 0*n:1*n] = (-1) * L
    LS[1*n:2*n, 1*n:2*n] = (-1) * L
    LS[2*n:3*n, 2*n:3*n] = (-1) * L

    for i in range(n):
        nb_idx = get_local_neighbor(subgraph, i, l2g, g2l)
        ring = np.array([i] + nb_idx)
        V_ring = V[ring]
        n_ring = V_ring.shape[0]

        A = np.zeros([n_ring * 3, 7])
        for j in range(n_ring):
            A[j]          = [V_ring[j,0],           0 ,   V_ring[j,2], -V_ring[j,1], 1, 0, 0]
            A[j+n_ring]   = [V_ring[j,1], -V_ring[j,2],            0 ,  V_ring[j,0], 0, 1, 0]
            A[j+2*n_ring] = [V_ring[j,2],  V_ring[j,1], -V_ring[j, 0],           0 , 0, 0, 1]

        # Moore-Penrose Inversion
        A_pinv = np.linalg.pinv(A)
        s = A_pinv[0]
        h = A_pinv[1:4]
        t = A_pinv[4:7]

        T_delta = np.vstack([
             Delta[i,0]*s    - Delta[i,1]*h[2] + Delta[i,2]*h[1],
             Delta[i,0]*h[2] + Delta[i,1]*s    - Delta[i,2]*h[0],
            -Delta[i,0]*h[1] + Delta[i,1]*h[0] + Delta[i,2]*s   ,
        ])

        LS[i, np.hstack([ring, ring+n, ring+2*n])] += T_delta[0]
        LS[i+n, np.hstack([ring, ring+n, ring+2*n])] += T_delta[1]
        LS[i+2*n, np.hstack([ring, ring+n, ring+2*n])] += T_delta[2]

    # ------------------- Add Constraints to the Linear System ------------------- #
    constraint_coef = []
    constraint_b = []

    # Boundary constraints
    boundary_idx = [g2l[i] for i in boundary_ctrl_points]
    for idx in boundary_idx:
        constraint_coef.append(np.arange(3*n) == idx)
        constraint_coef.append(np.arange(3*n) == idx + n)
        constraint_coef.append(np.arange(3*n) == idx + 2*n)
        constraint_b.append(V[idx, 0])
        constraint_b.append(V[idx, 1])
        constraint_b.append(V[idx, 2])

    # Handle constraints
    for gid, pos in handles.items():
        idx = g2l[gid]
        constraint_coef.append(np.arange(3*n) == idx)
        constraint_coef.append(np.arange(3*n) == idx + n)
        constraint_coef.append(np.arange(3*n) == idx + 2*n)
        constraint_b.append(pos[0])
        constraint_b.append(pos[1])
        constraint_b.append(pos[2])

    constraint_coef = np.matrix(constraint_coef)
    constraint_b = np.array(constraint_b)

    # -------------------------- Solve the Linear System ------------------------- #
    A = np.vstack([LS, constraint_coef])
    b = np.hstack([np.zeros(3*n), constraint_b])
    spA = scipy.sparse.coo_matrix(A)

    V_prime = scipy.sparse.linalg.lsqr(spA, b)

    # -------------------------- Output the Edited Mesh -------------------------- #
    new_pnts = []
    for i in range(n):
        new_pnts.append([V_prime[0][i], V_prime[0][i+n], V_prime[0][i+2*n]])

    new_mesh = mesh.copy()
    for idx, pnt in enumerate(new_pnts):
        gid = l2g[idx]
        new_mesh.vertices[gid] = pnt

    new_mesh.export(export_fn)

    print(np.asarray(new_mesh.faces))
    '''final_mesh=o3d.geometry.TriangleMesh()
    final_mesh.vertices=o3d.utility.Vector3dVector(new_mesh.vertices)
    final_mesh.triangles=o3d.utility.Vector3dVector(new_mesh.faces)'''
    final_mesh=new_mesh.as_open3d
    final_mesh.compute_triangle_normals()
    final_mesh.compute_vertex_normals()
    return final_mesh

if __name__ == "__main__":
    # --------------------------------- Load Mesh -------------------------------- #
    mesh = trimesh.load('./meshes/bunny.ply', process=False)
    export_fn = './exports/bunny_%s.ply' % (time.strftime("%Y%m%d%H%M%S", time.localtime()))

    # ---------------------------- Editing Parameters ---------------------------- #
    mesh = o3d.io.read_triangle_mesh("./meshes/bunny.ply")
    Laplac(mesh, None, None)


import openai
import os

class ChatOpenAI:
    def __init__(self, temperature=0.8, max_tokens=50):
        self.api_key = os.environ.get('OPENAI_API_KEY')
        self.temperature = temperature
        self.max_tokens = max_tokens

    def generate_response(self, conversation, question):
        openai.api_key = os.environ.get('OPENAI_API_KEY')
        prompt = self._format_conversation(conversation)
        response = openai.Completion.create(
            engine="text-davinci-003",
            prompt=prompt,
            max_tokens=self.max_tokens,
            temperature=self.temperature,
        )
        answer = response.choices[0].text.strip()
        return answer

    def _format_conversation(self, conversation):
        formatted_conversation = ""
        for message in conversation:
            role = message["role"]
            content = message["content"]
            formatted_conversation += f"{role}: {content}\n"
        return formatted_conversation


from cookiecutter.main import cookiecutter

def create_app(
    template: str,
    extra_context_dict: dict,
    output_dir: str,
    no_input: bool=True,
    overwrite_if_exists: bool=True
    ) -> None:
    """
    Create a new app from a template.
    Parameters
    ----------
    template : str
        The name of the template to use.
    extra_context_dict : dict
        The extra context to pass to the template.
    output_dir : str
        The output directory.
    no_input : bool, optional
        If True, do not prompt for parameters and only use
    overwrite_if_exists : bool, optional
        If True, overwrite the output directory if it already exists.
    Returns
    -------
    None
    """
    cookiecutter(
        "https://github.com/castorini/hf-spacerini.git",
        directory="templates/" + template,
        no_input=no_input,
        extra_context=extra_context_dict,
        output_dir=output_dir,
        overwrite_if_exists=overwrite_if_exists,
    )

    return None


# Built In Imports
import os
import sys
import subprocess
import requests
from time import sleep
from sys import exit

# Dependencies
Dependencies = input("Update & Install Dependencies? Y/N \> ").lower()
if Dependencies == "y":
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'wheel'])
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'json_minify'])
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'colorama'])
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'art'])
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'lolpython'])
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'amino.py'])
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'amino.py', '--upgrade'])
else:
    pass

if os.path.exists("device.json"):
      os.remove("device.json")
else:
    print("did not find")
    pass

# PYPI Imports
import colorama
import lolpython
import art
import amino
from colorama import Fore, Style, Back
from  lolpython import lol_py as lolpy
from amino.lib.util.exceptions import *
from art import *

colorama.init(autoreset=True)

# Updates Amino.py
#os.system("python3 pip -m install amino.py --upgrade")

# Handles Device ID For Remote Updates Without needing To Modify Script Directly.
Git_deviceId = requests.get("https://raw.githubusercontent.com/ODYSSE3US/Stand_Alone_Build_Data/main/Aminoapps/SYS_MSG_SENDER/deviceId.txt")
Git_deviceId_text = Git_deviceId.text
deviceId = str(Git_deviceId_text.rstrip("\n"))

#deviceId = "428320C1CBC8CB809BE9C4246907ED0598CC5023E777BC3E5EF3F4DE41626A4B443AB7A58183D424CD"

# Random Comment // Announcement banner | Not Yet Implimented.
Git_banner = requests.get("https://raw.githubusercontent.com/ODYSSE3US/Stand_Alone_Build_Data/main/Aminoapps/SYS_MSG_SENDER/Banner.txt")
Git_OTA_Banner = Git_deviceId.text

# Colour Shortcuts
White_TXT = Fore.WHITE + Style.BRIGHT
RED = Fore.RED
YELLOW = Fore.YELLOW
GREEN = Fore.GREEN
CYAN = Fore.CYAN
Reset = Fore.RESET + Style.RESET_ALL

# Confirm Dialogue But Repetitive.
def Redo():
    try:
        RMSG = input(White_TXT + 'Type Message Here: ')
        subclient.send_message(chatId,message=RMSG, messageType="109")
    except ValueError:
        print(RED + "Message Failed, Please Try again..")
        Redo()

    print(White_TXT + f"Type Y for Yes And N for No.")
    print(White_TXT + "Type 'a' For Advanced Mode To Get Rid Of This Annoying Reminder.")
    party = input(White_TXT + "Wanna Send Another? ").lower()
    if party == "y":
        Redo()
    elif party == "n":
        exit(0)
    elif party == "a":
        skip_annoying_Reminder()
    elif party == "clear":
        os.system('cls' if os.name == 'nt' else 'clear')
        Redo()
    else:
        print(f'Make sure you either said Y or N, Type "clear" To Clear Screen.')

# This Skips That Annoying Reminder And Enables More Possible Functions
def skip_annoying_Reminder():
    os.system('cls' if os.name == 'nt' else 'clear')
    print(Fore.LIGHTWHITE_EX + Back.RED + "Advanced Mode:")
    print("Type '!help' for help")

    ThisIsDefined = input(White_TXT + 'Type Message Here: ')

    if ThisIsDefined == "!help":
        print(help_msg)
        input("Continue? /> ")
        skip_annoying_Reminder()

    elif ThisIsDefined == "!clear":
        os.system('cls' if os.name == 'nt' else 'clear')
        skip_annoying_Reminder()

    elif ThisIsDefined == "!exit":
        print(RED + "Exiting Script..")
        sleep(1.7)
        os.system('cls' if os.name == 'nt' else 'clear')
        exit(0)

    elif ThisIsDefined == "!gaymode":
        print("Congrats! You Just Found An Easter Egg.")
        sleep(0.6)
        os.system('cls' if os.name == 'nt' else 'clear')
        LGBT_MODE()
    else:
        subclient.send_message(chatId,message=ThisIsDefined, messageType="109")
        skip_annoying_Reminder()

# Useless But Fun Addition.... I was bored so why not?
def LGBT_MODE():
    if os.name == "nt":

        lolpy("This Is Unfortunately Not Compatible With Windows. Returning..")
        # Or More Specifically Machines that support ANSI Color Coding.
        sleep(1.5)
        skip_annoying_Reminder()

    else:
        gay_mode_ASCII = """
 ██████   █████  ██    ██     ███    ███  ██████  ██████  ███████
██       ██   ██  ██  ██      ████  ████ ██    ██ ██   ██ ██
██   ███ ███████   ████       ██ ████ ██ ██    ██ ██   ██ █████
██    ██ ██   ██    ██        ██  ██  ██ ██    ██ ██   ██ ██
 ██████  ██   ██    ██        ██      ██  ██████  ██████  ███████
        Dyed with 100% Genuine, Cruelty Free Unicorn Piss.
    """
        os.system('cls' if os.name == 'nt' else 'clear')
        lolpy(gay_mode_ASCII)
        lolpy("This is just here purely for my amusement... 5hrs later.. lol")
        lolpy("Type '!help' for help")

        RainbowInput = input(White_TXT + 'Type Message Here: ')

        if RainbowInput == "!help":
            lolpy(help_msg)
            input("Continue? /> ")
            skip_annoying_Reminder()

        elif RainbowInput == "!clear":
            os.system('cls' if os.name == 'nt' else 'clear')
            skip_annoying_Reminder()

        elif RainbowInput == "!exit":
            lolpy("Exiting Script..")
            sleep(1.7)
            os.system('cls' if os.name == 'nt' else 'clear')
            exit(0)

        elif RainbowInput == "!gaymode":
            lolpy("Congrats! You Just Found An Easter Egg.")
            sleep(0.6)
            os.system('cls' if os.name == 'nt' else 'clear')
            skip_annoying_Reminder()
        else:
            try:
                subclient.send_message(chatId,message=RainbowInput, messageType="109")
                LGBT_MODE()
            except ValueError:
                print(RED + "Something went wrong on amino's end. Try again in a few minutes.")
                exit(1)

help_msg = """

    !help       -     Displays This message
    !clear      -     Clears The Screen
    !exit       -     Exits The Script
    !gaymode    -     ????????????????
"""

# The Main Event.. The Thing That Starts On Start Up.
try:
    os.system('cls' if os.name == 'nt' else 'clear')

    client = amino.Client()
    tprint("Sys Messenger")
    U = input(White_TXT + 'Enter Your Email Here: ')
    P = input(White_TXT + 'Enter Your Password Here: ')

    client.login(email=U, password=P)
    print(f"Successfully Logged In As  {RED}'{client.profile.nickname}'")
    sleep(2)

    os.system('cls' if os.name == 'nt' else 'clear')
    clients = client.sub_clients(start=0, size=1000)

    for A, name in enumerate(clients.name, 1):
        print(f"{YELLOW}|{CYAN}{A}{YELLOW}| {GREEN}{name}")
    aminoIdent = clients.comId[int(input("Select the community: "))-1]
    subclient = amino.SubClient(comId=aminoIdent, profile=client.profile)

    os.system('cls' if os.name == 'nt' else 'clear')
    chatLink = input(White_TXT + 'Paste Chat Link Here: ')
    chatId = client.get_from_code(chatLink).objectId
    MSG = input(White_TXT + 'Type Message Here: ')
    if MSG == "!exit":
        print(White_TXT + "Exiting Script...")
        exit(0)

    else:
        subclient.send_message(chatId,message=MSG,messageType="109")
        print(RED + "Fake System Message Sent.")

        print("Type Y for Yes And N for No. **Case Sensitive**")
        party = input(White_TXT + "Wanna Send Another? ")
        if party == "Y":
            Redo()
        elif party == "y":
            Redo()
        elif party == "N":
            exit(0)
        elif party == "n":
            exit(0)
        else:
            print("Make sure you either said Y or N")

except amino.lib.util.exceptions.InvalidPassword as invalidpw:
    print(RED + "Invalid Password", "An Error Has Occurred Please Restart The Program.")
    sleep(2)
    exit(0)

except amino.lib.util.exceptions.InvalidEmail as invalidemail:
    print(RED + "Invalid Email", "An Error Has Occurred Please Restart The Program.")
    sleep(2)
    exit(0)

except ValueError:
    print(RED + "Something went wrong on amino's end. Try again in a few minutes.")
    exit(1)


#  This file is part of Atarashii.
#
#  Atarashii is free software: you can redistribute it and/or
#  modify it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  Atarashii is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along with
#  Atarashii. If not, see <http://www.gnu.org/licenses/>.

# Settings Dialog --------------------------------------------------------------
# ------------------------------------------------------------------------------
import pygtk
pygtk.require('2.0')
import gtk
import gobject

from dialog import Dialog
from settings_dialog_sub import SettingsPages, SettingsSaves
from lang import LANG as lang

from constants import UNSET_USERNAME, UNSET_COLUMN, FONT_SIZES, AVATAR_SIZES
from constants import ST_CONNECT, ST_LOGIN_COMPLETE

# This thing is most likely the worst part of Atarashii ------------------------
# At some point I'll need to spend a whole day cleaning this up ----------------
class SettingsDialog(Dialog, SettingsPages, SettingsSaves):
    resource = 'settings.glade'
    instance = None

    def __init__(self, parent):
        Dialog.__init__(self, parent, False, False, True)
        self.parent = parent
        self.blocked = False
        self.username_dialog = None
        self.question_dialog = None
        self.saved = False
        self.oldusername = self.main.username
        self.settings.check_autostart()
        self.dlg.set_title(lang.settings_title)

        # Tabs
        self.get('users').set_label(lang.settings_tab_accounts)
        self.get('general').set_label(lang.settings_tab_general)
        self.get('atarashii').set_label(lang.settings_tab_atarashii)
        self.get('syncing').set_label(lang.settings_tab_syncing)
        self.get('notifications').set_label(lang.settings_tab_notifications)
        self.get('theme').set_label(lang.settings_tab_theme)

        # Pages
        self.page_accounts(self.settings)
        self.page_atarashii(self.settings)
        self.page_syncing(self.settings)
        self.page_theme(self.settings)
        self.page_notify_sounds(self.settings)

        # Activate
        if (not self.main.status(ST_LOGIN_COMPLETE) \
           and self.main.username != UNSET_USERNAME) \
           or self.main.status(ST_CONNECT):

            self.activate(False)

        # Events
        self.close_button.set_label(lang.settings_button)
        self.close_button.connect('clicked', self.on_save)

        cancel_button = self.get('cancelbutton')
        cancel_button.set_label(lang.settings_button_cancel)
        cancel_button.connect('clicked', self.on_close)
        gobject.idle_add(self.accounts.grab_focus)
        self.dlg.set_size_request(-1, -1)

    def on_save(self, *args):
        if not self.save_syncing(self.settings):
            return False

        self.save_atarashii(self.settings)
        self.save_theme(self.settings)
        self.save_notify_sounds(self.settings)
        self.saved = True
        self.main.save_mode()
        self.settings.css()

        # Save Settings
        self.main.save_settings(False)
        self.gui.tray.update_account_menu()
        self.on_close()

    def on_close(self, *args):
        if self.blocked:
            return False

        if self.file_chooser is not None:
            self.file_chooser.close()

        if not self.saved:
            if self.get_active_account() == -1 \
               or not self.oldusername in self.settings.get_accounts():

                self.main.logout()

            if FONT_SIZES[self.fonts.get_active()] != self.old_font_size \
               or AVATAR_SIZES[self.avatars.get_active()] \
                  != self.old_avatar_size \
               or self.color_ids[self.themes.get_active()] \
                  != self.old_color_theme:

                self.settings.css()
                gobject.idle_add(self.gui.tweet.update_css)
                gobject.idle_add(self.gui.message.update_css)
                gobject.idle_add(self.gui.profile.update_css)

        self.__class__.instance = None
        self.gui.settings_dialog = None
        self.dlg.hide()

    # Helpers ------------------------------------------------------------------
    # --------------------------------------------------------------------------
    def activate(self, mode):
        if self.accounts is not None:
            self.accounts.set_sensitive(mode)
            self.add.set_sensitive(mode)
            if mode:
                self.account_changed()

            else:
                self.edit.set_sensitive(mode)
                self.delete.set_sensitive(mode)

    def unblock(self):
        self.blocked = False

    def hideall(self, sub_only=False):
        if not sub_only:
            self.gui.settings_dialog = None
            self.dlg.hide()
            if self.file_chooser is not None:
                self.file_chooser.close()

        if self.username_dialog is not None:
            self.username_dialog.on_close()

        if self.question_dialog is not None:
            self.blocked = False
            self.question_dialog.destroy()
            self.question_dialog = None

    def update_css(self, *args):
        self.settings.css(FONT_SIZES[self.fonts.get_active()],
                          AVATAR_SIZES[self.avatars.get_active()],
                          self.color_ids[self.themes.get_active()])

        gobject.idle_add(self.gui.tweet.update_css)
        gobject.idle_add(self.gui.message.update_css)
        gobject.idle_add(self.gui.profile.update_css)

    def create_boxlist(self, item, values, default, callback=None):
        item = self.get(item)
        item_list = gtk.ListStore(str)
        cell = gtk.CellRendererText()
        item.pack_start(cell, True)
        item.add_attribute(cell, 'text', 0)
        item.set_model(item_list)

        if not default in values:
            values.append(default)
            values.sort()

        for i, k in enumerate(values):
            item_list.append((k,))
            if k == default:
                item.set_active(i)

        if callback is not None:
            item.connect('changed', callback)

        return item

    # Users --------------------------------------------------------------------
    # --------------------------------------------------------------------------
    def get_active_account(self):
        i = self.accounts.get_selection().get_selected_rows()[1]
        if i is None or len(i) == 0:
            return -1

        return i[0][0]

    def select_account(self, num):
        self.accounts.get_selection().select_path((num,))
        self.account_changed()

    def create_account_list(self, name=None):
        self.user_accounts = self.settings.get_accounts()
        self.accounts_list = gtk.ListStore(str, str, str, str)
        selected = -1
        for num, user in enumerate(self.user_accounts):
            self.accounts_list.append(self.get_account_entry(user))
            if user == name:
                selected = num

            elif name is None and user == self.main.username:
                selected = num

            elif self.main.username == UNSET_USERNAME and selected == -1:
                selected = num

        self.accounts.set_model(self.accounts_list)
        if selected != -1:
            self.select_account(selected)

        else:
            self.account_changed()

    def get_account_entry(self, name):
        tweets = self.settings['count_tweets_' + name]
        follower = self.settings['count_followers_' + name]
        following = self.settings['count_friends_' + name]

        if str(tweets) in ('', 'None'):
            tweets = UNSET_COLUMN

        if str(follower) in ('', 'None'):
            follower = UNSET_COLUMN

        if str(following) in ('', 'None'):
            following = UNSET_COLUMN

        return [name, str(tweets), str(follower), str(following)]

     # Setup Account List
    def account_changed(self, *args):
        i = self.get_active_account()
        self.edit.set_sensitive(i != -1)
        self.delete.set_sensitive(i != -1)

    # Editing ------------------------------------------------------------------
    def edit_account(self, username):
        name = self.user_accounts[self.get_active_account()]
        if name != username:
            ft_tmp = self.settings['firsttweet_' + name]
            lt_tmp = self.settings['lasttweet_' + name]
            fm_tmp = self.settings['firstmessage_' + name]
            lm_tmp = self.settings['lastmessage_' + name]
            lo_tmp = self.settings['mode_' + name]

            at_tmp = self.settings['count_tweets_' + name]
            af_tmp = self.settings['count_followers_' + name]
            ag_tmp = self.settings['count_friends_' + name]

            del self.settings['mode_' + name]
            del self.settings['account_' + name]
            del self.settings['firsttweet_' + name]
            del self.settings['lasttweet_' + name]
            del self.settings['firstmessage_' + name]
            del self.settings['lastmessage_' + name]
            del self.settings['xkey_' + name]
            del self.settings['xsecret_' + name]
            del self.settings['count_tweets_' + name]
            del self.settings['count_followers_' + name]
            del self.settings['count_friends_' + name]

            self.settings['mode_' + username] = lo_tmp
            self.settings['account_' + username] = UNSET_USERNAME
            self.settings['firsttweet_' + username] = ft_tmp
            self.settings['lasttweet_' + username] = lt_tmp
            self.settings['firstmessage_' + username] = fm_tmp
            self.settings['lastmessage_' + username] = lm_tmp
            self.settings['count_tweets_' + username] = at_tmp
            self.settings['count_followers_' + username] = af_tmp
            self.settings['count_friends_' + username] = ag_tmp

            # Edit active account?
            if self.main.username == name:
                self.main.username = username
                self.main.syncer.reset()
                self.main.logout()

            # update menu
            self.main.gui.tray.update_account_menu()
            self.settings.save()
            self.create_account_list(username)

    # Create -------------------------------------------------------------------
    def create_account(self, username):
        self.settings['account_' + username] = UNSET_USERNAME

        # update menu
        self.main.gui.tray.update_account_menu()
        self.settings.save()
        self.create_account_list(username)
        if len(self.user_accounts) == 1:
            self.select_account(0)

    # Delete -------------------------------------------------------------------
    def delete_account(self):
        self.blocked = False
        name = self.user_accounts[self.get_active_account()]
        del self.settings['mode_' + name]
        del self.settings['account_' + name]
        del self.settings['firsttweet_' + name]
        del self.settings['lasttweet_' + name]
        del self.settings['firstmessage_' + name]
        del self.settings['lastmessage_' + name]
        del self.settings['xkey_' + name]
        del self.settings['xsecret_' + name]
        del self.settings['count_tweets_' + name]
        del self.settings['count_followers_' + name]
        del self.settings['count_friends_' + name]

        self.settings.delete_userlist(name)

        # Delete active account?
        if self.main.username == name:
            self.main.username = UNSET_USERNAME
            self.main.logout()

        # update menu
        self.main.gui.tray.update_account_menu()
        self.settings.save()
        self.create_account_list()


# © 2020 Comunitea - Javier Colmenero <javier@comunitea.com>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from odoo import models, fields, api, _

class ResPartner(models.Model):

    _inherit = "res.partner"

    admin_fact = fields.Float('Factor administrativo (%)')
    require_num_order = fields.Boolean('Requires num order')
    supplier_number = fields.Char('Supplier Number')
    valued_picking = fields.Boolean(
        default=False,)

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=100):
        """Give preference to commercial names on name search, appending
        the rest of the results after. This has to be done this way, as
        Odoo overwrites name_search on res.partner in a non inheritable way."""
        if not args:
            args = []
        partners = self.search(
            [('vat', operator, name)] + args, limit=limit,
        )
        res = partners.name_get()
        if limit:
            limit_rest = limit - len(partners)
        else:  # pragma: no cover
            # limit can be 0 or None representing infinite
            limit_rest = limit
        if limit_rest or not limit:
            args += [('id', 'not in', partners.ids)]
            res += super(ResPartner, self).name_search(
                name, args=args, operator=operator, limit=limit_rest,
            )
        return res

    @api.multi
    def _get_admin_fact(self):
        if self.admin_fact:
            return self.admin_fact
        elif self.parent_id and self.parent_id.admin_fact:
            return self.parent_id.admin_fact
        else:
            return self.commercial_partner_id.admin_fact

    def _get_name(self):
        """ Utility method to allow name_get to be overrided without re-browse the partner """
        partner = self
        name = super()._get_name()
        print(name)
        if self._context.get('show_phone') :
            if partner.mobile or partner.phone:
                name = "%s \n %s  %s" % (name, partner.mobile or "", partner.phone or "")
        for cat in self.category_id:
            print(cat.name)
            if cat.name == 'Web F2P':
                name_arr = name.split('\n', 1)
                if len(name_arr) > 1:
                    name = "%s *\n%s" % (name_arr[0], name_arr[1])
                else:
                    name = "%s *" % (name)
        print(name)
        return name


import tensorflow as tf

a = tf.constant(2)
b = tf.constant(3)

# TensorFlow will define a graph to store variables then this graph is run through session

with tf.Session() as sess:
    print("a: %i" % sess.run(a), "b: %i" % sess.run(b))
    print("Addition with constants: %i" % sess.run(a+b))
    print("Multiplication with constants %i" % sess.run(a*b))

# tf.placeholder make a tensor that can take specific values, here it is 16bit integer
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)

add = tf.add(a,b)
mul = tf.multiply(a,b) # Supports Broadcasting

# feed_dict is used to feed values in variable tensors
with tf.Session() as sess:
    print("Addition with variables: %i" %sess.run(add, feed_dict={a:2, b:3}))
    print("Multiplication with variables: %i" % sess.run(mul, feed_dict={a: 2, b: 3}))

#1x2 matrix
matrix1 = tf.constant([[3., 3.]])
#2x1 matrix
matrix2 = tf.constant([[2.],[2.]])
#tf.matmul is used to multiply matix, also supports broadcasting
product = tf.matmul(matrix1, matrix2)

#IMPORTANT: None of the above operations are executed untill session is run as it only create the graph

with tf.Session() as sess:
    result = sess.run(product)
    print(result)


def alphabet_position(letter):
    import string
    if letter.islower():
        position = string.ascii_lowercase.index(letter)
    else:
        position = string.ascii_uppercase.index(letter)
    return position

def rotate_character(char, rot):
    import string
    new_char = alphabet_position(char)
    new_char = new_char + rot
    new_char = new_char % 26
    if char.islower():
        new_char = string.ascii_lowercase[new_char]
    else:
        new_char = string.ascii_uppercase[new_char]
    return new_char

def encrypt(text, rot):
    import string
    encrypt_text = ""
    for char in text:
        if char.isalpha():
            encrypt_char = rotate_character(char, rot)
            encrypt_text = encrypt_text + encrypt_char
        else:
            encrypt_char = char
            encrypt_text = encrypt_text + encrypt_char

    return encrypt_text


def get_input():

    not_float = 1
    second = 1
    D = [0]

    while not_float != 0 and second != 0:
        mon = input("Type in any amount of money, cents included (__.__) :")
        try:
            float(mon)
            if "." in mon:
                result = mon.index('.')
                print("You have this much money : $"+mon)
                cents=(mon[result+1] + mon[result+2])
                not_float = 0
                second = 0

            elif "." not in mon:
                print("Please type any amount of money in this format __.__ ")
                not_float = 1

        except ValueError:
            print("Please type any amount of money in this format __.__ ")
            not_float = 1

        except IndexError:
            print("Please type any amount of money in this format __.__ ")
            second = 1

    dig = 0
    amt = 0

    for y in range(0, len(mon)):

        if (result>dig):
            amt=amt+1
        dig = dig + 1

    dig = 0
    D = [0]*amt
    for x in range(0, len(mon)):

        if (result>dig):
            dollars = mon[dig]
            D[dig] = dollars
        dig = dig + 1

    print("Dollars :", end='')

    gawk = str("")
    for i in D:
        gawk = gawk + (i)
    print(gawk)

    return cents, gawk

def get_change():
    cents, gawk = get_input()
    dollars = int(gawk)

    print("Cents :" + cents)
    cents = int(cents)

    h = 0
    f = 0
    t = 0
    ten = 0
    five = 0
    one = 0
    Q = 0
    D = 0
    N = 0
    P = 0

    while dollars%100 != dollars:
        dollars = dollars-100
        h = h+1
    while dollars%50 != dollars:
        dollars = dollars-50
        f = f+1
    while dollars%20 != dollars:
        dollars = dollars-20
        t = t+1
    while dollars%10 != dollars:
        dollars = dollars-10
        ten = ten+1
    while dollars%5 != dollars:
        dollars = dollars-5
        five = five+1

    one = dollars

    while cents%25 != cents:
        cents = cents-25
        Q = Q+1
    while cents%10 != cents:
        cents = cents-10
        D = D+1
    while cents%5 != cents:
        cents = cents-5
        N = N+1
    P = cents

    h = str(h)
    f = str(f)
    t = str(t)
    ten = str(ten)
    five = str(five)
    one = str(one)
    Q = str(Q)
    D = str(D)
    N = str(N)
    P = str(P)
    print("Hundred dollar bills : "+h)
    print("Fifty dollar bills : "+f)
    print("Twenty dollar bills : "+t)
    print("Ten dollar bills : "+ten)
    print("Five dollar bills : "+five)
    print("One dollar bills : "+one)
    print(" ")
    print("Quarters : "+Q)
    print("Dimes : "+D)
    print("Nickles : "+N)
    print("Pennies : "+P)

get_change()


import pandas as pd

df = pd.read_csv("./sample.csv")

print(df)
print("-----")

def sample_method(row):
  comment = str(row['comment']).rjust(7, '0')
  master = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  ary = []
  for index, char in enumerate(comment):
    if char == '1':
      ary.append(master[index])
  row['comment'] = ','.join(ary)

  return row

df = df.apply(sample_method, axis=1)
print(df)


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

import pytest
import time
import math

url1 = "236895/step/1"
url2 = "236897/step/1"
url3 = "236898/step/1"
url4 = "236899/step/1"
url5 = "236903/step/1"
url6 = "236904/step/1"
url7 = "236905/step/1"

#final_txt = ""

@pytest.mark.parametrize('url', [url1, url2, url3, url4, url5, url6, url7])
class TestUFO:
    def test_I_am_should_login(self, browser, url):
        link = f"https://stepik.org/lesson/{url}"
        browser.get(link)
        browser.implicitly_wait(10)
        msg_elemnt = ""

        browser.find_element(By.CSS_SELECTOR, "a[id='ember33']").click()
        browser.find_element(By.CSS_SELECTOR, "input[id='id_login_email']").send_keys("xxxxxxxxxxxxxxx@xxxxxxxxxx.xxx")
        browser.find_element(By.CSS_SELECTOR, "input[id='id_login_password']").send_keys("xxxxxxxxxxxxxx")
        browser.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
        WebDriverWait(browser, 10).until(EC.invisibility_of_element_located((By.CSS_SELECTOR, "button[type='submit']")))
        browser.refresh()

        WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "textarea:required")))
        browser.find_element(By.CSS_SELECTOR, "textarea:required").send_keys(math.log(int(time.time())))
        WebDriverWait(browser, 2).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[class='submit-submission']")))
        #browser.find_element(By.CSS_SELECTOR, "button[class='again-btn white']").click()
        browser.find_element(By.CSS_SELECTOR, "button[class='submit-submission']").click()

        WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "p[class='smart-hints__hint']")))
        msg_elemnt = browser.find_element(By.CSS_SELECTOR, "p[class='smart-hints__hint']").text

        WebDriverWait(browser, 2).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "button[class='again-btn white']")))
        browser.find_element(By.CSS_SELECTOR, "button[class='again-btn white']").click()

        #assertEqual(msg_elemnt, "Correct!", f"{msg_elemnt}")

        try:
            assert "Correct!" in msg_elemnt
        except:
            with open("3_6_5_test_Errors.log", "a") as f:
                f.write(msg_elemnt)
            raise AssertionError('Error! See "3_6_5_test_Errors.log"')


"""
Дана последовательность чисел N (N > 0)
Найти максимальное число в последовательности
"""

def findmax(seq):
    num = seq[0]
    for i in range(1, len(seq)):
        if seq[i] > num:
            num = seq[i]
    return num


import pygame
from mysprite import *
pygame.init()
screen = pygame.display.set_mode((480,700))
bg = pygame.image.load("/home/laowang/1807/images/background.png")
#screen.blit(bg,(0,0))

hero = pygame.image.load("/home/laowang/1807/images/hero1.png")
#screen.blit(hero,(200,500))
herorect = pygame.Rect(200,500,120,120)
clock = pygame.time.Clock()#创建游戏时钟

enemy = EnemySprite()#创建敌机精灵
enemy1 = EnemySprite()#创建敌机精灵
enemy1.rect.x = 50
enemy1.speed = 2
enemy2 = EnemySprite()
enemy2.rect.x = 250
enemy2.speed = 1
enemy_group = pygame.sprite.Group(enemy,enemy1,enemy2)

while True:
	clock.tick(60)#一秒刷新60次
	herorect.y -= 1 #相当于速度
	screen.blit(bg,(0,0))
	screen.blit(hero,herorect)
	if herorect.bottom <= 0:#控制飞机返航
		herorect.top = 700
	enemy_group.update()#更新
	enemy_group.draw(screen)#画到哪

	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			print("退出游戏")
			pygame.quit()
			exit()

	pygame.display.update()#更新

pygame.init()


import robotoc
import numpy as np
import math

model_info = robotoc.RobotModelInfo()
model_info.urdf_path = '../icub_description/urdf/icub.urdf'
model_info.base_joint_type = robotoc.BaseJointType.FloatingBase
baumgarte_time_step = 0.05
model_info.surface_contacts = [robotoc.ContactModelInfo('l_sole', baumgarte_time_step),
                               robotoc.ContactModelInfo('r_sole', baumgarte_time_step)]
robot = robotoc.Robot(model_info)

dt = 0.02
jump_length = np.array([0.5, 0, 0])
flying_time = 0.25
ground_time = 0.7
t0 = 0.

cost = robotoc.CostFunction()
q_standing = np.array([0, 0, 0.592, 0, 0, 1, 0,
                       0.20944, 0.08727, 0, -0.1745, -0.0279, -0.08726, # left leg
                       0.20944, 0.08727, 0, -0.1745, -0.0279, -0.08726, # right leg
                       0, 0, 0, # torso
                       0, 0.35, 0.5, 0.5, 0, 0, 0, # left arm
                       0, 0.35, 0.5, 0.5, 0, 0, 0]) # right arm
q_ref = q_standing.copy()
q_ref[0:3] += jump_length
q_weight = np.array([0, 1, 1, 100, 100, 100,
                     0.001, 0.001, 0.001, 0.001, 0.001, 0.001,
                     0.001, 0.001, 0.001, 0.001, 0.001, 0.001,
                     0.001, 1, 1,
                     0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001,
                     0.001, 0.001, 0.001, 0.001, 0.001, 0.001, 0.001])
q_weight_terminal = q_weight
v_weight = np.full(robot.dimv(), 1.0e-03)
a_weight = np.full(robot.dimv(), 1.0e-05)
q_weight_impact = 1.0 * q_weight
v_weight_impact = 1.0 * v_weight
config_cost = robotoc.ConfigurationSpaceCost(robot)
config_cost.set_q_ref(q_standing)
config_cost.set_q_weight(q_weight)
config_cost.set_q_weight_terminal(q_weight)
config_cost.set_q_weight_impact(q_weight_impact)
config_cost.set_v_weight(v_weight)
config_cost.set_v_weight_terminal(v_weight)
config_cost.set_v_weight_impact(v_weight_impact)
config_cost.set_a_weight(a_weight)
cost.add("config_cost", config_cost)

# Create the constraints
constraints           = robotoc.Constraints(barrier_param=1.0e-03, fraction_to_boundary_rule=0.995)
joint_position_lower  = robotoc.JointPositionLowerLimit(robot)
joint_position_upper  = robotoc.JointPositionUpperLimit(robot)
joint_velocity_lower  = robotoc.JointVelocityLowerLimit(robot)
joint_velocity_upper  = robotoc.JointVelocityUpperLimit(robot)
joint_torques_lower   = robotoc.JointTorquesLowerLimit(robot)
joint_torques_upper   = robotoc.JointTorquesUpperLimit(robot)
# contact_wrench_cone  = robotoc.ContactWrenchCone(robot, 0.1, 0.05)
friction_cone  = robotoc.FrictionCone(robot)
constraints.add("joint_position_lower", joint_position_lower)
constraints.add("joint_position_upper", joint_position_upper)
constraints.add("joint_velocity_lower", joint_velocity_lower)
constraints.add("joint_velocity_upper", joint_velocity_upper)
constraints.add("joint_torques_lower", joint_torques_lower)
constraints.add("joint_torques_upper", joint_torques_upper)
# constraints.add("contact_wrench_cone", contact_wrench_cone)
constraints.add("friction_cone", friction_cone)

# Create the contact sequence
contact_sequence = robotoc.ContactSequence(robot)
mu = 0.6
friction_coefficients = {'l_sole': mu, 'r_sole': mu}

robot.forward_kinematics(q_standing)
x3d0_L = robot.frame_placement('l_sole')
x3d0_R = robot.frame_placement('r_sole')
contact_placements = {'l_sole': x3d0_L, 'r_sole': x3d0_R}

contact_status_standing = robot.create_contact_status()
contact_status_standing.activate_contacts(['l_sole', 'r_sole'])
contact_status_standing.set_contact_placements(contact_placements)
contact_status_standing.set_friction_coefficients(friction_coefficients)
contact_sequence.init(contact_status_standing)

contact_status_flying = robot.create_contact_status()
contact_sequence.push_back(contact_status_flying, t0+ground_time, sto=True)

contact_placements['l_sole'].trans = contact_placements['l_sole'].trans + jump_length
contact_placements['r_sole'].trans = contact_placements['r_sole'].trans + jump_length
contact_status_standing.set_contact_placements(contact_placements)
contact_sequence.push_back(contact_status_standing, t0+ground_time+flying_time, sto=True)

contact_sequence.push_back(contact_status_flying, t0+2*ground_time+flying_time, sto=True)

contact_placements['l_sole'].trans = contact_placements['l_sole'].trans + jump_length
contact_placements['r_sole'].trans = contact_placements['r_sole'].trans + jump_length
contact_status_standing.set_contact_placements(contact_placements)
contact_sequence.push_back(contact_status_standing, t0+2*ground_time+2*flying_time, sto=True)

# Create the STO cost function. This is necessary even empty one to construct an OCP with a STO problem
sto_cost = robotoc.STOCostFunction()
# Create the STO constraints
sto_constraints = robotoc.STOConstraints(minimum_dwell_times=[0.6, 0.2, 0.6, 0.2, 0.6],
                                         barrier_param=1.0e-03,
                                         fraction_to_boundary_rule=0.995)

T = t0 + 2*flying_time + 3*ground_time
N = math.floor(T/dt)
# Create the OCP with the STO problem
ocp = robotoc.OCP(robot=robot, cost=cost, constraints=constraints,
                  sto_cost=sto_cost, sto_constraints=sto_constraints,
                  contact_sequence=contact_sequence, T=T, N=N)
# Create the OCP solver
solver_options = robotoc.SolverOptions()
solver_options.kkt_tol_mesh = 0.1
solver_options.max_dt_mesh = T/N
solver_options.max_iter = 350
solver_options.initial_sto_reg_iter = 10
solver_options.nthreads = 4
ocp_solver = robotoc.OCPSolver(ocp=ocp, solver_options=solver_options)

# Initial time and intial state
t = 0.
q = q_standing
v = np.zeros(robot.dimv())
ocp_solver.discretize(t)
ocp_solver.set_solution("q", q)
ocp_solver.set_solution("v", v)

ocp_solver.init_constraints()
print("Initial KKT error: ", ocp_solver.KKT_error(t, q, v))
ocp_solver.solve(t, q, v)
print("KKT error after convergence: ", ocp_solver.KKT_error(t, q, v))
print(ocp_solver.get_solver_statistics())

# Display results
viewer = robotoc.utils.TrajectoryViewer(model_info=model_info, viewer_type='gepetto')
viewer.set_contact_info(mu=mu)
viewer.display(ocp_solver.get_time_discretization(),
               ocp_solver.get_solution('q'),
               ocp_solver.get_solution('f', 'WORLD'))


# Import the necessary libraries
from gensim.models import Word2Vec
import nltk

corpus = nltk.corpus.brown.sents()
# Load the Brown corpus from NLTK
# corpus = brown.sents()

# Train the Word2Vec model on the corpus
model = Word2Vec(corpus, vector_size=100, window=5, min_count=1, workers=4)

# Get the embedding vector for a word
embedding = model.wv['dog']

# Find the most similar words to a given word
similar_words = model.wv.most_similar('dog')

# Print the embedding vector and similar words
print('Embedding vector for "dog":', embedding)
print('Most similar words to "dog":', similar_words)


import yaml
import os
from XtDac.ChandraUtils.sanitize_filename import sanitize_filename

class ReadOnlyContainer(object):

    def __init__(self, dictionary):

        self._dict = dict(dictionary)

    def __getitem__(self, item):

        return self._dict[item]

def get_configuration(filename):

    filename = sanitize_filename(filename)

    assert os.path.exists(filename), "Configuration file %s does not exist!" % filename

    try:

        with open(filename, "r") as f:

            configuration_dict = yaml.safe_load(f)

    except:

        raise IOError("Couldn't read configuration file %s. File is not readable, or wrong format." % (filename))

    configuration = ReadOnlyContainer(configuration_dict)

    return configuration


# STEPC
# A fast and extensible linear system and controller simulator
# for evaluation of predictive controllers
#
# Jon Sowman 2014 <j.sowman@soton.ac.uk>

from ..stepc.controller import LinearMPCController
from ..stepc.linsystem import LinSystem

import numpy as np

class TestLinearMPC(object):

    def setup(self):
        """
        Create all the bits needed to test the ability of a LinearMPCController
        to derive and formulate a solution framework, and then find a solution
        to a toy problem.
        """

        self.__sys = LinSystem(2, 1, 1)
        # Test system is from 12mr (mass/spring)
        self.__sys.A = np.array([[0.1, 1], [1, -0.1]])
        self.__sys.B = np.array([[0], [0.1]])
    setup.__test__ = False

    def teardown(self):
        pass
    teardown.__test__ = False

    def test_generate_G(self):
        mpc = LinearMPCController(self.__sys)
        mpc.P = mpc.Q = mpc.R = 1
        mpc.set_prediction_horizon(1)
        mpc.set_control_horizon(1)
        mpc.set_target(np.array([[0], [0]]))
        mpc.generate_matrices()

        expected_G = np.array([[0, 0.2]])

        assert np.allclose(expected_G, mpc._LinearMPCController__G)

    def test_generate_H(self):
        mpc = LinearMPCController(self.__sys)
        mpc.P = mpc.Q = mpc.R = 1
        mpc.set_prediction_horizon(1)
        mpc.set_control_horizon(1)
        mpc.set_target(np.array([[0], [0]]))
        mpc.generate_matrices()

        expected_H = np.array([[2.02]])

        assert np.allclose(expected_H, mpc._LinearMPCController__H)


#This is for pollard p-1 method for finding ladder of primes and gcd
#written by Dylan Kelly for Discrete mathematics 265

#composite of odd number
n = 21
#the bound in which sets the bound for finding primes and pollard
bound = 35
#to hold all the primes in b
primes_in_b = []

#start the program
def main():
    find_primes_in_b(bound)
#method to pull all primes out of bound
def find_primes_in_b(bound):
    prime = False
    #loop through b and append all primes to array
    for i in range(2,bound):
        #get all the number between 2 and [i]
        for k in range(2, i):
            #if k > half of i pass becuase no number can be divided by more then its half
            if k > (i//2) + 1:
                continue
            #if [i] divides any number from 2-i its not prime break
            if i % k == 0:
                prime = False
                break;
            #set prime to true but keep looping
            else:
                prime = True
        #append the primes to the array
        if prime:
            primes_in_b.append(i)

    #call the next step
    p_minus_one(n, primes_in_b)

#method to preform the ladder of c with primes
def p_minus_one(n, primes_in_b):
    #the number to begin the ladder could be arbitrary
    c = 2
    #loop through prime array
    for p in primes_in_b:
        #set the power of the prime sin pwoer_prime
        power_prime = p
        #while laddering if it greater then bound stop
        while power_prime < bound:
            #raise c to the power of the prime
            c = c**p
            #mod c by the n value
            c = c % n
            #set the power prime multiplied by all primes(kinda like lcm)
            power_prime = power_prime * p
    #call th next step of finding the gcd
    g = find_gcd(c-1, n)

    #if g is 1<g<n then its valid else its not valid and most likely 1
    if g > 1 and g < n:
        print("The g is " + str(g) + " and is valid bc it's between 1<" + str(g) + "<" + str(n))
    else:
        print("The g is " + str(g) + " and g is not valid and is not between 1<" + str(g) + "<" + str(n))

#using euclidean algorithm find the gcd
def find_gcd(c_minus_one, n):
    while (n):
        c_minus_one, n = n, c_minus_one % n
    return c_minus_one

if __name__ == "__main__":
    main()


import flwr as fl
from src.fl.fl_utils import TabularClient
from src.plp_extract.extract import extract
from src.train_prep.utils import split_patients, get_dense_sparse_features, df_to_loader
from omegaconf import OmegaConf
import warnings
import pandas as pd
from src.utils.misc import retry
from src.train_prep.dataset import TabularDataset

warnings.filterwarnings("ignore")

def main():
    """Create model, load data, define Flower client, start Flower client."""
    client_conf = OmegaConf.load("./client_conf.yaml")
    train_conf = OmegaConf.load("./train_conf.yaml")

    # build package
    extract(train_conf=train_conf, client_conf=client_conf)
    cov_pop = pd.read_parquet(f"./temps/cov_{train_conf.project}.parquet")

    # split data
    train, valid, test = split_patients(cov_pop, pct=[0.7, 0.1, 0.2])
    train, valid, test = (
        train.reset_index(drop=True),
        valid.reset_index(drop=True),
        test.reset_index(drop=True),
    )
    train_loader, valid_loader, test_loader = df_to_loader(
        train, valid, test, TabularDataset, train_conf.batch_size
    )

    # Define client
    fl_client = TabularClient(
        train_loader,
        valid_loader,
        test_loader,
        client_conf=client_conf,
        train_conf=train_conf,
    )

    # try_client()
    fl.client.start_numpy_client(
        server_address=train_conf.fl_server_port, client=fl_client
    )

if __name__ == "__main__":
    main()


import os
from os.path import exists

from setuptools import find_packages, setup

description = open("README.md").read() if exists("README.md") else ""

setup(
    name="sqlmesh",
    description="",
    long_description=description,
    long_description_content_type="text/markdown",
    url="https://github.com/TobikoData/sqlmesh",
    author="TobikoData Inc.",
    author_email="engineering@tobikodata.com",
    license="Apache License 2.0",
    packages=find_packages(include=["sqlmesh", "sqlmesh.*", "web*"]),
    package_data={"web": ["client/dist/**"]},
    entry_points={
        "console_scripts": [
            "sqlmesh = sqlmesh.cli.main:cli",
            "sqlmesh_cicd = sqlmesh.cicd.bot:bot",
        ],
        "airflow.plugins": [
            "sqlmesh_airflow = sqlmesh.schedulers.airflow.plugin:SqlmeshAirflowPlugin",
        ],
    },
    use_scm_version={
        "write_to": "sqlmesh/_version.py",
        "fallback_version": "0.0.0",
        "local_scheme": "no-local-version",
    },
    setup_requires=["setuptools_scm"],
    install_requires=[
        "astor",
        "click",
        "croniter",
        "duckdb",
        "dateparser",
        "fsspec",
        "hyperscript",
        "ipywidgets",
        "jinja2",
        "pandas<2.1.0",
        "pydantic[email]>=1.10.7,<2.0.0",
        "requests",
        "rich[jupyter]",
        "ruamel.yaml",
        "sqlglot~=19.0.2",
    ],
    extras_require={
        "bigquery": [
            "google-cloud-bigquery[pandas]",
            "google-cloud-bigquery-storage",
        ],
        "databricks": [
            "databricks-sql-connector",
            "databricks-cli",
        ],
        "dev": [
            f"apache-airflow=={os.environ.get('AIRFLOW_VERSION', '2.3.3')}",
            "autoflake==1.7.7",
            "agate==1.6.3",
            "google-cloud-bigquery",
            "google-cloud-bigquery-storage",
            "black==22.6.0",
            "dbt-core",
            "dbt-duckdb>=1.4.2",
            "Faker",
            "freezegun",
            "google-auth",
            "isort==5.10.1",
            "mkdocs-include-markdown-plugin==4.0.3",
            "mkdocs-material==9.0.5",
            "mypy~=1.4.0",
            "pre-commit",
            "pandas-stubs",
            "pdoc",
            "psycopg2-binary",
            "pyarrow>=10.0.1,<10.1.0",
            "PyGithub",
            "pytest",
            "pytest-asyncio",
            "pytest-lazy-fixture",
            "pytest-mock",
            "pyspark>=3.4.0",
            "pytz",
            "snowflake-connector-python[pandas,secure-local-storage]>=3.0.2",
            "sqlalchemy-stubs",
            "tenacity==8.1.0",
            "types-croniter",
            "types-dateparser",
            # Remove once fix is ready for 4.6.0
            "typing-extensions==4.5.0",
            "types-pytz",
            "types-requests==2.28.8",
        ],
        "dbt": [
            "dbt-core<1.5.0",
        ],
        "gcppostgres": [
            "cloud-sql-python-connector[pg8000]",
        ],
        "github": [
            "PyGithub",
        ],
        "llm": [
            "langchain",
            "openai",
        ],
        "mssql": [
            "pymssql",
        ],
        "mysql": [
            "mysql-connector-python",
        ],
        "mwaa": [
            "boto3",
        ],
        "postgres": [
            "psycopg2",
        ],
        "redshift": [
            "redshift_connector",
        ],
        "slack": [
            "slack_sdk",
        ],
        "snowflake": [
            "snowflake-connector-python[pandas,secure-local-storage]",
            "pyarrow>=10.0.1,<10.1.0",
        ],
        "trino": [
            "trino",
        ],
        "web": [
            "fastapi==0.100.0",
            "watchfiles>=0.19.0",
            "pyarrow>=10.0.1",
            "uvicorn[standard]==0.22.0",
            "sse-starlette>=0.2.2",
        ],
    },
    classifiers=[
        "Intended Audience :: Developers",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: Apache Software License",
        "Operating System :: OS Independent",
        "Programming Language :: SQL",
        "Programming Language :: Python :: 3 :: Only",
    ],
)


from seleniumbase import BaseCase
BaseCase.main(__name__, __file__)

class DialogBoxTests(BaseCase):
    def test_dialog_boxes(self):
        self.open("https://xkcd.com/1920/")
        self.assert_element('img[alt="Emoji Sports"]')
        self.highlight("#comic img")

        skip_button = ["SKIP", "red"]  # Can be a [text, color] list or tuple.
        buttons = ["Fencing", "Football", "Metaball", "Go/Chess", skip_button]
        message = "Choose a sport:"
        choice = None
        while choice != "STOP":
            choice = self.get_jqc_button_input(message, buttons)
            if choice == "Fencing":
                self.open("https://xkcd.com/1424/")
                buttons.remove("Fencing")
            elif choice == "Football":
                self.open("https://xkcd.com/1107/")
                buttons.remove("Football")
            elif choice == "Metaball":
                self.open("https://xkcd.com/1507/")
                buttons.remove("Metaball")
            elif choice == "Go/Chess":
                self.open("https://xkcd.com/1287/")
                buttons.remove("Go/Chess")
            else:
                break
            self.highlight("#comic img")
            if len(buttons) == 2:
                message = "One Sport Remaining:"
            if len(buttons) == 1:
                message = "Part One Complete. You saw all 4 sports!"
                btn_text_1 = "NEXT Tutorial Please!"
                btn_text_2 = "WAIT, Go/Chess is a sport?"
                buttons = [(btn_text_1, "green"), (btn_text_2, "purple")]
                choice_2 = self.get_jqc_button_input(message, buttons)
                if choice_2 == btn_text_2:
                    self.open_if_not_url("https://xkcd.com/1287/")
                    message = "Brain sports count as sports!

"
                    message += "Are you ready for more?"
                    self.get_jqc_button_input(message, ["Let's Go!"])
                break

        self.open("https://xkcd.com/1117/")
        sb_banner_logo = "//seleniumbase.io/cdn/img/sb_logo_10.png"
        self.set_attributes("#news img", "src", sb_banner_logo)
        options = [("theme", "material"), ("width", "52%")]
        message = 'With one button, you can press "Enter/Return", "Y", or "1".'
        self.get_jqc_button_input(message, ["OK"], options)

        self.open("https://xkcd.com/556/")
        self.set_attributes("#news img", "src", sb_banner_logo)
        options = [("theme", "bootstrap"), ("width", "52%")]
        message = 'If the lowercase button text is "yes" or "no", '
        message += '

you can use the "Y" or "N" keys as shortcuts. '
        message += "

Other shortcuts include:

"
        message += '"1": 1st button, "2": 2nd button, etc. Got it?'
        buttons = [("YES", "green"), ("NO", "red")]
        choice = self.get_jqc_button_input(message, buttons, options)

        message = 'You said "%s"!

' % choice
        if choice == "YES":
            message += "Wonderful! Let's continue with the next example..."
        else:
            message += "You can learn more from SeleniumBase Docs..."
        choice = self.get_jqc_button_input(message, ["OK"], options)

        self.open("https://seleniumbase.io")
        self.set_jqc_theme("light", color="green", width="38%")
        message = "This is the SeleniumBase Docs website!

"
        message += "What would you like to search for?
"
        text = self.get_jqc_text_input(message, ["Search"])
        self.type('input[aria-label="Search"]', text + "\n")
        self.wait_for_ready_state_complete()
        self.set_jqc_theme("bootstrap", color="red", width="32%")
        if self.is_text_visible("No matching documents", ".md-search-result"):
            self.get_jqc_button_input("Your search had no results!", ["OK"])
        elif self.is_text_visible("Type to start searching", "div.md-search"):
            self.get_jqc_button_input("You did not do a search!", ["OK"])
        else:
            self.click_if_visible("a.md-search-result__link")
            self.set_jqc_theme("bootstrap", color="green", width="32%")
            self.get_jqc_button_input("You found search results!", ["OK"])

        self.open("https://seleniumbase.io/help_docs/ReadMe/")
        self.highlight("h1")
        self.highlight_click('a:contains("Running Example Tests")')
        self.highlight("h1")

        self.set_jqc_theme("bootstrap", color="green", width="52%")
        message = 'See the "SeleniumBase/examples" section for more info!'
        self.get_jqc_button_input(message, ["OK"])

        self.set_jqc_theme("bootstrap", color="purple", width="56%")
        message = "Now let's combine form inputs with multiple button options!"
        message += "

"
        message += "Pick something to search. Then pick the site to search on."
        buttons = ["SeleniumBase.io", "Wikipedia.org"]
        text, choice = self.get_jqc_form_inputs(message, buttons)
        if choice == "SeleniumBase.io":
            self.open("https://seleniumbase.io/")
            self.highlight_type('input[aria-label="Search"]', text + "\n")
        else:
            self.open("https://en.wikipedia.org/wiki/Special:Search")
            self.highlight_type('input[id*="search"]', text + "\n")
        self.wait_for_ready_state_complete()
        self.sleep(1)
        self.highlight("body")
        self.reset_jqc_theme()
        self.get_jqc_button_input("Here are your results.", ["OK"])
        message = "
You've reached the end of this tutorial!

"
        message += "Now you know about SeleniumBase Dialog Boxes!
"
        message += "
Check out SeleniumBase on GitHub for more!"
        self.set_jqc_theme("modern", color="purple", width="56%")
        self.get_jqc_button_input(message, ["Goodbye!"])


import os

libN = 2
threads = libN
print("threads =%s" % threads)
os.environ["OMP_NUM_THREADS"] = "%s" % threads
# pool = Pool(processes=cpu_count())
import time
from multiprocessing import get_context

import matplotlib.pyplot as plt
import numpy as np

import definition as harmonic
# This contains the stuff needed to calculate some expectations. Generally contains stuff
# that applies operators to the wave function
# These also contain various important observable calculators
# Contains lots of important functions.
# Sets up the lattice for the system
import poolscripts

# input units: THz (field), eV (t, U), MV/cm (peak amplitude, F0), Angstroms (systems[0]tice cst, a)
# they're then converted to t-normalised atomic units. bc='pbc' for periodic and 'abc' for antiperiodic

if __name__ == '__main__':
    neighbour = []
    neighbour_check = []
    energy = []
    doublon_energy = []
    phi_original = []
    phi_reconstruct = [0., 0.]
    boundary_1 = []
    boundary_2 = []
    two_body = []
    two_body_old = []
    error = []
    D = []
    X = []
    singlon = []
    systems = []
    number = 3
    nelec = (number, number)
    nx = 6
    ny = 0
    t = 0.52
    # t=1.91
    # t=1
    U = 1 * t
    delta = 0.02
    cycles = libN + 1
    field = 32.9
    # field=32.9*2
    F0 = 10
    a = 4

    U_delta = -15
    U_start = 1 * t
    U_end = U_start + (10 ** U_delta) * t
    sections = (cycles - 1) / libN
    U_list = np.linspace(U_start, U_end, libN)

    #
    # def info(title):
    #     print(title)
    #     print('module name:', __name__)
    #     # only available on Unix
    #     if hasattr(os, 'getppid'):
    #         print('parent process:', os.getppid())
    #     print('process id:', os.getpid())
    #

    def f(name):
        # info('function f')
        # print('hello', name)
        return name

    # x=pool.map(f,['bob','alice'])

    # print(x[0])
    # print(x[1])

    pool = get_context("spawn").Pool(processes=threads)
    parameternames = '-%s-nsites-%s-cycles--%s-t-%s-n-%s-delta-%s-field-%s-amplitude-%s-libN-%s-U_start-%s-U_end' % (
        nx, cycles, t, number, delta, field, F0, libN, U_start, U_end)

    def setup(U_input):
        system = harmonic.hhg(cycles=cycles, delta=delta, libN=libN, field=field, nup=number, ndown=number, nx=nx, ny=0,
                              U=U_input, t=t, F0=F0, a=a, bc='pbc')
        return system

    systems = []
    for U in U_list:
        systems.append(setup(U))

    N = int(cycles / (systems[0].freq * delta))
    N_sec = int(1 / (systems[0].freq * delta))
    secN = int(N / (libN + 1))

    """returns systems with both their last current and . First index is process number, second number is either """
    parallel_start = time.time()

    """Adaptive timestep method"""
    systems = pool.map(poolscripts.long_pump, systems)
    print("pump done")

    parallel_end = time.time()
    phi_original = systems[0].phi
    plt.plot(phi_original)
    plt.show()
    for k in range(0, libN):
        plt.plot(systems[k].last_J, '*-')
    plt.show()
    for k in range(0, libN):
        plt.plot(systems[k].neighbourexpec, '*-')
    plt.show()
    for k in range(0, libN):
        ne = systems[k].neighbourexpec
        mag = np.abs(ne)
        theta = np.angle(ne)
        plt.plot(systems[k].last_J, '*-')
        plt.plot(-2 * systems[k].a * systems[k].t * mag * np.sin(phi_original - theta))
    plt.show()
    for system in systems:
        parameternames = '-%s-nsites-%s-cycles-%s-U-%s-t-%s-n-%s-delta-%s-field-%s-amplitude-%s-libN-%s-U_start-%s-U_end' % (
            nx, cycles, system.U, t, number, delta, field, F0, libN, U_start, U_end)
        np.save('./data/discriminate/Jfieldpump' + parameternames, system.last_J)

    print("Time for using multiprocessing pool: %s seconds" % (parallel_end - parallel_start))

    parameternames = '-%s-nsites-%s-cycles-%s-t-%s-n-%s-delta-%s-field-%s-amplitude-%s-libN-%s-U_start-%s-U_end' % (
        nx, cycles, t, number, delta, field, F0, libN, U_start, U_end)
    np.save('./data/original/pumpfield' + parameternames, phi_original)

    #     prop=systems[k]
    #     r = ode(evolve.integrate_f_discrim).set_integrator('zvode', method='bdf')
    #     r.set_initial_value(psi_temp, 0).set_f_params(systems[0],h,phi_func)
    #     branch = 0
    #     delta=delta
    #     while r.successful() and r.t < k*time/(libN*systems[0].freq):
    #         oldpsi=psi_temp
    #         r.integrate(r.t + delta)
    #         psi_temp = r.y
    #         newtime = r.t
    #         # add to expectations
    #
    #         # double occupancy fails for anything other than half filling.
    #         # D.append(evolve.DHP(prop,psi))
    #         harmonic.progress(N, int(newtime / delta))
    #         # psierror=evolve.f(systems[0],evolve.ham1(systems[0],h,newtime,time),oldpsi)
    #         # diff = (psi_temp - oldpsi) / delta
    #         # newerror = np.linalg.norm(diff + 1j * psierror)
    #         # error.append(newerror)
    #         neighbour.append(har_spec.nearest_neighbour_new(systems[0], h, psi_temp))
    #         # neighbour_check.append(har_spec.nearest_neighbour(systems[0], psi_temp))
    #         # X.append(observable.overlap(systems[0], psi_temp)[1])
    #         phi_original.append(phi_func(newtime))
    #         J_field.append(har_spec.J_expectation_track(systems[0], h, psi_temp, phi_original[-1]))
    #         two_body.append(har_spec.two_body_old(systems[0], psi_temp))
    #         D.append(observable.DHP(systems[0], psi_temp))
    #
    #
    # last=J_field[-1]
    # lastime=newtime
    # def J_func(current_time):
    #     J=last*np.exp(-2*(current_time-lastime))
    #     return J
    #
    #
    # r = ode(evolve.integrate_f_track_J).set_integrator('zvode', method='bdf')
    # r.set_initial_value(psi_temp, newtime).set_f_params(systems[0],h,J_func)
    # branch = 0
    # delta=delta
    # while r.successful() and r.t < time/(systems[0].freq):
    #     oldpsi=psi_temp
    #     r.integrate(r.t + delta)
    #     psi_temp = r.y
    #     newtime = r.t
    #     # add to expectations
    #     neighbour.append(har_spec.nearest_neighbour_new(systems[0], h, psi_temp))
    #     two_body.append(har_spec.two_body_old(systems[0], psi_temp))
    #
    #     # tracking current
    #     phi_original.append(evolve.phi_J_track(systems[0], newtime, J_func, neighbour[-1], psi_temp))
    #
    #     # tracking D
    #     # phi_original.append(evolve.phi_D_track(lat,newtime,D_func,two_body[-1],psi_temp))
    #
    #     J_field.append(har_spec.J_expectation_track(systems[0], h, psi_temp, phi_original[-1]))
    #     # double occupancy fails for anything other than half filling.
    #     # D.append(evolve.DHP(prop,psi))
    #     harmonic.progress(N, int(newtime / delta))

    # np.save('./data/original/Jfield'+parameternames,J_field)
    # np.save('./data/original/phi'+parameternames,phi_original)
    # np.save('./data/original/discriminatorfield', phi_original)
    # np.save('./data/original/phirecon'+parameternames,phi_reconstruct)
    # np.save('./data/original/neighbour'+parameternames,neighbour)
    # np.save('./data/original/energy'+parameternames,energy)
    # np.save('./data/original/doublonenergy'+parameternames,doublon_energy)
    # np.save('./data/original/singlonenergy'+parameternames,singlon)

    # np.save('./data/original/position'+parameternames,X)

    # plot_observables(systems[0], delta=0.02, time=5., K=.1)
    # spectra(systems[0], initial=None, delta=delta, time=cycles, method='welch', min_spec=7, max_harm=50, gabor='fL')


import requests
import time
from datetime import datetime

islem = input("payload i giriniz: ")
kanal_id= input("Kanal id' sini girin:")
if (islem == "0"):
	payload ={"type":2,
		"application_id":"624187616312426512",
		"guild_id":"787718450206343218",
		"channel_id":kanal_id,
		"session_id":"14351d4f4e9897f76ddb2b2a0df20245",
		"data":{
    	"version":"1042350843300679691",
    	"id":"1042350843103547441",
    	"name":"hunt",
    		}}
#Burada benim kullanacağım komutun kodu var kullanacağınız koda göre değiştirmelisiniz
token = input("Auth tokeni giriniz:")
header = {
    'authorization': token
}
times=int(input("Tekrarlanacak islem sayisini giriniz:"))
b=1
for i in range(times):
	r = requests.post("https://discord.com/api/v9/interactions", json=payload, headers=header)
	time.sleep(5)
	r = requests.post("https://discord.com/api/v9/interactions", json=payload, headers=header)
	now =datetime.now()
	current_time = now.strftime("%H:%M:%S")
	print("yapilan islem sayisi : {}   Saat : ".format(b),current_time)
	b=b+1
	time.sleep(620)


import sys

def primes (max):
	array = []
	for i in range(2, (max + 1)):
		isPrime = True
		for n in range ((i - 1), 2, -1):
			if (i % n == 0):
				isPrime = False
				break
		if (isPrime): array.append(i)
	return array

print(primes(int(sys.argv[1])))


# standard libraries imports
from __future__ import print_function
import os
import itertools

# external libraries imports
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# fullrmc library imports
from fullrmc.Engine import Engine

# create figure
FIG = plt.figure()
FIG.patch.set_facecolor('white')
grid = gridspec.GridSpec(nrows=2, ncols=2)
grid.update(left=0.1, bottom=0.1, right=0.95, wspace=0.05)

totalAx = plt.subplot(grid[0, :])
lowRAx  = plt.subplot(grid[1, 0])
highRAx = plt.subplot(grid[1, 1])

# set axis ticks
highRAx.get_yaxis().set_ticks([])
lowRAx.get_yaxis().set_ticks([])

# Create plotting styles
colors = ["b",'g','r','c','m','y']
markers = ["",'.','+','^','|']
INTRA_STYLES = [r[0] + r[1]for r in itertools.product(['--'], colors)]
INTRA_STYLES = [r[0] + r[1]for r in itertools.product(markers, INTRA_STYLES)]
INTER_STYLES = [r[0] + r[1]for r in itertools.product(['-'], colors)]
INTER_STYLES = [r[0] + r[1]for r in itertools.product(markers, INTER_STYLES)]

# dirname
DIR_PATH = os.path.dirname( os.path.realpath(__file__) )
engineFilePath = os.path.join(DIR_PATH, "thf_engine.rmc")

# load
ENGINE = Engine(path=None)
result, mes = ENGINE.is_engine(engineFilePath, mes=True)
if result:
    ENGINE = ENGINE.load(engineFilePath)
    PDF = ENGINE.constraints[0]
else:
    print(mes)

# plot total
output = PDF.get_constraint_value()
totalAx.plot(PDF.experimentalDistances, ENGINE.constraints[0].experimentalPDF, 'ro', label="observed", markersize=7.5, markevery=1 )
lowRAx.plot(PDF.experimentalDistances, ENGINE.constraints[0].experimentalPDF, 'ro', label="observed", markersize=7.5, markevery=1 )
highRAx.plot(PDF.experimentalDistances, ENGINE.constraints[0].experimentalPDF, 'ro', label="observed", markersize=7.5, markevery=1 )
totalAx.plot(PDF.shellCenters, output["pcf"], 'k', linewidth=3.0,  markevery=25, label="total" )
lowRAx.plot(PDF.shellCenters, output["pcf"], 'k', linewidth=3.0,  markevery=25, label="total" )
highRAx.plot(PDF.shellCenters, output["pcf"], 'k', linewidth=3.0,  markevery=25, label="total" )

# plot inter and intra
#intraStyleIndex = 0
#interStyleIndex = 0
#for key in output:
#    val = output[key]
#    if key in ("pdf_total", "pdf"):
#        continue
#    elif "intra" in key:
#        totalAx.plot(PDF.shellCenters, val, INTRA_STYLES[intraStyleIndex], markevery=5, label=key.split("rdf_")[1] )
#        lowRAx.plot(PDF.shellCenters, val, INTRA_STYLES[intraStyleIndex], markevery=5, label=key.split("rdf_")[1] )
#        highRAx.plot(PDF.shellCenters, val, INTRA_STYLES[intraStyleIndex], markevery=5, label=key.split("rdf_")[1] )
#        intraStyleIndex+=1
#    elif "inter" in key:
#        totalAx.plot(PDF.shellCenters, val, INTER_STYLES[interStyleIndex], markevery=5, label=key.split("rdf_")[1] )
#        lowRAx.plot(PDF.shellCenters, val, INTRA_STYLES[intraStyleIndex], markevery=5, label=key.split("rdf_")[1] )
#        highRAx.plot(PDF.shellCenters, val, INTRA_STYLES[intraStyleIndex], markevery=5, label=key.split("rdf_")[1] )
#        interStyleIndex+=1

# set legend
totalAx.legend(ncol=2, frameon=False, fontsize=20)#, loc=(1.05,-1.25))
totalAx.set_xlim([0,16])
totalAx.set_ylim([-1,6.2])

# remove y ticks labels
lowRAx.set_yticklabels([])
highRAx.set_yticklabels([])

# set x limits
lowRAx.relim()
highRAx.relim()
lowRAx.set_xlim([0.5,3])
lowRAx.set_ylim([-1, 6.2])
highRAx.set_xlim([3,16])
highRAx.set_ylim([0.25, 1.25])

# add title
plt.suptitle("$stdErr=%.6f$"%ENGINE.totalStandardError, fontsize=20)

# show plot
plt.show()


import requests

image = '/home/mayur/Desktop/Model_Deployment/sample_image.jpg'

resp = requests.post("http://0.0.0.0:8000/predict",
                     files={"file": open(image,'rb')})

# extracting the response
print("{}".format(resp.text))


import run as exCode
import ui as userInterface
import compileFile as compileFile

def main():
    uiResults = userInterface.main()

    if uiResults[0] == 1:
        run_file(uiResults[1])

    if uiResults[0] == 2:
        compile_file(uiResults[1], uiResults[2], uiResults[3])

def run_file(path):
    print("\nOpening File {}...".format(path))

    try:
        with open(path, "r") as f:
            print("Succsefully opened the file {}.".format(path))
            exCode.main(f.read())
    except FileNotFoundError as E:
        print("\nAn error has occured. The file you entered does not exist")
        print(E)
    #except:
        #print("\nAn error has occured")

def compile_file(Ipath, Opath, code):
    compileFile.main(Ipath, Opath, code)

main()


#!/usr/bin/python3
import os
import tkinter as tk
import wgkinter as wk
import logging
from PIL import Image, ImageTk
import constants as const

class CGWindowBase:
    def __init__(self, master=None):
        # build ui
        self.mainwindow = tk.Tk() if master is None else tk.Toplevel(master)
        self.mainwindow.configure(background="#252526")
        self.mainwindow.geometry("800x480+0+0")
        self.mainwindow.attributes('-fullscreen', True)
        #self.mainwindow.overrideredirect("True")
        self.top_frame = tk.Frame(self.mainwindow)
        self.top_frame.configure(background="#323233", pady=2)

        self.lb_message = tk.Label(self.mainwindow)
        self.lb_message_txt = tk.StringVar()
        self.lb_message.configure(
            background="#323233",
            font="{Arial} 10 {italic}",
            foreground="white",
            textvariable=self.lb_message_txt)
        self.lb_message.place(anchor="nw", x=1, y=4)

        frame1 = tk.Frame(self.top_frame)
        frame1.configure(background="#323233")
        self.lb_title = tk.Label(frame1)
        self.lb_title.configure(
            background="#323233",
            font="{Arial} 14 {}",
            foreground="white",
            text='CG Meter')
        self.lb_title.pack(side="left")
        self.lb_version = tk.Label(frame1)
        self.lb_version_txt = tk.StringVar(value='v0.0')
        self.lb_version.configure(
            background="#323233",
            font="{Arial} 8 {}",
            foreground="white",
            text='v0.0',
            textvariable=self.lb_version_txt)
        self.lb_version.pack(anchor="s", side="left")
        frame1.grid(column=0, row=0)
        self.lb_author = tk.Label(self.top_frame)
        self.lb_author.configure(
            background="#323233",
            font="{Arial} 6 {italic}",
            foreground="white",
            text='by WGS')
        self.lb_author.grid(column=1, row=0, sticky="s", padx="0 5")
        self.top_frame.pack(fill="x", side="top")
        self.top_frame.columnconfigure(0, weight=1)

        self.content_frame = tk.Frame(self.mainwindow)
        self.content_frame.configure(background="#252526")

        # the canvas frame
        self.img = Image.open(os.path.join(const.APP_ROOT_FOLDER,"gui","top_view_800.png"))
        self.sketch = ImageTk.PhotoImage(self.img)
        self.canvas = tk.Canvas(self.content_frame, width=self.img.size[0], height=self.img.size[1])
        self.canvas.create_image(0, 0, image=self.sketch, anchor="nw")
        self.canvas.configure(background="#252526", borderwidth=0, highlightthickness=0)
        self.canvas.pack(side="top",fill="both", expand="yes")

        # the model name and menu
        self.model_frame = tk.Frame(self.content_frame)
        self.model_frame.configure(background="#252526")
        self.lb_model = tk.Label(self.model_frame)
        self.lb_model_name = tk.StringVar()
        self.lb_model.configure(
            background="#252526",
            font="{Arial} 12 {italic}",
            foreground="white",
            textvariable=self.lb_model_name)
        self.lb_model.pack(side="left")
        """ Activate in next version
        self.menu_btn_model = tk.Menubutton(self.model_frame)
        self.menu_btn_model.configure(
            activebackground="#252526",
            activeforeground="#0e639c",
            background="#252526",
            font="{Wingdings} 12 {}",
            foreground="white",
            highlightthickness=0,
            relief="flat",
            text='▼')
        self.menu_model = tk.Menu(self.menu_btn_model)
        self.menu_model.configure(
            activebackground="#0e639c",
            activeborderwidth=0,
            activeforeground="white",
            background="#333333",
            borderwidth=0,
            font="{Arial} 10 {}",
            foreground="white",
            selectcolor="#2a2d2e")
        self.menu_model.add("command", label='    Model 1 ')
        self.menu_model.add("command", label='    Model 2 ')
        self.menu_btn_model.configure(menu=self.menu_model)
        self.menu_btn_model.pack(side="right")
        """
        self.model_frame.place(anchor="ne", relx=1.0)

        # the weights and CG labels
        self.lb_cg_position = []
        self.lb_cg_position.append(wk.Label(self.content_frame))
        self.lb_cg_position.append(wk.Label(self.content_frame))
        for i in range(2):
            self.lb_cg_position[i].configure(highlightbackground="#007fd4", highlightthickness=1, text=f'{0} mm')

        self.lb_cg_position[0].place(anchor="w", relx=0, rely=0, x=const.ORIGIN[0], y=20, width=200)
        self.lb_cg_position[1].place(anchor="w", relx=0, rely=0.5, width=75)

        for label in self.lb_cg_position:
            label.place_hide()

        self.lb_weights = {}
        self.lb_weights['total'] = wk.Label(self.content_frame)
        self.lb_weights['mwheels'] = wk.Label(self.content_frame)
        self.lb_weights['RightWheel'] = wk.Label(self.content_frame)
        self.lb_weights['TailWheel'] = wk.Label(self.content_frame)
        self.lb_weights['LeftWheel'] = wk.Label(self.content_frame)
        for key in self.lb_weights:
            self.lb_weights[key].configure(highlightbackground="#007fd4", highlightthickness=1, text=f'{0} g')
            self.lb_weights[key].place(anchor="center", relx=0, rely=0, width=80)

        self.lb_weights['RightWheel'].place(x=const.RWHEEL[0], y=const.RWHEEL[1])
        self.lb_weights['LeftWheel'].place(x=const.LWHEEL[0], y=const.LWHEEL[1])
        self.lb_weights['TailWheel'].place(x=const.TWHEEL[0], y=const.TWHEEL[1])
        self.lb_weights['mwheels'].place(x=const.LWHEEL[0], y=378)
        self.lb_weights['total'].place(x=378, y=378)

        for key in self.lb_weights:
            self.lb_weights[key].place_hide()

        self.content_frame.pack(
            expand="true",
            fill="both",
            padx=5,
            pady=5,
            side="top")
        self.bottom_frame = tk.Frame(self.mainwindow)
        self.bottom_frame.configure(background="#252526", height=30)
        self.btn_calibrate = wk.Button(self.bottom_frame)
        self.btn_calibrate.configure(text='Calibrate', width=10)
        self.btn_calibrate.pack(padx="3 0", side="left")
        self.btn_calibrate.configure(command=self.on_calibrate)
        self.btn_tare = wk.Button(self.bottom_frame)
        self.btn_tare.configure(text='Tare', width=10)
        self.btn_tare.pack(padx="3 0", side="left")
        self.btn_tare.configure(command=self.on_tare)
        self.btn_start = wk.Button(self.bottom_frame)
        self.btn_start.configure(text='Start', width=5)
        self.btn_start.pack(padx="30 0", side="left")
        self.btn_start.configure(command=self.on_start)
        self.btn_stop = wk.Button(self.bottom_frame)
        self.btn_stop.configure(text='Stop', width=5)
        self.btn_stop.pack(side="left")
        self.btn_stop.configure(command=self.on_stop)
        self.btn_exit = wk.Button(self.bottom_frame)
        self.btn_exit.configure(text='Exit', width=10)
        self.btn_exit.pack(padx=3, pady=3, side="right")
        self.btn_exit.configure(command=self.on_exit)
        self.bottom_frame.pack(fill="x", side="top")

        # Main widget
        self.root = self.mainwindow
        self.mainwindow = self.mainwindow

    def run(self):
        self.mainwindow.mainloop()

    def on_calibrate(self):
        pass

    def on_tare(self):
        pass

    def on_start(self):
        pass

    def on_stop(self):
        pass

    def on_exit(self):
        pass

if __name__ == "__main__":
    raise Exception("This is a module, not a program. It should not be run directly.")


import os
import re

from praatio.utilities.constants import Interval
from praatio.textgrid import Textgrid, IntervalTier, openTextgrid

root_dir  = r'D:\Data\speech\english_corpora\coraal'

replacements = {
'[ ': '[',
'[<': '[',
'>]': ']',
'.]': ']',
' ]': ']',
'2K': 'two k',
'9:30': 'nine thirty',
'd2D': 'd two d',
'104': 'one oh four',
'ICD-9': 'i c d nine',
'2400': 'twenty four hundred',
'1613': 'sixteen thirteen',
'M1s': 'm ones',
'PS4': 'p s four',
'401k': 'four oh one k',
'50 Cent': 'fifty cent',
'/RD-NAME-3.': '[RD-NAME-3]',
'/RD-NAME- 4/': '[RD-NAME-4]',
'[/RD-NAME-2/-]': '[RD-NAME-2]',
'/[RD-SCHOOL-4/': '[RD-SCHOOL-4]',
'[RD-SCHOOL-3/': '[RD-SCHOOL-3]',
'RD- NAME-3': 'RD-NAME-3',
'/RD-NAME-2,': '[RD-NAME-2]',
'/RD-NAME-2]': '[RD-NAME-2]',
'like/RD-NAME-2/': 'like [RD-NAME-2]',
'And/RD-NAME-2/': 'And [RD-NAME-2]',
'/RD-NAME- 6/': '[RD-NAME-6]',
'into/RD-SCHOOL-2/': 'into [RD-SCHOOL-2]',
'8': 'eight',
'[laugh>_': '[laugh_',
'<laugh]': '[laugh]',
'[laugh>': '[laugh]',
'[laughing]': '[laugh]',
'9': 'nine',
'0': 'zero',
    '12': 'twelve',
    '13': 'thirteen',
    '18': 'eighteen',
}

word_replacements = {
    '1': 'one',
    '2': 'two',
    '3': 'three',
    '4': 'four',
    '5': 'five',
    '6': 'six',
    '7': 'seven',
    '8': 'eight',
    '9': 'nine',
    '10': 'ten',
    '11': 'eleven',
    '12': 'twelve',
    '13': 'thirteen',
    '14': 'fourteen',
    '14': 'fifteen',
}

bracket_pattern = re.compile(r'(\[.*?])')
slash_pattern = re.compile(r'([</(].*?[/)>]-?)')

for directory in os.listdir(root_dir):
    sub_dir = os.path.join(root_dir, directory)
    if not os.path.isdir(sub_dir):
        continue
    for file in os.listdir(sub_dir):
        if not file.endswith('.TextGrid'):
            continue
        print(file)
        tg_path = os.path.join(sub_dir, file)
        tg = openTextgrid(tg_path, includeEmptyIntervals=False)

        for tier_name in tg.tierNameList:
            intervals = []
            tier = tg.tierDict[tier_name]
            for interval in tier.entryList:
                label = interval.label
                if label.startswith('/not'):
                    label = label[1:]
                if label.endswith('/RD-NAME-2'):
                    label += '/'
                elif label == '/RD-NAME-4':
                    label = '/RD-NAME-4/'
                elif label == 'RD-WORK-4,':
                    label = '/RD-WORK-4/'
                for k,v in replacements.items():
                    label = label.replace(k, v)
                #if '/- ' in label:
                #    print(label)
                    #error
                for m in bracket_pattern.finditer(label):
                    #print(m)
                    text = m.groups()[0]
                    replacement =  text.replace('/', '_').replace(' ', '_')
                    label = label.replace(text, replacement)
                for m in slash_pattern.finditer(label):
                    #print(m)
                    text = m.groups()[0]
                    replacement = text[1:-1]
                    if replacement.endswith('/'):
                        replacement = replacement[:-1]
                    replacement = '['+ replacement + ']'
                    label = label.replace(text, replacement)
                if label.endswith('.'):
                    label = label[:-1]
                if  not label:
                    continue
                print(label)
                intervals.append(Interval(interval.start, interval.end, label))
            new_tier = IntervalTier(maxT=tier.maxTimestamp,
                                    minT=tier.minTimestamp,
                                    name = tier.name,
                                    entryList=intervals)
            tg.replaceTier(tier.name, new_tier)
            print(tier_name)
        print(tg_path)
        print(tg)
        tg.save(tg_path, format='short_textgrid', includeBlankSpaces=True)