from machine import UART, Pin,SPI,I2C
import utime,time

gps = UART(0,baudrate = 9600,tx = Pin(0),rx = Pin(1))

def convert_to_degrees(raw_value):
    decimal_value = raw_value/100.00
    degrees = int(decimal_value)
    mm_mmmm = (decimal_value - int(decimal_value))/0.6
    position = degrees + mm_mmmm
    position = "%.4f" %(position)
    return position

def RMC_Read():
            data = "$GNRMC,"
            info = data
            received_data = (str)(gps.read()) #read NMEA string received
            data_available = received_data.find(info)
            if (data_available>0):
                buffer = received_data.split(data,1)[1]  #store data coming
                buff = (buffer.split(','))
                nmea_time = []
                nmea_latitude = []
                nmea_longitude = []
                date = []
                speed_over_ground = []
                nmea_time = buff[0]
                speed_over_ground = buff[6]#extract time from GPGGA string
                nmea_latitude = buff[2]
                nmea_longitude = buff[4]
                date = buff[8]
                lat = (float)(nmea_latitude)
                lat = convert_to_degrees(lat)
                longi = (float)(nmea_longitude)
                longi = convert_to_degrees(longi)
                return lat,longi,nmea_time,speed_over_ground,date

while 1:
  x = RMC_Read() #Recommended minimum specific GNSS data
  if x is not None:
                a = list(x)
                print("Latitude = ",a[0] + "    Longitude = ",a[1])
                print("UTC Time = ",a[2])
                print("Date = ",a[4])
                print("speed over ground = ",a[3])
                print("\n")
                time.sleep(0.2)

Run raspberry HAT's on PiSquare/GPS HAT/gps_hat.py


import sys
from csv import reader
from pyspark import SparkContext

sc = SparkContext()

lines = sc.textFile(sys.argv[1], 1)
lines = lines.mapPartitions(lambda x: reader(x))

sum_of_value = lines.map(lambda x: (x[2], float(x[12])))
total_sum = sum_of_value.reduceByKey(lambda x, y: x + y)

counts_of_value = lines.map(lambda x: (x[2], 1))
count = counts_of_value.reduceByKey(lambda x, y: x + y)

average = total_sum.join(count).map(lambda x: (x[0], x[1][0], float((x[1][0] / x[1][1]))))
output = average.map(lambda x: x[0] + '\t' + "{0:.2f}".format(x[1]) + ', ' + "{0:.2f}".format(x[2]))
output.saveAsTextFile("task3.out")


from PIL import Image

from pagermaid.listener import listener
from pagermaid.enums import Message, Client
from pagermaid.single_utils import safe_remove

@listener(
    command="sticker_to_pic", description="将你回复的静态贴纸转换为图片", parameters="（是否发送原图，默认为否）"
)
async def sticker_to_pic(bot: Client, message: Message):
    origin = bool(message.arguments)
    reply = message.reply_to_message
    if not reply:
        return await message.edit("请回复一个静态贴纸")
    if not reply.sticker:
        return await message.edit("请回复一个静态贴纸")
    if reply.sticker.is_animated or reply.sticker.is_video:
        return await message.edit("请回复一个静态贴纸")
    try:
        photo = await bot.download_media(reply, in_memory=True)
        message: Message = await message.edit("正在转换...\n███████70%")
        image = Image.open(photo)
        image.save("sticker.png", "PNG")
    except Exception as e:
        return await message.edit(f"转换失败：{e}")
    if origin:
        await reply.reply_document("sticker.png", quote=True)
    else:
        await reply.reply_photo("sticker.png", quote=True)
    safe_remove("sticker.png")
    await message.safe_delete()


import numpy as np

def log_marginal(emd):
    # Initialization of the log  marginal likelihood
    log_p = 0
    # Calculating the log marginal likelihood
    for t in range(emd.T):
        for i in range(emd.N):
            # Logarithm of the determinant
            # sign, logdet_sigma_f = np.linalg.slogdet(emd.sigma_f[t,i])
            # sign, logdet_sigma_o = np.linalg.slogdet(emd.sigma_o[t,i])

            # Computing the integrand at the map estimate
            a = emd.theta_f[t,i] - emd.theta_o[t,i]
            b = .5*np.dot(np.dot(a.T,emd.sigma_o_i[t,i]),a)
            # Calculation of psi summed over trials
            PSI = 0
            for l in range(emd.R):

                s = np.append(1, emd.spikes[t,l])
                PSI += np.log(1+np.exp(np.dot(emd.theta_f[t,i],s)))
                # print('emd.theta_f[t,i]',emd.theta_f[t,i])
                # print("emd.FSUM[t,i]",emd.FSUM[t,i])

            q = (np.dot(emd.theta_f[t,i], emd.FSUM[t,i]) - PSI) - b
            # log_p += .5*logdet_sigma_f - .5*logdet_sigma_o + q
            log_p += .5*np.log(np.linalg.det(emd.sigma_f[t,i])) \
            - .5*np.log(np.linalg.det(emd.sigma_o[t,i])) + q

    return log_p


def main():
    inn = input('please enter value in division : ')
    firstcheck = convert(inn)
    print (gauge(firstcheck))

def convert(fraction):
    while True:
        try:
            x,y = fraction.split('/')
            x,y = int(x), int(y)
            p = x/y
            if p >= 0 and p <= 1:
                return (round(p*100))
            else:
                fraction = input("please enter value in division : ")
                continue

        except (ValueError, TypeError, ZeroDivisionError):
            raise

def gauge(percentage):

        if percentage <= 1 :
            return ('E')

        elif percentage >= 99:
            return ('F')

        else:
            return ( f'{percentage}%' )

if __name__ == "__main__":
    main()


import re
ls = []

def sortTitles(title):
	pattern = re.compile(r"(^[\w ]+) \((\b\d{4})\)$")

	for book in title:
		match=pattern.search(book)
		result = pattern.sub("\g<2> - \g<1>", book )
		ls.append(result)
	ls.sort()
	print(ls)

title = ["abc sdgsdf fsdf (1987)", "rtretrt  gd rewr e (1873)", "rtrtrtrw wer a ewr (1935)", "af asgffdshs (1840)"]

sortTitles(title)


import requests

headers = {'Authorization': 'Bearer 635812bd9ead41dcb46169a629e4f6e7918715e8'}
endpoint = "http://localhost:8000/api/products/"

data = {
    "title": "This field is done",
    "price": 32.00
}

get_response = requests.post(endpoint, json=data, headers=headers)
print(get_response.json())


from matplotlib import *
import matplotlib.pyplot as plt
import numpy as np
from subprocess import *
#rom subprocess import run
ok = subprocess.call('./dec.exe encryptx.txt')
print("\n--------  raw out  ----------")
print(ok)
print("--------  raw tmp  ----------")
file = open("tmp", "r")
string = file.read()
file.close()
print(string)
print("--------  data  ----------")
data = string.split()
integ = []
for k in data:
	j = int(k)
	#if j == 0: j = 6000
	integ.append(j)
x = np.linspace(-0.5244, 3.6644, len(integ))
print(integ)
#plt.plot(data) #linear mode
#plt.show() #linear mode
plt.polar(x, integ)
plt.show()


# coding: utf8
class projetService(object):

    # get dossier par son id
    @staticmethod
    def getDossierById(unid):
        rows = db.dossier[unid]
        return rows

    # insertion d'un dossier en base
    @staticmethod
    def insertDossier(vars):
        return db.dossier.insert(**db.dossier._filter_fields(vars))

    # mise a jour des informations d'un dossier par son id
    @staticmethod
    def updateDossier(vars, idDossier):
        rowDos = projetService.getDossierById(idDossier)
        rowDos.update_record(**db.dossier._filter_fields(vars))
        return rowDos.porteur_id

    # mis a jour du commentaire et de l'état d'un dossier
    @staticmethod
    def updateStatusDossier(comment, etat_id, idDossier):

        # on met a jour le commentaire
        if idDossier is not None:
            rowDos = projetService.getDossierById(idDossier)
            rowDos.update_record(commentaire= comment)

        # s'il y a un état lors de l'udpate du dossier, on va mettre a jour l'état du dossier
        if etat_id is not None and etat_id != 0 and etat_id != '0':
              projetService.updateEtat(etat_id,idDossier)

              # et en plus, si l'état est accepté, on met a jour le budget_id de chaque produits du dossier (null par défaut)
              if etat_id == str(Constantes.ACCEPTE):
                  achatService.updateBudgetOfProduitsDuDossier(rowDos)

    # mis a jour de l'état d'un dossier
    @staticmethod
    def updateEtat(etat_id, idDossier):
         if idDossier is not None:
              rowDos = projetService.getDossierById(idDossier)
              rowDos.update_record(etat_dossier_id=etat_id)

    # get la query qu'il faut transmettre au tableau
    @staticmethod
    def getQueryOfDossier(session):

          # le user connecté est il un président, représentant ou user (demandeur)
          isPresident = session.auth.user.group_id == Constantes.PRESIDENT
          isRepresentant = session.auth.user.group_id == Constantes.REPRESENTANT

          # get infos du user
          user = userService.getInfosUser(session.auth.user.id)

          # si c'est un président, on affiche tous les dossier dans le tableau
          if(isPresident):
            queryFinal = db.dossier
          else:
            # sinon, affichage tous les dossiers en tant que demandeur
            query1 = db.dossier.user_id==session.auth.user.id

            query2 = None
            # si c'est un représentant, on affiche tous les dossiers de son entité
            if(isRepresentant):
                query2 = db.dossier.entite_id == user.entite_id
            else:
                query2 = db.dossier.user_id==session.auth.user.id

            queryFinal = query1 | query2

          return queryFinal


#  "Aggies do not lie, cheat, or steal, or tolerate those who do"
#  "I have not given or received any unauthorized aid on this assignment"
#
# Name:        Chase Albright
# Section:     480
# Assignment:  Lab 5
# Date:        22 september 2020
#-----------------------------------------------------------------------------------------------------
print('Enter as many measurements as you need, a negative value will terminate process')
measurements = 1
total = 0
min = 10**6
max = 0
i = 0

while measurements >= 0:
    measurements = float(input('What are the measurements?: '))

    if measurements >= 0: # finds the average
        i = i + 1
        total = total + measurements

        if measurements > max:
            max = measurements

        if measurements < min:
            min = measurements

print('-------------------------------------------------------------------------')
print('average =',total/i)
print('min =', min)
print('max =',max)


from googletrans import Translator
from gtts import gTTS
from tkinter import *

window = Tk()
window.geometry('1600x800')
window.config(bg="grey")
set_bg = PhotoImage(file="logo.png")
label_1 = Label(window, image=set_bg)
label_1.place(x=0, y=0)
e1 = Entry(window, bg="white",fg="black",font=("Arial",25,"bold"))
e1.place(x=20,y=20)

def convert_language():
    a1 = e1.get()
    t1 = Translator()
    t2 = click_option.get()
    if t2 == "afrikaans":
        convert = "af"
    elif t2 == "albanian":
        convert = "sq"
    elif t2 == "amharic":
        convert = "am"
    elif t2 == "arabic":
        convert = "ar"
    elif t2 == "Hindi":
        convert = "hi"
    elif t2 == "English":
        convert = "en"
    trans_text = t1.translate(a1, dest=convert)
    trans_text = trans_text.text
    ob1 = gTTS(text=trans_text, slow=False, lang=convert)
    label_2.config(text=trans_text)
choices = [
    "English",
    "Hindi",
    "arabic",
    "amharic",
    "albanian",
    "afrikaans"
]
click_option = StringVar()
click_option.set("Select Language")
list_drop = OptionMenu(window, click_option, *choices)
list_drop.configure(background="green", foreground="white", font=('Arial',15,"bold"))
list_drop.place(x=400,y=20)

label_2 = Label(window, text="Translated text",bg="black", fg="white",font=("Arial",10,"bold"))
label_2.place(x=180,y=120)

Button_1 = Button(window, text="Translate",bg="red",fg="white",font=("Arial",25,"bold"),command=convert_language)
Button_1.place(x=220,y=200)

