import argparse
import torch
import os

import logging

import asyncio
import aiohttp.web

import nermodel.version
from nermodel.model_wrapper import ModelWrapper
from nermodel.http_handler import HTTPHandler
from nermodel.globals import RespType

parser = argparse.ArgumentParser(description='A simple NER serving application by using PyTorch and aiohttp.')
parser.add_argument('--epochs', type=int, default=50,
                    help='number of epochs for train')
parser.add_argument('--batch-size', type=int, default=512,
                    help='batch size for training')
parser.add_argument('--seed', type=int, default=1,
                    help='random seed')
parser.add_argument('--use-cuda', type=bool,default=False,
                    help='enables cuda')
parser.add_argument('--lr', type=float, default=0.0001,
                    help='learning rate')
parser.add_argument('--use-crf', action='store_true',
                    help='use crf')

parser.add_argument('--mode', type=str, default='train',
                    help='train mode or test mode')

parser.add_argument('--save', type=str, default='/model/lstm_crf.pth',
                    help='path to save the final model')
parser.add_argument('--save-epoch', action='store_true',
                    help='save every epoch')
parser.add_argument('--data', type=str, default='dataset',
                    help='location of the data corpus')

parser.add_argument('--word-ebd-dim', type=int, default=300,
                    help='number of word embedding dimension')
parser.add_argument('--dropout', type=float, default=0.5,
                    help='the probability for dropout')
parser.add_argument('--lstm-hsz', type=int, default=512,
                    help='BiLSTM hidden size')
parser.add_argument('--lstm-layers', type=int, default=2,
                    help='biLSTM layer numbers')
parser.add_argument('--l2', type=float, default=0.005,
                    help='l2 regularization')
parser.add_argument('--clip', type=float, default=.5,
                    help='gradient clipping')
parser.add_argument('--cudaID', type=int, default=1,
                    help='cuda-device-id')
parser.add_argument('--vocab-path', type=str, default='/model/vocab.pkl',
                    help='cuda-device-id')
parser.add_argument('--default-response-type', type=str, default='json',
                    help='The default response type if request does not specify. Should in (msgpack, json).')
parser.add_argument('--unix-socks-path', type=str, default='',
                    help='Unix socks file path')
parser.add_argument('--port', type=int, default=8000,
                    help='http port')
parser.add_argument('--host', type=str, default='0.0.0.0',
                    help='http host')

args = parser.parse_args()

torch.manual_seed(args.seed)

__all__ = ['entry_point']
logger = logging.getLogger('ner-serving')

def _str2bool(s: str) -> bool:
    return s.lower() in ['t', 'true', 'on', '1']

def entry_point():
    print(args)
    path = args.unix_socks_path
    try:
        port = args.port
    except (TypeError, ValueError):
        port = None
    host = args.host

    model = ModelWrapper(args)

    handler = HTTPHandler(model=model,
                          default_response_type=RespType[
                              args.default_response_type.upper()])
    app = aiohttp.web.Application()
    app.add_routes([aiohttp.web.post('/', handler.post)])

    app.on_startup.append(model.startup)

    # aiohttp.web.run_app(app, port=port, path=path, host=host)
    aiohttp.web.run_app(app, port=port, host=host)


import tkinter
import time
base=tkinter.Tk()
base.wm_title("study2")
base.minsize(600,500)
base.maxsize(700,600)
def show_lab():
      global base
      lab=tkinter.Label(base,text=time.ctime())

      lab.pack()

exit_bt=tkinter.Button(base,text="exit",command=show_lab)
exit_bt.pack()
time_l=tkinter.Label(base,text=time.ctime())
time_l.pack()

if __name__ == '__main__':
      base.mainloop()


from flask import Flask, render_template, url_for, redirect, request
import functions

############################
### Initialize flask app ###
############################
app = Flask(__name__)

##############
### ROUTES ###
##############
#-----------------------------------------------------------------
@app.route('/')
def go_home():
    return redirect('/index')
#-----------------------------------------------------------------
@app.route('/index')
def index():
    top10_df, df_table = functions.get_map_data()
    df_table.set_index(str('CBSA'), inplace=True)
    mode = functions.setMode(request.args.get('mode'))
    return render_template('index.html', title="MetroGnomics Dashboard", top10=top10_df.to_dict(), data_table=df_table.to_dict(), theme=mode)
#-----------------------------------------------------------------
@app.route('/table')
def table():
    html_table = functions.get_table_data()
    mode = functions.setMode(request.args.get('mode'))
    return render_template('table.html', title="MetroGnomics Forecasts", table=html_table, theme=mode)
#-----------------------------------------------------------------
@app.route('/comparison')
def comparison():
    mode = functions.setMode(request.args.get('mode'))
    return render_template('comparison.html', title="MetroGnomics Comparison", theme=mode)
#-----------------------------------------------------------------
@app.route('/about')
def about():
    mode = functions.setMode(request.args.get('mode'))
    return render_template('about.html', title="About MetroGnomics", theme=mode)
#-----------------------------------------------------------------

# app import check
if __name__ == '__main__':
    app.run()


import numpy as np
import sys
import os
import cv2
import time

"""
TEKNOMO-FERNANDEZ ALGORITHM FOR BACKGROUND GENERATION
ADAPTED BY ALEJANDRO CASTANEDA AND RENEE WU
CREATED FOR COMPUTER VISION 410, FENG LIU
"""

def get_mode(img1, img2, img3):
    """
    get_mode
    Boolean Operation to Determine the Mode.
    Compares three images and gets the binary value for the value that occurs
    most frequently in the images.

    ARGS --
    img1, img2, img3 - A series of input images (created by cv2.imread)

    RETURNS --
    b - The resultant numpy array of the values through the boolean equation.

    Returns the background
    """

    # Per Paper: b = (g3 and (g1 xor g2)) or (g1 and g2)
    b = (img3 & (img1^img2)) | (img1 & img2)
    return b

def tf_background_generation(seq, L):
    """
    tf_background_generation

    Generates the background by iterating through a sequence of frames
    a certain amount of time. Collected from the Teknomo Fernandez Algorithm
    located on https://arxiv.org/abs/1510.00889.

    ARGS --
    seq - The sequence of image frames (list of images read by cv2.imread)
    L - The amount of times the procedure is repeated until the level L.

    RETURNS --
    Returns an np array ready for cv2 to imwrite.
    """
    result = []

    if L <= 0:
        print("Error, level must be a positive, nonzero number.")
        return None

    for i in range(3**(L-1) -1):
        s = np.random.choice(len(seq), 3, replace=False)
        result.append(get_mode(seq[s[0]], seq[s[1]], seq[s[2]]))

    for i in range(2, L):
        for j in range(3**(L-i)-1):
            img1 = result[3*j]
            img2 = result[3*j+1]
            img3 = result[3*j+2]
            result[j] = get_mode(img1, img2, img3)

    return result[0]

def mc_get_mode(frames):
    """
    mc_get_mode

    Monte Carlo's version of Get Mode, which will get the modal bit.
    The idea behind this is to utilize bit shifting to find which
    bits will occur most frequently in the sequence of images provided.
    * Spatial temporality is terrible with this, can be optimized.

    ARGS --
    frames - The frames of the images that are being put in.

    RETURNS --
    Returns the 'mode' for the bits of the frames provided.
    """
    w, h, p = frames[0].shape
    f = np.zeros((frames[0].shape))

    for y in range(w):
        for x in range(h):
            for c in range(p):
                n = 0
                while n < 8:
                    diff = 0
                    for frame in frames:
                        pix = frame[y][x][c]
                        if pix & (1<<n): #np.bitwise_xor(pix,bit) > 0:
                            diff += 1
                        else:
                            diff -= 1
                    if diff > 0:
                        f[y][x][c] += (1<<n)#bit
                    n += 1
    return f

def mc_background_generation(seq, S, L):
    """
    mc_background_generation

    Generates the background by iterating through a sequence of frames
    a certain amount of time. Collected from the Monte Carlo inspired RCF Algorithm
    located on https://www.researchgate.net/publication/282155172_A_Monte-Carlo-based_Algorithm_for_Background_Generation.

    ARGS --
    seq - The sequence of image frames (list of images read by cv2.imread)
    S - Sampling size. Adjustable by user.
    L - The amount of times the procedure is repeated until the level L.

    RETURNS --
    Returns an np array ready for cv2 to imwrite.
    """
    result = []

    if L <= 0:
        print("Error, level must be a positive, nonzero number.")
        return None

    N = len(seq)
    arrF = []

    for i in range(S**L):
        r = np.random.randint(N-1)
        arrF.append(seq[r])

    for l in range(L):
        b = 0
        for i in range(S):
            f = mc_get_mode(seq[b:b+S])
            b += S
            arrF[i] = f

    return arrF[0]

