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

    Всего: 331

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

    +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
    // https://habr.com/ru/post/440388/
    // Интервалы: грядущая эволюция C++ 
    
    // Давайте теперь рассмотрим следующую задачу: имеется вектор, необходимо удалить
    // из него все повторяющиеся элементы. В рамках текущего стандарта мы решали бы её так:
    
    std::vector<T> vec=...;
    std::sort( vec.begin(), vec.end() );
    vec.erase( std::unique( vec.begin(), vec.end() ), vec.end() );
    
    
    // При этом мы указываем имя вектора аж 6 раз! Однако, используя концепцию интервалов
    // (объединив итераторы на начало и конец вектора в один объект), можно написать в разы проще, указав искомый вектор лишь единожды:
    
    tc::unique_inplace( tc::sort(vec) );
    
    //... Че, серьезно? Я так тоже могу:
    // Однако, используя сишный препроцессор™, можно написать в разы проще, указав искомый вектор лишь единожды:
    
    #define DELETE_DUPS(x) do{ std::sort( x.begin(), x.end() ); x.erase( x::unique( x.begin(), x.end() ), x.end() );}while(0)
    
    DELETE_DUPS(vec);

    Тоже мне революция.

    j123123, 15 Февраля 2019

    Комментарии (26)
  3. Си / Говнокод #25375

    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
    // https://git.zx2c4.com/BruteZip/tree/read.c?id=e4e9c17b99e0d108136b8a07632b1ebaa7d09d28#n26
    
    int main(int argc, char *argv[])
    {
    	union {
    		long int l;
    		char c[sizeof(long int)];
    	} u;
    	u.l = 1;
    	if (u.c[sizeof(long int) - 1] == 1) {
    		printf("This program only runs on little endian archs, because I'm lazy. Sorry.\n");
    		return -2;
    	}

    Хуйня какая-то. Ведь sizeof(long int) может быть равен sizeof(char).

    Но над такой питушней обычно никто не задумывается

    j123123, 13 Февраля 2019

    Комментарии (223)
  4. Си / Говнокод #25372

    −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
    // http://p99.gforge.inria.fr/p99-html/group__flexible.html
    
    //C99 allows a flexible array member to be defined as the last member of a struct,
    // namely an array of undetermined length.
    //P99_DECLARE_STRUCT(package_head);
    
    struct package_head {
      char name[20];
      size_t len;
      uint64_t data[];
    };
    
    // Such a struct can then be allocated on the heap with a suitable size such 
    // that the field data has as many elements as fit in the allocated space from
    // the start of data onward. Usually one would allocate such struct with
    
    package_head *a = malloc(sizeof(package_head) + 10 * sizeof(uint64_t));
    package_head *b = malloc(sizeof(*b) + 12 * sizeof(b->data[0]));
    
    // This has several disadvantages. Firstly, the syntax is clumsy. We have to
    // use a relatively complicated expression that uses two elements of the specification of a or b.
    
    // Secondly, it wastes space. Due to packing of the struct the offset of data "inside"
    //  the struct may be less than sizeof(package_head). In most cases the real size
    // of the object that we want to construct is
    
    offsetof(package_head, data) + N * sizeof(uint64_t)
    
    // so we are wasting
    
    sizeof(package_head) - offsetof(package_head, data)
    
    // bytes.
    
    // The above formula for the exact size is only valid for larger values of N. We must
    // also ensure that we allocate at least sizeof(package_head) bytes. So the complete
    // formula looks something like
    
    #define P99_FSIZEOF(T, F, N) P99_MAXOF(sizeof(T), offsetof(T, F) + P99_SIZEOF(T, F[0]) * N)
    
    // which is probably not something that you want to write on a daily basis.
    
    // We provide several interfaces to allocate struct with flexible members

    Херню написали какую-то. Забыли самое главное : нельзя так в лоб аллоцировать память под структуры. Потому что выравнивание может не то быть.
    Надо использовать http://man7.org/linux/man-pages/man3/aligned_alloc.3.html

    j123123, 12 Февраля 2019

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

    +5

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    // https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
    
    // The Curiously Recurring Template Pattern (CRTP)
    template<class T>
    class Base
    {
        // methods within Base can use template to access members of Derived
    };
    class Derived : public Base<Derived>
    {
        // ...
    };

    > The Microsoft Implementation of CRTP in Active Template Library (ATL) was independently discovered, also in 1995 by Jan Falkin who accidentally derived a base class from a derived class. Christian Beaumont, first saw Jan's code and initially thought it couldn't possibly compile in the Microsoft compiler available at the time. Following this revelation that it did indeed work, Christian based the entire ATL and Windows Template Library (WTL) design on this mistake.

    А какая ошибка по-вашему положена в основу всего дизайна языка C++?

    j123123, 06 Февраля 2019

    Комментарии (119)
  6. Си / Говнокод #25349

    −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
    #include <stdio.h>
    #include <stdlib.h>
    #include <inttypes.h>
    
    int main(void)
    {
      char a[8], b[8];
      char *a_ptr = a+8;
      char *b_ptr = b;
      printf("a_ptr = %p, b_ptr = %p\n", a_ptr, b_ptr);
      if (a_ptr != b_ptr)
      {
        printf("a_ptr != b_ptr\n");
      }
      else
      {
        printf("a_ptr == b_ptr\n");
      }
      
      
      if ((uintptr_t)a_ptr != (uintptr_t)b_ptr)
      {
        printf("(uintptr_t)a_ptr != (uintptr_t)b_ptr\n");
      }
      else
      {
        printf("(uintptr_t)a_ptr == (uintptr_t)b_ptr\n");
      }
      return EXIT_SUCCESS;
    }

    Что по-вашему тут происходит?

    j123123, 02 Февраля 2019

    Комментарии (39)
  7. C++ / Говнокод #25343

    −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
    // https://habr.com/ru/company/jugru/blog/438260/
    
    template<Semiregular T>
    struct maybe_view : view_interface<maybe_view<T>> {
      maybe_view() = default;
      maybe_view(T t) : data_(std::move(t)) {
      }
      T const *begin() const noexcept {
        return data_ ? &*data_ : nullptr;
      }
      T const *end() const noexcept {
        return data_ ? &*data_ + 1 : nullptr;
      }
    private:
      optional<T> data_{};
    };
    inline constexpr auto for_each =
      []<Range R,
         Iterator I = iterator_t<R>,
         IndirectUnaryInvocable<I> Fun>(R&& r, Fun fun)
            requires Range<indirect_result_t<Fun, I>> {
          return std::forward<R>(r)
            | view::transform(std::move(fun))
            | view::join;
      };
    inline constexpr auto yield_if =
      []<Semiregular T>(bool b, T x) {
        return b ? maybe_view{std::move(x)}
                 : maybe_view<T>{};
      };
    
    /*
    > Быть может, что для кого-то это язык родной, но для меня всё
    это ощущается как если бы кто-то решил, что Perl излишне читабельный,
    а Brainfuck — излишне нечитабельный, поэтому давайте целиться между
    ними. Я программировал в основном на C++ все последние 20 лет. Может
    быть, я слишком тупой, чтобы во всём этом разобраться, отлично.
    */

    Какой багор)))

    j123123, 31 Января 2019

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

    +1

    1. 1
    https://i.imgur.com/7uRLULs.mp4

    Аппаратная нейросеть в мозгах петуха совершила ошибку классификации.

    j123123, 30 Января 2019

    Комментарии (80)
  9. Си / Говнокод #25334

    +2

    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
    void add_SSE(uint8_t a[static 7], uint8_t b[static 7], uint8_t out[static 7])
    {
      uint64_t a_64 = 0;
      uint64_t b_64 = 0;
      for (size_t i = 0; i < 7; i++) // можно наанроллить
      {
        a_64 |= (uint64_t)a[i] << (i*9);
        b_64 |= (uint64_t)b[i] << (i*9);
      }
      
      uint64_t c_64 = a_64 + b_64;
      
      for (size_t i = 0; i < 7; i++) // можно наанроллить
      {
        out[i] = (uint64_t)c_64 >> (i*9);
      }
    }

    SSE

    j123123, 28 Января 2019

    Комментарии (32)
  10. Java / Говнокод #25332

    +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
    // https://github.com/TigerVNC/tigervnc/blob/8c6c584377feba0e3b99eecb3ef33b28cee318cb/java/com/jcraft/jsch/Buffer.java#L65-L85
    
      public void putInt(int val) {
        tmp[0]=(byte)(val >>> 24);
        tmp[1]=(byte)(val >>> 16);
        tmp[2]=(byte)(val >>> 8);
        tmp[3]=(byte)(val);
        System.arraycopy(tmp, 0, buffer, index, 4);
        index+=4;
      }
      public void putLong(long val) {
        tmp[0]=(byte)(val >>> 56);
        tmp[1]=(byte)(val >>> 48);
        tmp[2]=(byte)(val >>> 40);
        tmp[3]=(byte)(val >>> 32);
        System.arraycopy(tmp, 0, buffer, index, 4);
        tmp[0]=(byte)(val >>> 24);
        tmp[1]=(byte)(val >>> 16);
        tmp[2]=(byte)(val >>> 8);
        tmp[3]=(byte)(val);
        System.arraycopy(tmp, 0, buffer, index+4, 4);
        index+=8;
      }

    Жабовское байтоебство (судя по всему это такой ntohl) из реализации VNC.
    Вот интересно, в жабке-то unsigned типов нет нихера, но почему-то сделали unsigned двоичный сдвиг (>>>), который работает для этих встроенных signed типов как если б это были unsigned. А как насчет unsigned умножения и деления (сложение и вычитание - то один хер, без разницы, если у нас two's complement)?

    j123123, 28 Января 2019

    Комментарии (58)
  11. C++ / Говнокод #25327

    +2

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    https://www.opennet.ru/opennews/art.shtml?num=50026
    
    После двух лет разработки компания The Qt Company представила
    компактный встроенный http-сервер для Qt, доступный для
    разработчиков приложений в виде класса QHttpServer. Сервер
    пока развивается как экспериментальный проект Qt Labs, но
    запланирован для включения в основной состав Qt 6.

    Вот жеж этим [censored] делать нехер. Вы уже в Qt встроили жабаскрипт ( https://doc.qt.io/qt-5/topics-scripting.html ), и даже встроили браузер, но вам этого мало, вы еще и вебсервер встроили. Встройте еще туда и PHP, чтоб вообще всё возможное говно в себя вобрать

    j123123, 26 Января 2019

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