window.mainloop()


from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail.message import EmailMessage

from common.models import TemplateModel

def send_voting_email(request, voting, exclude_memberships=None):
    ctx_dict = {
        'voting': voting,
        'site': get_current_site(request),
        'protocol': settings.SSL_ON and 'https' or 'http',
    }

    for voter in voting.voters.all():
        member = voter.membership
        if exclude_memberships and member in exclude_memberships:
            continue

        ctx_dict['recipient'] = member
        ctx_dict['link'] = '{procotol}://{site}{url}'.format(procotol=ctx_dict['protocol'], site=ctx_dict['site'], url=voter.get_voting_url())

        tmpl = TemplateModel.objects.get(name=TemplateModel.VOTING_INVITATION)
        subject = tmpl.generate_title(ctx_dict) or voting.account.name
        message = tmpl.generate(ctx_dict)

        mail = EmailMessage(subject, message, settings.DEFAULT_FROM_EMAIL, [member.user.email])
        admin_emails = [m.user.email for m in voting.account.get_admin_memberships() if m.id != member.id]
        if admin_emails:
            mail.extra_headers['Reply-To'] = ', '.join(admin_emails)

        mail.content_subtype = "html"
        mail.send()


from tkinter import *
import tkinter as tk

def on_button_click(event):
    text = event.widget.cget("text")
    if text == "=":
        try:
            result = eval(entry.get())
            entry.delete(0, tk.END)
            entry.insert(tk.END, str(result))
        except Exception as e:
            entry.delete(0, tk.END)
            entry.insert(tk.END, "Error")
    elif text == "C":
        entry.delete(0, tk.END)
    else:
        entry.insert(tk.END, text)

# Create the main application window
app = tk.Tk()
app.title("Calculator")
app.geometry("1000x600")

# Center the frame on the window
frame = tk.Frame(app,background="cyan", width=1000, height=600)
frame.pack_propagate(False)  # Prevent the frame from resizing to its contents
frame.pack()

# Create the entry field for displaying calculations
entry = tk.Entry(frame,background="red", font=("Arial", 30), justify="right")
entry.pack(pady=20, padx=10, fill=tk.X)

# Custom button styles
button_styles = {
    "bg": "red",  # Background color
    "fg": "white",    # Foreground (text) color
    "activebackground": "red",
    "activeforeground": "white",
    "borderwidth": 8,
    "relief": tk.GROOVE,
    "font": ("Arial", 30),
    "padx": 30,
    "pady": 5,
}

# Create the buttons
button_values = [
    ("7","8","9","/"),
    ("4","5","6","*"),
    ("1","2","3","-"),
    ("C", "0", "=", "+"),
]

for i, row_values in enumerate(button_values):
    button_row = tk.Frame(frame)
    button_row.pack()

    for value in row_values:
        button = tk.Button(button_row, text=value, **button_styles)
        button.pack(side=tk.LEFT, padx=10, pady=10)
        button.bind("<Button-1>", on_button_click)

# Center the frame on the window
app.update()
frame.place(x=(app.winfo_width() - frame.winfo_width()) // 2, y=(app.winfo_height() - frame.winfo_height()) // 2)

# Start the main event loop
app.mainloop()


# -*- coding: utf-8 -*-

from setuptools import setup, find_packages

with open('README.md') as f:
    readme = f.read()

with open('LICENSE') as f:
    license = f.read()

setup(
    name='preseries_api',
    version='0.1.0',
    description='Preseries API for Python & Examples',
    long_description=readme,
    author='Javier Alperte',
    author_email='alperte@preseries.com',
    url='https://github.com/preseries/api_examples',
    license=license,
    setup_requires=[],
    namespace_packages=['preseries'],
    packages=find_packages('src', exclude=['tests', 'docs']),
    package_dir={'': 'src'},
    include_package_data=True,
    install_requires=[
        'openpyxl==2.4.8',
        'python-Levenshtein==0.12.0',
        'requests==2.18.4',
        'httplib2==0.10.3',
        'xlrd==1.1.0',
        'xlwt==1.3.0'
    ]
)


## Exercise 12 :
# Implement Batch Gradient Descent with early stopping
# for Softmax Regression (without using Scitkit-Learn).

from sklearn import datasets
import soft_max_scratch
import numpy as np
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split

## Converts class labels to one hot encodings
def convert_to_one_hot(labels):

    class_count = len(set(labels))
    one_hot = np.zeros((len(labels),class_count))

    for i in range(len(labels)):
        one_hot[i][labels[i]] = 1

    return one_hot

def main():
    iris = datasets.load_iris()
    data = iris["data"]
    labels_one_hot = convert_to_one_hot(iris["target"])

    ## shuffle training data and labels (Gradient Descent performs better this way)
    rand = np.random.permutation(len(data))
    X_train, X_test, y_train, y_test = train_test_split(data[rand],
                                                        labels_one_hot[rand],
                                                        test_size = .33)

    soft_clf = soft_max_scratch.SoftMaxClassifier(learning_rate = 0.05,
                                                max_iter = 40000,
                                                minimum_step_size = 0.0001,
                                                early_stopping = True,
                                                n = 2000)
    soft_clf.train(X_train,y_train)

    y_pred = soft_clf.predict(X_test)

    print(accuracy_score(y_test,y_pred))

if __name__ == "__main__":
    main()

Chapter 4 - Training/chapter_4_exercise_12.py


# -*- coding: utf-8 -*-
import discord
from discord.ext import commands

class AdminCommands(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command(hidden=True)
    @commands.has_permissions(kick_members=True)
    async def kick(self, ctx, member : discord.Member,*, reason = "surplus de wati-bizarrerie"):
        """Permet de kick qlqun"""
        await member.send("Yo la frappe \n Tu t'es fait **kick** du wati-serv pour : "+reason +"\n \n CHEH :woman_in_manual_wheelchair:")
        await member.kick(reason = reason)

    @commands.command(aliases=['clear'], hidden=True)
    @commands.has_permissions(manage_messages = True)
    async def clean(self, ctx, number:int):
        if number<=16:
            await ctx.channel.purge(limit=int(number))
        else:
            await ctx.reply(f'Cannot delete more than 15 messages at once', delete_after=10)

    @commands.command(hidden=True)
    @commands.is_owner()
    async def statut(self,ctx,*,statut=''):
        if statut == "":
            await self.client.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.listening, name = "p!help"))
        else:
            await self.client.change_presence(status=discord.Status.online, activity=discord.Game(kk))
        await ctx.message.delete()

    @commands.command(hidden=True)
    @commands.is_owner()
    async def serverslist(self, ctx):
        letxt = str("```")
        guilds = await self.client.fetch_guilds(limit=150).flatten()
        for server in guilds:
            l = len(server.name)
            letxt += str(server.name) + (30-l)*" " + ":" + str(server.id) + "\n"
        letxt += "```"
        await ctx.author.send(letxt)
        await ctx.message.delete()

    @commands.command(hidden=True)
    @commands.is_owner()
    async def channelslist(self, ctx, serverid):
        """Donne la liste des channels d'un server et leur id"""
        f = open("temp.txt", "w")
        server = self.client.get_guild(int(serverid))
        for channel in server.text_channels:
            l = len(channel.name)
            f.write( channel.name + (30-l)*" " + str(channel.id) + "\n" )
        f.close()
        await ctx.author.send(f"Here's the list of all channles in server : {serverid}",file = discord.File("temp.txt"))
        f = open("temp.txt", "w")
        f.truncate(0)
        f.close()
        await ctx.message.delete()

    @commands.command(hidden=True)
    @commands.is_owner()
    async def getinvite(self, ctx, channelid):
        channel = self.client.get_channel(int(channelid))
        inv = await channel.create_invite()
        await ctx.author.send(inv)
        await ctx.message.delte()

    @commands.command(hidden=True)
    @commands.is_owner()
    async def attachmentslist(self, ctx, channelid):
        """Donne la liste des attachements dans le channel"""
        f = open("temp.txt", "w")
        channel = self.client.get_channel(int(channelid))
        messages = await channel.history(limit=None, oldest_first=True).flatten()
        print(f"je got la listen de longueur : {len(messages)}")
        for message in messages:
            if message.attachments:
                for image in message.attachments:
                    f.write(str(image.url) + "\n")
            elif "http" in message.content:
                for mot in message.content.split():
                    if mot.startswith("http"):
                        f.write(mot + "\n")
        f.close()
        await ctx.author.send(f"Here's the list of all images in channel : {channelid}",file = discord.File("temp.txt"))
        f = open("temp.txt", "w")
        f.truncate(0)
        f.close()
        await ctx.message.delete()

async def setup(bot: commands.Bot):
    await bot.add_cog(AdminCommands(bot))


"""
Hacker Rank - Service Lane
https://www.hackerrank.com/challenges/service-lane
"""

def main():
    len_freeway, num_cases = (int(i) for i in input().strip().split(' '))
    width_list = [int(i) for i in input().strip().split(' ')]
    for i in range(num_cases):
        i, j = (int(l) for l in input().strip().split(' '))
        min_width = float('inf')
        for index in range(i, j+1):
            if width_list[index] < min_width:
                min_width = width_list[index]
        if min_width >= 3:
            print('3')
        elif min_width >= 2:
            print('2')
        elif min_width >= 1:
            print('1')

if __name__ == '__main__':
	main()


import boto3
from requests_aws4auth import AWS4Auth
import requests
import JaSONx
import os
import time
from utility import binary_to_dict, createFileList
from PyQt5 import QtCore
import httpReq
import os
import sys, os, base64, datetime, hashlib, hmac

dict_credentials = {}
dict_response = {}
r = ''
def readCredentials(account):
    pathcredentials = QtCore.QDir.homePath() + '/.aws/credentials'
    with open( pathcredentials , 'r') as fin:
        credentials = fin.read()
    list_credentials = credentials.split("[")
    for lis in list_credentials:
        if( account in lis):
            for attr in lis.split("\n"):
                if("region" in attr or "aws_access_key_id" in attr or "aws_secret_access_key" in attr or "aws_session_token" in attr or "aws_security_token" in attr):
                        key, val =attr.split(" = ")
                        dict_credentials[key] = val
    return dict_credentials

def readfilejson(path):
        with open(path, 'r') as json_file:
            return json_file.read()

def activateThing(hierarchy_name, file, dict_credentials, api_id):

    payload = readfilejson(os.path.join(os.path.realpath(''),'json_files', hierarchy_name, file))
    endpoint = 'https://' + api_id + '.execute-api.eu-central-1.amazonaws.com/dev/v1/gateways/conad-eig1/command'
    post_response = httpReq.post(dict_credentials, endpoint, payload)

    if(post_response[0] == 200):
        endpoint = 'https://' + api_id + '.execute-api.eu-central-1.amazonaws.com/dev/v1/gatewayCommands/'
        response = httpReq.get(dict_credentials,
            endpoint,
            binary_to_dict(post_response[1])["command_id"]
            )
        return response
    else:
        status = post_response[0]
        message = binary_to_dict(post_response[1])["errors"][0]["error_message"]
        response = (status,message)
        return response

#Initialize the activations getting the credentials with readCredentials() and posting all the payloads in list_json_file with activateThing()
def initializeActivations(hierarchy_name, list_json_file, account, api_id):

    #Populate dict_credentials with STS from .\.aws\credentials for the account selected
    dict_credentials = readCredentials(account)

    #Initialize response dictionary
    dict_response = {}
    if(list_json_file != []):
        for file in list_json_file:
            response = activateThing(hierarchy_name, file, dict_credentials, api_id)
            dict_response[file] = "STATUS:" + str(response[0]) + ";" + "MESSAGE:" + response[1]
    print(dict_response)
    return dict_response


# stack 구현 및 테스트
stack = []

while True:
    cmds = input('>> ').split()

    # cmds[0] >> command
    # cmds[1] >> 1st parameterd
    if cmds[0] == 'quit': break

    if cmds[0] == 'push':
        stack.append(cmds[1])
    elif cmds[0] == 'pop':
        print(stack.pop())
    elif cmds[0] == 'top':
        print(stack[-1])
    elif cmds[0] == 'empty':
        print(len(stack) == 0)