def median_filter(seq,n):
    '''
    median_filter

    Median filter method for background subtraction. Stores all elements of an
    array, then will return the median of each pixel.

    ARGS:
    seq - The sequence of image frames
    n - a parameter for the number of frames

    RETURNS:
    An numpy array that outputs the image of the background
    '''

    if n <= 0:
        print('Error, level must be a positive, nonzero number')
        return None

    s = np.random.choice(len(seq), n, replace=True)

    img = []

    for i in range(n):
        img.append(seq[s[i]])
    result = np.median(img, axis=0)

    return result

if __name__ == "__main__":
    """ python3 bggen.py sample/ sampleimg.jpg """

    path = sys.argv[1]
    result_path = sys.argv[2]

    image_sequence = []
    for image in os.listdir(path):
        image_path = os.path.join(path, image)
        if os.path.isfile(image_path):
            img = cv2.imread(image_path)
            if img is not None:
                image_sequence.append(img)

    start = time.time()
    tfrgb_result = tf_background_generation(image_sequence, L=6)
    if tfrgb_result is not None:
        cv2.imwrite(filename='tfrgb'+result_path, img=tfrgb_result)
    end = time.time()
    print("Teknomo Fernandez ran in ", end-start, " seconds.")

    start = time.time()
    mcrgb_result = mc_background_generation(image_sequence, S=3, L=2)
    if mcrgb_result is not None:
        cv2.imwrite(filename='mcrgb'+result_path, img=mcrgb_result)
    end = time.time()
    print("Monte Carlo ran in ", end-start, " seconds.")

    start = time.time()
    median_result = median_filter(image_sequence,n = 10)
    if median_result is not None:
        cv2.imwrite(filename='median'+result_path, img=median_result)
    end = time.time()
    print("Median Filter ran in ", end-start, " seconds.")

    """
    CODE USED FOR HSV -- FOUND INEFFECTIVE, THEREFORE REMOVED.
    hsv_seq = []
    for image in image_sequence:
        hsv_seq.append(cv2.cvtColor(image, cv2.COLOR_BGR2HSV))

    tfhsv_result = tf_background_generation(hsv_seq, L=6)
    if tfhsv_result is not None:
        tfhsvrgb_result = cv2.cvtColor(tfhsv_result, cv2.COLOR_HSV2BGR)
        cv2.imwrite(filename='tfhsv'+result_path, img=tfhsvrgb_result)

    mchsv_result = mc_background_generation(hsv_seq, S=3, L=3)
    if mchsv_result is not None:
        mchsvrgb_result = cv2.cvtColor(mchsv_result.astype('float32'), cv2.COLOR_HSV2BGR)
        cv2.imwrite(filename='mchsv'+result_path, img=mchsvrgb_result)
    """


from django.shortcuts import redirect, render
from .models import Project
from .forms import ProjectForm

# Information about my projects

def projects(request):
    projects = Project.objects.all()
    context = {"projects": projects}
    return render(request, "Projects/projects.html", context)

# Information about an individual project

def project(request, pk):
    projectObj = Project.objects.get(id=pk)
    # tags = projectObj.tag.all()
    # reviews = projectObj.review_set.all()
    context = {"project": projectObj}
    return render(request, "Projects/project.html", context)

def createProject(request):
    form = ProjectForm()
    if request.method == "POST":
        form = ProjectForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect("allProjects")

    context = {"form": form}
    return render(request, "Projects/project-form.html", context)

def updateProject(request, pk):
    project = Project.objects.get(id=pk)
    form = ProjectForm(instance=project)

    if request.method == "POST":
        form = ProjectForm(request.POST, request.FILES, instance=project)
        if form.is_valid():
            form.save()
            return redirect("allProjects")

    context = {"form": form}
    return render(request, "Projects/project-form.html", context)

def deleteProject(request, pk):
    project = Project.objects.get(id=pk)
    if request.method == "POST":
        project.delete()
        return redirect("allProjects")
    return render(request, "Projects/delete.html", {"object": project})


def isEven(x):
    if x % 2 == 0:
        return True
    else:
        return False

l = [20, 15, 67, 24, 32, 48, 41]
l1 = list(filter(isEven, l))
print(l1)

# l1 = [20, 15, 67, 24, 32, 48, 41]
# l2 = list(filter(lambda x : True if x%2 == 0 else False, l1))
# print(l1)


from pandas import DataFrame
from sklearn.cluster import KMeans
from sklearn import datasets , svm , metrics
from PIL import Image , ImageDraw
from PIL import ImageFilter
import numpy as np
import os
import dlib
from skimage import io
from skimage.color import rgb2gray
from skimage.filters import sobel

class findplate:
    def __init__(self):
        print("inited.......")

    #def __read_image(self,images):
        ################custom train
        dataimage=[]
        target=[]
        train_imgs=os.listdir('train/')
        cnt=0
        self.dict_label={}
        size=28,42
        for train_img in train_imgs:
            #print(train_img)
            img_label=train_img.split('.')[0]
            img_label=img_label[:-2]
            #if not img_label.isdigit():
            #    continue
            img_label=img_label.rjust(3,' ')
            try:
                imgg=dlib.load_rgb_image("train/"+train_img)
                imgg=dlib.as_grayscale(imgg)
                #imgg,rect=dlib.gaussian_blur(imgg,max_size=2000L)
                imgg=dlib.threshold_image(imgg)
                #img=Image.open("train/"+train_img)
                img=Image.fromarray(imgg)
                img=img.resize((30,43), Image.ANTIALIAS)
                #img=img.filter(ImageFilter.GaussianBlur())
                #data_img=rgb2gray(io.imread("train/"+train_img,as_gray=True))
                #data_img=sobel(data_img)
                img=img.convert('L')
                #img.show()
                data_img=np.asarray(img,dtype="int32")
                data_img=np.concatenate(data_img,axis=0)
                #print(data_img)
                print("-------------------"+train_img)
                #print(img_label)
                cnt +=1
                cntp=cnt
                if not self.dict_label.has_key(img_label):
                    self.dict_label[img_label]=cntp
                else:
                    cntp=self.dict_label[img_label]
                dataimage.append(data_img)
                #print(cntp)
                #target.append(cntp)
                target.append(img_label)
            except IOError:
                pass

        print("-------------------",len(dataimage))
        #self.classifier = svm.SVC(probability=True,  kernel="rbf", C=2.8, gamma=.00073,verbose=10)#gamma=0.001 , C=100.)
        self.classifier = svm.SVC(gamma=0.000001 , C=100. )
        self.classifier.fit(dataimage, target)
        y_hat = self.classifier.predict(dataimage)#[dataimage[3],dataimage[15]])
        #print(y_hat)
        #print(target[3],target[15])
        acc = np.mean(y_hat == target)
        print("\n\nTraining Accuracy for  %.2f\n"%(acc))

    def __read_image(self,images):
        dataimage=[]
        for image in images:
            #mage=Image.open('test.jpg')
            #image=image.rotate(180)
            #crope=(30,10,155,80)
            #image=image.crop(crope)
            image=dlib.as_grayscale(image)
            image=dlib.threshold_image(image)
            #img_arr=np.asarray(image,dtype='int32')
            img_int=Image.fromarray(image)
            img_int=img_int.resize((30,43),Image.ANTIALIAS)#30,43
            img_int=img_int.convert('L')

            #img_int.show()
            #img_name=str(raw_input("enter image name this:"))
            #print(type(img_name))
            #imagename="train/"+str(img_name)+".jpg"
            #if not os.path.isfile(imagename):
            #    img_int.save("train/"+img_name+".jpg")
            #else:
            #    print("image exists.")
            img_arr=np.asarray( img_int,dtype="int32")
            img_arr=np.concatenate(img_arr,axis=0)
            #print(img_arr)
            #imagefinal=ImageDraw.Draw(image)
            #for point in centroids:
                #imagefinal.rectangle(((point[0]-15,point[1]-20),(point[0]+15,point[1]+23)),outline="black")
            #image.show()
            #print(img_arr)
            dataimage.append(img_arr)

        #print(dataimage[0].shape)
        predicted = self.classifier.predict(dataimage)#img_arr)
        self.number_string=''
        print(predicted)
        for i in predicted:
            self.number_string+=i.strip()
            #print(i)
        ############################

    def get_platestr_from_image(self,src_img):
        self.__read_image(src_img)
        return self.number_string


