move dirs
This commit is contained in:
11
code/Python/README.md
Normal file
11
code/Python/README.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# Python
|
||||
|
||||
## std
|
||||
- [`os_env.py`](os_env.py) - Получение значений переменных окружения
|
||||
|
||||
## Stuff
|
||||
- [`irc-bot.py`](irc-bot.py) - Простой IRC бот на Python 3
|
||||
|
||||
## Tests
|
||||
|
||||
- [`picalc.py`](picalc.py) - Вычисления числа Пи
|
||||
26
code/Python/Tk/select-file-folder.py
Normal file
26
code/Python/Tk/select-file-folder.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from tkinter import filedialog
|
||||
from tkinter import *
|
||||
|
||||
root = Tk()
|
||||
root.withdraw()
|
||||
|
||||
def select_file():
|
||||
file_selected = filedialog.askopenfilename(
|
||||
title='Open a file',
|
||||
initialdir='/',
|
||||
filetypes=(
|
||||
('Text files', '*.txt'),
|
||||
('All files', '*.*')
|
||||
)
|
||||
)
|
||||
|
||||
print(file_selected)
|
||||
|
||||
def select_folder():
|
||||
folder_selected = filedialog.askdirectory()
|
||||
|
||||
print(folder_selected)
|
||||
|
||||
if __name__ == '__main__':
|
||||
select_file()
|
||||
select_folder()
|
||||
18
code/Python/array_methods.py
Normal file
18
code/Python/array_methods.py
Normal file
@@ -0,0 +1,18 @@
|
||||
array.typecode # TypeCode символ, использованный при создании массива.
|
||||
array.itemsize # размер в байтах одного элемента в массиве.
|
||||
array.append(х) # добавление элемента в конец массива.
|
||||
array.buffer_info() # кортеж (ячейка памяти, длина). Полезно для низкоуровневых операций.
|
||||
array.byteswap() # изменить порядок следования байтов в каждом элементе массива. Полезно при чтении данных из файла, написанного на машине с другим порядком байтов.
|
||||
array.count(х) # возвращает количество вхождений х в массив.
|
||||
array.extend(iter) # добавление элементов из объекта в массив.
|
||||
array.frombytes(b) # делает массив array из массива байт. Количество байт должно быть кратно размеру одного элемента в массиве.
|
||||
array.fromfile(F, N) # читает N элементов из файла и добавляет их в конец массива. Файл должен быть открыт на бинарное чтение. Если доступно меньше N элементов, генерируется исключение EOFError , но элементы, которые были доступны, добавляются в массив.
|
||||
array.fromlist(список) # добавление элементов из списка.
|
||||
array.index(х) # номер первого вхождения x в массив.
|
||||
array.insert(n, х) # включить новый пункт со значением х в массиве перед номером n. Отрицательные значения рассматриваются относительно конца массива.
|
||||
array.pop(i) # удаляет i-ый элемент из массива и возвращает его. По умолчанию удаляется последний элемент.
|
||||
array.remove(х) # удалить первое вхождение х из массива.
|
||||
array.reverse() # обратный порядок элементов в массиве.
|
||||
array.tobytes() # преобразование к байтам.
|
||||
array.tofile(f) # запись массива в открытый файл.
|
||||
array.tolist() # преобразование массива в список.
|
||||
29
code/Python/irc-bot.py
Executable file
29
code/Python/irc-bot.py
Executable file
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import socket
|
||||
import time
|
||||
|
||||
server = 'iiiypuk.me'
|
||||
channel = '#admin'
|
||||
botnick = 'porteus'
|
||||
|
||||
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
print('Connecting to: ' + server)
|
||||
|
||||
irc.connect((server, 6667))
|
||||
irc.send(str.encode('USER ' + botnick + ' localhost localhost :This is a bot!\n'))
|
||||
irc.send(str.encode('NICK ' + botnick + '\n'))
|
||||
irc.send(str.encode('JOIN '+ channel +'\n'))
|
||||
|
||||
while True:
|
||||
text = irc.recv(2040)
|
||||
print(text)
|
||||
|
||||
if text.find(str.encode('PING')) != -1:
|
||||
irc.send(str.encode('PONG ' + str(text.split()[1]) + '\r\n'))
|
||||
|
||||
# !time - return current timestamp
|
||||
if text.find(str.encode('!time')) != -1:
|
||||
ts = time.time()
|
||||
irc.send(str.encode('PRIVMSG #admin :{}\r\n'.format(int(ts))))
|
||||
|
||||
2
code/Python/opencv/.gitignore
vendored
Normal file
2
code/Python/opencv/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
*.png
|
||||
haarcascade_*.xml
|
||||
21
code/Python/opencv/capture-image.py
Executable file
21
code/Python/opencv/capture-image.py
Executable file
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import cv2
|
||||
|
||||
cam_port = 2
|
||||
cam = cv2.VideoCapture(cam_port)
|
||||
|
||||
while True:
|
||||
result, image = cam.read()
|
||||
|
||||
cv2.imshow('Camera', image)
|
||||
|
||||
if cv2.waitKey(1) & 0xFF == ord('s'):
|
||||
cv2.imwrite('capture.png', image)
|
||||
|
||||
if cv2.waitKey(1) & 0xFF == ord('q'):
|
||||
break
|
||||
|
||||
cam.release()
|
||||
cv2.destroyWindow('Camera')
|
||||
cv2.destroyAllWindows()
|
||||
34
code/Python/opencv/face-detect-realtime.py
Executable file
34
code/Python/opencv/face-detect-realtime.py
Executable file
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import cv2
|
||||
|
||||
|
||||
def face_detect(capture):
|
||||
gray_image = cv2.cvtColor(capture, cv2.COLOR_BGR2GRAY)
|
||||
faces = face_classifier.detectMultiScale(
|
||||
gray_image, scaleFactor=1.1, minNeighbors=5, minSize=(40, 40)
|
||||
)
|
||||
|
||||
for x, y, w, h in faces:
|
||||
cv2.rectangle(capture, (x, y), (x + w, y + h), (0, 255, 0), 2)
|
||||
|
||||
return faces
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
camera = cv2.VideoCapture(2)
|
||||
face_classifier = cv2.CascadeClassifier(
|
||||
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
|
||||
)
|
||||
|
||||
while True:
|
||||
if cv2.waitKey(1) & 0xFF == ord('q'):
|
||||
break
|
||||
|
||||
result, image = camera.read()
|
||||
|
||||
faces = face_detect(image)
|
||||
cv2.imshow('Face Realtime Detector', image)
|
||||
|
||||
camera.release()
|
||||
cv2.destroyAllWindows()
|
||||
24
code/Python/opencv/face-detect.py
Executable file
24
code/Python/opencv/face-detect.py
Executable file
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import cv2
|
||||
|
||||
img = cv2.imread('face.png')
|
||||
|
||||
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||
|
||||
face_classifier = cv2.CascadeClassifier(
|
||||
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
|
||||
)
|
||||
|
||||
face = face_classifier.detectMultiScale(
|
||||
gray_image, scaleFactor=1.1, minNeighbors=5, minSize=(40, 40)
|
||||
)
|
||||
|
||||
for x, y, w, h in face:
|
||||
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
|
||||
|
||||
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
||||
|
||||
cv2.imshow('Face Detector', img_rgb)
|
||||
cv2.waitKey(0)
|
||||
cv2.destroyAllWindows()
|
||||
7
code/Python/opencv/open-image.py
Normal file
7
code/Python/opencv/open-image.py
Normal file
@@ -0,0 +1,7 @@
|
||||
import cv2
|
||||
|
||||
img = cv2.imread('image.png')
|
||||
|
||||
cv2.imshow('Images from Files', img)
|
||||
cv2.waitKey(0)
|
||||
cv2.destroyAllWindows()
|
||||
4
code/Python/opencv/pyproject.toml
Normal file
4
code/Python/opencv/pyproject.toml
Normal file
@@ -0,0 +1,4 @@
|
||||
[tool.black]
|
||||
skip-string-normalization = true
|
||||
pycodestyle = true
|
||||
line-length = 100
|
||||
2
code/Python/opencv/requirements.txt
Normal file
2
code/Python/opencv/requirements.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
numpy==1.25.2
|
||||
opencv-python==4.8.0.76
|
||||
2
code/Python/os_env.py
Normal file
2
code/Python/os_env.py
Normal file
@@ -0,0 +1,2 @@
|
||||
import os
|
||||
print(os.environ['HOME'])
|
||||
40
code/Python/picalc.py
Normal file
40
code/Python/picalc.py
Normal file
@@ -0,0 +1,40 @@
|
||||
# Source: https://stackoverflow.com/questions/9004789/1000-digits-of-pi-in-python
|
||||
|
||||
import time
|
||||
|
||||
|
||||
def make_pi():
|
||||
q, r, t, k, m, x = 1, 0, 1, 1, 3, 3
|
||||
for j in range(10000):
|
||||
if 4 * q + r - t < m * t:
|
||||
yield m
|
||||
q, r, t, k, m, x = (
|
||||
10 * q,
|
||||
10 * (r - m * t),
|
||||
t,
|
||||
k,
|
||||
(10 * (3 * q + r)) // t - 10 * m,
|
||||
x,
|
||||
)
|
||||
else:
|
||||
q, r, t, k, m, x = (
|
||||
q * k,
|
||||
(2 * q + r) * x,
|
||||
t * x,
|
||||
k + 1,
|
||||
(q * (7 * k + 2) + r * x) // (t * x),
|
||||
x + 2,
|
||||
)
|
||||
|
||||
|
||||
t1 = time.time()
|
||||
|
||||
pi_array = []
|
||||
for i in make_pi():
|
||||
pi_array.append(str(i))
|
||||
|
||||
pi_array = pi_array[:1] + ['.'] + pi_array[1:]
|
||||
pi_array_str = ''.join(pi_array)
|
||||
|
||||
print('PI:', pi_array_str)
|
||||
print('dT:', time.time() - t1)
|
||||
22
code/Python/unixsockets/client.py
Normal file
22
code/Python/unixsockets/client.py
Normal file
@@ -0,0 +1,22 @@
|
||||
import socket
|
||||
import os
|
||||
|
||||
# Set the path for the Unix socket
|
||||
socket_path = '/tmp/myapp.sock'
|
||||
|
||||
# Create the Unix socket client
|
||||
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
|
||||
# Connect to the server
|
||||
client.connect(socket_path)
|
||||
|
||||
# Send a message to the server
|
||||
message = 'Hello from the client!'
|
||||
client.sendall(message.encode())
|
||||
|
||||
# Receive a response from the server
|
||||
response = client.recv(1024)
|
||||
print(f'Received response: {response.decode()}')
|
||||
|
||||
# Close the connection
|
||||
client.close()
|
||||
49
code/Python/unixsockets/server.py
Normal file
49
code/Python/unixsockets/server.py
Normal file
@@ -0,0 +1,49 @@
|
||||
import socket
|
||||
import sys
|
||||
import os
|
||||
import base64
|
||||
|
||||
def prep():
|
||||
srv_sock = '/tmp/myapp.sock'
|
||||
try:
|
||||
os.unlink(srv_sock)
|
||||
except:
|
||||
if os.path.exists(srv_sock):
|
||||
raise
|
||||
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
try:
|
||||
print('Setting up server socket on %s\n' % srv_sock)
|
||||
sock.bind(srv_sock)
|
||||
sock.listen(1)
|
||||
print('Success, listening on unix domain socket %s\n' % srv_sock)
|
||||
return(sock)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return False
|
||||
|
||||
def main():
|
||||
sock = prep()
|
||||
if not sock:
|
||||
return False
|
||||
while True:
|
||||
connection, client_address = sock.accept()
|
||||
try:
|
||||
buffer = ''
|
||||
rcvd_bytes = 0
|
||||
while True:
|
||||
data = connection.recv(1024)
|
||||
rcvd_bytes = rcvd_bytes + len(data)
|
||||
if not data:
|
||||
print('Finished receiving data\n')
|
||||
break
|
||||
buffer = buffer + data.decode()
|
||||
buffer = buffer[:-1]
|
||||
# print(base64.b64encode(buffer.rstrip('\x00')))
|
||||
print('Total bytes received bytes: %s\n' % len(buffer))
|
||||
finally:
|
||||
print('Closing the connection\n')
|
||||
connection.close()
|
||||
print('Connection closed\n')
|
||||
|
||||
if __name__=="__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user