#!/usr/local/bin/python3

import sys, os, math
from collections import deque

class AOC2022:
    def __init__(s, filename):
        s.f = filename
        s.S1 = 0
        s.S2 = 0

        s.blizzards = [set(), set(), set(), set()] # <>^v
        for r, line in enumerate(open(s.f).read().splitlines()[1:]):
            for c, item in enumerate(line[1:]):
                if item in '<>^v':
                    s.blizzards['<>^v'.find(item)].add((r,c))

        s.r = r
        s.c = c
        s.target = (r,c-1)
        s.lcm = c*r//math.gcd(r,c)
        print('target ',s.target)

    def solve(s):
        targets = [s.target, (-1,0)]
        stage = 0
        Q = deque([(0, -1, 0, stage)])
        seen = set()
        while Q:
            time, cr, cc, stage = Q.popleft()
            time += 1

            for dr, dc in [(0,1), (0,-1), (-1,0), (1,0), (0,0)]:
                nc = cc + dc
                nr = cr + dr

                if (nr,nc) == targets[stage%2]:
                    if stage == 0:
                        print(f'target {(nr,nc)} reached in ', time)
                        s.S1 = time
                    if stage == 2:
                        print(f'target {(nr,nc)} reached in ', time)
                        s.S2 = time
                        return
                    stage += 1

                if (nr < 0 or nc < 0 or nr > s.r or nc > s.c) and ((nr,nc) != (-1,0)) and ((nr,nc) not in targets):
                    continue

                for i, tr, tc in [(0,0,-1), (1,0,1), (2,-1,0), (3,1,0)]:
                    if ((nr - tr * time) % s.r, (nc - tc * time) % s.c) in s.blizzards[i]:
                        break
                else:
                    key = (nr, nc, time % s.lcm, stage)
                    if key in seen:
                        continue

                    seen.add(key)
                    Q.append((time, nr, nc, stage))
#
# #
#

if __name__ == '__main__':
    infile = sys.argv[1] if len(sys.argv) > 1 else 'test.txt'

    if infile == 'test.txt':
        m = AOC2022(infile)
    else:
        m = AOC2022(infile)

    # Part I & II
    m.solve()

    print("------------- A -------------")
    print('S1 ', m.S1)
    print("------------- B -------------")
    print('S2 ', m.S2)
    print("-----------------------------")


print ("Pleasw enter a sequence")
character = input ()
print ("Please enter the character for the marker")
marker = input ()
for x in character:
  lox = len(character)
  for y in character:
    kiki=character.count(marker)
    distance = lox-kiki
  #print (lox)
print ("The distance between the marker is",distance)


#!/usr/bin/python3
class Contact:
    all_contacts = []

    def __init__(self, name, email):
        self.name = name
        self.email = email
        Contact.all_contacts.append(self)

#this class will override the __init__method by using a third argument
#called phone, in thys wy overrriding is altering or replacing a method of the superclass.
#new __init__ method in subclass is automatically called instead of the superclass method
class Friend(Contact):
    def __init__(self, name, email, phone):
        self.name = name
        self.email = email
        self.phone = phone

#The super() functon method is a way to call code on the parent class, it returns th object as an instanc of th parent class, allowing us to calll the parent method directly

class NewFriend(Contact):
    def __init__(self, name, email, phone):
        super().__init__(name, email)
        self.phone = phone


import numpy as np
from numpy import linalg as LA
from pylab import *
import cvxpy  as cp

#if using termux
import subprocess
import shlex
#end if

# ax+by <= d
A = np.array(( [3, 3], [3, 2])).T  #
B = np.array([18,15]).reshape(2,1)  #Total available Floor & Fat

# objective function coeffs
c = np.array([30,25])
x = cp.Variable((2,1),nonneg=True)

#Cost function
f = c@x     #P = max(30 25)x
obj = cp.Maximize(f)

#Constraints
constraints = [A@x <= B]

#solution
prob = cp.Problem(obj, constraints)
prob.solve()
print("Maximun :", f.value)
print("Number of type_1 :", x.value[0])
print("Number of type_2 :", x.value[1])

x1=np.linspace(0,8,200)
#print(len(x1))
y1=(18-3*x1)/3
y2=(15-3*x1)/2
plt.plot(x1,y1,label='3x+3y=18')
plt.plot(x1,y2,label='3x+2y=15')

y4=np.zeros(len(x1))
plt.plot(x1,y4,label='y=0')
plt.plot(y4,x1,label='x=0')
plt.title('')
plt.ylim([-2,8])
# Add X and y Label
plt.xlabel('x axis')
plt.ylabel('y axis')

# Add a grid
plt.grid(alpha=1,linestyle='--')
plt.legend()
plt.savefig('/sdcard/download/opt/opt1.pdf')
subprocess.run(shlex.split("termux-open /sdcard/Download/opt/opt1.pdf"))
plt.show()


# calc energy of a certain configuration

import numpy as np

class energyCalc():
	def __init__(self):
		self.kapa = 1.0

	def createFaceList(self, vert, faces):
		# find all faces that contain a certain vertex
		faceList = []
		for faceIndex in range(len(faces)):
			if (faces[faceIndex][0] == int(vert) or faces[faceIndex][1] == int(vert) or faces[faceIndex][2] == int(vert) ):
				faceList.append(faces[faceIndex])
		return faceList

	def createEdgeList(self, vert, faceList):
		# find all edges that belong to a certain vertex (so the other vertex of the edge)
		edgeList = []
		for faceIndex in range(len(faceList)):
			for i in range(3):
				if faceList[faceIndex][i] != vert:
					edgeList.append(faceList[faceIndex][i])
		# eliminate the doulbe edges
		edgeList = list(set(edgeList))
		return edgeList

	def calcPhi(self, vert1, edgeListIndex, faceList, verts1):
		# calculate the angle between the unit normal vectors of two triangles sharing an edge

		# define all vectors
		i = verts1[vert1]
		j = verts1[edgeListIndex]
		ijVec = np.subtract(i,j)

		#find remeining vertices
		mnlist = []
		for a in range(len(faceList)):
			if faceList[a][0] == edgeListIndex or faceList[a][1] == edgeListIndex or faceList[a][2] == edgeListIndex:
				for b in range(3):
					if faceList[a][b] != vert1 and faceList[a][b] != edgeListIndex:
						mnlist.append(faceList[a][b])

		if len(mnlist) < 2:
			phi = np.pi
		else:
			m = verts1[mnlist[0]]
			n = verts1[mnlist[1]]

			# define remaining two vectors
			inVec = np.subtract(i,n)
			imVec = np.subtract(i,m)

			# calculate normal vectors of the two faces
			n1 = np.cross(imVec, ijVec)
			norm1 = np.linalg.norm(n1)
			if norm1 <= 0.0000001:
				norm1 = 1.0
			n1 = n1/norm1

			n2 = np.cross(ijVec, inVec)
			norm2 = np.linalg.norm(n2)
			if norm2 <= 0.0000002:
				norm2 = 1.0
			n2 = n2/norm2

			# calculate the angle between the two normal vectors
			test = np.dot(n1,n2)
			if test >= 1.0: test = 0.99999
			if test <= -1.0: test = -0.99999

			phi = np.arccos( test )

		return phi

	def calcLength(self, vert, edge, verts):
		# calculate length of an edge
		i = verts[vert]
		j = verts[edge]
		ijVec = np.subtract(i,j)
		length = np.linalg.norm(ijVec)

		return length

	def calcM(self, vertex, faces, verts):
		# calculate the mean curvature curvature contribution M of a vertex
		M = 0.0

		faceList = self.createFaceList(vertex, faces)
		edgeList = self.createEdgeList(vertex, faceList)

		for i in range(len(edgeList)):
			#calculate the angle between to faces
			phi = self.calcPhi(vertex, edgeList[0], faceList, verts)

			# calculate length of edge
			length = self.calcLength(vertex, edgeList[0], verts)

			M += phi*length

		M *= 0.25

		return M

	def calcAreaTriangel(self, face, verts):
		# calculate area of a face (triangel) using Herons formula
		A = verts[face[0]]
		B = verts[face[1]]
		C = verts[face[2]]
		a = np.linalg.norm( np.subtract(B,C) )
		b = np.linalg.norm( np.subtract(A,C) )
		c = np.linalg.norm( np.subtract(A,B) )

		s = (a+b+c)*0.5
		area = np.sqrt( s*(s-a)*(s-b)*(s-c) )

		return area

	def calcA(self, vertex, faces, verts):
		# calculate the area corresponding to a vertex
		A = 0.0

		faceList = self.createFaceList(vertex, faces)
		for i in range(len(faceList)):
			A += self.calcAreaTriangel(faceList[i], verts)

		A *= 1.0/3.0
		return A

	def calcEbend(self, verts, faces):
		# calulate the bending energy of the membrane
		Ebend = 0.0

		for i in range(len(verts)):
			M = self.calcM(i, faces, verts)
			A = self.calcA(i, faces, verts)
			if A < 0.0000000000001:
				Ebend += 0.0
			else:
				Ebend += M*M/A

		Ebend *= 2*self.kapa

		return Ebend


import numpy as np
import pandas as pd
import statistics
from sklearn.model_selection import train_test_split
import streamlit as st
import models
import seaborn as sns

from matplotlib import pyplot as plt
from sklearn.tree import DecisionTreeRegressor,plot_tree
from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error
from validation_functions import regression

def airbnb_regression_prep():
    airbnb_data = pd.read_csv('../xlsx-csv/NYAirbnb/AB_NYC_2019.csv')
    raw_data = airbnb_data
    sns.catplot(x="room_type", y="price", data=raw_data)
    st.pyplot()
    sns.catplot(x="neighbourhood", y="price", data=raw_data)
    st.pyplot()
    sns.catplot(x="neighbourhood_group", y="price", data=raw_data)
    st.pyplot()
    sns.catplot(x="neighbourhood", y="number_of_reviews", data=raw_data)
    st.pyplot()
    sns.catplot(x="neighbourhood_group", y="number_of_reviews", data=raw_data)
    st.pyplot()
    data = airbnb_data.sort_values(["neighbourhood", "room_type"], ascending=(True, True))
    data1 = data.groupby(["neighbourhood", "room_type"])["price"].mean()
    merged_left = pd.merge(left=data, right=data1, how='left', left_on=("neighbourhood", "room_type"),
                           right_on=("neighbourhood", "room_type"))
    merged_left['price_y'] = merged_left['price_y'].astype('category')
    X = merged_left[['room_type', 'neighbourhood_group', 'neighbourhood']]
    y = merged_left[['price_y']]

    X = pd.get_dummies(X)
    return (X, y)

def airbnb_regression():
    X, Y = airbnb_regression_prep()
    X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.10, random_state=42)
    model = ["-----","OLS", "Decision Tree Regression"]
    option = st.sidebar.selectbox('Machine Learning Model', model)
    if option == "OLS":
        model = models.transcendence_ols(X, Y)
    if option == "Decision Tree Regression":
        model = models.transcendence_dt_regression(X, Y,max_depth=20)
    else:
        pass
    return


import sys
words = input()
moves = len(words)
lens = moves + 1

num = int(input())

def minuses(x):
    if x > 0:
        x += -1
    return x

for i in range(num):
    tem = sys.stdin.readline().split()
    if tem[0] == 'L':
        moves = minuses(moves)
    elif tem[0] == 'D':
        if moves == lens:
            continue
        moves += 1
    elif tem[0] == 'B':
        if moves == 0:
            continue
        words = words[:(moves-1)] + words[moves:]
        moves = minuses(moves)
        lens = minuses(lens)
    else:
        words = words[:(moves)] + tem[1] + words[(moves):]
        moves += 1
        lens += 1

print(words)


# coding: utf-8
# Author: wanhui0729@gmail.com

# https://leetcode.com/problems/house-robber/description/

'''
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.
Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.
'''

