Snippets Collections
from cryptography.fernet import Fernet
import sqlite3

# Generate key to use it
#print(Fernet.generate_key())

key = b'rMqQ4gNSsvkubQnn9CmW25PTFDwNlQPUp7YN4qDVSts='
cipher_suite = Fernet(key)

db_name = 'mydb.db'

conn = sqlite3.connect(db_name)
cursor = conn.cursor()

# create a table
cursor.execute('create table if not exists items (name STRING, price INTEGER)')

def add_item(name, price):
    name = cipher_suite.encrypt(name.encode())
    price = cipher_suite.encrypt(str(price).encode())

    cursor.execute('insert into items (name, price) values (?, ?)', (name, price))

    conn.commit()

add_item('test', 50)

def get_items():
    results = cursor.execute('select * from items').fetchall()
    for item in results:
        name = cipher_suite.decrypt(item[0]).decode()
        price = cipher_suite.decrypt(item[1]).decode()
        print(name, price)

get_items()
import pendulum

def calc_expire_date(prodact_date, expiry):
    prodact_date = pendulum.parse('{:0>2}-{:0>2}-{:0>2}'.format(*prodact_date))
    target_date = pendulum.duration(**expiry) + prodact_date
    days_to_expire = (target_date.date() - pendulum.now().date()).days
    print(f'Product vaild until : {target_date} You have {days_to_expire} days')


calc_expire_date((2024, 11, 15), expiry = {'days': 15})
import tkinter as tk

root = tk.Tk()
root.geometry('200x200')

def close_window():
    root.destroy()

close_bt = tk.Button(root, text = 'close', command = close_window)
close_bt.pack()

def disable_close_bt():
    return

root.protocol('WM_DELETE_WINDOW', disable_close_bt)
root.mainloop()

pattrens = [
    '123456',
    '6665522',
    '887799',
    '123456',
    '6665522',
    '1111222',
    '123456',
    '6665522',
    '887799',
    '123456',
    '111111'
]


def classify_pattrens(pattrens_list):
    labels = {k : [] for k in pattrens_list}
    for pattren in pattrens_list:
        labels[pattren].append(pattren)

    return labels

print(classify_pattrens(pattrens))
from yattag import Doc

import webbrowser

doc, tag, text = Doc().tagtext()

doc.asis('<!DOCTYPE html>')

with tag('html') as html:
    with tag('head') as head:
        with tag('title') as title:
            text('This is test web page')
    with tag('body') as body:
        with tag('h2') as h2:
            text('This is h2')

page = doc.getvalue()

f = open('page.html', 'w')
f.write(page)
f.close()

webbrowser.open('page.html')
import time
import pygame
import pendulum

def alarm():
    pygame.mixer.init()
    pygame.mixer.music.load('alarm.mp3')
    pygame.mixer.music.play()

    while pygame.mixer.music.get_busy():
        time.sleep(1)


def set_alarm(target_time):
    while True:
        dt = pendulum.now()
        current_time = dt.strftime('%I:%M:%S %p')
        print(current_time, target_time)
        time.sleep(1)
        if current_time == target_time:
            break


target_time = '07:09:00 PM'
set_alarm(target_time)
alarm()
import pendulum

current_date = pendulum.now().date()
uploaded_date = pendulum.date(2018, 8, 1)

diff_days = current_date.diff(uploaded_date).in_days()

print(current_date.subtract(days = diff_days).diff_for_humans()) # 6 years ago
import pendulum

try:
    print(pendulum.parse('{:0>2}-{:0>2}-{:0>2}'.format(2024, 9, 21)))
except Exception as e:
    print(e)
from pynput.keyboard import Listener

def on_press(key):
    print(str(key))


with Listener(on_press = on_press) as l:
    l.join()
import random

number = random.randint(1, 6)

guess = 0

while guess != number:
    guess = int(input('Number : '))
    if guess == number:
        print('You won ;)')
# main.py

from fastapi import FastAPI
from routes.tasks import tasks_route

