Snippets Collections
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

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