class Solution(object):
    '''
    动态规划转换方程：dp[i] = max(dp[i - 2] + nums[i - 2], dp[i - 1])
    时间复杂度: O(n)
    空间复杂度: O(1)
    '''
    def rob(self, nums):
        if not nums:
            return 0
        prevMax = 0
        currMax = 0
        for num in nums:
            currMax, prevMax = max(prevMax + num, currMax), currMax
        return currMax

if __name__ == '__main__':
    s = Solution()
    assert s.rob([1, 2, 3, 1]) == 4
    assert s.rob([2, 7, 9, 3, 1]) == 12

'''
intuition
a, b = b, a利用python的语言特性可以更加高效的编程
动态规划的重点是找到转换方程和初始值，然后迭代更新中间状态就可以了
'''


from . import views
from django.urls import path

urlpatterns = [
    path('', views.home_page, name="home"),
    path('projects/', views.project_page, name="project_page"),
    path('about/', views.about_page, name="about_page"),
    # path('project/<str:pk>/', views.project_details, name="project"),
    path('workhistory/', views.work_history_page, name="work_history_page"),
    # path('roles/<str:pk>/', views.roles_page, name="roles_page"),

#     path('add-project/', views.addProject, name="add-project"),
#     path('edit-project/<str:pk>/', views.editProject, name="edit-project"),

#     path('inbox/', views.inboxPage, name="inbox"),
#     path('message/<str:pk>/', views.messagePage, name="message"),

#     path('add-skill/', views.addSkill, name="add-skill"),

#     path('add-endorsement/', views.addEndorsement, name="add-endorsement"),

#     path('donation/', views.donationPage, name="donation"),

#     path('chart/', views.chartPage, name="chart"),
]


def solve(n, d, x):
    peak = 0
    for i in range(n - 1, -1, -1):
        d = d - d % x[i]
    return d

t = int(input()) # read a line with a single integer
for i in range(1, t + 1):
    (n, d) = [int(x) for x in input().split(" ")]
    x = [int(x) for x in input().split(" ")]
    print("Case #{}: {}".format(i, solve(n, d, x)))


import os
import rrdtool
from period import period_conv

#rrdtool create termserver2_cpu.rrd \
#    --start $(date +%s --date="-2years") \
#    --step 900 \
#    DS:load:GAUGE:1200:0:5000 \
#    DS:loadavg:GAUGE:1200:0:5000 \
#    DS:cores:GAUGE:1200:0:5000 \
#    RRA:AVERAGE:0.5:1:1200 \
#    RRA:AVERAGE:0.5:6:1200 \
#    RRA:AVERAGE:0.5:24:1200 \
#    RRA:MIN:0.5:1:1200 \
#    RRA:MIN:0.5:6:1200 \
#    RRA:MIN:0.5:24:1200 \
#    RRA:MAX:0.5:1:1200 \
#    RRA:MAX:0.5:6:1200 \
#    RRA:MAX:0.5:24:1200 \
#    RRA:LAST:0.5:1:1200 \
#    RRA:LAST:0.5:6:1200 \
#    RRA:LAST:0.5:24:1200

def graph1(hostname, period):
    test = rrdtool.graphv("-", "--start", period_conv(period), "-w 800", "--title=Load %s" % hostname,
                          "DEF:load=rrds/%s_cpu.rrd:load:MAX" % (hostname),
                          "CDEF:load100=load,100,/",
                          "LINE2:load#0000FF:load",
                          "CDEF:unavailable=load,UN,INF,0,IF",
                          "AREA:unavailable#f0f0f0",
                         )
    return test['image']

def graph2(hostname, period):
    test = rrdtool.graphv("-", "--start", period_conv(period), "-w 800", "--title=Load %s" % hostname,
                          "DEF:cores=rrds/%s_cpu.rrd:cores:LAST" % (hostname),
                          "LINE2:cores#00FFFF:cores",
                          "CDEF:unavailable=cores,UN,INF,0,IF",
                          "AREA:unavailable#f0f0f0",
                         )
    return test['image']

def graph3(hostname, period):
    test = rrdtool.graphv("-", "--start", period_conv(period), "-w 800", "--title=Load %s" % hostname,
                          "DEF:loadavg=rrds/%s_cpu.rrd:loadavg:LAST" % (hostname),
                          "LINE2:loadavg#FF00FF:loadavg",
                          "CDEF:unavailable=loadavg,UN,INF,0,IF",
                          "AREA:unavailable#f0f0f0",
                         )
    return test['image']

def insert(hostname, data, timestamp="N"):
    if not exists(hostname):
        create(hostname)
    rrdname = "rrds/" + hostname + "_cpu.rrd"
    rrdtool.update(rrdname, '%s:%s:%s:%s' % (timestamp, data[0], data[1], data[2]))

def exists(hostname):
    rrdname = "rrds/" + hostname + "_cpu.rrd"
    return os.path.exists(rrdname)

def create(hostname):
    if not exists(hostname):
        rrdname = "rrds/" + hostname + "_cpu.rrd"
        rrdtool.create(rrdname, '--start', '-2years',
                       '--step', '900',
                       'DS:load:GAUGE:1200:0:5000',
                       'DS:loadavg:GAUGE:1200:0:5000',
                       'DS:cores:GAUGE:1200:0:5000',
                       'RRA:AVERAGE:0.5:1:1200',
                       'RRA:AVERAGE:0.5:6:1200',
                       'RRA:AVERAGE:0.5:24:1200',
                       'RRA:MIN:0.5:1:1200',
                       'RRA:MIN:0.5:6:1200',
                       'RRA:MIN:0.5:24:1200',
                       'RRA:MAX:0.5:1:1200',
                       'RRA:MAX:0.5:6:1200',
                       'RRA:MAX:0.5:24:1200',
                       'RRA:LAST:0.5:1:1200',
                       'RRA:LAST:0.5:6:1200',
                       'RRA:LAST:0.5:24:1200'
                      )
        return True
    else:
        return False

def last(hostname):
    rrdname = "rrds/" + hostname + "_cpu.rrd"
    try:
        last = rrdtool.last(rrdname)
    except:
        return None
    return last

def latest(hostname):
    rrdname = "rrds/" + hostname + "_cpu.rrd"
    try:
        info = rrdtool.info(rrdname)
        lastupdate = [info['last_update'], float(info['ds[load].last_ds']), float(info['ds[loadavg].last_ds'], float(info['ds[cores].last_ds']))]
        return lastupdate
    except:
        return None


from flexx import flx

class LobbyConfigMenuWidget(flx.Widget):
    client = flx.Property()

    def init(self):
        with flx.Widget(style={
            "text-align": "center",
            "margin-bottom": "20px"
        }):
            flx.Label(text="Presets:")
            with flx.Widget():
                self.preset_button_1 = flx.Button(text="Singleplayer")
                self.preset_button_2 = flx.Button(text="2-player co-op")
                self.preset_button_3 = flx.Button(text="3-player co-op")

        with flx.Widget(style={
            "display": "flex",
            "justify-content": "space-evenly"
        }):
            with flx.Widget():
                flx.Label(text="Lobby name:")
                self.name_field = flx.LineEdit()

            with flx.Widget():
                flx.Label(text="Players (1-3):")
                self.playercount_field = flx.LineEdit()

        with flx.Widget(style={
            "text-align": "center",
            "margin-top": "20px",
            "font-style": "italic"
        }):
            self.error_label = flx.Label(text="Lobby name must be between 2 and 35 characters.")

    @flx.reaction("preset_button_1.pointer_click")
    def _preset_button_1_handler(self, *events):
        self.load_preset(self.client.username + "'s solo game", "1")

    @flx.reaction("preset_button_2.pointer_click")
    def _preset_button_3_handler(self, *events):
        self.load_preset(self.client.username + "'s co-op game", "2")

    @flx.reaction("preset_button_3.pointer_click")
    def _preset_button_2_handler(self, *events):
        self.load_preset(self.client.username + "'s co-op game", "3")

    def load_preset(self, name, players):
        self.name_field.set_text(name)
        self.playercount_field.set_text(players)

    def set_disabled_all(self, disabled):
        self.name_field.set_disabled(disabled)
        self.playercount_field.set_disabled(disabled)
        self.preset_button_1.set_disabled(disabled)
        self.preset_button_2.set_disabled(disabled)
        self.preset_button_3.set_disabled(disabled)


import numpy as np
import matplotlib.pyplot as plt

def load_data():
  data = np.loadtxt('ex2data2.txt', delimiter=',')
  X = data[:,:2]
  y = data[:,2]
  return X, y

def plot_data(X, y):
  plot_data_helper(X, y)
  plt.show()

def plot_cost(J):
  l = list(np.linspace(0, len(J), len(J)))
  plt.plot(J, l)
  plt.show()

def plot_data_helper(X, y):
  neg = ( 0 == y )
  pos = ( 1 == y )
  plt.scatter(X[pos, 0], X[pos, 1], label="Admitted")
  plt.scatter(X[neg, 0], X[neg, 1], label="Not Admitted")
  plt.legend()

def plot_data_helper_2(X, y):
  neg = ( 0 == y )
  pos = ( 1 == y )
  fig, (ax1, ax2, ax3) = plt.subplots(3, 9)
  axs = [ax1, ax2, ax3]
  b=-1
  for a in axs:
    b += 1
    for i in range(9):
      a[i].scatter(X[pos, b], X[pos, i+3*b], label="Admitted")
      a[i].scatter(X[neg, b], X[neg, i+3*b], label="Not Admitted")
  plt.legend()
  return axs

def plot_db(X, y, w, b):
  # axs = plot_data_helper_2(X, y)
  plot_data_helper(X, y)

  if X.shape[1] <= 2:
    plot_x = np.array([min(X[:, 0]), max(X[:, 0])])
    plot_y = (-1. / w[1]) * (w[0] * plot_x + b)

    plt.plot(plot_x, plot_y, c="b")

  else:
    u = np.linspace(-1, 1.5, 50)
    v = np.linspace(-1, 1.5, 50)

    z = np.zeros((len(u), len(v)))

    # Evaluate z = theta*x over the grid
    for i in range(len(u)):
      for j in range(len(v)):
        z[i,j] = sig(np.dot(map_feature(u[i], v[j]), w) + b)

    # important to transpose z before calling contour
    z = z.T

    # Plot z = 0
    # for a in axs:
    #   for i in range(9):
    #     a[i].contour(u,v,z, levels = [0.5], colors="g")
    plt.contour(u,v,z, levels = [0.5], colors="g")

  plt.show()

def sig(z):

    return 1/(1+np.exp(-z))

def map_feature(X1, X2):
    """
    Feature mapping function to polynomial features
    """
    X1 = np.atleast_1d(X1)
    X2 = np.atleast_1d(X2)
    degree = 6
    out = []
    for i in range(1, degree+1):
        for j in range(i + 1):
            out.append((X1**(i-j) * (X2**j)))
    return np.stack(out, axis=1)


from __future__ import print_function
from __future__ import print_function
from __future__ import print_function
from __future__ import print_function
from __future__ import print_function
from __future__ import print_function
from __future__ import print_function
from __future__ import print_function
from os import walk
import numpy as np
import os
from alertSignalAndScenarios.scenarios import getScenery
from alertSignalAndScenarios.alertSignal import computerContourFromFilterbank
import ConfigParser
from sys import exit

def computeContourBatchAux(inputFolderPath, fRange, alpha, kernelType, nHarmonics,
                           NFFT, df, outputFolder, verbose=False):
    # save the path of all files inside the input directory
    f = []
    for (dirpath, _, filenames) in walk(inputFolderPath):
        f.extend(filenames)

    # initialize matrix of contours
    names = []  # list of the names of the recordings analized
    N = len(f)

    if N == 0:
        print('Error: no wav files were found in "%s"' % inputFolderPath)
        exit()

    # calculate the contour of all files and store in a list
    fsp = 0
    for iF in range(0, N):
        filepath = '%s/%s' % (inputFolderPath, f[iF])
        if verbose:
            print('Analizando: "%s"' % filepath)
        names.append(f[iF])
        T = None  # no importa porque no estamos usando TS2Means
        thresholdMethod = 'fixed'  # fixed con alpha=0 (para considerar el ruido posible)
        [nf0s, fsp, t, c] = computerContourFromFilterbank(filepath, NFFT, fRange, df,
                                                          kernelType, nHarmonics, alpha, T, thresholdMethod)
        p = c

        outfilename = '%s/%s' % (outputFolder, f[iF].split('.')[-2])
        np.save(outfilename, p)
        if verbose:
            print("Saved %s" % outfilename)

    return fsp, names