app = FastAPI()

app.include_router(tasks_route)

-------------------------

# routes > tasks.py

from fastapi import APIRouter

tasks_route = APIRouter()

@tasks_route.get('/tasks')
def get_tasks():
  return {'tasks': []}
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from uuid import UUID, uuid4

class Task(BaseModel):
    id : UUID = Field(default_factory = uuid4)
    name : str
    description : str
    done: bool = False

tasks_db = []

def find_task(_id):
    for idx, task in enumerate(tasks_db):
        if task.id == _id:
            return idx, task

app = FastAPI()

@app.get('/')
def index():
    return {'msg': 'hello, world'}

# Add new task to database
@app.put('/add_task')
def add_task(task : Task):
    tasks_db.append(task)

    return {'msg': 'Task created', 'task': task}

# Get all tasks from database
@app.get('/tasks')
def get_tasks():
    return {'tasks': tasks_db}

# Get one task by id
@app.get('/task/{_id}')
def get_task(_id: UUID):
    task = find_task(_id)[1]
    if task:
        return {'task': task}
    
    
    return HTTPException(status_code = 404, detail = 'This task is not found :(')

# Update task by id
@app.put('/update_task/{_id}')
def update_task(_id : UUID, updatedtask : Task):
    task = find_task(_id)
    if task:
        task_idx = task[0]
        tasks_db[task_idx] = updatedtask
        return {'msg': 'Task updated', 'task': updatedtask}
    
    return HTTPException(status_code = 404, detail = 'This task is not found :(')

# Delete task
@app.delete('/delete_task/{_id}')
def delete_task(_id : UUID):
    task = find_task(_id)[1]
    tasks_db.remove(task)

    return {'msg': f'task {task.name} deleted ;)'}
import pendulum

items = [
    {'name': 'Milk', 'expire_date': '2024-09-15'},
    {'name': 'Bread', 'expire_date': '2024-09-18'},
    {'name': 'Yogurt', 'expire_date': '2024-09-25'},
]

def check_expire_date(items):
    for item in items:
        expire_date = pendulum.parse(item.get('expire_date'))
        cuurent_date = pendulum.now()

        if expire_date <= cuurent_date:
            print(f' {item.get('name')} expired')


check_expire_date(items=items)
from faker import Faker
from SmileyDB3 import SmileyDB3
from random import randint

import webbrowser

f = Faker()
db = SmileyDB3('mydb.db')

users = db.table('users')

for i in range(20):
    users.Insert(data={
        'name': f.name(),
        'email': f.email(),
        'age': randint(20, 40)
    })

users.convert().to_html('out.html')

webbrowser.open('out.html')
import sqlite3

db = sqlite3.connect('mydb.db')
cur = db.cursor()

# create users table
cur.execute('CREATE TABLE IF NOT EXISTS users (name str, image blob)')

# insert new user in users table
cur.execute(
    'INSERT INTO users (name, image) VALUES (?, ?)', 
    ('USER-123', open('smile.png', 'rb').read())
)

db.commit()
import customtkinter as ctk

root = ctk.CTk()
root.geometry('200x200')

led_on = '#4cff66'
led_off = '#1e3c22'

led = ctk.CTkLabel(root, text='\t', width=50, bg_color=led_off)
led.place(x = 80, y = 80)

def off_on():
    if led._bg_color == led_off:
        led.configure(bg_color = led_on)
        led.update()
        return
    
    if led._bg_color == led_on:
        led.configure(bg_color = led_off)
        led.update()
        return


bt = ctk.CTkButton(root, text = 'OFF/ON', command=off_on, width=70)
bt.place(x = 80, y = 150)

root.mainloop()
from faker import Faker
from random import randint

f = Faker()

data = {'name': 'Barry Long', 'email': 'tammy28@example.com', 'age': 20}

