Змея / Говнокод #28531 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
key_base_len = random.randint(30,61)
key_base = bytearray(key_base_len)
for i in range(key_base_len):
    key_base[i] = random.randint(0,255)

key = bytearray(8)
key[0] = chip_uid_chksum ^ key_base[ 4 * (key_base_len // 7)]
key[1] = chip_uid_chksum ^ key_base[      key_base_len // 5 ]
key[2] = chip_uid_chksum ^ key_base[      key_base_len // 7 ]
key[3] = chip_uid_chksum ^ key_base[ 6 * (key_base_len // 7)]
key[4] = chip_uid_chksum ^ key_base[ 3 * (key_base_len // 7)]
key[5] = chip_uid_chksum ^ key_base[ 3 * (key_base_len // 5)]
key[6] = chip_uid_chksum ^ key_base[ 5 * (key_base_len // 7)]
key[7] = (chip_id + key[0]) & 0xff

return key, key_base

Китайцы и криптография.

Сначала программатор отдаёт контроллеру key_base, а затем юзает key чтобы ксорить с ним заливаемую прошивку.

bormand bormand, (Updated )

Комментарии (41, +41)

Змея / Говнокод #28524 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
def __get_column_names(table: str) -> tuple:
    try:
        with conn:
            cur.execute("SELECT name FROM PRAGMA_TABLE_INFO(?)", (table,))
            column_names = cur.fetchall()
    except Exception as excpt:
        print(excpt)
    column_names = tuple(i[0] for i in column_names)
    return column_names


def db_register_user(user_data: types.User):
    """
    SQL запрос для внесения данных о пользователе

    Args:
        user_data: telebot User объект, содержащий словарь с параметрами пользователя
    """
    user_data = user_data.to_dict()
    column_names: tuple = __get_column_names('Users')
    user_values = tuple(user_data.get(key) for key in column_names if key in user_data)
    try:
        with conn:
            query = 'INSERT INTO Users cn'.replace('cn', str(column_names))+' VALUES (?,?,?,?,0,3)'
            parameters = (*user_values,)
            conn.execute(query, parameters)
    except Exception as excpt:
        print(excpt)
    conn.close()

На сколько в такой ситуации .format не безопасен? Идея в том, чтобы не объебошится программисту в коде введя неверное значение колонки. Для этого имена колонок берутся из самой базы (есть мысль ещё и типы брать). Есть вариант реализации получше? Спасибо

rockkley94 rockkley94, (Updated )

Комментарии (22, +22)

Змея / Говнокод #28503 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
#!/usr/bin/env python3

import sys
import socket


def main():
    if len(sys.argv) != 2:
        print("Программа ожидает 1 аргумент: доменное имя хоста")
        return 1

    # Input.

    host_name = sys.argv[1]
    print(f"Доменное имя хоста: {host_name}")

    host_ip = socket.gethostbyname(host_name)
    print(f"IP-адрес хоста: {host_ip}")

    host_port = 33433
    timeout = 2 # Seconds.

    receiving_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    receiving_socket.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
    receiving_socket.settimeout(timeout)
    receiving_socket.bind(("", host_port))

    sending_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sending_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    received_ip = None
    current_hop = 1
    max_hop = 100
    while received_ip != host_ip and current_hop < max_hop:
        sending_socket.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, current_hop)
        sus = True
        for i in range(7):
            try:
                sending_socket.sendto(bytes(str(current_hop), 'utf-8'), (host_ip, host_port))
                data, addr = receiving_socket.recvfrom(1)
                if addr:
                    received_ip = addr[0]
                    print(f"hop: {current_hop} -> {received_ip}")
                    sus = False
                    break
                else:
                    raise "sus"
            except:
                continue
        if sus:
            print(f"hop: {current_hop} -> *")
        current_hop += 1


if __name__ == "__main__":
    main()

Что-то я давно не заходил... был занят, писал утилиту. Лицензия – «MIT».

JloJle4Ka JloJle4Ka, (Updated )

Комментарии (9, +9)

Змея / Говнокод #28439 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
def make_coffie(water_amount: int = 0) -> object:
    
    class Coffie_Constructor:
        
        def __init__(self, beans_amount: int = 0):
            self.water_amount = water_amount
            self.beans_amount = beans_amount
        
        def __call__(self, milk_amount: int = 0) -> int:
            return self.water_amount + self.beans_amount + milk_amount

        def __repr__(self) -> str:
            return 'Not enought call brakets were given'
        
    return Coffie_Constructor

print(make_coffie(120)(50)(50))

rockkley94 rockkley94, (Updated )

Комментарии (14, +14)

Змея / Говнокод #28427 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
#Ввод пользователем шахматной клетки
chess_cell = input("Введите шахматную клетку ")
 
horizontal_chess = chess_cell[0] #присовение в переменную буквы клетки
vertical_chess = int (chess_cell[1]) #присовение в переменную цифры клетки
 
#Вычисление условий для определения цвета ячейки
if vertical_chess > 8:
    print ("Число клетки не может быть больше 8! ") #Условие ограничивающее количество клеток по вертикали
 
elif horizontal_chess != "a" and horizontal_chess != "A" and horizontal_chess != "b" and horizontal_chess != "B"\
and horizontal_chess != "c" and horizontal_chess != "C" and horizontal_chess != "d" and horizontal_chess != "D"\
and horizontal_chess != "e" and horizontal_chess != "E" and horizontal_chess != "f" and horizontal_chess != "F"\
and horizontal_chess != "g" and horizontal_chess != "G" and horizontal_chess != "h" and horizontal_chess != "H":
    print ("такой буквы ячейки не существует!") #Условие ограничивающее количество букв по горизонтали
 
elif horizontal_chess == "a" or horizontal_chess == "A" or horizontal_chess == "c" or horizontal_chess == "C"\
or horizontal_chess == "e" or horizontal_chess == "E" or horizontal_chess == "g" or horizontal_chess == "G": 
    if vertical_chess%2 == 1:
        print ("ячейка черная ") 
    else:
        print ("ячейка белая") #определение цвета клеток в вертикали А, C, E, G
 
elif horizontal_chess == "b" or horizontal_chess == "B"or horizontal_chess == "d" or horizontal_chess == "D"\
or horizontal_chess == "f" or horizontal_chess == "F" or horizontal_chess == "h" or horizontal_chess == "H": 
    if vertical_chess%2 == 0:
        print ("ячейка черная ") 
    else:
        print ("ячейка белая") #определение цвета клеток в вертикали B, D, F, H

Определение цвета ячейки шахматной доски. Перевести букву в число с помощью ord()? Не, это мы не проходили.

govnobot govnobot, (Updated )

Комментарии (10, +10)

Змея / Говнокод #28423 Ссылка на оригинал

0

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
  75. 75
  76. 76
  77. 77
  78. 78
  79. 79
  80. 80
  81. 81
  82. 82
  83. 83
  84. 84
  85. 85
  86. 86
  87. 87
  88. 88
  89. 89
  90. 90
  91. 91
  92. 92
  93. 93
  94. 94
  95. 95
#!/usr/bin/env python3
# -*- coding: UTF8 -*-
from datetime import date
from os import environ, mkdir, system
from os.path import dirname, exists, join as path_join
from time import time


def check_verbose():
    return environ.get("DEBUG") in ("true", "True", "TRUE", True, "yes", "Yes", "YES")


class Timer:
    def __init__(self):
        """
        Объект добавляет в начале текста временные метки
        """
        self.start_epoch = self.last_call = time()

    @staticmethod
    def __fully_scope(timer: int or str) -> str:
        """
        Преобразует однозначные значения в двузначные.
        :param timer: Время
        :return: Двузначное значение
        """
        if len(str(timer)) == 2:
            return str(timer)
        elif len(str(timer)) == 1:
            return "0" + str(timer)
        elif len(str(timer)) <= 0:
            return "00"
        elif len(str(timer)) >= 2:
            return str(timer)[:2]

    def __formatter(self, timestep: float) -> str:
        """
        Форматирует время
            :return: время hh:mm:ss
        """
        _hours = int(timestep // 3600), int(timestep % 3600)
        _minute = int(_hours[1] // 60), int(_hours[1] % 60)

        _current_epoch = f"{self.__fully_scope(_minute[0])}:{self.__fully_scope(_minute[1])}"
        if _hours[0] > 0:
            _current_epoch = f"{_hours[0]}:" + _current_epoch
        return _current_epoch

    def __call__(self, fix_call: bool = True) -> str:
        """
        Считает время с начала сценария + с последнего шага
            :return: время hh:mm:ss(+hh:mm:ss)
        """
        current_epoch = self.__formatter(time() - self.start_epoch)
        timedelta_epoch = self.__formatter(time() - self.last_call)
        if fix_call:
            self.last_call = time()

        return f"{current_epoch}(+{timedelta_epoch})"

    def __bool__(self):
        return True


class Logger:
    def __init__(self, name: str):
        self.start_time = time()
        self.name = name.upper()
        self.timer = Timer()
        self.log_file = path_join(environ["RESULT_DIR"], name, f"{name}_{date.today().isoformat()}.log")

    def check_file(self):
        if not exists(self.log_file):
            if not exists(dirname(self.log_file)):
                mkdir(dirname(self.log_file))
            system(f"echo {date.today().isoformat()}> {self.log_file}")

    def save_log(self, msg: str):
        self.check_file()
        with open(self.log_file, "a+") as _log_file:
            _log_file.write(msg + "\n")

    def massage(self, msg: str):
        print(f"{self.timer()}::{self.name}::{msg}")
        self.check_file()
        self.save_log(f"{self.timer()}::{self.name}::{msg}")

    def multi_msg(self, level: str, msg: any):
        if isinstance(msg, (str, int, float, bool)):
            self.massage(f"{level.upper()}::{msg}")
        elif isinstance(msg, (tuple, list, set)):
            for _msg in msg:
                self.multi_msg(level, _msg)
        elif isinstance(msg, dict):
            for _msg_key in msg:

Ну собственно самописный логгер, потому что "библиатечный логгер переусложнен НИНАДА!"

dicklover dicklover, (Updated )

Комментарии (50, +50)