def computeContourBatch(inputFolderPath, outputFolderPath, alpha, fRanges, kernelType, nHarmonics, dfs,
                        NFFT=256, verbose=False):
    # fRanges is something like this: {'cuckoo':[800, 1200], 'highchirp':[1900, 3100], 'lowchirp':[850, 1850]}
    # iterate through folders

    if verbose:
        print(fRanges)
        print(dfs)

    for apsType in fRanges.keys():
        cInputFolder = '%s/%s' % (inputFolderPath, apsType)
        cOutputFolder = '%s/%s' % (outputFolderPath, apsType)

        # create output folder if it does not exist
        if not os.path.exists(cOutputFolder):
            os.makedirs(cOutputFolder)

        # compute contours in batch of each subfolder of APS
        [fsp, names] = computeContourBatchAux(cInputFolder, fRanges[apsType], alpha, kernelType, nHarmonics, NFFT,
                                              dfs[apsType], cOutputFolder)

def run(verbose=False):
    configParser = ConfigParser.RawConfigParser()
    configParser.read(r'../configurations.properties')
    wavInputFolder = configParser.get('output', 'wavCutsFolderPath')
    contourOutputFolder = configParser.get('output', 'contoursFolderPath')

    NFFT = 256
    alpha = 0.0
    nArm = 3

    idScenery = 'scenery3'
    esc = getScenery(idScenery)
    fRanges = {'cuckoo': esc['cuckoo']['fRange'], 'highchirp': esc['highchirp']['fRange'],
               'lowchirp': esc['lowchirp']['fRange']}
    dfs = {'cuckoo': esc['cuckoo']['df'], 'highchirp': esc['highchirp']['df'], 'lowchirp': esc['lowchirp']['df']}

    if verbose:
        print('Parameters')
        print('------------')
        print(esc)

    computeContourBatch(wavInputFolder, contourOutputFolder, alpha, fRanges, 'propuestoPrimo', nArm, dfs, NFFT)

'''
MAIN
'''
if __name__ == "__main__":
    # save current working directory and change to script's directory
    cwd = os.getcwd()
    os.chdir(os.path.dirname(os.path.realpath(__file__)))

    run()

    os.chdir(cwd)  # restore directory


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def longestUnivaluePath(self, root: TreeNode) -> int:
        self.res = 0
        self.helper(root)
        return self.res

    def helper(self, root):
        # base case
        if not root:
            return 0

        # Logic
        left_length = self.helper(root.left)
        right_length = self.helper(root.right)

        l, r = 0, 0

        if root.left and root.val == root.left.val:
            l = left_length + 1

        if root.right and root.val == root.right.val:
            r = right_length + 1

        self.res = max(self.res, l + r)

        return max(l, r)


#!/usr/bin/python
# -*- coding: utf-8 -*-

# Model.py

from scipy.optimize import minimize
import wx
from math import exp

from Corridor import *
from Line import *
from OD import *
from Parameters import *

class Model():
	""" This class contains all the objects and data needed to run the model.

	It enables to clearly separate the user interface and the visualization of
	the results from the model. It also manages the interactions between the different
	components of the model.
	"""

	def __init__(self, main_window=None):
		self.main_window = main_window
		self.param = Parameters()

		# Defining the initial corridor which is the reference situation
		self.length = 15
		self.typo = 0
		self.reference = Corridor("Référence", self.length, self.typo)

		# Defining some lists that will contain the scenarios and their results
		# Structure :
		# 	- optimizations : [[corridor with lines which won't be optimized,
		#						[lines to optimize],
		#						elasticity (boolean)],...]
		#	- simulations : [[corridor to simulate, elasticity (boolean)],...]
		#	- optimizations_results : [corridor, ...]
		#	- simulations_results : [corridor, ...]
		self.optimizations = []
		self.simulations = []
		self.optimizations_results = []
		self.simulations_results = []

	def SetLength(self, length):
		""" Modify the length of all corridors. """
		self.reference.SetLength(length)
		for opt in self.optimizations:
			opt[0].SetLength(length)
		for sim in self.simulations:
			sim[0].SetLength(length)

	def SetOD(self, i, j, demand):
		""" Modify the demand for the given OD for all corridors. """
		self.reference.GetOD(i,j).demand = demand
		for opt in self.optimizations:
			opt[0].GetOD(i,j).demand = demand
		for sim in self.simulations:
			sim[0].GetOD(i,j).demand = demand

	def SetTypology(self, typo):
		""" Modify the typo of the reference corridor.

		It will erase all lines of the reference and all scenarios. """
		self.reference.SetTypology(typo)
		self.optimizations = []
		self.simulations = []
		self.optimizations_results = []
		self.simulations_results = []
		if self.main_window != None:
			self.main_window.simulation_panel.UpdateUI()
			self.main_window.DeleteResults()

	def Calculate(self):
		""" This class computes the model for the different scenarios and
		give the results to the user interface.
		"""

		# Opening a progess dialog and creating variables to estimate the progression
		if self.main_window != None:
			self.progress_dialog = wx.ProgressDialog(	"Simulation et optimisation",
														"Calculs en cours")
			self.progress_dialog.Update(0)
		self.progress_total = 1 + len(self.simulations) + len(self.optimizations)
		self.progress_count = 0

		# Deleting all former results
		self.optimizations_results = []
		self.simulations_results = []
		if self.main_window != None:
			self.main_window.DeleteResults()
		self.results_success = [] # Elements : [name, success, message]

		# Computing the model
		self.Simulate()
		self.Optimize()

		if self.main_window != None:
			self.main_window.InsertResults()
			self.progress_dialog.Update(100)
			if self.results_success:
				self.main_window.SuccessDialog(self.results_success)

	def Simulate(self):
		""" Computes all the simulation scenarios.

		Uses self.simulations as input and self.simulations_results as output.
		"""
		for sim in self.simulations:
			corridor = sim[0]
			elasticity = sim[1]
			# If demand is elastic, we calculate the new demand
			if elasticity:
				corridor.demand = self.reference.GetElasticDemand(self.param, corridor)
			self.simulations_results.append(corridor)
			# Updating progress dialog
			self.progress_count += 1
			if self.main_window != None:
				self.progress_dialog.Update(100*self.progress_count/self.progress_total)

	def	Optimize(self):
		""" Computes all the optimization scenarios.

		Uses self.optimizations as input and self.optimizations_results as output.
		"""
		for opt in self.optimizations:
			corridor = opt[0] # Corridor with lines which won't get optimized
			lines = opt[1] # List of lines which will be optimized
			elasticity = opt[2]

			def ObjectiveFunction(x):
				new_corridor = corridor.Duplicate("")

				# The argument x is a vector that contains the optimization variables
				# in their order of appearance in the list "lines".
				c = 0 # A counter to identify the elements of x

				# Construction of the set of lines for the new corridor
				# with the data contained in list lines and vector x.
				for i in range(len(lines)):
					# Frequency
					if lines[i].opt[0] == 0:
						f = lines[i].f
					else:
						f = x[c]
						c += 1

					# Stop spacing
					s = []
					for j in range(corridor.n):
						if lines[i].opt[1][j] == 0:
							s.append(lines[i].s[j])
						else:
							s.append(x[c])
							c += 1

					line = Line(new_corridor,
								lines[i].m,
								f,
								s,
								lines[i].v,
								lines[i].k,
								lines[i].dt,
								lines[i].price,
								lines[i].name,
								lines[i].opt)
					new_corridor.lines.append(line)

				for l in corridor.lines:
					new_corridor.lines.append(l.Duplicate())

				if elasticity:
					new_corridor.demand = self.reference.GetElasticDemand(self.param, new_corridor)

				# Capacity constraints are managed by giving a malus
				# if a line is too crowded.
				malus = 0
				for l in new_corridor.lines:
					max_load = new_corridor.Demand(self.param, l) / new_corridor.TotalDemand() * \
									max(new_corridor.MaxLoadA(), new_corridor.MaxLoadB())
					capacity = l.f * l.k
					if max_load > capacity:
						malus += (max_load - capacity)**2

				if elasticity:
					r = -self.reference.TotalSurplus(self.param, new_corridor) + malus
				else:
					r = new_corridor.TotalCost(self.param) + malus
				return r

			# Defining the optimization program
			x0 = []
			bounds = []
			for i in range(len(lines)):
				# Frequency
				if lines[i].opt[0] == 1:
					x0.append(lines[i].f)
					bounds.append(lines[i].cons[0])
				# Stop spacing
				for j in range(corridor.n):
					if lines[i].opt[1][j] == 1:
						x0.append(lines[i].s[j])
						bounds.append(lines[i].cons[1][j])

			if len(x0) != 0:
				r = minimize(ObjectiveFunction, x0, method="L-BFGS-B", bounds=bounds)
				self.results_success.append([corridor.name, r.success, r.message])

				# Construction of the set of lines for the new corridor
				# with the data contained in list lines and optimized vector x.
				c = 0
				new_corridor = corridor.Duplicate(corridor.name)

				# Frequency
				for i in range(len(lines)):
					if lines[i].opt[0] == 0:
						f = lines[i].f
					else:
						f = r.x[c]
						c += 1
					# Stop spacing
					s = []
					for j in range(corridor.n):
						if lines[i].opt[1][j] == 0:
							s.append(lines[i].s[j])
						else:
							s.append(r.x[c])
							c += 1

					line = Line(corridor,
								lines[i].m,
								f,
								s,
								lines[i].v,
								lines[i].k,
								lines[i].dt,
								lines[i].price,
								lines[i].name,
								lines[i].opt)
					new_corridor.lines.append(line)

				for l in corridor.lines:
					new_corridor.lines.append(l.Duplicate())
				if elasticity:
					new_corridor.demand = self.reference.GetElasticDemand(self.param, new_corridor)

				# Updating progress dialog
				self.progress_count += 1
				if self.main_window != None:
					self.progress_dialog.Update(100*self.progress_count/self.progress_total)

				self.optimizations_results.append(new_corridor)


# -*- coding: utf-8 -*-

"""
For Managing NiFi Templates
"""

from __future__ import absolute_import

import json
import io
from os import access, R_OK, W_OK
from os.path import isfile, dirname
import logging
import six
import xmltodict
from lxml import etree
import nipyapi

log = logging.getLogger(__name__)

__all__ = [
    "list_all_templates", "get_template_by_name", "deploy_template",
    "upload_template", "create_pg_snippet", "create_template",
    "delete_template", "export_template", 'get_template',
    "load_template_from_xml_file_path", "load_template_from_xml_file_stream",
    "load_template_from_xml_string"
]

def get_template_by_name(name):
    """
    DEPRECATED
    Returns a specific template by name, if it exists.

    Note: This function is replaced by get_template

    Args:
        name (str): The Name of the template, exact match required

    Returns:
        (TemplateEntity)

    """
    out = [
        i for i in
        list_all_templates(native=False)
        if
        name == i.template.name
    ]
    if len(out) == 1:
        return out[0]
    return None

def get_template(identifier, identifier_type='name', greedy=False):
    """
    Filters the list of all Templates for a given string in a given field.
    Note that filters are configured in config.py

    Args:
        identifier (str): The string to filter on
        identifier_type (str): The identifier of the field to filter on
        greedy (bool): True for greedy match, False for exact match

    Returns:
        None for no matches, Single Object for unique match,
        list(Objects) for multiple matches

    """
    assert isinstance(identifier, six.string_types)
    assert identifier_type in ['name', 'id']
    with nipyapi.utils.rest_exceptions():
        obj = nipyapi.templates.list_all_templates(native=False)
    if obj:
        return nipyapi.utils.filter_obj(obj, identifier, identifier_type,
                                        greedy)
    return None