# Generate data from this 
def Generate_like_this(data : dict, f : Faker):
    result = {}

    funcs = {
        'name': f.name,
        'email': f.email
    }

    for k in data:

        if k in funcs:
            result[k] = funcs[k]()

        if isinstance(data[k], int):
            result[k] = randint(1, data[k])
        
    
    return result

print(Generate_like_this(data = data, f = Faker()))
from pydantic import BaseModel, Field
from uuid import UUID, uuid4

class item(BaseModel):
    name : str
    price : float
    item_id : UUID = Field(default_factory = uuid4)


items = []

for i in range(3):
    items.append(item(name = 'test', price = 20))


print(items)
# Analyzing Clicks A Python Function for Extracting Weekly Stats

users_data = [
    {'day': 0, 'clicks': 100}, {'day': 1, 'clicks': 10},
    {'day': 2, 'clicks': 150}, {'day': 3, 'clicks': 1000},
    {'day': 4, 'clicks': 100}, {'day': 5, 'clicks': 190},
    {'day': 6, 'clicks': 150}, {'day': 7, 'clicks': 1000}
]

def get_stats(day):
    # -1 to start from day 0 because day in date is 1
    return users_data[day - 1: day + 7]

print(get_stats(1))
import sqlite3

# Connect to the database
con = sqlite3.connect('database.db')

# Create a cursor object
cursor = con.cursor()

# Define the data to be inserted as a list of tuples
data = [
    ('John Doe', 'johndoe@example.com'),
    ('Jane Smith', 'janesmith@example.com'),
    ('Mike Johnson', 'mikejohnson@example.com')
]

# Use executemany() to insert the data into the "users" table
cursor.executemany("INSERT INTO users (name, email) VALUES (?, ?)", data)

# Commit the changes
con.commit()
import sqlite3

# Connect to the database
con = sqlite3.connect('database.db')

# Create a cursor object
cursor = con.cursor()

# Update user name based on ID
user_id = 2
new_name = "John Doe"

cursor.execute("UPDATE users SET name = ? WHERE id = ?", (new_name, user_id))

# Commit the changes
con.commit()
import sqlite3

# Connect to the database
con = sqlite3.connect('database.db')

# Create a cursor object
cursor = con.cursor()

# Fetch all data from the "users" table
cursor.execute("SELECT * FROM users")
data = cursor.fetchall()

# Print the retrieved data
for row in data:
    print(row)
import sqlite3

# Connect to the database
con = sqlite3.connect('database.db')

# Create a cursor object
cursor = con.cursor()

# Delete user based on ID
user_id = 123

cursor.execute("DELETE FROM users WHERE id = ?", (user_id,))

# Commit the changes
con.commit()
import sqlite3

# Connect to the database
con = sqlite3.connect('database.db')

# Create a cursor object
cursor = con.cursor()

# Fetch data based on the ID filter
cursor.execute("SELECT * FROM users WHERE id = ?", (123,))
data = cursor.fetchall()

# Print the retrieved data
for row in data:
    print(row)

import sqlite3

# Connect to the database
con = sqlite3.connect('database.db')

# Create a cursor object
cursor = con.cursor()

# Create a cursor object
cursor = con.cursor()

# Insert a new user
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("John Doe", "johndoe@example.com"))

# Commit the changes
con.commit()

from docx import Document
import pandas as pd

df = pd.read_csv('out.csv').to_dict()
word_doc = Document()

table_head = list(df.keys())

table_head_len = len(table_head)
tables_rows_len = len(df['name'])

# create tabel
table = word_doc.add_table(cols = table_head_len, rows = tables_rows_len)

# add the first row in the table
for i in range(table_head_len):
    table.cell(row_idx = 0, col_idx = i).text = table_head[i]


# add rows for name col
for i in range(1, tables_rows_len):
    table.cell(row_idx = i, col_idx = 0).text = df['name'][i]


# add rows for age col
for i in range(1, tables_rows_len):
    table.cell(row_idx = i, col_idx = 1).text = str(df['age'][i])