"""
Write a program to find the n-th ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.

Example:

Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note:

1 is typically treated as an ugly number.
n does not exceed 1690.

"""

class Solution:
    """超过时间复杂度"""

    def is_ugly(self,number):
        while number % 2 == 0:
            number //= 2

        while number % 3 == 0:
            number //= 3

        while number % 5 == 0:
            number //= 5

        return number == 1

    def nthUglyNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        number = 0
        while count != n:
            number += 1
            if self.is_ugly(number):
                count +=1

        return number

class Solution:
    def nthUglyNumber(self, n):
        result = [1]
        p1,p2,p3 = 0,0,0

        while len(result) < n:

            x1 = result[p1]*2
            x2 = result[p2]*3
            x3 = result[p3]*5

            num = min(x1,min(x2,x3))

            if num == x1:
                p1 += 1
            elif num == x2:
                p2 += 1
            elif num == x3:
                p3 += 1

            if num != result[-1]:
                result.append(num)

        return result[n-1]

import heapq
class Solution:
    def nthUglyNumber(self,n):
        pool = set()
        heap = []
        number_series = [1]
        count = 0

        while True:
            num = heapq.heappop(number_series)
            for ex in (num*2,num*3,num*5):
                if ex in pool:
                    continue
                else:
                    pool.add(ex)
                    heapq.heappush(number_series,ex)
            count += 1

            if count == n:
                return num

import heapq
class Solution:
    def nthUglyNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 0:
            return
        pool,count = set([1]),0
        heap = [1]
        heapq.heapify(heap)
        while True:
            cur = heapq.heappop(heap)
            count += 1
            if count == n:
                return cur

            for num in (cur*2,cur*3,cur*5):
                if num not in pool:
                    pool.add(num)
                    heapq.heappush(heap,num)
        return -1

import heapq
class Solution(object):
    def nthUglyNumber(self, n):
        """
        :type n: int
        :rtype: int
        """
        heap = [1]
        visited = set(heap)
        heapq.heapify(heap)
        index = 0

        while index < n:
            item = heapq.heappop(heap)
            index += 1
            if item*2 not in visited:
                heapq.heappush(heap,item*2)
                visited.add(item*2)

            if item*3 not in visited:
                heapq.heappush(heap,item*3)
                visited.add(item*3)

            if item*5 not in visited:
                heapq.heappush(heap,item*5)
                visited.add(item*5)

        return item

if __name__ == '__main__':
    print(Solution().nthUglyNumber(10))


# Runge Kutta 4th order to edo system of two equations.

"""
INPUT:  dy/dx = f1(x,y,z)  : differential equation 1
        dz/dx = f2(x,y,z)  : differential equation 2
        y(x(0)) = y0 : initial condition 1
        z(x(0)) = z0 : initial condition 2
        xf           : variable final which define range
        n            : number of points
OUTPUT: Aproximation solution of differential equations system whit its graph
"""

import numpy as np
import matplotlib.pyplot as plt

def solveSystem(x0,y0,z0,xf,n):

    h = (xf-x0)/(n-1)
    x = np.linspace(x0,xf,n)
    y = np.zeros([n,1])
    z = np.zeros([n,1])

    y[0] = y0
    z[0] = z0

    for i in range(1,n):
        k1 = h*f1(x[i-1],y[i-1],z[i-1])
        l1 = h*f2(x[i-1],y[i-1],z[i-1])
        k2 = h*f1(x[i-1]+h/2,y[i-1]+k1/2,z[i-1]+l1/2)
        l2 = h*f2(x[i-1]+h/2,y[i-1]+k1/2,z[i-1]+l1/2)
        k3 = h*f1(x[i-1]+h/2,y[i-1]+k2/2,z[i-1]+l2/2)
        l3 = h*f2(x[i-1]+h/2,y[i-1]+k2/2,z[i-1]+l2/2)
        k4 = h*f1(x[i-1]+h, y[i-1]+k3,z[i-1]+l3)
        l4 = h*f2(x[i-1]+h, y[i-1]+k3,z[i-1]+l3)

        y[i] = y[i-1] + (k1 + 2*k2 + 2*k3 + k4)/6
        z[i] = z[i-1] + (l1 + 2*l2 + 2*l3 + l4)/6

    plt.plot(x,y,label='Y aprox')
    plt.plot(x,z,label='Z aprox')
    plt.xlabel("X values")
    plt.ylabel("Y,Z values")
    plt.legend()
    plt.title("Sytem of First Order Differential Equations")
    plt.show()

def f1(x,y,z):
    return z

def f2(x,y,z):
    return 0.05*z-0.15*y

def main():

    x0 = 0.0
    y0 = 1.0
    z0 = 0.0
    xf = 5.0
    n  = 21  # 21 points -> 20 spaces between points.
    solveSystem(x0,y0,z0,xf,n,)

main()


#Implicit wait
#Explicit Wait
#Pause the test for few seconds using time class
import time

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

ValidateText = "Option3"
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
#driver.implicitly_wait(5)
# wait untill 5 seconds if object is not displayed
#Global wait
#1.5 second to reach next page - execution will resume in 1.5 seconds

driver.get("https://rahulshettyacademy.com/seleniumPractise/#/")
driver.find_element_by_css_selector("input.search-keyword").send_keys("ber")
time.sleep(4)
count = len(driver.find_elements_by_xpath("//div[@class='products']/div"))
assert count == 3
buttons = driver.find_elements_by_xpath("//div[@class='product-action']/button")

for button in buttons:
    button.click()

driver.find_element_by_css_selector("a.cart-icon").click()
driver.find_element_by_xpath("//button[text()='PROCEED TO CHECKOUT']").click()
wait = WebDriverWait(driver, 6)
wait.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, "input.promocode")))
driver.find_element_by_css_selector("input.promocode").send_keys("rahulshettyacademy")
driver.find_element_by_css_selector(".promoBtn").click()
wait.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, "span.promoInfo")))

print(driver.find_element_by_css_selector("span.promoInfo").text)


# the code to build the ML model

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

def train_model():
    # load the data
    df = pd.read_csv('Trai_Ticket.csv')
    # clean the data
    x = df.drop(['bookingStatus', 'createdAtDate', 'isActive', 'isChartPrepared', 'pnrNo', 'trainNo','status1Day','status2Days','status1Month','status1Week', 'updatedAt', 'label'], axis=1)

    y = df['label']

    # convert the categorical to numerical
    from sklearn.preprocessing import LabelEncoder
    label_encoder = LabelEncoder()

    x['from'] = label_encoder.fit_transform(x['from'])
    x['journeyDate'] = label_encoder.fit_transform(x['journeyDate'])
    x['to'] = label_encoder.fit_transform(x['to'])
    x['travelClass'] = label_encoder.fit_transform(x['travelClass'])

    # print(df.head(20))
    # print(df['region'].unique())

    # sex: 0: female, 1: male
    # smoker: 1: yes, 0: no
    # region: 3: southwest, 2: southeast, 1: northwest, 0: northeast

    # split the data into train and test
    from sklearn.model_selection import train_test_split
    x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, random_state=1234567)

    # model training
    from sklearn.svm import SVC
    model = SVC(kernel='rbf')
    model.fit(x_train, y_train)

    # dump the model
    import pickle
    file = open('model_lr.pkl', 'wb')
    pickle.dump(model, file)
    file.close()

    def test_model():
        from sklearn.metrics import accuracy_score
        predictions = model.predict(x_test)
        print(predictions)
        print(f"accuracy = {model.score(x_test, y_test)}%")

    # test_model()

    # def create_regression_line():
    #     predictions = model.predict(x)
    #     plt.scatter(x['bmi'], y)
    #     plt.plot(x['bmi'], predictions, color="red")
    #
    #     plt.xlabel('Age')
    #     plt.ylabel('charges')
    #     plt.title("regression line for insurance")
    #     plt.tight_layout()
    #     plt.savefig('static/regression.png')
    #     plt.show()
    #
    # create_regression_line()

