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

    В номинации:
    За время:
  2. C++ / Говнокод #26389

    +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
    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
    // https://www.linux.org.ru/forum/development/15496357
    
    // Нужен нормальный способ сказать компилятору что type aliasing невозможен на некотором участке кода. Минимальный пример:
    
    template<typename T> struct f final {
    	void bad(T v) noexcept { while (b != e) *b++=v; }
    	void good(T v) noexcept {
    		auto tb(b), te(e);
    		while (tb != te) *tb++=v;
    		b=tb;
    		e=te;
    	}
    
    	T* b, * e;
    };
    template struct f<char>;
    /*
    Выхлоп gcc-8:
    
    $ g++ -xc++ -std=c++14 -pedantic-errors -Os -c -of.o f.cc
    $ objdump -Cd f.o
    f.o:     file format elf64-x86-64
    
    
    Disassembly of section .text._ZN1fIcE3badEc:
    
    0000000000000000 <f<char>::bad(char)>:
       0:	48 8b 07             	mov    (%rdi),%rax
       3:	48 3b 47 08          	cmp    0x8(%rdi),%rax
       7:	74 0c                	je     15 <f<char>::bad(char)+0x15>
       9:	48 8d 50 01          	lea    0x1(%rax),%rdx
       d:	48 89 17             	mov    %rdx,(%rdi)
      10:	40 88 30             	mov    %sil,(%rax)
      13:	eb eb                	jmp    0 <f<char>::bad(char)>
      15:	c3                   	retq   
    
    Disassembly of section .text._ZN1fIcE4goodEc:
    
    0000000000000000 <f<char>::good(char)>:
       0:	48 8b 07             	mov    (%rdi),%rax
       3:	48 8b 57 08          	mov    0x8(%rdi),%rdx
       7:	48 39 d0             	cmp    %rdx,%rax
       a:	74 09                	je     15 <f<char>::good(char)+0x15>
       c:	48 ff c0             	inc    %rax
       f:	40 88 70 ff          	mov    %sil,-0x1(%rax)
      13:	eb f2                	jmp    7 <f<char>::good(char)+0x7>
      15:	48 89 07             	mov    %rax,(%rdi)
      18:	48 89 47 08          	mov    %rax,0x8(%rdi)
      1c:	c3                   	retq
    */

    f<char>::bad(char)+0, f<char>::bad(char)+3 и f<char>::bad(char)+d - три раза за итерацию лезет в память. Разумеется, подобный код сливает в тестах производительности. Есть решение лучше, чем локальные переменные заводить каждый раз?

    j123123, 28 Января 2020

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

    +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
    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
    #include <iostream>
    using namespace std;
    bool check(int a, int b){
    	int ass[10] = {0}, bass[10] = {0};
    	while(a){
    		ass[a % 10]++;
    		bass[b % 10]++;
    		a /= 10;
    		b /= 10;
    	}
    	for(int i = 0; i < 10; i++){
    		if(ass[i] != bass[i]) return false;
    	}
    	return true;
    }
    int main() {
    	for(int i = 1; i < 10; i++){
    		for(int j = 0; j < 10; j++){
    			for(int k = 0; k < 10; k++){
    				for(int l = 0; l < 10; l++){
    					for(int m = 0; m < 10; m++){
    						for(int n = 0; n < 10; n++){
    							for(int o = 0; o < 10; o++){
    								for(int p = 0; p < 10; p++){
    									for(int r = 1; r < 10; r++){
    											long long a =
    											i * 100000000
    											+ j * 10000000
    											+ k * 1000000
    											+ l * 100000
    											+ m * 10000
    											+ n * 1000
    											+ o * 100
    											+ p * 10
    											+ 3;
    											long long z = r * 10000000
    											+ r * 1000000
    											+ r * 100000
    											+ r * 10000
    											+ r * 1000
    											+ r * 100
    											+ r * 10
    											+ r;
    											if(check(a, a + z)){
    												cout << a << " " << z << endl;
    											}
    									}
    								}
    							}
    						}
    					}
    				}
    			}
    		}
    	}
    }

    Коротко о переборах.

    Verenick, 28 Января 2020

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

    +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
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    // I'm interested in using something other than the C preprocessor to preprocess my C and Objective-C source code. Are there good alternatives?
    //
    // ---
    //
    // You can use PHP as a C preprocessor. The advantages are:
    //
    // - very similiar syntax, so syntax highlighting works.
    // - <? and ?> are not used in standard C (with non-standard C, the only thing that gets broken is old GCC extension operator that returns min/max)
    // - it's rich in libraries.
    // - it's turing complete.
    // - usage of macros is very explicit. (compared to sneaky C preprocessor macros)
    // For serious use though, making PHP print the #line directives is needed for debugging preprocessed code.
    
    <?php include_once "stdio.h"; ?>
    
    int main()
    {
        <?php
            for($i = 0; $i < 20; $i++)
                echo 'printf("%d\n", '.$i.');';
        ?>
    }

    https://stackoverflow.com/a/16256052

    абсолютно невыносимо

    Fike, 25 Января 2020

    Комментарии (9)
  5. Python / Говнокод #26356

    +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
    #  Пример #1
    class FastClass:
    
        def do_stuff(self):
            temp = self.value  # это ускорит цикл
            for i in range(10000):
                ...  # Выполняем тут некие операции с `temp`
    
    #  Пример #2
    import random
    
    def fast_function():
        r = random.random
        for i in range(10000):
            print(r())  # здесь вызов `r()` быстрее, чем был бы вызов random.random()

    Забавно, что в статье под названием «Разработка чрезвычайно быстрых программ на Python» (https://habr.com/ru/company/ruvds/blog/483678) этот самый «Python» оказался обосран (ненамеренно) куда качественнее, чем в недавно обсуждённом высере (https://govnokod.ru/26050#comment517858).

    Неужели конпелятор/интерпретатор «Питона» настолько туп, что не может самостоятельно провести вот эти вот микрооптимизации?

    gost, 16 Января 2020

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

    +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
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1371r1.pdf#section.4
    // Pattern Matching P1371R1
    
    // before
    
    auto&& [x, y] = p;
    if (x == 0 && y == 0) {
      std::cout << "on origin";
    } else if (x == 0) {
      std::cout << "on y-axis";
    } else if (y == 0) {
      std::cout << "on x-axis";
    } else {
      std::cout << x << ',' << y;
    }
    
    // after
    
    inspect (p) {
      [0, 0]: std::cout << "on origin";
      [0, y]: std::cout << "on y-axis";
      [x, 0]: std::cout << "on x-axis";
      [x, y]: std::cout << x << ',' << y;
    }

    Говностандартизаторы очередную хуйню изобретают. Нет чтоб нормальную гомоиконность сделать, чтоб через нее любую такую поебень синтезировать можно было, не изменяя говностандарт, не добавляя всяких новых statement. И почему они не хотят эту херню прикрутить тупо к switch? Что если у меня переменная называется inspect, мне ее что, переименовывать?

    Давайте пропосал напишем, чтоб для стейтментов отдельные неймспейсы были, и чтоб можно было свои самопальные стейтменты написать на каком-то отдельном говноязыке (шаблоны под эту хуйню, как я понял, не подходят)? Ну чтоб у всех окончательно сорвало крышу от обилия хуйни.

    j123123, 10 Января 2020

    Комментарии (76)
  7. SQL / Говнокод #26334

    +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
    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
    SELECT SQL_NO_CACHE IT.itemCode,
                                    SUBSTRING_INDEX(GROUP_CONCAT(IT.ean),",", 1) as ean,
                                    SUBSTRING_INDEX(GROUP_CONCAT(IT.artCode),",", 1) as artCode,
                                    SUBSTRING_INDEX(GROUP_CONCAT(IT.description),",", 1) as description,
                                    SUBSTRING_INDEX(GROUP_CONCAT(IT.siteName),",", 1) as siteName,
                                    SUBSTRING_INDEX(GROUP_CONCAT(IT.familyName),",", 1) as familyName,
                                    SUBSTRING_INDEX(GROUP_CONCAT(IT.familyCode),",", 1) as familyCode,
                                    SUBSTRING_INDEX(GROUP_CONCAT(IT.SSfamilyCode),",", 1) as SSfamilyCode,
                                    SUBSTRING_INDEX(GROUP_CONCAT(IT.SSfamilyName),",", 1) as SSfamilyName,
                                    SUBSTRING_INDEX(GROUP_CONCAT(IT.sectorCode),",", 1) as sectorCode,
                                    SUBSTRING_INDEX(GROUP_CONCAT(IT.sectorName),",", 1) as sectorName,
                                    SUBSTRING_INDEX(GROUP_CONCAT(IT.radiusCode),",", 1) as radiusCode,
                                    SUBSTRING_INDEX(GROUP_CONCAT(IT.radiusName),",", 1) as radiusName,
                                    FI.areaName,
                                    FI.areaCode,
                                    ROUND(SUM(IT.price), 2) as price,
                                    SUM(IT.quantity) as theoreticalQty,
                                    IFNULL(FI.countedQty, 0) as countedQty,
                                    ROUND(SUM(IT.quantity) * ROUND(SUM(IT.price), 2), 2) as theoreticalQtyValue,
                                    ROUND(IFNULL(FI.countedQty, 0) * ROUND(SUM(IT.price), 2), 2) as countedQtyValue,
                                    IFNULL(FI.countedQty, 0) - SUM(IT.quantity) as stockGapQty,
                                    ROUND((IFNULL(FI.countedQty, 0) - SUM(IT.quantity)) * SUM(IT.price), 2) as stockGapValue,
                                    DATE_FORMAT(ST.lastImport, "%d-%m-%Y %H:%i:%s") as dateOfLastImport,
                                    DATE_FORMAT(NOW(), "%d-%m-%Y %H:%i:%s") as dateOfExport
                            FROM Items as IT
                            LEFT JOIN ( 
                                SELECT MIN(FI.ean) as ean, SUM(FI.quantity) as countedQty, IT.itemCode,
                                GROUP_CONCAT(DISTINCT AR.name) as areaName,
                                GROUP_CONCAT(DISTINCT AR.code) as areaCode
                                FROM FoundItems as FI
                                INNER JOIN Items as IT ON FI.ean = IT.ean
                                LEFT JOIN Areas as AR ON AR.id = FI.areaId
                                
                                INNER JOIN Stores as ST ON ST.id = IT.storeId
                                
                                WHERE eventId = ${args.eventId}
                                AND IT.storeId = (SELECT storeId FROM Events WHERE id = ${args.eventId})
                                GROUP BY IT.itemCode
                            ) as FI ON IT.itemCode = FI.itemCode
                            INNER JOIN Stores as ST ON ST.id = IT.storeId
                            WHERE IT.storeId = (SELECT storeId FROM Events WHERE id = ${args.eventId})
                            GROUP BY IT.itemCode, FI.areaName, FI.areaCode, FI.countedQty, dateOfLastImport

    а що ця конструкція вміє, а ета що, про та ще й ето потрібно впихнути сюди

    silverreve23, 09 Января 2020

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

    +2

    1. 1
    2. 2
    Сколько красивых подростков проходит мимо каждый день...
    Почему нельзя просто взять - и отсосать, прямо на улице?

    Можно? Да ну нахуй!

    fuckyou, 28 Декабря 2019

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

    +2

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    Widget&& var1 = someWidget;      // here, “&&” means rvalue reference
     
    auto&& var2 = var1;              // here, “&&” does not mean rvalue reference
     
    template<typename T>
    void f(std::vector<T>&& param);  // here, “&&” means rvalue reference
     
    template<typename T>
    void f(T&& param);               // here, “&&”does not mean rvalue reference

    В мире нет ничего более сложного, запутанного и неадекватно раздутого, чем семантика ссылок и категорий значений в «C++».

    Заглянуть в ад одним глазком: https://en.cppreference.com/w/cpp/language/value_category
    Впустить Ад в себя: https://eli.thegreenplace.net/2014/perfect-forwarding-and-universal-references-in-c
    Поехать кукухой: https://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers

    gost, 28 Декабря 2019

    Комментарии (411)
  10. Куча / Говнокод #26268

    +2

    1. 1
    2. 2
    3. 3
    4. 4
    Ну я думаю все уже в курсе этой хуйни с обыском в Nginx
    Обыски, Сысоев и Коновалов были задержаны и прочая такая хуйня, традиционная для жителей РФ
    https://habr.com/ru/company/itsumma/blog/479942/
    Потом всякие набросы на всё том же хабре в духе "Я-МЫ Nginx" и так далее.

    Особенно забавно например такое:
    https://pbs.twimg.com/media/ELqxwTcXkAA04zq?format=jpg&name=large
    Социальная сеть, отжатая в результате налета на создателя силовиков большой IT-корпорацией во главе олигарха, выступает против налета силовиков на создателя веб-сервера, предпринятого в попытке отжать компанию большой IT-корпорацией во главе олигарха.

    j123123, 14 Декабря 2019

    Комментарии (156)
  11. Си / Говнокод #26067

    +2

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    /* ../COBYLA2/cobyla2.f -- translated by f2c (version 20100827) */
    ...
    /* Subroutine */ int cobyla_(integer *n, integer *m, doublereal *x, 
    	doublereal *rhobeg, doublereal *rhoend, integer *iprint, integer *
    	maxfun, doublereal *w, integer *iact)
    {
        static integer ia, idx, mpp, icon, isim, isigb, idatm, iveta, isimi, 
    	    ivsig, iwork;
        extern /* Subroutine */ int cobylb_(integer *, integer *, integer *, 
    	    doublereal *, doublereal *, doublereal *, integer *, integer *, 
    	    doublereal *, doublereal *, doublereal *, doublereal *, 
    	    doublereal *, doublereal *, doublereal *, doublereal *, 
    	    doublereal *, doublereal *, integer *);
        /* Parameter adjustments */
        --iact;
        --w;
        --x;
    
        /* Function Body */
        mpp = *m + 2;
        icon = 1;
        isim = icon + mpp;
        isimi = isim + *n * *n + *n;
        idatm = isimi + *n * *n;
        ia = idatm + *n * mpp + mpp;
        ivsig = ia + *m * *n + *n;
        iveta = ivsig + *n;
        isigb = iveta + *n;
        idx = isigb + *n;
        iwork = idx + *n;
        cobylb_(n, m, &mpp, &x[1], rhobeg, rhoend, iprint, maxfun, &w[icon], &w[
    	    isim], &w[isimi], &w[idatm], &w[ia], &w[ivsig], &w[iveta], &w[
    	    isigb], &w[idx], &w[iwork], &iact[1]);
        return 0;
    } /* cobyla_ */
    ...
    /* Subroutine */ int cobylb_(integer *n, integer *m, integer *mpp, doublereal 
    	*x, doublereal *rhobeg, doublereal *rhoend, integer *iprint, integer *
    	maxfun, doublereal *con, doublereal *sim, doublereal *simi, 
    	doublereal *datmat, doublereal *a, doublereal *vsig, doublereal *veta,
    	 doublereal *sigbar, doublereal *dx, doublereal *w, integer *iact)
    {
        /* Format strings */
        static char fmt_10[] = "(/3x,\002The initial value of RHO is\002,1pe13.6"
    	    ",2x,\002and PARMU is set to zero.\002)";
        static char fmt_50[] = "(/3x,\002Return from subroutine COBYLA because t"
    	    "he \002,\002MAXFUN limit has been reached.\002)";
        static char fmt_70[] = "(/3x,\002NFVALS =\002,i5,3x,\002F =\002,1pe13.6,"
    	    "4x,\002MAXCV =\002,1pe13.6/3x,\002X =\002,1pe13.6,1p4e15.6)";
        static char fmt_80[] = "(1pe19.6,1p4e15.6)";
        static char fmt_210[] = "(/3x,\002Return from subroutine COBYLA because"
    	    " \002,\002rounding errors are becoming damaging.\002)";
        static char fmt_410[] = "(/3x,\002Increase in PARMU to\002,1pe13.6)";
        static char fmt_580[] = "(/3x,\002Reduction in RHO to\002,1pe13.6,\002  "
    	    "and PARMU =\002,1pe13.6)";
        static char fmt_590[] = "(/3x,\002Normal return from subroutine COBYL"
    	    "A\002)";
    
        /* System generated locals */
        integer sim_dim1, sim_offset, simi_dim1, simi_offset, datmat_dim1, 
    	    datmat_offset, a_dim1, a_offset, i__1, i__2, i__3;
        doublereal d__1, d__2;
    
        /* Builtin functions */
        integer s_wsfe(cilist *), do_fio(integer *, char *, ftnlen), e_wsfe(void);
        double sqrt(doublereal);
    
        /* Local variables */
        static doublereal f;
        static integer i__, j, k, l, mp, np, iz;
        static doublereal phi, rho, sum, beta, cmin, cmax;
        static integer ivmc;
        static doublereal weta;
        static integer ivmd;
        static doublereal temp, wsig, gamma;
        static integer iflag;
        static doublereal alpha, delta, denom, tempa, barmu;
        static integer nbest, ifull, iptem, jdrop;
        static doublereal ratio, vmold, parmu, error, vmnew;
        extern /* Subroutine */ int calcfc_(integer *, integer *, doublereal *, 
    	    doublereal *, doublereal *);
        static integer ibrnch;
        static doublereal edgmax, pareta, prerec, phimin, parsig;
        static integer isdirn, nfvals, izdota;
        static doublereal cvmaxm, dxsign, prerem;
        static integer iptemp;
        static doublereal resmax, cvmaxp;
        static integer idxnew;
        static doublereal resnew, trured;
        extern /* Subroutine */ int trstlp_(integer *, integer *, doublereal *, 
    	    doublereal *, doublereal *, doublereal *, integer *, integer *, 
    	    doublereal *, doublereal *, doublereal *, doublereal *, 
    	    doublereal *, doublereal *);
    
        /* Fortran I/O blocks */
        static cilist io___22 = { 0, 6, 0, fmt_10, 0 };
        static cilist io___29 = { 0, 6, 0, fmt_50, 0 };
        static cilist io___33 = { 0, 6, 0, fmt_70, 0 };
        static cilist io___34 = { 0, 6, 0, fmt_80, 0 };
        static cilist io___39 = { 0, 6, 0, fmt_210, 0 };

    Найдено в зависимостях «SlangTNG». Библиотека «COBYLA», автоматически переведённая с «Фортрана».

    /* This subroutine minimizes an objective function F(X) subject to M */
    /* inequality constraints on X, where X is a vector of variables that has */
    /* N components. The algorithm employs linear approximations to the */
    /* objective and constraint functions, the approximations being formed by */
    /* linear interpolation at N+1 points in the space of the variables. */

    https://tng.tuxfamily.org/index.php?title=Main_Page

    XYPO3BO3, 05 Декабря 2019

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