word_doc.save('word_doc.docx')
myData = [
    {'a': 1},
    {'a': 1},
    {'b': 1},
    {'b': 1},
    {'c': 1},
    {'c': 1},
]

# Use a set to track seen tuples of items (key-value pairs as tuples)
seen = set()
unique_data = []

for d in myData:
    # Convert each dictionary to a tuple of its items, then convert to frozenset
    # to make it hashable and suitable for use in a set
    dict_items = frozenset(d.items())
    
    # Check if the frozenset of items is already in the set
    if dict_items not in seen:
        # If not seen, add to both set and result list
        seen.add(dict_items)
        unique_data.append(d)

print(unique_data)
import pandas as pd

dict_data = {
    'users': ['user_123', 'user_abc'],
    'tasks': ['test1', 'test2']
}

df = pd.DataFrame.from_dict(dict_data)
df.to_html('out.html')
import pandas as pd

dict_data = {
    'users': ['user_123', 'user_abc'],
    'tasks': ['test1', 'test2']
}

df = pd.DataFrame.from_dict(dict_data)
df.to_pickle('out.pkl')

# read pkl file
print(pd.read_pickle('out.pkl'))
import pandas as pd

# All arrays must be of the same length
dict_data = {
    'users': [{'name': 'test'}, {'name': '123'}], 
    'tasks': [{'name': 'test123'}, {'name': '45456'}]
}

df = pd.DataFrame.from_dict(dict_data)
df.to_json('out.json', indent = 4)
from random import randint
from faker import Faker
from datetime import date
import pandas as pd

f = Faker()

s_date = date(2018, 5, 1)
e_date = date(2018, 5, 30)

dict_data = {'date': [], 'email': [], 'money': []}

for _date in pd.date_range(start = s_date, end = e_date):
    dict_data['date'].append(_date)
    dict_data['email'].append(f.email())
    dict_data['money'].append(randint(1, 100) * 0.99)

df = pd.DataFrame.from_dict(dict_data)
df.to_csv('out.csv', index = 0)
from human_readable.files import file_size
import os

print(file_size(value = os.stat('test.txt').st_size))
import pause

def test():
    print('done')

def run_after(func, amount_of_time):
    pause.milliseconds(amount_of_time)
    func()

run_after(test, 10000)
from textblob import TextBlob

text = 'how are you'

blob = TextBlob(text)

if blob.polarity > 0:
    print('Positive')
elif blob.polarity < 0:
    print('Negative')
else:
    print('Neutral')
users_db = [
    {'id': '2313', 'coins': 50},
    {'id': '8213', 'coins': 20},
    {'id': '9989', 'coins': 0},
    {'id': '4654', 'coins': 1},
    {'id': '7897', 'coins': 3},
    {'id': '9898', 'coins': 60}
]

users_db.sort(key = lambda user: user['coins'])
print(users_db)
users_db = [
    {'id': 'ax123', 'money': 5},
    {'id': 'z5541', 'money': 0}
]

def get_user_by_id(user_id):
    for user in users_db:
        if user['id'] == user_id:
            return user
        
def send_money(from_id, to_id, amount):
    from_user_a = get_user_by_id(from_id)
    to_user_b = get_user_by_id(to_id)

    if from_user_a and to_user_b:
        if from_user_a['money'] >= amount:
            from_user_a['money'] -= amount
            to_user_b['money'] += amount
        else:
            print('the amount of money is large than your balance')
        
    

send_money('ax123', 'z5541', 2)
send_money('ax123', 'z5541', 2)
print(users_db)
from faker import Faker
from random import randint, choice

f = Faker()
payment_methods = ['paypal', 'bitcoin']

for _ in range(20):
    money = randint(1, 100) * 0.99
    pyment_method = choice(payment_methods)
    user_email = "*****" + f.email()[6:]
    print(f'{money}$ --- {user_email} --- {pyment_method}')
# Quotes API
from fastapi import FastAPI, Request
from slowapi.util import get_ipaddr
from slowapi.errors import RateLimitExceeded
from slowapi import Limiter, _rate_limit_exceeded_handler