def deploy_template(pg_id, template_id, loc_x=0.0, loc_y=0.0):
    """
    Instantiates a given template request in a given process group

    Args:
        pg_id (str): The UUID of the Process Group to deploy into
        template_id (str): The UUID of the Template to deploy. Note that the
            Template must already be uploaded and available to the target
            Process Group
        loc_x (float): The X coordinate to deploy the Template at. Default(0.0)
        loc_y (float): The X coordinate to deploy the Template at. Default(0.0)

    Returns:
        (FlowEntity): The FlowEntity of the Process Group with the deployed
            template

    """
    with nipyapi.utils.rest_exceptions():
        return nipyapi.nifi.ProcessGroupsApi().instantiate_template(
            id=pg_id,
            body=nipyapi.nifi.InstantiateTemplateRequestEntity(
                origin_x=loc_x,
                origin_y=loc_y,
                template_id=template_id
            )
        )

def create_pg_snippet(pg_id):
    """
    Creates a snippet of the targeted process group, and returns the object
    ready to be turned into a Template

    Args:
        pg_id: UUID of the process Group to snippet

    Returns:
        (SnippetEntity): The Snippet Object
    """
    target_pg = nipyapi.canvas.get_process_group(pg_id, 'id')
    new_snippet_req = nipyapi.nifi.SnippetEntity(
        snippet={
            'processGroups': {
                target_pg.id: target_pg.revision
            },
            'parentGroupId':
                target_pg.component.parent_group_id
        }
    )
    with nipyapi.utils.rest_exceptions():
        snippet_resp = nipyapi.nifi.SnippetsApi().create_snippet(
            new_snippet_req
        )
    return snippet_resp

def create_template(pg_id, name, desc=''):
    """
    Creates a Template from a Process Group

    Args:
        pg_id (str): The UUID of the target Process Group
        name (str): The name for the new Template. Must be unique
        desc (optional[str]): The description for the new Template

    Returns:
        (TemplateEntity): The newly created Template

    """
    snippet = create_pg_snippet(pg_id)
    with nipyapi.utils.rest_exceptions():
        new_template = nipyapi.nifi.CreateTemplateRequestEntity(
            name=str(name),
            description=str(desc),
            snippet_id=snippet.snippet.id
        )
        return nipyapi.nifi.ProcessGroupsApi().create_template(
            id=snippet.snippet.parent_group_id,
            body=new_template
        )

def delete_template(t_id):
    """
    Deletes a Template

    Args:
        t_id (str): UUID of the Template to be deleted

    Returns:
        The updated Template object
    """
    with nipyapi.utils.rest_exceptions():
        return nipyapi.nifi.TemplatesApi().remove_template(id=t_id)

def upload_template(pg_id, template_file):
    """
    Uploads a given template xml from from the file system to the given
    Process Group

    Args:
        pg_id (str): The UUID of the Process Group to upload to
        template_file (str): The path including filename to the template file

    Returns:
        (TemplateEntity): The new Template object

    """
    with nipyapi.utils.rest_exceptions():
        this_pg = nipyapi.canvas.get_process_group(pg_id, 'id')
        assert isinstance(this_pg, nipyapi.nifi.ProcessGroupEntity)
    log.info("Called upload_template against endpoint %s with args %s",
             nipyapi.config.nifi_config.api_client.host, locals())
    # Ensure we are receiving a valid file
    assert isfile(template_file) and access(template_file, R_OK), \
        SystemError("File {0} invalid or unreadable".format(template_file))
    # Test for expected Template XML elements
    tree = etree.parse(template_file)
    root_tag = tree.getroot().tag
    if root_tag != 'template':
        raise TypeError(
            "Expected 'template' as xml root element, got {0} instead."
            "Are you sure this is a Template?"
            .format(root_tag)
        )
    t_name = tree.find('name').text
    with nipyapi.utils.rest_exceptions():
        # For some reason identical code that produces the duplicate error
        # in later versions is going through OK for NiFi-1.1.2
        # The error occurs as normal in Postman, so not sure what's going on
        # Will force this error for consistency until it can be investigated
        if nipyapi.templates.get_template(t_name):
            raise ValueError('A template named {} already exists.'
                             .format(t_name))
        nipyapi.nifi.ProcessGroupsApi().upload_template(
            id=this_pg.id,
            template=template_file
        )
        return nipyapi.templates.get_template(
            tree.find('name').text
        )

def export_template(t_id, output='string', file_path=None):
    """
    Exports a given Template as either a string or a file.

    Note that to reimport the Template it must be a file

    Args:
        t_id (str): The UUID of the Template to export
        output (str): 'string' or 'file' to set the export action
        file_path (Optional [str]): The full path including filename to write
            the Template export to

    Returns:
        (str): A String representation of the exported Template XML. Note
            that this may not be utf-8 encoded.

    """
    assert output in ['string', 'file']
    assert file_path is None or isinstance(file_path, six.string_types)
    template = nipyapi.templates.get_template(t_id, 'id')
    assert isinstance(template, nipyapi.nifi.TemplateEntity)
    obj = nipyapi.nifi.TemplatesApi().export_template(t_id)
    assert isinstance(obj, six.string_types)
    assert obj[0] == '<'
    if output == 'string':
        return obj
    if output == 'file':
        assert access(dirname(file_path), W_OK), \
            "File_path {0} is inaccessible or not writable".format(file_path)
        nipyapi.utils.fs_write(obj, file_path)
        return obj

def list_all_templates(native=True):
    """
    Gets a list of all templates on the canvas

    Returns:
        (list[TemplateEntity]): A list of TemplateEntity's
    """
    with nipyapi.utils.rest_exceptions():
        templates = nipyapi.nifi.FlowApi().get_templates()
    if not native:
        if templates:
            return templates.templates
        return None
    return templates

def load_template_from_xml_file_path(file_path):
    """
    Loads a TemplateEntity from an xml file for a
    given path

    Args:
        file_path (str): path to the xml file

    Returns:
        TemplateEntity
    """
    assert isfile(file_path) and access(file_path, R_OK), \
        SystemError("File {0} invalid or unreadable".format(file_path))
    with io.open(file_path, "r", encoding='utf8') as template_file:
        return load_template_from_xml_file_stream(template_file)

def load_template_from_xml_file_stream(file_stream):
    """
    Loads a TemplateEntity from a template xml file

    Args:
        file_stream (io stream): the xml file stream as returned by open

    Returns:
        TemplateEntity
    """
    return load_template_from_xml_string(file_stream.read())

def load_template_from_xml_string(xml_string):
    """
    Loads a TemplateEntity from xml string, as if
    you had read in the xml file to string

    Args:
        xml_string (str): string of xml

    Returns:
        TemplateEntity
    """
    assert isinstance(xml_string, six.string_types)

    json_string = json.dumps(xmltodict.parse(xml_string))
    unset = False
    if nipyapi.config.nifi_config.api_client is None:
        unset = True
        nipyapi.config.nifi_config.api_client = nipyapi.nifi.ApiClient()

    template_entity = nipyapi.utils.load(json_string,
                                         ('nifi', 'TemplateEntity'))
    if unset:
        nipyapi.config.nifi_config.api_client = None
    return template_entity


L = 0
while L == 0:
    num = input('numero: ')
    if num.isnumeric() and num.isnumeric() > 0:
        num = int(num)
        for i in range(1, num+1):
            if (num%i) == 0:
                print(i)
        L = 1
    else:
        print('digite numeros positivos')


from tensorflow.keras.layers import Dense, Layer, Dropout
import tensorflow as tf

class Image_Encoder(Layer):
    def __init__(self, embedding_dim, dropout=0.1, activiation_type='relu'):
        super(Image_Encoder, self).__init__()
        self.dense = Dense(embedding_dim,
                           activation=activiation_type
                           )
        self.dropout1 = Dropout(dropout)

    def call(self, inputs, training=True):
        # (batch_size, context vector) -> (batch_size, embedding_dim)
        output = self.dense(inputs)
        # (batch_size, embedding_dim) -> (batch_size, 1, embedding_dim)
        output = tf.expand_dims(output, 1)

        output = self.dropout1(output, training=training)

        return output


# -*- coding: utf-8 -*-

__license__   = 'GPL v3'

import os, re

try:
    from qt.core import (Qt, QVBoxLayout, QLabel, QComboBox, QApplication, QSizePolicy,
                  QGroupBox, QButtonGroup, QRadioButton, QDialogButtonBox, QHBoxLayout,
                  QProgressDialog, QSize, QDialog, QCheckBox, QSpinBox, QScrollArea, QWidget,
                  QPushButton)
except ImportError:
    from PyQt5.Qt import (Qt, QVBoxLayout, QLabel, QComboBox, QApplication, QSizePolicy,
                          QGroupBox, QButtonGroup, QRadioButton, QDialogButtonBox, QHBoxLayout,
                          QProgressDialog, QSize, QDialog, QCheckBox, QSpinBox, QScrollArea, QWidget,
                          QPushButton)

from calibre.utils.config import config_dir

from calibre.gui2.tweak_book.widgets import Dialog

'''
ConversionDialog
The conversion dialog asks/displays the following:
    -Which direction of conversion is desired (i.e. Traditional->Simplified, Simplified->Traditional, or Traditional->Traditional)
    -If converting from Traditional, what country style is the source of the text (Hong Kong, Mainland, or Taiwan)
    -If converting to Traditional, what country style is desired (Hong Kong, Mainland, or Taiwan)
    -What text should be converted (the currently entire book, current file or selected text)

The chosen settings are saved between program starts.

Note: This code is based on the Calibre plugin Diap's Editing Toolbag
'''

class ConversionDialog(Dialog):
    def __init__(self, parent, prefs, punc_dict, default_omitted_puncuation, force_entire_book=False):
        self.prefs = prefs
        self.parent = parent
        self.force_entire_book = force_entire_book
        Dialog.__init__(self, _('Chinese Conversion'), 'chinese_conversion_dialog', parent)
        self.punctuation_dialog = PuncuationDialog(self.parent, self.prefs, punc_dict, default_omitted_puncuation)

    def setup_ui(self):