def predict(from_1 , to_1 ,  travelClass ,journeyDate):

    # date incoded by using inbuilt function of python
    j=journeyDate
    day = j.split("-")
    journeyDate=day[1]
    # load the model
    import pickle

    filename = 'model_lr.pkl'

    with open(filename, 'rb') as file:
        model = pickle.load(file)

    confirm = model.predict([[from_1, to_1 , travelClass , journeyDate]])
    print(confirm[0])

    return confirm[0]

if __name__ == '__main__':
    train_model()
    # predict(19, 0, 27.9, 0, 1, 3)


"""
PublicIP related functions.

PublicIPs object variables:

	public_ips.public_ips - list of PublicIP objects

PublicIP object variables:

	public_ip.id - alias of public
	public_ip.public
	public_ip.internal
	public_ip.ports - list of port/protocol dicts

Port object variables:

	port.protocol
	port.port
	port.port_to

Source Restriction object variables:

	source_restriction.cidr

"""
from __future__ import print_function, absolute_import, unicode_literals

# vCur:

# vNext:
# TODO - PublicIPs search by port and source restriction
# TODO - Access PublicIPs by index - map directly to public_ips.public_ipds list
# TODO - wait on request and ID/store assigned public IP
# TODO - optional param to not call PublicIP.Update() with port/src changes so they can be batched

import re
import json
import clc

class PublicIPs(object):

	def __init__(self,server,public_ips_lst,session=None):
		self.server = server
		self.public_ips = []
		self.session = session

		for public_ip in public_ips_lst:
			if 'public' in public_ip:
				self.public_ips.append(PublicIP(id=public_ip['public'],parent=self,public_ip_obj=public_ip,session=self.session))

	def Get(self,key):
		"""Get public_ip by providing either the public or the internal IP address."""

		for public_ip in self.public_ips:
			if public_ip.id == key:  return(public_ip)
			elif key == public_ip.internal:  return(public_ip)

	def Add(self,ports,source_restrictions=None,private_ip=None):
		"""Add new public_ip.

		Specify one or more ports using a list of dicts with the following keys:

			protocol - TCP, UDP, or ICMP
			port - int 0-65534
			port_to - (optional) if specifying a range of ports then the rqange end.  int 0-65534

		Optionally specify one or more source restrictions using a list of dicts with the following keys:

			cidr - string with CIDR notation for the subnet (e.g. "132.200.20.0/24")

		private_ip is the existing private IP address to NAT to (optional)

		# New public IP with single port
		>>> p = clc.v2.Server(alias='BTDI',id='WA1BTDIX03').PublicIPs()
		>>> p.Add(ports=[{"protocol": "TCP","port":5}]).WaitUntilComplete()
		0

		# New public IP with port range
		>>> p.Add([{"protocol": "UDP","port":10,"port_to":50}]).WaitUntilComplete()
		0

		# Map existing private IP to single port
		>>> p.Add(ports=[{"protocol": "TCP","port":22}],k
		          source_restrictions=[{'cidr': "132.200.20.0/24"}],
				  private_ip="10.80.148.13").WaitUntilComplete()
		0

		* Note this API is subject to revision to make ports and source restrictions access to parallel
		  that used for accessors.

		* public_ips.public_ips will not be updated to reflect this addition. Recreate object after request completes
		  to access new info including getting the IP itself

		"""

		payload = {'ports': []}
		for port in ports:
			if 'port_to' in port:  payload['ports'].append({'protocol':port['protocol'], 'port':port['port'], 'portTo':port['port_to']})
			else:  payload['ports'].append({'protocol':port['protocol'], 'port':port['port']})
		if source_restrictions:  payload['sourceRestrictions'] = source_restrictions
		if private_ip:  payload['internalIPAddress'] = private_ip

		return(clc.v2.Requests(clc.v2.API.Call('POST','servers/%s/%s/publicIPAddresses' % (self.server.alias,self.server.id),
		                                       json.dumps(payload),session=self.session),
		                       alias=self.server.alias,session=self.session))

class PublicIP(object):

	def __init__(self,id,parent,public_ip_obj=None,session=None):
		"""Create PublicIP object."""

		self.id = id
		self.internal = public_ip_obj['internal']
		self.parent = parent
		self.data = None
		self.session = session

	def _Load(self,cached=True):
		"""Performs a full load of all PublicIP metadata."""

		if not self.data or not cached:
			self.data = clc.v2.API.Call('GET','servers/%s/%s/publicIPAddresses/%s' % (self.parent.server.alias,self.parent.server.id,self.id),
										session=self.session)

			# build ports
			self.data['_ports'] = self.data['ports']
			self.data['ports'] = []
			for port in self.data['_ports']:
				if 'portTo' in port:  self.ports.append(Port(self,port['protocol'],port['port'],port['portTo']))
				else:  self.ports.append(Port(self,port['protocol'],port['port']))

			# build source restriction
			self.data['_source_restrictions'] = self.data['sourceRestrictions']
			self.data['source_restrictions'] = []
			for source_restriction in self.data['_source_restrictions']:
				self.source_restrictions.append(SourceRestriction(self,source_restriction['cidr']))

		return(self.data)

	def Delete(self):
		"""Delete public IP.

		>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Delete().WaitUntilComplete()
		0

		"""

		self.parent.public_ips = [o for o in self.parent.public_ips if o!=self]
		return(clc.v2.Requests(clc.v2.API.Call('DELETE','servers/%s/%s/publicIPAddresses/%s' % (self.parent.server.alias,self.parent.server.id,self.id),
											   session=self.session),
		                       alias=self.parent.server.alias,
							   session=self.session))

	def Update(self):
		"""Commit  current PublicIP definition to cloud.

		Usually called by the class to commit changes to port and source restriction policies.

		>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Update().WaitUntilComplete()
		0

		"""

		return(clc.v2.Requests(clc.v2.API.Call('PUT','servers/%s/%s/publicIPAddresses/%s' % (self.parent.server.alias,self.parent.server.id,self.id),
						                       json.dumps({'ports': [o.ToDict() for o in self.ports],
											               'sourceRestrictions': [o.ToDict() for o in self.source_restrictions] }),
											   session=self.session),
							   alias=self.parent.server.alias,
							   session=self.session))

	def AddPort(self,protocol,port,port_to=None):
		"""Add and commit a single port.

		# Add single port
		>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].AddPort(protocol='TCP',port='22').WaitUntilComplete()
		0

		# Add port range
		>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].AddPort(protocol='UDP',port='10000',port_to='15000').WaitUntilComplete()
		0

		"""

		self.ports.append(Port(self,protocol,port,port_to))

		return(self.Update())

	def AddPorts(self,ports):
		"""Create one or more port access policies.

		Include a list of dicts with protocol, port, and port_to (optional - for range) keys.

		>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0]
				.AddPorts([{'protocol': 'TCP', 'port': '80' },
				           {'protocol': 'UDP', 'port': '10000', 'port_to': '15000'}]).WaitUntilComplete()
		0

		"""

		for port in ports:
			if 'port_to' in port:  self.ports.append(Port(self,port['protocol'],port['port'],port['port_to']))
			else:  self.ports.append(Port(self,port['protocol'],port['port']))

		return(self.Update())

	def AddSourceRestriction(self,cidr):
		"""Add and commit a single source IP restriction policy.

		>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0]
				.AddSourceRestriction(cidr="132.200.20.1/32").WaitUntilComplete()
		0

		"""

		self.source_restrictions.append(SourceRestriction(self,cidr))

		return(self.Update())

	def AddSourceRestrictions(self,cidrs):
		"""Create one or more CIDR source restriction policies.

		Include a list of CIDR strings.

		>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0]
				.AddSourceRestrictions(cidrs=["132.200.20.1/32","132.200.20.100/32"]).WaitUntilComplete()
		0

		"""

		for cidr in cidrs:  self.source_restrictions.append(SourceRestriction(self,cidr))

		return(self.Update())

	def __getattr__(self,var):
		if var in ('source_restrictions',):  key = var
		elif var[0] != "_": key = re.sub("_(.)",lambda pat: pat.group(1).upper(),var)
		else:  key = var

		if not self.data: self._Load()

		if key in self.data:  return(self.data[key])
		else:  raise(AttributeError("'%s' instance has no attribute '%s'" % (self.__class__.__name__,key)))

	def __str__(self):
		return(self.id)

class Port(object):

	def __init__(self,public_ip,protocol,port,port_to=None):
		self.public_ip = public_ip
		self.protocol = protocol
		self.port = port
		self.port_to = port_to

	def Delete(self):
		"""Delete this port and commit change to cloud.

		>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].ports[0].Delete().WaitUntilComplete()
		0

		"""

		self.public_ip.ports = [o for o in self.public_ip.ports if o!=self]

		return(self.public_ip.Update())

	def ToDict(self):
		d = {'protocol': self.protocol,'port': self.port}
		if self.port_to:  d['portTo'] = self.port_to

		return(d)

	def __str__(self):
		if self.port_to:  return("%s-%s/%s" % (self.port,self.port_to,self.protocol))
		else:  return("%s/%s" % (self.port,self.protocol))

class SourceRestriction(object):

	def __init__(self,public_ip,cidr):
		self.public_ip = public_ip
		self.cidr = cidr

	def Delete(self):
		"""Delete this source restriction and commit change to cloud.

		>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].source_restrictions[0].Delete().WaitUntilComplete()
		0

		"""

		self.public_ip.source_restrictions = [o for o in self.public_ip.source_restrictions if o!=self]

		return(self.public_ip.Update())

	def ToDict(self):
		d = {'cidr': self.cidr}

		return(d)

	def __str__(self):
		return("%s" % (self.cidr))


import pumpkin as PI
import random
import time

from const import *

pi = PI.PumpkinPi()

# pi.main_section.setString("Hello, World!", 3, 4, color = PINK)
# pi.main_section.setString("Hello, World!", 5, 4, reverse = True)

# pi.main_section.setString("Hello, World!", 10, 4, drawVertical = True)
# pi.main_section.setString("Hello, World!", 10, 6, drawVertical = True, cutoff = 8, reverse = True)

import string

def random_string(L):
    # Define characters: uppercase, lowercase, digits, and common punctuation symbols
    characters = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(characters) for _ in range(L))

X = PI.NumericVariable(This_is_a_very_very_very_very_very_very_very_very_long_label = 0, color = PINK)
Y = PI.NumericVariable(Y = 0, color = LIGHT_CYAN)

while(X() <= 5):
    X.incValue()
    Y.incValue(int(((round(random.random()) * 2) - 1) * random.random() * 50))
    pi.main_section.step(buffer_seconds_ = 1)

X.cut()
Y.cut()

# V = []
# for i in range(pi.num_rows - 6):
#     Z = PI.Variable(String = "", color = ORANGE)
#     V.append(Z)

# while(True):
#     pi.main_section.step(buffer_seconds_ = 0.25)

#     for v in V:
#         v.setValue(random_string(150))


from datetime import date

from aiogram import types

from bot.middlewares.config import dp
from bot.middlewares import api

@dp.message_handler(commands=['list_birthdays'])
async def list_birthdays(message: types.Message):
    print(message)
    birthdays = api.get(pk=message.chat.id, addr=api.user)['birthdays']
    if len(birthdays) == 0:
        await message.answer('Sizda hali tug`ilgan kun qo`shilmagan.')
        return

    birthdays.sort(key=lambda s: (date.fromisoformat(s['date']).month, date.fromisoformat(s['date']).day))

    text = ''
    curr = date.fromisoformat(birthdays[0]['date']).month
    text += month_name(curr) + ':' + '\n'
    for birthday in birthdays:
        birthdate = date.fromisoformat(birthday['date'])
        if curr != birthdate.month:
            curr = birthdate.month
            text += '\n' + month_name(curr) + ':' + '\n'
        text += '\t' + str(birthdate.day) + ' - ' + birthday['name'] + '\n'
    await message.answer(text=text)

def month_name(num: int):
    """
    This function return month name in UZBEK
    """

    if num == 1:
        return 'Yanvar'
    elif num == 2:
        return 'Fevral'
    elif num == 3:
        return 'Mart'
    elif num == 4:
        return 'Aprel'
    elif num == 5:
        return 'May'
    elif num == 6:
        return 'Iyun'
    elif num == 7:
        return 'Iyul'
    elif num == 8:
        return 'Avgust'
    elif num == 9:
        return 'Sentabr'
    elif num == 10:
        return 'Oktabr'
    elif num == 11:
        return 'Noyabr'
    elif num == 12:
        return 'Dekabr'
    else:
        return ''


from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, BooleanField, SubmitField, IntegerField, SelectField
from wtforms.validators import ValidationError, DataRequired

class SearchForm(FlaskForm):
	location = StringField('Location',validators=[DataRequired()])
	area = StringField('Area',validators=[DataRequired()])
	type_room = SelectField('Type of room', choices=[('Private room', 'Private room'), ('Entire home/apt', 'Entire home/apt'), ( 'Shared room', 'Shared room')])
	start_date = StringField('Start date')
	end_date = StringField('End date')
	guest = StringField('Number of guests')
	price_1 = StringField('Price from')
	price_2 = StringField('Price to')
	submit = SubmitField('Search')


def solution(s):
    s = s\
    .replace("zero","0")\
    .replace("one","1")\
    .replace("two","2")\
    .replace("three","3")\
    .replace("four","4")\
    .replace("five","5")\
    .replace("six","6")\
    .replace("seven","7")\
    .replace("eight","8")\
    .replace("nine","9")
    return int(s)

# 개선코드
num_dic = {"zero":"0", "one":"1", "two":"2", "three":"3", "four":"4", "five":"5", "six":"6", "seven":"7", "eight":"8", "nine":"9"}

def solution(s):
    answer = s
    for key, value in num_dic.items():
        answer = answer.replace(key, value)
    return int(answer)
# 딕셔너리를 통해서도 해결할 수 있다.

프로그래머스/lv1/81301. 숫자 문자열과 영단어/숫자 문자열과 영단어.py

숫자 문자열과 영단어.py


from . import idnadata
import bisect
import unicodedata
import re
import sys
from .intranges import intranges_contain

_virama_combining_class = 9
_alabel_prefix = b'xn--'
_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')

if sys.version_info[0] == 3:
    str = str
    chr = chr

class IDNAError(UnicodeError):
    """ Base exception for all IDNA-encoding related problems """
    pass

class IDNABidiError(IDNAError):
    """ Exception when bidirectional requirements are not satisfied """
    pass

class InvalidCodepoint(IDNAError):
    """ Exception when a disallowed or unallocated codepoint is used """
    pass

class InvalidCodepointContext(IDNAError):
    """ Exception when the codepoint is not valid in the context it is used """
    pass

def _combining_class(cp):
    return unicodedata.combining(chr(cp))

def _is_script(cp, script):
    return intranges_contain(ord(cp), idnadata.scripts[script])

def _punycode(s):
    return s.encode('punycode')

def _unot(s):
    return 'U+{0:04X}'.format(s)

def valid_label_length(label):

    if len(label) > 63:
        return False
    return True

def valid_string_length(label, trailing_dot):

    if len(label) > (254 if trailing_dot else 253):
        return False
    return True

def check_bidi(label, check_ltr=False):

    # Bidi rules should only be applied if string contains RTL characters
    bidi_label = False
    for (idx, cp) in enumerate(label, 1):
        direction = unicodedata.bidirectional(cp)
        if direction == '':
            # String likely comes from a newer version of Unicode
            raise IDNABidiError('Unknown directionality in label {0} at position {1}'.format(repr(label), idx))
        if direction in ['R', 'AL', 'AN']:
            bidi_label = True
            break
    if not bidi_label and not check_ltr:
        return True

    # Bidi rule 1
    direction = unicodedata.bidirectional(label[0])
    if direction in ['R', 'AL']:
        rtl = True
    elif direction == 'L':
        rtl = False
    else:
        raise IDNABidiError('First codepoint in label {0} must be directionality L, R or AL'.format(repr(label)))

    valid_ending = False
    number_type = False
    for (idx, cp) in enumerate(label, 1):
        direction = unicodedata.bidirectional(cp)

        if rtl:
            # Bidi rule 2
            if not direction in ['R', 'AL', 'AN', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']:
                raise IDNABidiError('Invalid direction for codepoint at position {0} in a right-to-left label'.format(idx))
            # Bidi rule 3
            if direction in ['R', 'AL', 'EN', 'AN']:
                valid_ending = True
            elif direction != 'NSM':
                valid_ending = False
            # Bidi rule 4
            if direction in ['AN', 'EN']:
                if not number_type:
                    number_type = direction
                else:
                    if number_type != direction:
                        raise IDNABidiError('Can not mix numeral types in a right-to-left label')
        else:
            # Bidi rule 5
            if not direction in ['L', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']:
                raise IDNABidiError('Invalid direction for codepoint at position {0} in a left-to-right label'.format(idx))
            # Bidi rule 6
            if direction in ['L', 'EN']:
                valid_ending = True
            elif direction != 'NSM':
                valid_ending = False

    if not valid_ending:
        raise IDNABidiError('Label ends with illegal codepoint directionality')

    return True

def check_initial_combiner(label):

    if unicodedata.category(label[0])[0] == 'M':
        raise IDNAError('Label begins with an illegal combining character')
    return True

def check_hyphen_ok(label):

    if label[2:4] == '--':
        raise IDNAError('Label has disallowed hyphens in 3rd and 4th position')
    if label[0] == '-' or label[-1] == '-':
        raise IDNAError('Label must not start or end with a hyphen')
    return True

def check_nfc(label):

    if unicodedata.normalize('NFC', label) != label:
        raise IDNAError('Label must be in Normalization Form C')

def valid_contextj(label, pos):

    cp_value = ord(label[pos])

    if cp_value == 0x200c:

        if pos > 0:
            if _combining_class(ord(label[pos - 1])) == _virama_combining_class:
                return True

        ok = False
        for i in range(pos-1, -1, -1):
            joining_type = idnadata.joining_types.get(ord(label[i]))
            if joining_type == 'T':
                continue
            if joining_type in ['L', 'D']:
                ok = True
                break

        if not ok:
            return False

        ok = False
        for i in range(pos+1, len(label)):
            joining_type = idnadata.joining_types.get(ord(label[i]))
            if joining_type == 'T':
                continue
            if joining_type in ['R', 'D']:
                ok = True
                break
        return ok

    if cp_value == 0x200d:

        if pos > 0:
            if _combining_class(ord(label[pos - 1])) == _virama_combining_class:
                return True
        return False

    else:

        return False

def valid_contexto(label, pos, exception=False):

    cp_value = ord(label[pos])

    if cp_value == 0x00b7:
        if 0 < pos < len(label)-1:
            if ord(label[pos - 1]) == 0x006c and ord(label[pos + 1]) == 0x006c:
                return True
        return False

    elif cp_value == 0x0375:
        if pos < len(label)-1 and len(label) > 1:
            return _is_script(label[pos + 1], 'Greek')
        return False

    elif cp_value == 0x05f3 or cp_value == 0x05f4:
        if pos > 0:
            return _is_script(label[pos - 1], 'Hebrew')
        return False

    elif cp_value == 0x30fb:
        for cp in label:
            if cp == '\u30fb':
                continue
            if not _is_script(cp, 'Hiragana') and not _is_script(cp, 'Katakana') and not _is_script(cp, 'Han'):
                return False
        return True

    elif 0x660 <= cp_value <= 0x669:
        for cp in label:
            if 0x6f0 <= ord(cp) <= 0x06f9:
                return False
        return True

    elif 0x6f0 <= cp_value <= 0x6f9:
        for cp in label:
            if 0x660 <= ord(cp) <= 0x0669:
                return False
        return True

def check_label(label):

    if isinstance(label, (bytes, bytearray)):
        label = label.decode('utf-8')
    if len(label) == 0:
        raise IDNAError('Empty Label')

    check_nfc(label)
    check_hyphen_ok(label)
    check_initial_combiner(label)

    for (pos, cp) in enumerate(label):
        cp_value = ord(cp)
        if intranges_contain(cp_value, idnadata.codepoint_classes['PVALID']):
            continue
        elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTJ']):
            if not valid_contextj(label, pos):
                raise InvalidCodepointContext('Joiner {0} not allowed at position {1} in {2}'.format(_unot(cp_value), pos+1, repr(label)))
        elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTO']):
            if not valid_contexto(label, pos):
                raise InvalidCodepointContext('Codepoint {0} not allowed at position {1} in {2}'.format(_unot(cp_value), pos+1, repr(label)))
        else:
            raise InvalidCodepoint('Codepoint {0} at position {1} of {2} not allowed'.format(_unot(cp_value), pos+1, repr(label)))

    check_bidi(label)

def alabel(label):

    try:
        label = label.encode('ascii')
        try:
            ulabel(label)
        except:
            raise IDNAError('The label {0} is not a valid A-label'.format(label))
        if not valid_label_length(label):
            raise IDNAError('Label too long')
        return label
    except UnicodeError:
        pass

    if not label:
        raise IDNAError('No Input')

    label = str(label)
    check_label(label)
    label = _punycode(label)
    label = _alabel_prefix + label

    if not valid_label_length(label):
        raise IDNAError('Label too long')

    return label

def ulabel(label):

    if not isinstance(label, (bytes, bytearray)):
        try:
            label = label.encode('ascii')
        except UnicodeError:
            check_label(label)
            return label

    label = label.lower()
    if label.startswith(_alabel_prefix):
        label = label[len(_alabel_prefix):]
    else:
        check_label(label)
        return label.decode('ascii')

    label = label.decode('punycode')
    check_label(label)
    return label

def uts46_remap(domain, std3_rules=True, transitional=False):
    """Re-map the characters in the string according to UTS46 processing."""
    from .uts46data import uts46data
    output = ""
    try:
        for pos, char in enumerate(domain):
            code_point = ord(char)
            uts46row = uts46data[code_point if code_point < 256 else
                bisect.bisect_left(uts46data, (code_point, "Z")) - 1]
            status = uts46row[1]
            replacement = uts46row[2] if len(uts46row) == 3 else None
            if (status == "V" or
                    (status == "D" and not transitional) or
                    (status == "3" and std3_rules and replacement is None)):
                output += char
            elif replacement is not None and (status == "M" or
                    (status == "3" and std3_rules) or
                    (status == "D" and transitional)):
                output += replacement
            elif status != "I":
                raise IndexError()
        return unicodedata.normalize("NFC", output)
    except IndexError:
        raise InvalidCodepoint(
            "Codepoint {0} not allowed at position {1} in {2}".format(
            _unot(code_point), pos + 1, repr(domain)))

def encode(s, strict=False, uts46=False, std3_rules=False, transitional=False):

    if isinstance(s, (bytes, bytearray)):
        s = s.decode("ascii")
    if uts46:
        s = uts46_remap(s, std3_rules, transitional)
    trailing_dot = False
    result = []
    if strict:
        labels = s.split('.')
    else:
        labels = _unicode_dots_re.split(s)
    while labels and not labels[0]:
        del labels[0]
    if not labels:
        raise IDNAError('Empty domain')
    if labels[-1] == '':
        del labels[-1]
        trailing_dot = True
    for label in labels:
        result.append(alabel(label))
    if trailing_dot:
        result.append(b'')
    s = b'.'.join(result)
    if not valid_string_length(s, trailing_dot):
        raise IDNAError('Domain too long')
    return s

def decode(s, strict=False, uts46=False, std3_rules=False):

    if isinstance(s, (bytes, bytearray)):
        s = s.decode("ascii")
    if uts46:
        s = uts46_remap(s, std3_rules, False)
    trailing_dot = False
    result = []
    if not strict:
        labels = _unicode_dots_re.split(s)
    else:
        labels = s.split('.')
    while labels and not labels[0]:
        del labels[0]
    if not labels:
        raise IDNAError('Empty domain')
    if not labels[-1]:
        del labels[-1]
        trailing_dot = True
    for label in labels:
        result.append(ulabel(label))
    if trailing_dot:
        result.append('')
    return '.'.join(result)


#!/usr/bin/env python
import unittest
from StringIO import StringIO
from tempfile import NamedTemporaryFile

from life_game.models.state import State
from life_game.models.organism import Organism
from life_game.io_handlers.xml_handler import XMLHandlerMixin, XMLFileError

class TestXMLHandlerMixin(unittest.TestCase):

    def setUp(self):
        self.xml_string = """<?xml version="1.0" encoding="UTF-8"?><life><world><cells>5</cells>
            <species>3</species><iterations>3</iterations></world><organisms><organism><x_pos>
            0</x_pos><y_pos>0</y_pos><species>2</species></organism><organism><x_pos>1</x_pos>
            <y_pos>0</y_pos><species>2</species></organism><organism><x_pos>4</x_pos><y_pos>
            0</y_pos><species>1</species></organism><organism><x_pos>0</x_pos><y_pos>1</y_pos>
            <species>2</species></organism><organism><x_pos>2</x_pos><y_pos>1</y_pos><species>1
            </species></organism><organism><x_pos>3</x_pos><y_pos>1</y_pos><species>1</species>
            </organism></organisms></life>"""
        self.input_file = StringIO(self.xml_string)

        self.xml_handler = XMLHandlerMixin()

    def test_read_state_from_xml_success(self):
        state = self.xml_handler.read_state_from_xml(self.input_file)

        self.assertEqual(state.cells_cnt, 5)
        self.assertEqual(state.species_cnt, 3)
        self.assertEqual(state.iterations_cnt, 3)

        self.assertEqual(len(state.organism_l), 6)

        organism = state.organism_l[0]
        self.assertEqual(organism.x, 0)
        self.assertEqual(organism.y, 0)
        self.assertEqual(organism.species, 2)

    def test_read_state_from_xml_not_valid(self):
        self.xml_string = self.xml_string[:20]
        self.input_file = StringIO(self.xml_string)

        with self.assertRaises(XMLFileError):
            self.xml_handler.read_state_from_xml(self.input_file)

    def test_read_state_from_xml_elements_with_not_value(self):
        self.xml_string = """<?xml version="1.0" encoding="UTF-8"?><life><world><cells></cells>
            </world></life>"""
        self.input_file = StringIO(self.xml_string)

        with self.assertRaises(XMLFileError):
            self.xml_handler.read_state_from_xml(self.input_file)

    def test_read_state_from_xml_wrong_elements(self):
        self.xml_string = """<?xml version="1.0" encoding="UTF-8"?><life><world><cat>1</cat>
            </world></life>"""
        self.input_file = StringIO(self.xml_string)

        with self.assertRaises(XMLFileError):
            self.xml_handler.read_state_from_xml(self.input_file)

    def test_write_state_to_xml_success(self):
        original_state = State(5, 4, 3, [Organism(3, 2, 1), Organism(3, 1, 2)])

        # test with temp file should be enough
        with NamedTemporaryFile(delete=False) as test_write_file:
            self.xml_handler.write_state_to_xml(test_write_file, original_state, 3)

        with open(test_write_file.name, 'r') as test_read_file:
            state = self.xml_handler.read_state_from_xml(test_read_file)

            self.assertEqual(state.cells_cnt, original_state.cells_cnt)
            self.assertEqual(state.species_cnt, original_state.species_cnt)
            self.assertEqual(state.iterations_cnt, original_state.iterations_cnt)

    def test_write_state_to_xml_file_does_not_exist(self):
        state = State(5, 4, 3, [Organism(3, 2, 1), Organism(3, 1, 2)])

        output_file = '/note/existing/nofile.xml'

        with self.assertRaises(XMLFileError):
            self.xml_handler.write_state_to_xml(output_file, state, 1)


import random
import itertools

def encontrarMultiploResta(n, ns):
    perm = itertools.permutations(ns, r=2)
    for p in perm:
        if p[0] > p[1] and (p[0] - p[1]) % n == 0:
            return p

n = 0
while n < 2:
    try:
        n = int(input("ingrese un numero ≥ 2: "))
    except:
        print("la entrada no fue un numero")

a = set()
for _ in range(n + 1):
    a.add(random.randint(1, 1000))

print(encontrarMultiploResta(n, a))


import os
from PyQt6.QtWidgets import (QApplication, QMainWindow, QVBoxLayout,
                               QPushButton, QWidget, QStackedLayout,QLineEdit,
                               QGridLayout, QLabel,QTableWidget, QCheckBox,
                               QTableWidgetItem,QGroupBox)
from PyQt6.QtGui import QAction, QColor , QPainter, QPixmap
from PyQt6.QtCore import Qt
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.colors import Normalize

import time
import networkx as nx
import math as m
from math import cos,sin, pi, sqrt
import numpy as np
from numpy.linalg import eig
from sympy import Symbol, expand

#==========================================================================

def cartesian_to_qrectf(x, y, height,width):
    y_qrectf = height - y
    x_1231 = width + x
    return x_1231, y_qrectf

def my_eval(str1):
    str2 = f"lambda x, y: {str1}"
    return eval(str2)

def my_eval_with_t(str1):
    x = Symbol("x")
    y = Symbol("y")
    t = Symbol("t")
    sssstr = expand(str1)
    print(str(sssstr))
    str2 = f"lambda x, y, t: {str(sssstr)}"
    #str2 = f"lambda x, y, t: {str1}"
    return eval(str2)

def enc(str1):
    if type(str1)!=type("a"):        str1 = str(str1)
    return "(" + str1 + ")"

def cell_dribling(item, leng):
    lengnew = leng*2
    new1 = 2*item-1+(item-1)//leng*lengnew
    new2 = new1+1
    new3 = new1+lengnew
    new4 = new2+lengnew
    return [new1, new2, new3, new4]

#==========================================================================

class MainWindow(QMainWindow):

    def __init__(self,name11):
        super(MainWindow, self).__init__()
        self.name = name11
        self.setWindowTitle("Построение меры максимальной энтропии")
        self.layout_stack = QStackedLayout()

#--------------------------------------------------------------------------
        self.layout_input = QGridLayout()

        self.group1 = QGroupBox("Система уравнений")
        self.group1.setMaximumSize(300, 200)
        layout1 = QGridLayout()
        self.funlabel1 = QLabel("f = ")
        self.funlabel2 = QLabel("g = ")
        self.fun1 = QLineEdit( "  x*x-y*y+a " )
        self.fun2 = QLineEdit( " - 2*x*y+b " )
        layout1.addWidget(self.funlabel1,0,0)
        layout1.addWidget(self.funlabel2,1,0)
        layout1.addWidget(self.fun1,0,1)
        layout1.addWidget(self.fun2,1,1)
        self.group1.setLayout(layout1)
        self.layout_input.addWidget( self.group1 ,1 , 0)

        self.group1 = QGroupBox("Параметры")
        self.group1.setMaximumSize(300, 200)
        layout1 = QGridLayout()
        self.labelparam = QLabel("Параметры уравнения ")
        self.listparam = QLineEdit( " a=0.3,b=0.2 " )
        layout1.addWidget(self.labelparam,0,0)
        layout1.addWidget(self.listparam,0,1)
        self.labelobl = QLabel("Область ")
        self.txtobl = QLineEdit( " [-2,-2]x[2,2] " )
        layout1.addWidget(self.labelobl,1,0)
        layout1.addWidget(self.txtobl,1,1)
        self.group1.setLayout(layout1)
        self.layout_input.addWidget( self.group1 ,1 , 1)

        self.group1.setLayout(layout1)
        self.layout_input.addWidget( self.group1 ,1 , 0)

        self.group1 = QGroupBox("Построить итераций и Достроить итераций")
        self.group1.setMaximumSize(300, 200)
        layout1 = QGridLayout()
        self.button1 = QPushButton("Построить график для итераций:")
        self.globiterc1 = QLineEdit( " 7 ")
        self.button1.clicked.connect(self.iterate_from_start)
        #self.button3 = QPushButton("[x]Проитерировать существующий:")
        #self.globiterc2 = QLineEdit( " 1 ")
        #self.button3.clicked.connect(self.iterate_from_current)
        layout1.addWidget(self.button1 , 0, 0)
        layout1.addWidget(self.globiterc1 , 0, 1)
        #layout1.addWidget(self.button3 , 1 , 0 )
        #layout1.addWidget(self.globiterc2 , 1, 1)
        self.button44 = QPushButton("Построить изображение")
        self.button44.clicked.connect(self.mymainpainter)
        layout1.addWidget(self.button44 , 2, 0)
        self.group1.setLayout(layout1)
        self.layout_input.addWidget( self.group1 ,2 ,0 )

        self.group1 = QGroupBox("Функция оснащения")
        self.group1.setMaximumSize(300, 200)
        layout1 = QGridLayout()
        self.labelextra= QLabel("φ(x,y) = ")
        layout1.addWidget(self.labelextra,0,0)
        self.txtfunnn = QLineEdit( "x*x+y*y" )
        layout1.addWidget(self.txtfunnn,0,1)
        self.extradefault = False
        self.group1.setLayout(layout1)
        self.layout_input.addWidget( self.group1 ,2 , 1)

        self.widget_input = QWidget()
        self.widget_input.setLayout(self.layout_input)
        self.layout_stack.addWidget(self.widget_input)

#--------------------------------------------------------------------------
        self.layout_graph = QVBoxLayout()

        self.W_HIGHT = 700
        self.W_WIDTH = 700

        self.picture_out1 = QLabel()
        self.picture_out1.setMinimumSize(self.W_WIDTH, self.W_HIGHT)
        self.layout_graph.addWidget( self.picture_out1)

        pixmap = QPixmap(self.W_HIGHT, self.W_WIDTH)
        pixmap.fill(QColor(255, 255, 255))
        self.picture_out1.setPixmap(pixmap)

        self.widget_graph = QWidget()
        self.widget_graph.setLayout(self.layout_graph)
        self.layout_stack.addWidget(self.widget_graph)

#--------------------------------------------------------------------------
        self.layout_out = QGridLayout()

        self.res_out1 = QLabel()
        self.res_neout1 = ""
        self.res_out1.setText(f"Количество ячеек,\n Время итерации")
        self.layout_out.addWidget( self.res_out1)

        self.widget_out = QWidget()
        self.widget_out.setLayout(self.layout_out)
        self.layout_stack.addWidget(self.widget_out)

#-------------------------------------------------------------------------
        self.central_widget = QWidget()
        self.central_widget.setLayout(self.layout_stack)
        self.setCentralWidget(self.central_widget)

#-------------------------------------------------------------------------
        self.menu = self.menuBar()
        self.viewMenu = self.menu.addMenu("Меню")

        self.switchAction1 = QAction("Ввод", self)
        self.switchAction1.triggered.connect(self.switch_layout_input)
        self.viewMenu.addAction(self.switchAction1)

        self.switchAction2 = QAction("Графики", self)
        self.switchAction2.triggered.connect(self.switch_layout_graph)
        self.viewMenu.addAction(self.switchAction2)

        self.switchAction3 = QAction("Результат", self)
        self.switchAction3.triggered.connect(self.switch_layout_out)
        self.viewMenu.addAction(self.switchAction3)

    def switch_layout_input(self):
        self.layout_stack.setCurrentIndex(0)

    def switch_layout_graph(self):
        self.layout_stack.setCurrentIndex(1)

    def switch_layout_out(self):
        self.layout_stack.setCurrentIndex(2)
    #==========================================================
    def extraaction(self):
        print("--")
        if self.extradefault:
            self.extradefault = False
            print("tofalse")
        else:
            print("totrue")
            self.extradefault = True

    def iterate_from_start(self):
        self.iternum = int(self.globiterc1.text())
        self.res_neout1 = ""
        self.mainiteration()

    def iterate_from_current(self):
        self.iternum += int(self.globiterc2.text())
        self.mainiteration()

    def draw_3d_bar(self):
        _x = np.arange(4)
        _y = np.arange(3)
        _xx, _yy = np.meshgrid(_x, _y)
        _x, _y = _xx.ravel(), _yy.ravel()

        _z = np.zeros_like(_x)
        _dx = _dy = np.ones_like(_z)
        _dz = [1, 2, 3, 4, 2, 3, 4, 2, 5, 7, 2, 1]

        self.axis.bar3d(_x, _y, _z, _dx, _dy, _dz)
        self.canvas.draw()

    def mainiteration(self):
        somelist1, somelist2 = (self.txtobl.text()).split("x")
        somelist1 = eval(str(somelist1))
        somelist2 = eval(str(somelist2))
        x0 = somelist1[0]
        y0 = somelist2[1]
        L = somelist2[0] - somelist1[0]
        H = somelist2[1] - somelist1[1]
        print(x0,y0,L,H)
        somelist1, somelist2 = (self.listparam.text()).split(",")
        a = str(somelist1).split("=")[1]
        b = str(somelist2).split("=")[1]
        print(a,b)
        iterations = self.globiterc1.text()
        #if self.iternum == int(self.globiterc1.text()):
            #self.res_neout1 = f"{matr}\nСобственные значения: {eig(matr)[0][0]} {eig(matr)[0][1]} {eig(matr)[0][2]}\n"
        self.start = time.time()
        os.system(f".\main.exe {x0} {y0} {L} {H} {a} {b} {iterations}") # {a32} {a33} {self.iternum}")
        #os.system(f".\main.exe {a11} {a12} {a13} {a21} {a22} {a23} {a31} {a32} {a33} {self.iternum}")

    def mymainpainter(self):
        with open('res.txt') as f:
            lines = f.readlines()

        print(lines[-1])
        print(lines[-2])
        print(lines[-3])
        toprintdiam = lines[-3]
        toprintcoms = lines[-2]
        toprintnumc = lines[-1]
        #toprintcomsnum = lines[-1].rstrip()
        #toprintcellamount = lines[-2].split(" ")[1].rstrip()
        #toprintentropy = lines[-3].rstrip()
        #toprintloglambda = lines[-4].rstrip()
        #self.res_neout1 = f"{self.res_neout1}Время подсчета { self.iternum } итераций: {restime}\nРазмер ячейки: {d}\n"
        lines = lines[:-3]
        celllist = lines

        pixmap = QPixmap(self.W_HIGHT, self.W_WIDTH)
        pixmap.fill(QColor(255, 255, 255))

        painter = QPainter(pixmap)
        painter.setPen(QColor(255, 0, 0))#
        painter.setBrush(QColor(255, 0, 0))

        painter.drawRect(int(self.W_WIDTH/2), 0, 0, self.W_HIGHT) #VERTICAL
        painter.drawRect(0, int(self.W_HIGHT/2), self.W_WIDTH, 0) #HORISONTAL

        painter.setPen(QColor(0, 0, 0))#
        painter.setBrush(QColor(0, 0, 0))

        self.x0 = -2
        self.x1 = 2
        self.y0 = -2
        self.y1 = 2
        self.h = float(toprintdiam)
        self.mashtab = self.W_HIGHT/abs(self.y0-self.y1)
        print(self.mashtab)
        self.xposition = lambda cell, leng: self.x0+self.h*(cell-(cell-1)//leng*leng-1)
        self.yposition = lambda cell, leng: self.y1-self.h*((cell-1)//leng+1)
        self.lengx = abs(self.x1 - self.x0) / self.h

        for e in celllist:
            e = eval(e)
            #print(e,self.lengx)
            x,y = cartesian_to_qrectf(self.xposition(e, self.lengx), self.yposition(e, self.lengx),  max([self.y1,self.y0]), max([self.x1,self.x0]))
            #print(x,y)
            painter.drawRect( int(x*self.mashtab), int(y*self.mashtab) ,int(self.h*self.mashtab), int(self.h*self.mashtab))
        painter.end()
        self.picture_out1.setPixmap(pixmap)

        try:
            restime = time.time() - self.start
        except AttributeError:
            restime = 0
            self.iternum = 0
        print(restime)
        self.res_neout1 = f"{self.res_neout1}Время подсчета { self.iternum } итераций: {restime}\nРазмер ячейки: {toprintdiam}\n"
        self.res_neout1 = f"{self.res_neout1}Количество ячеек { toprintnumc }\n Компонент сильной связности: {toprintcoms}\n"
        #self.res_neout1 = f"{self.res_neout1}Энтропия: { toprintentropy }\n ln(lambda): { toprintloglambda }\n"

        with open('res1.txt') as f:
            lines = f.readlines()

        for i,line in enumerate(lines):
            eee = line.split(" ; ")
            self.res_neout1 = f"{self.res_neout1}Для компоненты {i+1}\nЛучшее нижнее значение { eee[0] } Лучшее верхнее значение {eee[1]}\n"

        self.res_out1.setText(self.res_neout1)

#==========================================================
app = QApplication([])
window = MainWindow("window")
window.show()
app.exec()