import json

def get_quotes():
    return json.load(open('quotes.json', 'r'))

app = FastAPI()
limiter = Limiter(key_func = get_ipaddr)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@app.get('/')
@limiter.limit('10/minute')
def home(request: Request):
    return {'msg': 'Hello, World'}


@app.get('/quotes')
@limiter.limit('10/minute')
def quote(request: Request):
    return get_quotes()
from fastapi import FastAPI


db = [
 {'api_key': '437af89f-38ba-44f1-9eda-924f370193d4',
  'tokens': 3,
  'user_id': '6ddf9779-4be7-449c-a70d-51e81c19dd0b'},
 {'api_key': '48762b59-e968-459e-b28d-50e7a1ad37a4', 
  'tokens': 3,
  'user_id': 'daf36850-68ab-40fc-86af-e6093b6797dd'},
 {'api_key': 'dabbd875-acbd-4b98-a47f-a526075d41b4', 
  'tokens': 3,
  'user_id': '5750957f-a246-4290-a35e-2dec83bcfcea'},
 {'api_key': '604d5fe2-f7ce-4560-8137-eeae32091738',
  'tokens': 3,
  'user_id': '2d4ac462-b118-48d7-897e-163c2e8327aa'},
 {'api_key': '8540cbef-de3e-4cbd-83bc-f66297a7f407',
  'tokens': 3,
  'user_id': 'bb435e7e-b5da-4a8c-b860-e43a8e765f67'}
]



app = FastAPI()

def update_tokens_for_user(user_id, api_key):
    for user in db:
        if user['user_id'] == user_id and user['api_key'] == api_key:
            tokens = user['tokens']
            if tokens > 0:
                tokens = tokens - 1
                user['tokens'] = tokens

                return {'tokens': tokens}
            
            else:
                return {'tokens': tokens, 'msg': 'you need to get more tokens'}


@app.get('/test')
def test(user_id : str, api_key: str):
    result = update_tokens_for_user(user_id, api_key)
    if result:
        return result
    else:
        return {'msg': 'api key or user id is not found'}
import pprint

data = {'email': 'test@test.com', 'password': '123'}

print(data, type(data))

# convert dict to str
result = pprint.pformat(data)

print(result, type(result))
from peewee import Model, SqliteDatabase, CharField, IntegerField, UUIDField
from uuid import uuid4
from faker import Faker
from random import randint

fake = Faker()

db = SqliteDatabase('mydb.db')

class User(Model):
    name = CharField(max_length = 25)
    email = CharField(max_length = 25)
    age = IntegerField()
    password = CharField(max_length = 100)
    user_id = UUIDField(primary_key = True, default = uuid4)

    class Meta:
        database = db


db.connect()
db.create_tables([User])

for i in range(20):
    new_user = User.create(**{
        'name': fake.name(),
        'email': fake.email(),
        'age': randint(12, 45),
        'password': fake.password()
    })

    new_user.save()

db.commit()
myLists = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

def to_one_list(myLists):
    myList = []
    for _list in myLists:
        for l in _list:
            myList.append(l)

    return myList

print(to_one_list(myLists = myLists))
from random import randint
from PIL import Image
from os import listdir, path, mkdir
from uuid import uuid4
import moviepy.editor as mp

def generate_video(folder):
    if not path.exists(folder):
        mkdir(folder)

    # generate video frames
    for i in range(20):
        img = Image.new(
            mode = 'RGB',
            size = (500, 250),
            color = (0, 0, 0)
        )

        for x in range(img.size[0]):
            for y in range(img.size[1]):
                r, g, b = randint(0, 255), randint(0, 255), randint(0, 255)
                img.putpixel((x, y), value = (r, g, b))

        img.save(f'{folder}/{i}.png')
    
    # create video
    images = [f'{folder}/{img}' for img in listdir(folder)]
    clips = [mp.ImageClip(img).set_duration(0.08) for img in images]
    video = mp.concatenate_videoclips(clips, method = 'compose')
    video.to_videofile(f'{str(uuid4())}.mp4', fps = 24)


