1. Лучший говнокод

    В номинации:
    За время:
  2. Куча / Говнокод #27878

    +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
    EXAMPLE
    
    To specify what kind of authorization is needed to execute the program /usr/bin/pk-example-frobnicate as another user, simply write an action definition file like this
    
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE policyconfig PUBLIC
      "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
      "http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
    <policyconfig>
    
      <vendor>Examples for the PolicyKit Project</vendor>
      <vendor_url>http://hal.freedesktop.org/docs/PolicyKit/</vendor_url>
    
      <action id="org.freedesktop.policykit.example.pkexec.run-frobnicate">
        <description>Run the PolicyKit example program Frobnicate</description>
        <description xml:lang="da">Kør PolicyKit eksemplet Frobnicate</description>
        <message>Authentication is required to run the PolicyKit example program Frobnicate (user=$(user), program=$(program), command_line=$(command_line))</message>
        <message xml:lang="da">Autorisering er påkrævet for at afvikle PolicyKit eksemplet Frobnicate (user=$(user), program=$(program), command_line=$(command_line))</message>
        <icon_name>audio-x-generic</icon_name>
        <defaults>
          <allow_any>no</allow_any>
          <allow_inactive>no</allow_inactive>
          <allow_active>auth_self_keep</allow_active>
        </defaults>
        <annotate key="org.freedesktop.policykit.exec.path">/usr/bin/pk-example-frobnicate</annotate>
      </action>
    
    </policyconfig>

    Simply write an action definition file like this, they said...

    bormand, 17 Декабря 2021

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

    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
    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
    /* https://fstarlang.github.io/lowstar/html/Introduction.html#the-essence-of-low
    
    Consider the following very simple program:
    
    module Intro
    
    module P = LowStar.Printf
    module C = LowStar.Comment
    module B = LowStar.Buffer
    
    open FStar.HyperStack.ST
    open LowStar.BufferOps
    
    let main (): St Int32.t =
      push_frame ();
      let b: B.buffer UInt32.t = B.alloca 0ul 8ul in
      b.(0ul) <- 255ul;
      C.comment "Calls to printf are desugared via meta-programming";
      let s = "from Low*!" in
      P.(printf "Hello from %s\nbuffer contents: %xul\n"
        s 8ul b done);
      pop_frame ();
      0l
    
    ....
    
    Once compiled by the KreMLin compiler, we obtain the following C code:
    */
    
    int32_t main()
    {
      uint32_t b[8U] = { 0U };
      b[0U] = (uint32_t)255U;
      /* Calls to printf are desugared via meta-programming */
      Prims_string s = "from Low*!";
      LowStar_Printf_print_string("Hello from ");
      LowStar_Printf_print_string(s);
      LowStar_Printf_print_string("\nbuffer contents: ");
      LowStar_Printf_print_lmbuffer_u32((uint32_t)8U, (uint32_t *)b);
      LowStar_Printf_print_string("\n");
      return (int32_t)0;
    }

    Какая-то компилируемая в сишку хренотень с завтипами, разрабатываемая в Microsoft Research

    j123123, 29 Июля 2021

    Комментарии (66)
  4. JavaScript / Говнокод #27414

    +1

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    function main() {    
        const x = 21;
        let s = "foo";
        const r = `a${x * 2}X${s}X${s}Z`;
        print(r);
    }

    Продолжаем будни говно-писания говно-компилятора на LLVM. серия - а ваш говно-компилятор может так...

    и результат работы
    >>
    C:\temp\MLIR_to_exe>out.exe
    a42XfooXfooZ

    ASD_77, 10 Мая 2021

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

    +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
    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
    template<typename T>
    struct [[nodiscard]] InplacePointerGuard {
        InplacePointerGuard(T *& ptr_) : ptr(ptr_) {}
        ~InplacePointerGuard()
        {
            if (ptr != nullptr) {
                ptr->~T();
            }
        }
    
        T *& ptr;
    };
    
    template<typename EventType, typename... Args>
    bool publishEmplace(Args &&... args) const
    {
        static_assert((std::is_base_of_v<Event, EventType> && std::is_convertible_v<const EventType *, const Event *>),
                      "EventType must be a public subtype of Event");
        auto typeIdx = Event::getStaticIndex<EventType>();
    
        std::aligned_storage_t<sizeof(EventType), alignof(EventType)> eventStorage;
        EventType *eventConstructed = nullptr;
        auto guard = InplacePointerGuard(eventConstructed);
    
        publishEmplaceImpl<EventType>(typeIdx, eventStorage, eventConstructed, std::forward<Args>(args)...);
    
        return eventConstructed != nullptr;
    }
    
    template<typename EventType, typename... Args>
    static EventType *constructEvent(std::aligned_storage_t<sizeof(EventType), alignof(EventType)> & eventStorage,
                                     Args &&... args)
    {
        return std::launder(new(&eventStorage) EventType(std::forward<Args>(args)...));
    }
    
    template<typename EventType, typename... Args>
    void publishEmplaceImpl(const std::type_index & typeIdx,
                            std::aligned_storage_t<sizeof(EventType), alignof(EventType)> & eventStorage,
                            EventType *& eventConstructed,
                            Args &&... args) const
    {
        if (auto it = callbacks.find(typeIdx); it != callbacks.end()) {
            for (const auto & [subId, callback] : it->second) {
                if (!eventConstructed) {
                    eventConstructed = constructEvent<EventType>(eventStorage, std::forward<Args>(args)...);
                }
                callback(*eventConstructed);
            }
        }
    
        auto range = EventsRelation::RelationManager::getParentsRange(typeIdx);
        for (auto it = range.first; it != range.second; ++it) {
            if (!eventConstructed) {
                publishEmplaceImpl<EventType>(it->second, eventStorage, eventConstructed, std::forward<Args>(args)...);
            } else {
                publishImpl(it->second, *eventConstructed);
            }
        }
    }

    PolinaAksenova, 22 Марта 2021

    Комментарии (66)
  6. C++ / Говнокод #26962

    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
    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
    #include <iostream>
    #include <ctime>
    #include <cstdlib>
    #include <conio.h>
    const int x_size(20), y_size(10); int x_pos(x_size/2+1); int y_pos(y_size/2+1);
    enum border_types{lineNL, single, singleNL};
    enum directions{UpLeft=1, UpRight, DownLeft, DownRight}dir;
    void draw_border(enum border_types borders) {
    	do{
    		if(borders == single || borders == singleNL) break;
    		for(int i=0; i<x_size+1; i++)
    	  	  putchar('#');
    	}while(false);
    	putchar('#');
    	if(borders == singleNL || borders == lineNL) std::cout << '\n';}
    void display_update() {
    	system("cls");
    	draw_border(lineNL);
    	for(int i=1; i<=y_size; i++)
    	{
    		draw_border(single);
    		for(int j=1; j<=x_size; j++)
    		{
    			if(j == x_pos && i == y_pos)
    			{
    				putchar('x');
    				continue;
    			}
    			putchar(32);
    		}
    		draw_border(singleNL);;
    	}
    	draw_border(lineNL);
    	std::cout << "X: " << x_pos << "\tY: " << y_pos;}
    void logic() {
    	switch(x_pos)
    	{
    		case 1:
    			if(dir == UpLeft) dir = UpRight;
    			if(dir == DownLeft) dir = DownRight;
    			break;
    		case x_size:
    			if(dir == UpRight) dir = UpLeft;
    			if(dir == DownRight) dir = DownLeft;
    	}
    	switch(y_pos)
    	{
    		case 1:
    			if(dir == UpLeft) dir = DownLeft;
    			if(dir == UpRight) dir = DownRight;
    			break;
    		case y_size:
    			if(dir == DownLeft) dir = UpLeft;
    			if(dir == DownRight) dir = UpRight;
    	}}
    void move() {
    	switch(dir)
    	{
    		case UpLeft:
    			x_pos--;
    			y_pos--;
    			break;
    		case UpRight:
    			x_pos++;
    			y_pos--;
    			break;
    		case DownLeft:
    			x_pos--;
    			y_pos++;
    			break;
    		case DownRight:
    			x_pos++;
    			y_pos++;
    	}}
    int main() {
    	srand(time(0));
    	rand();
    	switch(rand()%4+1)
    	{
    		case UpLeft:
    			dir = UpLeft;
    			break;
    		case UpRight:
    			dir = UpRight;
    			break;
    		case DownLeft:
    			dir = DownLeft;
    			break;
    		case DownRight:
    			dir = DownRight;
    	}
    	while(!kbhit())
    	{
    		display_update();
    		logic();
    		move();
    	}
    	return 0;}

    Сорян, пришлось уплотнить фигурные скобки, чтобы код уместился в 100 строк.

    BelCodeMonkey, 18 Сентября 2020

    Комментарии (66)
  7. Куча / Говнокод #26735

    0

    1. 1
    https://www.facebook.com/FBE/videos/258830962097696/UzpfSTExNzQ4ODY0MjI6ODAzNDE1NzEwMDYyMjcw/

    MAKAKA, 04 Июня 2020

    Комментарии (66)
  8. C++ / Говнокод #26452

    +4

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    static bool ShouldIgnoreHeaderForCacheReuse(AtomicString header_name) {
      // FIXME: This list of headers that don't affect cache policy almost certainly
      // isn't complete.
      DEFINE_STATIC_LOCAL(
          HashSet<AtomicString>, headers,
          ({"Cache-Control", "If-Modified-Since", "If-None-Match", "Origin",
            "Pragma", "Purpose", "Referer", "User-Agent"}));
      return headers.Contains(header_name);
    }

    https://chromium.googlesource.com/chromium/src/+/refs/heads/master/third_party/blink/renderer/platform/loader/fetch/raw_resource.cc

    Вот есть такая крутая фича под названием «preload»: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content.
    Tl;dr: указываем «<link rel="preload" href="/comments.html" [...]>» в начале index.html, после чего браузер начнёт загружать comments.html в фоновом режиме. В «NGK» «Ангуляр» загружает этот самый comments.html для отрисовки главной страницы, поэтому предварительная загрузка (до того, как загрузится, собственно, «Ангуляр») может сэкономить несколько десятков миллисекунд. Ура.

    Но нельзя так просто взять и сделать что-то без пердолинга! Чтобы браузер смог использовать предварительно загруженный документ, необходимо, чтобы все заголовки, за исключением представленных в коде, в обоих запросах (из preload и из «Ангуляра») совпадали, что, конечно же, не лишено смысла. Поэтому, если просто взять и включить предварительную загрузку, «Хром» выдаст печальное «A preload for 'https://gcode.space/comments.html' is found, but is not used because the request headers do not match».

    Окей, повозившись с CORS, наш инженерный отдел добился полного совпадения заголовков, за исключением «Origin» (его браузер в «простых» запросах через XHR принципиально не ставит) и «Accept». «Ангуляр» по-умолчанию суёт в «Accept» «application/json, text/plain, */*», а для запроса через preload консоль разработчика показывает просто «*/*».
    Не беда! Наш инженерный отдел нагуглил, как поправить заголовки запросов в «Ангуляре», поставил там «*/*» и, довольный собой, приготовился наблюдать неебическое ускорение загрузки: https://i.imgur.com/q0CtQXp.png.

    gost, 27 Февраля 2020

    Комментарии (66)
  9. Куча / Говнокод #25674

    −3

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    В WSH есть объект WScript, расширяющий возможности языка и позволяющий управлять их поведением.
    Одно из его свойств - Interactive, оно позволяет разрешить либо запретить скрипту показывать пользователю диалоговые окна.
    
    Как-то так:
    
    WScript.Interactive=False
    MsgBox "Эй, ламер! Привет!"                 'этот диалог не будет показан
    WScript.Interactive=True
    msgbox wscript.scriptfullname                ' этот дилог будет по... нет, тоже не будет показан.

    А всё потому, что скриптовый движок выбирается только один раз и не может быть сменен динамически.
    Выбрать можно либо UI-движок, показывающий сообщения и ошибки, либо Silent-движок, который не показывает ничего.

    Вот уж какой багор!..

    cmepmop, 13 Июня 2019

    Комментарии (66)
  10. Pascal / Говнокод #25468

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    Ent := 0.0;
      for I := Low(Freq) to High(Freq) do
        Ent := Ent + Freq[I];
      Ent := Ln(FileSize(Input)) / Ln(2) * Ent;
      for I := Low(Freq) to High(Freq) do
      begin
        if Freq[I] > 0 then
          Ent := Ent - Freq[I] * Ln(Freq[I]) / Ln(2);
      end;
      Ent := Ent / FileSize(Input);

    Скучно, девочки!

    Increment_Excrement, 23 Марта 2019

    Комментарии (66)
  11. Pascal / Говнокод #24872

    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
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    procedure TMainForm.FormCreate(Sender: TObject);
    var
      s : String;
      reg : TRegistry;
    begin
      SetLength (s, Max_Path);
      SHGetSpecialFolderPath (0, PChar(s), CSIDL_COMMON_APPDATA, false);
      AppDataPath := s + '\Test\';
      ShowMessage (AppDATAPath);
    end;
    
    , где AppDataPath : string;
    Только вот в AppDataPath находиться только S, а должно быть s + '\Test\'
    Вопрос: Почему?
    Заранее благодарен
    
    
    
    Потому что нельзя передавать паскалевскую строку в виде PChar в функцию, которая будет её там модифицировать. Нужно делать так:
    
    Код:
    var
      s : array[ 0..MAX_PATH ] of Char;
      reg : TRegistry;
    begin
      s[ 0 ] := #0;
      SHGetSpecialFolderPath (0, s, CSIDL_COMMON_APPDATA, false);
      AppDataPath := s + '\Test\';
      ShowMessage (AppDATAPath);
    end;
    
    http://www.programmersforum.ru/showthread.php?t=84319

    @Потому что нельзя передавать паскалевскую строку в виде PChar в функцию, которая будет её там модифицировать.
    Ахуенно крутой спец по строкам.

    Кстати, https://primechaniya.ru/home/news/oktyabr-2018/v-tatarstane-18-podrostkov-otravilis-kitajskimi-duhami/

    BagorCtretora, 08 Октября 2018

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