##        print('Dialog preferences')
##        print(self.prefs['input_source'])           # 0=whole book, 1=current file, 2=selected text
##
##        print(self.prefs['conversion_type'])        # 0=No change, 1=trad->simp, 2=simp->trad, 3=trad->trad
##        print(self.prefs['input_locale'])           # 0=Mainland, 1=Hong Kong, 2=Taiwan 3=Japan
##        print(self.prefs['output_locale'])          # 0=Mainland, 1=Hong Kong, 2=Taiwan 3=Japan
##        print(self.prefs['use_target_phrases'])     # True/False
##
##        print(self.prefs['quotation_type'])         # 0=No change, 1=Western, 2=East Asian
##
##        print(self.prefs['output_orientation'])     # 0=No change, 1=Horizontal, 2=Vertical
##
##        print(self.prefs['punc_omits'])             # Horizontal mark string in horizontal/vertical
##                                                    # dictionary pairs that is NOT to be used. No
##                                                    # space between marks in string.

        self.quote_for_trad_target = _("Update quotes: “ ”,‘ ’ -> 「 」,『 』")
        self.quote_for_simp_target = _("Update quotes: 「 」,『 』 -> “ ”,‘ ’")

        # Create layout for entire dialog
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        #Create a scroll area for the top part of the dialog
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)

        # Create widget for all the contents of the dialog except the OK and Cancel buttons
        self.scrollContentWidget = QWidget(self.scrollArea)
        self.scrollArea.setWidget(self.scrollContentWidget)
        widgetLayout = QVBoxLayout(self.scrollContentWidget)

        # Add scrollArea to dialog
        layout.addWidget(self.scrollArea)

        self.operation_group_box = QGroupBox(_('Conversion Direction'))
        widgetLayout.addWidget(self.operation_group_box)
        operation_group_box_layout = QVBoxLayout()
        self.operation_group_box.setLayout(operation_group_box_layout)

        self.operation_group=QButtonGroup(self)
        self.no_conversion_button = QRadioButton(_('No Conversion'))
        self.operation_group.addButton(self.no_conversion_button)
        self.trad_to_simp_button = QRadioButton(_('Traditional to Simplified'))
        self.operation_group.addButton(self.trad_to_simp_button)
        self.simp_to_trad_button = QRadioButton(_('Simplified to Traditional'))
        self.operation_group.addButton(self.simp_to_trad_button)
        self.trad_to_trad_button = QRadioButton(_('Traditional to Traditional'))
        self.operation_group.addButton(self.trad_to_trad_button)
        operation_group_box_layout.addWidget(self.no_conversion_button)
        operation_group_box_layout.addWidget(self.trad_to_simp_button)
        operation_group_box_layout.addWidget(self.simp_to_trad_button)
        operation_group_box_layout.addWidget(self.trad_to_trad_button)
        self.operation_group.buttonClicked.connect(self.on_op_button_clicked)

        self.style_group_box = QGroupBox(_('Language Styles'))
        widgetLayout.addWidget(self.style_group_box)
        style_group_box_layout = QVBoxLayout()
        self.style_group_box.setLayout(style_group_box_layout)

        input_layout = QHBoxLayout()
        style_group_box_layout.addLayout(input_layout)
        self.input_region_label = QLabel(_('Input:'))
        input_layout.addWidget(self.input_region_label)
        self.input_combo = QComboBox()
        input_layout.addWidget(self.input_combo)
        self.input_combo.addItems([_('Mainland'), _('Hong Kong'), _('Taiwan'), _('Japan')])
        self.input_combo.setToolTip(_('Select the origin region of the input'))
        self.input_combo.currentIndexChanged.connect(self.update_gui)

        output_layout = QHBoxLayout()
        style_group_box_layout.addLayout(output_layout)
        self.output_region_label = QLabel(_('Output:'))
        output_layout.addWidget(self.output_region_label)
        self.output_combo = QComboBox()
        output_layout.addWidget(self.output_combo)
        self.output_combo.addItems([_('Mainland'), _('Hong Kong'), _('Taiwan'), _('Japan')])
        self.output_combo.setToolTip(_('Select the desired region of the output'))
        self.output_combo.currentIndexChanged.connect(self.update_gui)

        self.use_target_phrases = QCheckBox(_('Use output target phrases if possible'))
        self.use_target_phrases.setToolTip(_('Check to allow region specific word replacements if available'))
        style_group_box_layout.addWidget(self.use_target_phrases)
        self.use_target_phrases.stateChanged.connect(self.update_gui)

        self.quotation_group_box = QGroupBox(_('Quotation Marks'))
        widgetLayout.addWidget(self.quotation_group_box)
        quotation_group_box_layout = QVBoxLayout()
        self.quotation_group_box.setLayout(quotation_group_box_layout)

        quotation_group=QButtonGroup(self)
        self.quotation_no_conversion_button = QRadioButton(_('No Conversion'))
        quotation_group.addButton(self.quotation_no_conversion_button)
        self.quotation_trad_to_simp_button = QRadioButton(self.quote_for_simp_target)
        quotation_group.addButton(self.quotation_trad_to_simp_button)
        self.quotation_simp_to_trad_button = QRadioButton(self.quote_for_trad_target)
        quotation_group.addButton(self.quotation_simp_to_trad_button)
        quotation_group_box_layout.addWidget(self.quotation_no_conversion_button)
        quotation_group_box_layout.addWidget(self.quotation_simp_to_trad_button)
        quotation_group_box_layout.addWidget(self.quotation_trad_to_simp_button)
        self.quotation_no_conversion_button.toggled.connect(self.update_gui)
        self.quotation_trad_to_simp_button.toggled.connect(self.update_gui)
        self.quotation_simp_to_trad_button.toggled.connect(self.update_gui)

        self.other_group_box = QGroupBox(_('Other Changes'))
        widgetLayout.addWidget(self.other_group_box)
        other_group_box_layout = QVBoxLayout()
        self.other_group_box.setLayout(other_group_box_layout)

        text_dir_layout = QHBoxLayout()
        other_group_box_layout.addLayout(text_dir_layout)
        direction_label = QLabel(_('Text Direction:'))
        text_dir_layout.addWidget(direction_label)
        self.text_dir_combo = QComboBox()
        text_dir_layout.addWidget(self.text_dir_combo)
        self.text_dir_combo.addItems([_('No Conversion'), _('Horizontal'), _('Vertical')])
        self.text_dir_combo.setToolTip(_('Select the desired text orientation'))
        self.text_dir_combo.currentIndexChanged.connect(self.direction_changed)

        punctuation_layout = QHBoxLayout()
        other_group_box_layout.addLayout(punctuation_layout)
        self.update_punctuation = QCheckBox(_('Update punctuation'))
        punctuation_layout.addWidget(self.update_punctuation)
        self.update_punctuation.stateChanged.connect(self.update_gui)
        self.punc_settings_btn = QPushButton()
        self.punc_settings_btn.setText("Settings...")

        punctuation_layout.addWidget(self.punc_settings_btn)
        self.punc_settings_btn.clicked.connect(self.punc_settings_btn_clicked)
        self.punctuation_dialog = None

        source_group=QButtonGroup(self)
        self.book_source_button = QRadioButton(_('Entire eBook'))
        self.file_source_button = QRadioButton(_('Current File'))
        self.seltext_source_button = QRadioButton(_('Selected Text in Current File'))
        self.seltext_source_button.setToolTip(_('“Selected Text” is bracketed by <!--PI_SELTEXT_START--> and <!--PI_SELTEXT_END-->'))
        source_group.addButton(self.book_source_button)
        source_group.addButton(self.file_source_button)
        source_group.addButton(self.seltext_source_button)
        self.source_group_box = QGroupBox(_('Source'))
        if not self.force_entire_book:
            widgetLayout.addWidget(self.source_group_box)
            source_group_box_layout = QVBoxLayout()
            self.source_group_box.setLayout(source_group_box_layout)
            source_group_box_layout.addWidget(self.book_source_button)
            source_group_box_layout.addWidget(self.file_source_button)
            source_group_box_layout.addWidget(self.seltext_source_button)

        layout.addSpacing(10)
        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)

        self.button_box.accepted.connect(self._ok_clicked)
        self.button_box.rejected.connect(self._reject_clicked)
        layout.addWidget(self.button_box)

        self.set_to_preferences()
        self.update_gui()

    def on_op_button_clicked(self, btn):
        self.block_signals(True)
        if btn == self.no_conversion_button:
            self.input_combo.setCurrentIndex(-1)  # blank out the entry
            self.output_combo.setCurrentIndex(-1) # blank out the entry
        else:
            self.input_combo.setCurrentIndex(0)   # mainland
            self.output_combo.setCurrentIndex(0)  # mainland
        self.block_signals(False)
        self.update_gui()

    def block_signals(self, state):
        # block or unblock the signals generated by these objects to avoid recursive calls
        self.input_combo.blockSignals(state)
        self.output_combo.blockSignals(state)
        self.no_conversion_button.blockSignals(state)
        self.trad_to_simp_button.blockSignals(state)
        self.simp_to_trad_button.blockSignals(state)
        self.trad_to_trad_button.blockSignals(state)
        self.file_source_button.blockSignals(state)
        self.seltext_source_button.blockSignals(state)
        self.book_source_button.blockSignals(state)
        self.quotation_trad_to_simp_button.blockSignals(state)
        self.quotation_simp_to_trad_button.blockSignals(state)
        self.quotation_no_conversion_button.blockSignals(state)
        self.text_dir_combo.blockSignals(state)
        self.update_punctuation.blockSignals(state)

    def set_to_preferences(self):
        # set the gui values to match those in the preferences
        self.block_signals(True)

        self.input_combo.setCurrentIndex(self.prefs['input_locale'])
        self.output_combo.setCurrentIndex(self.prefs['output_locale'])

        if self.prefs['conversion_type'] == 0:
            self.no_conversion_button.setChecked(True)
        elif self.prefs['conversion_type'] == 1:
            self.trad_to_simp_button.setChecked(True)
        elif self.prefs['conversion_type'] == 2:
            self.simp_to_trad_button.setChecked(True)
        else:
            self.trad_to_trad_button.setChecked(True)

        if not self.force_entire_book:
            if self.prefs['input_source'] == 1:
                self.file_source_button.setChecked(True)
            elif self.prefs['input_source'] == 2:
                self.seltext_source_button.setChecked(True)
            else:
                self.book_source_button.setChecked(True)
        else:
            self.book_source_button.setChecked(True)
            self.file_source_button.setChecked(False)
            self.seltext_source_button.setChecked(False)

        if self.prefs['quotation_type'] == 1:
            self.quotation_trad_to_simp_button.setChecked(True)
        elif self.prefs['quotation_type'] == 2:
            self.quotation_simp_to_trad_button.setChecked(True)
        else:
            self.quotation_no_conversion_button.setChecked(True)

        self.text_dir_combo.setCurrentIndex(self.prefs['output_orientation'])
        if self.text_dir_combo.currentIndex() == 0:
            self.update_punctuation.setChecked(False)
        else:
            self.update_punctuation.setChecked(self.prefs['update_punctuation'])

        self.block_signals(False)

    def direction_changed(self):
        # callback when text direction changes
        self.update_punctuation.blockSignals(True)
        self.punc_settings_btn.blockSignals(True)

        if self.text_dir_combo.currentIndex() == 0:    # no direction change
            self.update_punctuation.setChecked(False)
            self.update_punctuation.setEnabled(False)
            self.punc_settings_btn.setEnabled(False)

        else:
            self.update_punctuation.setChecked(True)
            self.update_punctuation.setEnabled(True)
            self.punc_settings_btn.setEnabled(True)

        self.punc_settings_btn.blockSignals(False)
        self.update_punctuation.blockSignals(False)

    def update_gui(self):
        # callback to update other gui items when one changes
        if self.no_conversion_button.isChecked():
            self.input_combo.setEnabled(False)
            self.output_combo.setEnabled(False)
            self.input_combo.setToolTip(_('Valid input/output combinations:\nNot Applicable'))
            self.output_combo.setToolTip(_('Valid input/output combinations:\nNot Applicable'))
            self.use_target_phrases.setEnabled(False)
            self.output_region_label.setEnabled(False)
            self.input_region_label.setEnabled(False)
            self.style_group_box.setEnabled(False)

        elif self.trad_to_simp_button.isChecked():
            self.input_combo.setEnabled(True)
            self.output_combo.setEnabled(True)
            self.use_target_phrases.setEnabled(True)
            self.output_region_label.setEnabled(True)
            self.input_region_label.setEnabled(True)
            self.input_combo.setToolTip(_('Valid input/output combinations:\nHong Kong/Mainland\nMainland/Mainland\nTaiwan/Mainland\nMainland/Japan'))
            self.output_combo.setToolTip(_('Valid input/output combinations:\nHong Kong/Mainland\nMainland/Mainland\nTaiwan/Mainland\nMainland/Japan'))
            self.style_group_box.setEnabled(True)

        elif self.simp_to_trad_button.isChecked():
            self.input_combo.setEnabled(True)
            self.output_combo.setEnabled(True)
            self.input_combo.setToolTip(_('Valid input/output combinations:\nMainland/Hong Kong\nMainland/Mainland\nMainland/Taiwan\nJapan/Mainland'))
            self.output_combo.setToolTip(_('Valid input/output combinations:\nMainland/Hong Kong\nMainland/Mainland\nMainland/Taiwan\nJapan/Mainland'))
            self.use_target_phrases.setEnabled(True)
            self.output_region_label.setEnabled(True)
            self.input_region_label.setEnabled(True)
            self.style_group_box.setEnabled(True)

        elif self.trad_to_trad_button.isChecked():
            self.input_combo.setEnabled(True)
            self.output_combo.setEnabled(True)
            self.input_combo.setToolTip(_('Valid input/output combinations:\nHong Kong/Mainland\nMainland/Hong Kong\nTaiwan/Mainland\nMainland/Taiwan\nMainland/Mainland\nHong Kong/Hong Kong\nTaiwan/Taiwan'))
            self.output_combo.setToolTip(_('Valid input/output combinations:\nHong Kong/Mainland\nMainland/Hong Kong\nTaiwan/Mainland\nMainland/Taiwan\nMainland/Mainland\nHong Kong/Hong Kong\nTaiwan/Taiwan'))
            self.use_target_phrases.setEnabled(True)
            self.output_region_label.setEnabled(True)
            self.input_region_label.setEnabled(True)
            self.style_group_box.setEnabled(True)

        if self.text_dir_combo.currentIndex() == 0:
            self.update_punctuation.blockSignals(True)
            self.update_punctuation.setChecked(False)
            self.update_punctuation.setEnabled(False)
            self.update_punctuation.blockSignals(False)
        else:
            self.update_punctuation.blockSignals(True)
            self.update_punctuation.setEnabled(True)
            self.update_punctuation.blockSignals(False)

        if self.update_punctuation.isChecked():
            self.punc_settings_btn.setEnabled(True)
        else:
            self.punc_settings_btn.setEnabled(False)

    def _ok_clicked(self):
        # save current settings into preferences and close dialog
        self.savePrefs()
        self.accept()

    def _reject_clicked(self):
        # restore initial settings and close dialog
        self.set_to_preferences()
        self.update_gui()
        self.reject()

    def punc_settings_btn_clicked(self):
        # open the punctuation dialog
        self.punctuation_dialog.exec_()

    def savePrefs(self):
        # save the current settings into the preferences
        self.prefs['input_locale'] = self.input_combo.currentIndex()
        self.prefs['output_locale'] = self.output_combo.currentIndex()

        if self.trad_to_simp_button.isChecked():
            self.prefs['conversion_type'] = 1
        elif self.simp_to_trad_button.isChecked():
            self.prefs['conversion_type'] = 2
        elif self.trad_to_trad_button.isChecked():
            self.prefs['conversion_type'] = 3
        else:
            self.prefs['conversion_type'] = 0

        if self.file_source_button.isChecked():
            self.prefs['input_source'] = 1
        elif self.seltext_source_button.isChecked():
            self.prefs['input_source'] = 2
        else:
            self.prefs['input_source'] = 0

        self.prefs['use_target_phrases'] = self.use_target_phrases.isChecked()

        if self.quotation_trad_to_simp_button.isChecked():
            self.prefs['quotation_type'] = 1
        elif self.quotation_simp_to_trad_button.isChecked():
            self.prefs['quotation_type'] = 2
        else:
            self.prefs['quotation_type'] = 0

        self.prefs['output_orientation'] = self.text_dir_combo.currentIndex()
        self.prefs['update_punctuation'] = self.update_punctuation.isChecked()

    def getRegex(self):
        # getter for the punctuation conversion regular expression object
        return self.punctuation_dialog.getRegex()