generate_video('test')
from uuid import uuid4
import random

extintions = ['zip', 'exe', 'txt', 'py', 'mp4', 'mp3', 'png']

def generate_files(files_len, folder):
    for i in range(files_len):
        file_name = f'{folder}/{str(uuid4())}.{random.choice(extintions)}'
        file_size = (1024 * 1024) * random.randint(1, 10)
        file = open(file_name, 'wb')
        file.write(b'\b' * file_size)
        file.close()

generate_files(20, 'test')
from fastapi import FastAPI, Request
from slowapi.util import get_remote_address
import uvicorn


app = FastAPI()

@app.get('/')
def home(req : Request):
    return {'ip': get_remote_address(request=req)}
from peewee import SqliteDatabase, Model, UUIDField, CharField, IntegerField
from uuid import uuid4

db = SqliteDatabase('mydb.db')

# Create user Model
class User(Model):
    userId = UUIDField(primary_key = True, default = uuid4)
    name = CharField(max_length = 10)
    age = IntegerField()

    class Meta:
        database = db

# Connect to db
db.connect()
db.create_tables([User])
db.commit()

# Add new user to database
user = User.create(name = 'user123', age = 20)
user.save()

# Get all users
for user in User.select():
    print(user.name, user.userId)
from selenium import webdriver
from selenium.webdriver.common.by import By
from dotenv import load_dotenv

# https://pypi.org/project/2captcha-python/
from twocaptcha import TwoCaptcha


import time
import sys
import os

# https://github.com/2captcha/2captcha-python

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))


url = 'https://accounts.hcaptcha.com/demo'

driver = webdriver.Chrome()

driver.get(url=url)

time.sleep(2)

site_key = driver.find_element(
    by = By.XPATH, 
    value = '//*[@id="hcaptcha-demo"]').get_attribute('data-sitekey')




load_dotenv()

# create account in 2captcha from here : https://bit.ly/3MkkuPJ
# make deposit at least 3$
# https://2captcha.com/pay

# create env file or you can put your API key direct in TwoCaptcha function


api_key = os.getenv('APIKEY_2CAPTCHA')


api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY')

solver = TwoCaptcha(api_key)

try:
    result = solver.hcaptcha(
        sitekey=site_key,
        url=url,
    )

    code = result['code']
    print(code)

    

    driver.execute_script(f"document.getElementsByName('h-captcha-response')[0].innerHTML = '{code}'")
    
    # submit
    driver.find_element(by = By.ID, value = 'hcaptcha-demo-submit').click()
    

except Exception as e:
    sys.exit(e)



input()
# Create account from here : http://adfoc.us/831311103357835
# Go to https://adfoc.us/tools/api 
# http://adfoc.us/api/?key={}&url={}


import requests, os
from dotenv import load_dotenv

load_dotenv()

url = ''
api_key = os.getenv('api_key')

endpoint = f'http://adfoc.us/api/?key={api_key}&url={url}'

res = requests.get(url = endpoint)
print(res.text)
from PIL import Image, ImageDraw, ImageOps

def convert_image_to_circle(image_path):
    my_image = Image.open(image_path)
    # create mask 
    mask = Image.new('L', my_image.size)
    draw = ImageDraw.Draw(mask)
    # draw white circle
    draw.ellipse((0, 0) + mask.size, fill = 255)

    # create output image
    output = ImageOps.fit(my_image, mask.size, centering=(0.5, 0.5))
    output.putalpha(mask)
    output.save('out.png')



convert_image_to_circle('test.png')
import mido
import random

def generate_notes(notes_len):
    notes = []
    for i in range(notes_len):
        notes.append(random.randint(0, 127))

    return notes



