1. Список говнокодов пользователя gost

    Всего: 246

  2. C++ / Говнокод #26946

    +3

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    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
    foreach ($files as $n => $f) {
        $new_content = $common.$namespace_begin.$f.$namespace_end;
    
        $std_methods = array();
        preg_match_all('/std::[a-z_0-9]*/', $new_content, $std_methods);
        $std_methods = array_unique($std_methods[0]);
    
        $needed_std_headers = array();
        $type_headers = array(
            'std::move' => '',
            'std::vector' => '',
            'std::string' => '',
    // [...]
            'std::unordered_set' => 'unordered_set');
        foreach ($type_headers as $type => $header) {
            if (in_array($type, $std_methods)) {
                $std_methods = array_diff($std_methods, array($type));
                if ($header && !in_array($header, $needed_std_headers)) {
                    $needed_std_headers[] = $header;
                }
            }
        }
    
        if (!$std_methods) { // know all needed std headers
            $new_content = preg_replace_callback(
                '/#include <([a-z_]*)>/',
                function ($matches) use ($needed_std_headers) {
                    if (in_array($matches[1], $needed_std_headers)) {
                        return $matches[0];
                    }
                    return '';
                },
                $new_content
            );
        }

    Тут вот в https://govnokod.ru/20049 CHayT предлагал использовать «PHP» в качестве препроцессора для «C» — так вот в «Телеграме» совет оценили и решили взять на вооружение.
    https://github.com/tdlib/td/blob/master/SplitSource.php

    gost, 13 Сентября 2020

    Комментарии (20)
  3. C++ / Говнокод #26913

    +3

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    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
    int main()
    {   
        using output1 = Eval<
            Input<'H', 'e', 'l', 'l', 'o'>,
            App<
                ',', '>', ',', '>', ',', '>', ',', '>', ',', '>',
                '<', '.', '<', '.', '<', '.', '<', '.', '<', '.'
            >
        >;
        std::cout << "Hello reverse (read/write): " << SpanToStringContinuous<output1>::value() << std::endl;
    
        using output2 = Eval<
            Input<>,
            App<'+', '+', '+', '[', '-', ']'>
        >;
        std::cout << "Simple loop (empty output): " << SpanToStringContinuous<output2>::value() << std::endl;
    
        // Source: Wikipedia
        using output3 = Eval<
            Input<>,
            App<
                '+', '+', '+', '+', '+', '+', '+', '+', '[', '>', '+', '+', '+',
                '+', '[', '>', '+', '+', '>', '+', '+', '+', '>', '+', '+', '+',
                '>', '+', '<', '<', '<', '<', '-', ']', '>', '+', '>', '+', '>',
                '-', '>', '>', '+', '[', '<', ']', '<', '-', ']', '>', '>', '.',
                '>', '-', '-', '-', '.', '+', '+', '+', '+', '+', '+', '+', '.',
                '.', '+', '+', '+', '.', '>', '>', '.', '<', '-', '.', '<', '.',
                '+', '+', '+', '.', '-', '-', '-', '-', '-', '-', '.', '-', '-',
                '-', '-', '-', '-', '-', '-', '.', '>', '>', '+', '.', '>', '+',
                '+', '.'
            >
        >;
        std::cout << "Hello World (wiki): " << SpanToStringContinuous<output3>::value() << std::endl;
    
    
        return EXIT_SUCCESS;
    }

    https://wandbox.org/permlink/AERueBhsiS4WxGZY, https://pastebin.com/Cywe05JY

    Напейсал полностью компайл-таймовый интерпретатор «Брейнфака» на крестовых шаблонах.

    gost, 03 Сентября 2020

    Комментарии (104)
  4. C++ / Говнокод #26910

    +4

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    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
    96. 96
    97. 97
    98. 98
    // https://govnokod.ru/26890#comment571155
    // bormand 2 часа назад #
    // Можно брейнфак запилить на операторах. Как раз вроде унарных хватает.
    // & * - ~ ! -- + ++ --
    
    #include <array>
    #include <vector>
    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <limits>
    
    struct Brainfuck {
    public:
        using IPType = uint16_t;
        constexpr static size_t MAX_MEMORY = std::numeric_limits<IPType>::max();
    
        std::array<uint8_t, MAX_MEMORY> memory{};
        std::vector<char> app{};
        IPType ip = 0;
        IPType cell = 0;
    
        IPType find_matching_tag(IPType cur_ip, char open, char close, int ip_direction)
        {
            size_t stack_size = 0;
            do  {
                if (app[cur_ip] == close) {
                    --stack_size;
                }
                if (app[cur_ip] == open) {
                    ++stack_size;
                }
                cur_ip += ip_direction;
            } while (stack_size > 0);
            return cur_ip - ip_direction;
        }
    
        IPType find_matching_close_tag(IPType cur_ip)
        {
            return find_matching_tag(cur_ip, '[', ']', 1);
        }
    
        IPType find_matching_open_tag(IPType cur_ip)
        {
            return find_matching_tag(cur_ip, ']', '[', -1);
        }
    
        void loop_open()
        {
            if (memory[cell] == 0) {
                ip = find_matching_close_tag(ip);
            } else {
                ++ip;
            }
        }
    
        void loop_close()
        {
            if (memory[cell] != 0) {
                ip = find_matching_open_tag(ip);
            } else {
                ++ip;
            }
        }
    
        void exec(char op)
        {
            switch (op) {
                case '>': ++cell; break;
                case '<': --cell; break;
                case '+': ++memory[cell]; break;
                case '-': --memory[cell]; break;
                case '.': std::putchar(memory[cell]); break;
                case ',': memory[cell] = static_cast<uint8_t>(std::getchar()); break;
                case '[': loop_open(); return;   // no ip advancing
                case ']': loop_close(); return;  // no ip advancing
            }
            ip++;
        }
    
        void run()
        {
            while (ip < app.size()) {
                exec(app[ip]);
            }
        }
    
    public:
        Brainfuck & operator++() { app.push_back('>'); return *this; }
        Brainfuck & operator--() { app.push_back('<'); return *this; }
        Brainfuck & operator+() { app.push_back('+'); return *this; }
        Brainfuck & operator-() { app.push_back('-'); return *this; }
        Brainfuck & operator*() { app.push_back('.'); return *this; }
        Brainfuck & operator&() { app.push_back(','); return *this; }
        Brainfuck & operator!() { app.push_back('['); return *this; }
        Brainfuck & operator~() { app.push_back(']'); return *this; }
        Brainfuck & operator>>(const Brainfuck &) { run(); return *this; }
    };

    https://wandbox.org/permlink/XJUKGyb4YbnBVwOI

    Бонус («99 bottles of beer»): https://pastebin.com/s4sBK9nX (взято с https://github.com/fabianishere/brainfuck/blob/master/examples/bottles-1.bf).

    gost, 03 Сентября 2020

    Комментарии (244)
  5. C++ / Говнокод #26908

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    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
    void Argument::parseAsInt()
    {
        auto res = std::from_chars(data.data(), data.data() + data.size(), dataInt);
        if (res.ec == std::errc()) {
            setTypeFlag(ArgType::Int);
        }
    }
    
    void Argument::parseAsFloat()
    {
        // Rww: gcc still does not support float from_chars(), lol
        const char *begin = data.data();
        const char *end = begin + data.size();
        char *endPtr = nullptr;
    
        dataFloat = std::strtof(begin, &endPtr);
        if (endPtr == end || dataFloat != 0.0f) {
            setTypeFlag(ArgType::Float);
        } else {
            for (const char *it = endPtr; it < end; it++) {
                if (!std::isspace(*it)) {
                    return;
                }
            }
            setTypeFlag(ArgType::Float);
        }
    }

    Говнокодил тут недавно, долго думал, что считать числом (пет, ТЗ нет). В конце-концов решил считать всё, что можно распарсить.

    gost, 02 Сентября 2020

    Комментарии (14)
  6. Python / Говнокод #26889

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    # TODO: fix this shit
    def publish(self, session: requests.Session, auth_cookie: str, max_retries: int, retry_time: float) -> bool:
        for i in range(max_retries):
            L.info(f'PostForm.publish(), loading attempt #{i + 1}')
            if self.load_new(session, auth_cookie):
                break
            time.sleep(retry_time)
        else:  # No break
            L.error('PostForm.publish(): could not load the form')
            return False
        
        for i in range(max_retries):
            L.info(f'PostForm.publish(), posting attempt #{i + 1}')
            if not self.try_recognize_captcha(session):
                time.sleep(retry_time)
                continue  # Load an another captcha with the same csrf/captcha_id
            if self.try_post(session, auth_cookie) == PostForm.Status.POST_DONE:
                return True
            time.sleep(retry_time)
        L.error(f'PostForm.publish() failed, max_retries exceeded')
        return False

    Блять, отвратительно.

    gost, 24 Августа 2020

    Комментарии (4)
  7. Python / Говнокод #26880

    0

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    >>> def f(positional_only, /, regular, *varargs, kw_only, **kw_varargs):
        print(positional_only, regular, varargs, kw_only, kw_varargs)
    
    f(1, 2, 3, 4, 5, kw_only='kw_only', kw_var1='var1', kw_var2='var2')
    # 1 2 (3, 4, 5) kw_only {'kw_var1': 'var1', 'kw_var2': 'var2'}

    Блядь, как всё сложно…

    https://www.python.org/dev/peps/pep-0570/

    gost, 18 Августа 2020

    Комментарии (17)
  8. Python / Говнокод #26837

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    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
    from numba import jit
    
    
    def mults_no_jit(start, end, step):
        min_i = min(start, end)
        for i in range(start, end, step):
            if i < min_i:
                return
            for j in range(i, end, step):
                x = i * j
                x_orig = x
                x_reverse = 0
                while x > 0:
                    x_reverse *= 10
                    x_reverse += x % 10
                    x //= 10
                if x_orig == x_reverse:
                    min_i = max(min_i, j)
                    yield x_orig
                    break
                    
    
    @jit(nopython=True)
    def mults_jit(start, end, step):
        min_i = min(start, end)
        for i in range(start, end, step):
            if i < min_i:
                return
            for j in range(i, end, step):
                x = i * j
                x_orig = x
                x_reverse = 0
                while x > 0:
                    x_reverse *= 10
                    x_reverse += x % 10
                    x //= 10
                if x_orig == x_reverse:
                    min_i = max(min_i, j)
                    yield x_orig
                    break
    
    
    print(timeit.timeit('max(mults_no_jit(999, 99, -1))', globals=globals(), number=100))
    # 4.2907474 секунды
    
    print(timeit.timeit('max(mults_jit(999, 99, -1))', globals=globals(), number=100))
    # 0.1662201 секунд первый запуск, 0.0333973 последующие

    Теперь я за «Numba».

    gost, 02 Августа 2020

    Комментарии (232)
  9. PHP / Говнокод #26829

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    // Both set_time_limit(...) and  ini_set('max_execution_time',...); won't count the time cost of sleep,
    // file_get_contents,shell_exec,mysql_query etc, so i build this function my_background_exec(),
    // to run static method/function in background/detached process and time is out kill it:
    
    // my_exec.php:
    <?php
    function my_background_exec($function_name, $params, $str_requires, $timeout=600)
             {$map=array('"'=>'\"', '$'=>'\$', '`'=>'\`', '\\'=>'\\\\', '!'=>'\!');
              $str_requires=strtr($str_requires, $map);
              $path_run=dirname($_SERVER['SCRIPT_FILENAME']);
              $my_target_exec="/usr/bin/php -r \"chdir('{$path_run}');{$str_requires} \\\$params=json_decode(file_get_contents('php://stdin'),true);call_user_func_array('{$function_name}', \\\$params);\"";
              $my_target_exec=strtr(strtr($my_target_exec, $map), $map);
              $my_background_exec="(/usr/bin/php -r \"chdir('{$path_run}');{$str_requires} my_timeout_exec(\\\"{$my_target_exec}\\\", file_get_contents('php://stdin'), {$timeout});\" <&3 &) 3<&0";//php by default use "sh", and "sh" don't support "<&0"
              my_timeout_exec($my_background_exec, json_encode($params), 2);
             }
    // ...

    Шедевр (заплюсованный) из https://www.php.net/manual/ru/function.set-time-limit.php.

    gost, 30 Июля 2020

    Комментарии (4)
  10. Python / Говнокод #26823

    0

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    def __init__(self, text: str, description: str, category_id: int, auth_cookie: str) -> None:
        Form.__init__(self)
        CsrfForm.__init__(self)
        CaptchaForm.__init__(self)
        self.text: str = text
        self.description: str = description
        self.category_id = category_id
        self.auth_cookie = auth_cookie

    Какое наследование )))

    gost, 28 Июля 2020

    Комментарии (29)
  11. Куча / Говнокод #26810

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    // Это означает что, например, поведение следующего кода не определено:
    
    fn cast(x: f32) -> u8 {
        x as u8
    }
    
    fn main() {
        let f = 300.0;
    
        let x = cast(f);
    
        println!("x: {}", x);
    }

    https://habr.com/ru/post/511546/
    > Это мы называем ошибкой «корректности» (ведь unsafe кода тут нет) — то есть ошибка, когда компилятор делает неправильные вещи. Мы отмечаем их в нашем трекере как I-unsound, и относимся к ним очень серьёзно.

    gost, 18 Июля 2020

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