class PuncuationDialog(Dialog):

    def __init__(self, parent, prefs, punc_dict, default_omitted_puncuation):
        self.prefs = prefs
        self.punc_dict = punc_dict
        self.default_omitted_puncuation = default_omitted_puncuation
        self.parent = parent
        self.puncSettings = set()
        Dialog.__init__(self, _('Chinese Punctuation'), 'chinese_conversion_punctuation_dialog', parent)

    def setup_ui(self):
        self.punc_setting = {}
        self.checkbox_dict = {}

        # Create layout for entire dialog
        layout = QVBoxLayout(self)
        self.setLayout(layout)

        #Create a scroll area for the top part of the dialog
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)

        # Create widget for all the contents of the dialog except the buttons
        self.scrollContentWidget = QWidget(self.scrollArea)
        self.scrollArea.setWidget(self.scrollContentWidget)
        widgetLayout = QVBoxLayout(self.scrollContentWidget)

        # Add scrollArea to dialog
        layout.addWidget(self.scrollArea)

        self.punctuation_group_box = QGroupBox(_('Punctuation'))
        widgetLayout.addWidget(self.punctuation_group_box)

        self.punctuation_group_box_layout = QVBoxLayout()
        self.punctuation_group_box.setLayout(self.punctuation_group_box_layout)

        for x in self.punc_dict:
            str = x + " <-> " + self.punc_dict[x]
            widget = QCheckBox(str)
            self.checkbox_dict[x] = widget
            self.punctuation_group_box_layout.addWidget(widget)
            if x in self.prefs['punc_omits']:
                widget.setChecked(False)
            else:
                widget.setChecked(True)

        self.button_box_settings = QDialogButtonBox()
        self.clearall_button = self.button_box_settings.addButton("Clear All", QDialogButtonBox.ActionRole)
        self.setall_button = self.button_box_settings.addButton("Set All", QDialogButtonBox.ActionRole)
        self.default_button = self.button_box_settings.addButton("Default", QDialogButtonBox.ActionRole)
        self.button_box_settings.clicked.connect(self._action_clicked)
        layout.addWidget(self.button_box_settings)

        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.button_box.accepted.connect(self._ok_clicked)
        self.button_box.rejected.connect(self._reject_clicked)
        layout.addWidget(self.button_box)

    def savePrefs(self):
        setting = ""
        for x in self.puncSettings:
            setting = setting + x
        self.prefs['punc_omits'] = setting

    def _ok_clicked(self):
        self.puncSettings.clear()
        # Loop through and update set of unchecked items
        for x in self.checkbox_dict.keys():
            if not self.checkbox_dict[x].isChecked():
                self.puncSettings.add(x)
        self.savePrefs()
        self.accept()

    def _reject_clicked(self):
        # Restore back to values when first opened
        # This will be the same as the preferences
        ## loop through all checkboxes
        for x in self.checkbox_dict.keys():
            self.checkbox_dict[x].blockSignals(True)
            if x in self.prefs['punc_omits']:
                self.checkbox_dict[x].setChecked(False)
            else:
                self.checkbox_dict[x].setChecked(True)
            self.checkbox_dict[x].blockSignals(False)
        self.reject()

    def _action_clicked(self, button):
        ## Find out which button is pressed
        if button is self.clearall_button:
            ## loop through all checkboxes and unset
            for x in self.checkbox_dict.values():
                x.blockSignals(True)
                x.setChecked(False)
                x.blockSignals(False)

        elif button is self.setall_button:
            ## loop through all checkboxes and set
            for x in self.checkbox_dict.values():
                x.blockSignals(True)
                x.setChecked(True)
                x.blockSignals(False)

        elif button is self.default_button:
            ## loop through all checkboxes
            for x in self.checkbox_dict.keys():
                self.checkbox_dict[x].blockSignals(True)
                if x in self.default_omitted_puncuation:
                    self.checkbox_dict[x].setChecked(False)
                else:
                    self.checkbox_dict[x].setChecked(True)
                self.checkbox_dict[x].blockSignals(False)


# -*- coding: utf-8 -*-

from typing import Dict, Any

import os
import pkg_resources

from bag.design import Module

yaml_file = pkg_resources.resource_filename(__name__, os.path.join('netlist_info',
                                                                   'res_term_diff.yaml'))

# noinspection PyPep8Naming
class bag_analog_ec__res_term_diff(Module):
    """Module for library bag_analog_ec cell res_term_diff.

    Fill in high level description here.
    """

    def __init__(self, bag_config, parent=None, prj=None, **kwargs):
        Module.__init__(self, bag_config, yaml_file, parent=parent, prj=prj, **kwargs)

    @classmethod
    def get_params_info(cls):
        # type: () -> Dict[str, str]
        return dict(
            l='unit resistor length, in meters.',
            w='unit resistor width, in meters.',
            intent='resistor type.',
            nser='number of resistors in series in a branch.',
            npar='number of branches in parallel.',
            ndum='number of dummy resistors.',
            sub_name='substrate name.  Empty string to disable'
        )

    @classmethod
    def get_default_param_values(cls):
        # type: () -> Dict[str, Any]
        return dict(
            sub_name='VSS',
        )

    def design(self, l, w, intent, nser, npar, ndum, sub_name):
        """To be overridden by subclasses to design this module.

        This method should fill in values for all parameters in
        self.parameters.  To design instances of this module, you can
        call their design() method or any other ways you coded.

        To modify schematic structure, call:

        rename_pin()
        delete_instance()
        replace_instance_master()
        reconnect_instance_terminal()
        restore_instance()
        array_instance()
        """
        if ndum < 0 or npar <= 0 or nser <= 0:
            raise ValueError('Illegal values of ndum, npar, or nser.')

        # handle substrate pin
        if not sub_name:
            # delete substrate pin
            self.remove_pin('VSS')
        elif sub_name != 'VSS':
            self.rename_pin('VSS', sub_name)

        # design dummy
        if ndum == 0:
            self.delete_instance('RDUM')
        else:
            self.instances['RDUM'].design(w=w, l=l, intent=intent)
            if ndum > 1:
                if sub_name and sub_name != 'VSS':
                    term_list = [dict(BULK=sub_name)]
                else:
                    term_list = None
                self.array_instance('RDUM', ['RDUM<%d:0>' % (ndum - 1)], term_list=term_list)
            elif sub_name and sub_name != 'VSS':
                self.reconnect_instance_terminal('RDUM', 'BULK', sub_name)

        # design main resistors
        for inst_name, in_name, mid_name in (('RP', 'inp', 'midp'), ('RN', 'inn', 'midn')):
            self.instances[inst_name].design(w=w, l=l, intent=intent)
            if nser == 1:
                if npar == 1:
                    if sub_name and sub_name != 'VSS':
                        self.reconnect_instance_terminal(inst_name, 'BULK', sub_name)
                else:
                    if sub_name and sub_name != 'VSS':
                        term_list = [dict(BULK=sub_name)]
                    else:
                        term_list = None
                    self.array_instance(inst_name, ['%s<%d:0>' % (inst_name, npar - 1)], term_list=term_list)
            else:
                name_list = []
                term_list = []
                for par_idx in range(npar):
                    if nser == 2:
                        pos_name = '%s,%s%d' % (in_name, mid_name, par_idx)
                        neg_name = '%s%d,incm' % (mid_name, par_idx)
                    else:
                        pos_name = '%s,%s%d<%d:0>' % (in_name, mid_name, par_idx, nser - 2)
                        neg_name = '%s%d<%d:0>,incm' % (mid_name, par_idx, nser - 2)
                    if sub_name and sub_name != 'VSS':
                        term_dict = dict(PLUS=pos_name, MINUS=neg_name, BULK=sub_name)
                    else:
                        term_dict = dict(PLUS=pos_name, MINUS=neg_name)
                    name_list.append('%s%d<%d:0>' % (inst_name, par_idx, nser - 1))
                    term_list.append(term_dict)

                self.array_instance(inst_name, name_list, term_list=term_list)


import logging

from microserviceutil.migrations.migrate_mongo_pro_to_dev import MigrateMongoProToDev

class Migrations:
    try:
        JOBS = {
            "mongo_pro_to_dev": MigrateMongoProToDev
        }

        def __init__(self, args):
            # check the number of arguments
            if len(args) >= 2:
                self.job_name = args[0]
                self.params = args[1:]

                if self.job_name in self.JOBS:
                    job = self.JOBS[self.job_name](self.params)
                    job.run_job()
    except Exception as error:
        logging.error(error)


def miFun(email):
    return len(email)

fd = open("Temas de Clase/Archivos/mbox-short.txt", "r")

# para hacer el ejercicio con listas y que no se repitan
setEmailListas = []
for linea in fd:
    if linea.startswith("To:"):
        setEmailListas.append(linea.split()[1])

fd.close()

cl = len(setEmailListas)
print("Cantidad de correos de origen distintos:", cl)

# for email in sorted(setEmail, reverse=False, key=lambda x:len(x)):
#     print(email)

for email in sorted(setEmailListas, reverse=False, key=miFun):
    print(f"{email} enviado [ok]")


import serial
import socket

arduino= serial.Serial('/dev/ttyACM0' , 9600)
while True:
    a=arduino.readline()
    s=socket.socket()
    s.connect(("169.254.139.148", 8888))
    s.send(a)
    s.close()
arduino.close()

Codi Electrònica/Codi Referència/Codi Raspberry/cliente.py