def create_midi_file(notes):
    output_midi = mido.MidiFile()
    # create a track 
    track = mido.MidiTrack()
    # add track
    output_midi.tracks.append(track)

    # write notes
    for note in notes:
        track.append(mido.Message('note_on', note = note, velocity=64, time = 120))
        track.append(mido.Message('note_off', note = note, velocity=64, time = 120))

    # write midi file
    output_midi.save('out.mid')

notes = generate_notes(100)
create_midi_file(notes)
import tkinter as tk


root = tk.Tk()
root.attributes('-fullscreen', True)

# this is very important
def close_fullscreen():
    root.attributes('-fullscreen', False)

# add bt to close fullscreen mode this is very important
close_bt = tk.Button(root, text='Close full screen mode', command=close_fullscreen)
close_bt.pack(fill=tk.BOTH)

root.mainloop()
def generate_file(file_size_mb, file_name):
    file_size = file_size_mb * 1024 * 1024
    with open(file_name, 'wb') as f:
        f.write(b'\b' * file_size)


generate_file(file_size_mb=2, file_name='test.test')
from tqdm import tqdm
from time import sleep

text = """
This is text 123
""" * 100

# repeate text 100 times

with open('out.txt', 'w') as f:
    bar = tqdm(total=len(text), unit='B', unit_scale=True)
    for c in text:
        f.write(c)
        bar.update(1)
        sleep(0.0005)

from datetime import date
from pandas import date_range
from uuid import uuid4
from random import randint


s_date = date(2019, 1, 1)
e_date = date(2019, 1, 30)

stats = {}

for d in date_range(start=s_date, end=e_date):
    d = str(d.date())
    stats[d] = {
        'user_id': str(uuid4()),
        'clicks': randint(0, 1000)
    }


print(stats)
import pyaudio
import numpy as np
import pyqtgraph as pg

# Initialize PyAudio
pa = pyaudio.PyAudio()

# Set up audio stream
stream = pa.open(
    format=pyaudio.paInt16,
    channels=1,
    rate=44100,
    input=True,
    frames_per_buffer=1024
)

# Set up PyQTGraph
app = pg.mkQApp()
win = pg.GraphicsLayoutWidget()
win.show()
plot = win.addPlot(title='Real-time Audio Waveform')
curve = plot.plot()

# Function to update the plot
def update():
    wf_data = np.frombuffer(stream.read(1024), dtype=np.int16)
    curve.setData(wf_data)

# Start the audio stream
timer = pg.QtCore.QTimer()
timer.timeout.connect(update)
timer.start(50)

# Start Qt event loop
pg.mkQApp().exec()

import customtkinter as ctk
import threading


run = True

def task():
    while run:
        print('Task running...')
        if not run:
            print('Task closed')
            return
        
def start_task():
    global run
    run = True
    threading.Thread(target=task).start()


def close_task():
    global run
    run = False

root = ctk.CTk()
root.geometry('500x60')

ctk.CTkButton(root, text='start task', command=start_task).place(x = 20, y = 10)
ctk.CTkButton(root, text='close task', command=close_task).place(x = 220, y = 10)

root.mainloop()
import time
from functools import wraps

def rate_limiter(max_calls, period=60):
    def decorator(func):
        timestamps = []

        @wraps(func)
        def wrapper(*args, **kwargs):
            nonlocal timestamps
            current_time = time.time()
            # Remove timestamps outside of the current period
            timestamps = [t for t in timestamps if current_time - t < period]
            if len(timestamps) < max_calls:
                timestamps.append(current_time)
                return func(*args, **kwargs)
            else:
                print(f"Rate limit exceeded. Try again in {int(period - (current_time - timestamps[0]))} seconds.")
        return wrapper
    return decorator

# Example usage:
@rate_limiter(max_calls=5)
def my_function():
    # Your function implementation here
    print("Function is called")

# Test the rate limiter
for i in range(10):
    my_function()
    time.sleep(1)  # Sleep for demonstration purposes
import requests

bad_links = []

def check_link(link):
    res = requests.get(link)
    if res.status_code == 200:
        print('working')
    else:
        print('not working')
        bad_links.append(link)

links = [
    'http://127.0.0.1:8000/',
    'http://127.0.0.1:8000/test1',
    'http://127.0.0.1:8000/test2'
]


for link in links:
    check_link(link)
import requests
from tqdm import tqdm

url = 'https://player.vimeo.com/external/121142413.sd.mp4?s=1b8ed80f9ce01d9ecf4af3eb12c879e00f29850f&profile_id=112&oauth2_token_id=57447761'

res = requests.get(url, stream = True)
total_size = int(res.headers.get('content-length', 0))
progress_bar = tqdm(total = total_size, unit = 'iB', unit_scale = True)

with open('video.mp4', 'wb') as file:
    for data in res.iter_content(1024):
        file.write(data)
        progress_bar.update(len(data))


progress_bar.close()
def every(arr, every_num):
    new_list = []
    for i in range(0, len(arr), every_num):
        new_list.append(arr[i: i + every_num])

    return new_list


mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = every(mylist, 4)
print(result)
star

Sun Dec 01 2024 22:53:40 GMT+0000 (Coordinated Universal Time)

##python #coding #python
star

Sun Nov 24 2024 16:01:45 GMT+0000 (Coordinated Universal Time)

##python #coding #python #tkinter #ttk
star

Fri Oct 25 2024 19:39:51 GMT+0000 (Coordinated Universal Time)

##python #coding #python #algorithm
star

Wed Oct 23 2024 19:52:13 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming
star

Fri Sep 20 2024 17:17:06 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #error
star

Fri Sep 20 2024 16:02:56 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #game
star

Wed Sep 18 2024 17:46:12 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #game
star

Mon Sep 16 2024 09:29:46 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #todolist
star

Mon Sep 16 2024 05:56:02 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming
star

Wed Aug 14 2024 13:55:13 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #tkinter
star

Wed Jun 19 2024 08:47:26 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #html
star

Wed Jun 19 2024 08:45:33 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #pickle
star

Wed Jun 19 2024 08:27:37 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #json
star

Sun Jun 16 2024 19:07:29 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #time
star

Sun Jun 16 2024 14:31:23 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming
star

Sun Jun 16 2024 14:15:11 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming
star

Sun Jun 16 2024 13:01:54 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming
star

Sun May 12 2024 17:56:50 GMT+0000 (Coordinated Universal Time)

##python #coding #python #api #programming #file
star

Sat May 11 2024 07:23:11 GMT+0000 (Coordinated Universal Time)

##python #coding #python #api #programming
star

Fri Apr 26 2024 08:42:02 GMT+0000 (Coordinated Universal Time)

##python #coding #python #earn #shortlink #api #api
star

Sat Apr 20 2024 10:35:22 GMT+0000 (Coordinated Universal Time)

##python #coding #python #image #pil #pillow
star

Sat Apr 13 2024 19:42:26 GMT+0000 (Coordinated Universal Time)

##python #coding #python #midi #music #audio
star

Sat Apr 13 2024 08:57:39 GMT+0000 (Coordinated Universal Time)

##python #coding #tkinter #gui #python
star

Sun Apr 07 2024 20:22:01 GMT+0000 (Coordinated Universal Time)

##python #coding #limiter #decorators
star

Wed Nov 29 2023 15:30:22 GMT+0000 (Coordinated Universal Time) https://dev.to/amr2018/a-simple-python-script-to-check-for-broken-links-1b35

##python #coding
star

Wed Nov 29 2023 15:29:23 GMT+0000 (Coordinated Universal Time) https://dev.to/amr2018/how-to-create-a-progress-bar-for-downloading-files-in-python-2a8b

##python #coding #progressbar
star

Wed Nov 29 2023 13:53:44 GMT+0000 (Coordinated Universal Time)

##python #coding
star

Tue Mar 15 2022 04:13:20 GMT+0000 (Coordinated Universal Time) https://www.digitalocean.com/community/conceptual_articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design

#standards #php #coding

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension