1. C++ / Говнокод #24324

    0

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    void Foo::singleShot()
    {
        QTime delay = QTime::currentTime().addMSecs(50);  
        while(QTime::currentTime() < delay ) {
           QCoreApplication::processEvents(QEventLoop::AllEvents, 5;
        }
        // do something
    }

    Вот такой бриллиант инженерной мысли, написанный с использованием фреймворка Qt.
    Товарисч ещё спрашивал, чем его реализация хуже чем QTimer::singleShot() :D

    Titus_PuIIo, 26 Мая 2018

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

    +3

    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
    using namespace std;
    #include <typeinfo>
    #include <stdlib.h>
    #include <stdio.h>
    #include <string>
    #include <math.h>
    #include <stdarg.h>
    
    template <unsigned FRA,unsigned EXP>
    struct F {
        union{
            float     f;
            unsigned ui;
            unsigned ef : FRA+EXP;	    
            struct
            {
    	        unsigned f : FRA;
    	        unsigned e : EXP;
    	        unsigned s : 1;
            } s;
        };
        F (double x){f=x;}
        F operator =(const double x) { 
            f=x; return *this;
        }    
        
    #define NOOP ;
    #define  UN(OP,BODY, RET)   float    operator OP(	) { BODY; return RET;}
    #define BIN(OP,BODY, RET)   F    operator OP(F other	) { BODY; return RET;}
    #define BINF(OP,BODY,RET)   F    operator OP(const float other) { BODY; } BIN(OP,BODY,RET)
    #define CMP(OP)        bool operator OP(const F& other) 
    
        UN ( -  ,   s.s^=1   ,     (f)       )
        BIN( += , f+=other.f , (  *this  )   )
        BIN( +  , NOOP       , { f+other.f}   )
        BIN( -  ,++other.s.s , {*this+other} )
        BIN( *  ,   NOOP    ,   fmul(f,{other})        )
        BIN( /  , div(other), (  *this  ) )
        BINF(*=, ui=fmul(*this   ,{other}).ui, (  *this  )   )  
        BINF(/=, ui=fmul(*this,rcp(other)).ui, (  *this  )   )  
    
    
        CMP(==){
            return other.ui==ui;
        }    
    
        F out(string s) const{
            printf("> %s%f\n",s.c_str(),f);
        }
        F plus(F other)
        {
            f+=other.f;
            return *this;        
        }    
        
        F div(F other)
        {
            ui=fmul(rcp(other),{f}).ui;
            return *this;        
        }    
        F sqrt()
        {
            s.e-=127;
            ui>>=1; 
            s.f-=(s.f>>4);
            s.e+=127;        
            return *this;        
        }
        F pow(int n)
        {
            s.e-=127;
            ui*=n; 
            ef+=(ef>>4);
            ef-=(ef>>9);
            s.e+=127;
            return *this;
        }    
    
    private:    
        static F rcp(F f) {
            f.s.e=(~f.s.e-2);
            f.s.f=(~f.s.f-2);
            return f;
        }
        
        static F fmul(F r,F b)
        {
            r.s.s   ^= b.s.s;
            r.ef += ((r.s.f&b.s.f)>>4);
            r.ef += b.ef ;
            r.s.e+= 129;
            return r;
        }
    
     
    };
    
    using F32 = F<23,8>;
    
    static F32 of32(float x)

    Царь был прав. Во всём.
    Патамучто это плавающий питух, который априори говно. И чем вы быстрее это поймёте, чем будет лучше.

    В соответствии со своим пониманием сделал мммаксимально простую реализацию плавающих питухов произвольного размера.
    Строго на интах.


    Пример здесь:
    uhttps://ideone.com/dDrj7s

    3.14159265, 16 Мая 2018

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

    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
    https://github.com/dotnet/coreclr/blob/a589e3926a1780256fdb52376f8681fe047daf54/src/vm/i386/cgenx86.cpp#L1551-L1553
    
        PAL_TRY(Param *, pParam, &param)
        {
            unsigned char buffer[16];
            DWORD* dwBuffer = NULL;
    
            DWORD maxCpuId = getcpuid(0, buffer);
    
            if (maxCpuId < 1)
                goto lDone;
    
            dwBuffer = (DWORD*)buffer;
    
            if (dwBuffer[1] == 'uneG') {
                if (dwBuffer[3] == 'Ieni') {
                    if (dwBuffer[2] == 'letn')  {  // get SMT/multicore enumeration for Intel EM64T

    С каких пор в одинарные кавычки можно писать больше одного символа? Это какое-то MSVC или что?

    j123123, 09 Мая 2018

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

    −1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    // https://github.com/dotnet/coreclr/blob/a589e3926a1780256fdb52376f8681fe047daf54/src/vm/binder.cpp#L503-L511
    
    const MscorlibBinder::OffsetAndSizeCheck MscorlibBinder::OffsetsAndSizes[] =
    {
        #define DEFINE_CLASS_U(nameSpace, stringName, unmanagedType) \
            { PTR_CSTR((TADDR) g_ ## nameSpace ## NS ), PTR_CUTF8((TADDR) # stringName), sizeof(unmanagedType), 0, 0, 0 },
        
        #define DEFINE_FIELD_U(stringName, unmanagedContainingType, unmanagedOffset) \
            { 0, 0, 0, PTR_CUTF8((TADDR) # stringName), offsetof(unmanagedContainingType, unmanagedOffset), sizeof(((unmanagedContainingType*)1)->unmanagedOffset) },
        #include "mscorlib.h"
    };

    Дух старой школы всё еще живет в майкрософт

    j123123, 08 Мая 2018

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

    −1

    1. 1
    2. 2
    3. 3
    j123123, ты вообще пишешь полезный код или занимаешься 
    только тем, что постишь на говнокод советы космического масштаба
    и комической же глупости о том, как всё оптимизировать?

    dm_fomenok, 07 Мая 2018

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

    +2

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    struct Bar {};
    
    class Foo {
    public:
        Bar& bar() const { return *bp; }
    
    private:
        Bar b;
        Bar * const bp = &b;
    };

    https://wandbox.org/permlink/7JPzrvslrUwbvREb

    Как называется данный говнопаттерн?

    Elvenfighter, 27 Апреля 2018

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

    −6

    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
    /* Q: Can someone recommend a more elegant way to achieve these compile-time constants? */
    template <int> struct Map;
    template <> struct Map<0> {static const int value = 4;};
    template <> struct Map<1> {static const int value = 8;};
    template <> struct Map<2> {static const int value = 15;};
    
    template <int> struct MapInverse;
    template <> struct MapInverse<4> {static const int value = 0;};
    template <> struct MapInverse<8> {static const int value = 1;};
    template <> struct MapInverse<15> {static const int value = 2;};
    
    
    /* A: Another TMP approach for a linear search using C++11: */
    #include <type_traits>
    
    // === Types:
    // Usage:
    //    Function<Map<x1,y1>,Map<x2,y2>,...>
    template<int D, int R> struct Map { enum { domain=D, range=R }; };
    template<typename ...A> struct Function {};
    
    // === Metafunctions:
    // Usage:
    //    ApplyFunction<x,F>::value
    template<int I, typename M> struct ApplyFunction;
    // Usage:
    //    ApplyFunctionInverse<x,F>::value
    template<int I, typename M> struct ApplyFunctionInverse;
    
    // ==== Example:
    // Define function M to the mapping in your original post.
    typedef Function<Map<0,4>,Map<1,8>,Map<2,15>> M;
    
    // ==== Implementation details
    template<typename T> struct Identity { typedef T type; };
    template<int I, typename A, typename ...B> struct ApplyFunction<I, Function<A,B...> > {
       typedef typename
          std::conditional <I==A::domain
                           , Identity<A>
                           , ApplyFunction<I,Function<B...>> >::type meta;
       typedef typename meta::type type;
       enum { value = type::range };
    };
    template<int I, typename A> struct ApplyFunction<I, Function<A>> {
       typedef typename
           std::conditional <I==A::domain
                            , Identity<A>
                            , void>::type meta;
       typedef typename meta::type type;
       enum { value = type::range };
    };
    // Linear search by range
    template<int I, typename A> struct ApplyFunctionInverse<I, Function<A>> {
       typedef typename
           std::conditional <I==A::range
                            , Identity<A>
                            , void>::type meta;
       typedef typename meta::type type;
       enum { value = type::domain };
    };
    template<int I, typename A, typename ...B> struct ApplyFunctionInverse<I, Function<A,B...> > {
       typedef typename
           std::conditional <I==A::range
                            , Identity<A>
                            , ApplyFunctionInverse<I,Function<B...>> >::type meta;
       typedef typename meta::type type;
       enum { value = type::domain };
    };
    
    // ==============================
    // Demonstration
    #include <iostream>
    int main()
    {
       // Applying function M
       std::cout << ApplyFunction<0,M>::value << std::endl;
       std::cout << ApplyFunction<1,M>::value << std::endl;
       std::cout << ApplyFunction<2,M>::value << std::endl;
    
       // Applying function inverse M
       std::cout << ApplyFunctionInverse<4,M>::value << std::endl;
       std::cout << ApplyFunctionInverse<8,M>::value << std::endl;
       std::cout << ApplyFunctionInverse<15,M>::value << std::endl;
    }

    Элегантненько.
    s: https://stackoverflow.com/questions/26075969/compile-time-map-and-inverse-map-values

    gost, 25 Апреля 2018

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

    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
    #include "stdafx.h"
    #include<iostream>
    #include<vector>
    
    using namespace std;
    /*
    Задание: перемножить две матрицы и вывести результат на экран
    */
    
    vector<vector<int>> inputToVector(int n,int m) {
    	vector<vector<int>>vec(n, vector<int>(m));
    	for (int i = 0; i < n; i++) {
    		for (int j = 0; j < m; j++) {
    			cin >> vec[i][j];
    
    		}
    	}
    	return vec;
    }
    template<class T>
    void multiple(vector<T>a,vector<T>b,int x1,int y1,int y2) {
    	int ans = 0;
    	for (int i = 0; i < x1; i++) {
    		for (int j = 0; j < y2; j++) {
    			for (int k = 0; k < y1; k++) {
    				ans += a[i][k] * b[k][j];
    			}
    			cout << ans << '\t';
    			ans = 0;
    		}
    		
    		cout << endl;
    	}
    }
    int main()
    {
    	setlocale(LC_ALL, "Russian");
    	int x1, y1, x2, y2,temp;
    	cout << "Требуется вычислить произведение двух матриц А и В" << endl;
    	cout << "Введите размерность матрицы А" << endl;
    	cin >> x1 >> y1;
    	cout << "Введите элементы матрицы А" << endl;
    	vector<vector<int>>one = inputToVector(x1, y1);
    	cout << "Введите размерность матрицы B" << endl;
    	cin >> x2 >> y2;
    	cout << "Введите элементы матрицы B" << endl;
    	vector<vector<int>>two = inputToVector(x2, y2);
    	cout << "Результирующая матрица, полученная перемножением матрицы А на матрицу В" << endl;
    	multiple(one, two,  x1,  y1, y2);
    	system("pause");
    	return 0;
    }

    ArthurMakaev, 13 Апреля 2018

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

    +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
    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
    #include "stdafx.h"
    #include <fstream>
    #include <iostream>
    using namespace std;
    int isMax(char mask[], int num, char in[]);        //Функция проверки символа
    int main(int argc, char* argv[])
    {
        if (argc == 1) {
            cout << "Use PasswordGenerator [Mask] [quantity of passwwords] [Path to file]\n";        //Проверка входных параметров
            return 1;
        }
        ofstream out;            //Выходной файл
        out.open(argv[3]);        //Открываем файл с именем которое ввел пользователь
        int len = 0;                    //Длина пароля
        char mask[1024] = "hll";       //Маска пароля
        char buff[1024] = { 0 };        //Буфер под пароль
        double quant = 0;                //Количество паролей в выходном файле
        strcpy_s(mask, argv[1]);        //копируем маску введённую пользователем
        len = strlen(mask);                //Узнаем длину
        for (int ii = 0; ii < len; ii++) {
            if ((mask[ii]= 'l') && (mask[ii]= 'h')&& (mask[ii]= 'n')) {           //Проверка маски на корректность
                cout << "Mask can be l h n\n";                                        //Маска может содержать только: l маленькие латинские буквы; h большие латинские буквы; n цифры
                    return 2;
            }
        }
        quant = atoi(argv[2]);                      //Запоминаем количество комбинаций
        if (quant == 0) {                           //Если пользователь ввел "0"
            quant = 1;                                //То считаем все возможные комбинации
            for (int ii = 0; ii < len; ii++) {         
                switch (mask[ii])
                {
                case 'l': quant *= 26; break;       //26 - количество возможных букв
                case 'h': quant *= 26; break;
                case 'n': quant *= 10; break;       //10 - количество возможных цифр
                default:
                    break;
                }
            }
        }
        int ii = 0;        //Нужная переменная
        for (ii = 0; ii < len; ii++) {               //Тут создается стартовая комбинация
    
            switch (mask[ii])                        //Например для nnllh будет 00aaA
            {
            case 'l': buff[ii] = 'a'; break;
            case 'h': buff[ii] = 'A'; break;
            case 'n': buff[ii] = '0'; break;
                default:
                    break;
            }
        }
        ii++;
        buff[ii] = '\0';                            //Добавляем маркер конца строки
        double flagc = quant / 10;                  //Константа для поиска процента завершения
        double flag = flagc;                        //Переменная процента завершения
        int per = 1;                                //Множитель процента
        for ( ii = 0; ii < quant; ii++) {                                   //Основной цикл
            out << buff << endl;                                            //Сохраняем пароль в файл
            if (ii >= flag) {                        //Если программа завершила 10%
                cout << per * 10 << "%\n";           //Выводим проценты
                per++;
                flag += flagc;
            }
            for (int ii = len - 1; ii >= 0; ii--) {                        //начинаем посимвольный перебор с конца строки
                if (isMax(mask, i, buff) == 1) {                           //Если встречаем последний возможный символ в данной позиции, то меняем его на стартовый
                    switch (mask[ii])
                   {
                    case 'l': if (buff[ii] == 'z')buff[ii] = 'a'; break;
                    case 'h': if (buff[ii] == 'Z')buff[ii] = 'A'; break;
                    case 'n': if (buff[ii] == '9')buff[ii] = '0'; break;
                  default:
                        break;
                    }
                    continue;    //Переход в следующую итерацию цикла
                }
                buff[ii] +=1;     //Сама инкрементация пароля
                break;            //Конец внутреннего цикла
            }
    }
        return 0;
    }
    int isMax(char mask[], int num, char in[]){
        switch (mask[num])
        {
    case 'l': if (in[num] == 'z')return 1; else return 0;            //Если символ последний, то возвращаем "1", в противном случае "0"
        case 'h': if (in[num] == 'Z')return 1; else return 0;
        case 'n': if (in[num] == '9')return 1; else return 0;
        default:
            break;
        }
    }

    Простой генератор паролей на C++
    https://codeby.net/forum/threads/prostoj-generator-parolej-na-c.61639/

    lolka, 11 Апреля 2018

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

    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
    #include "stdafx.h"
    #include<iostream>
    #include<map>
    #include<set>
    #include<string>
    #include<fstream>
    #include<iomanip>
    #include<algorithm>
    //#include<algorithm>
    using namespace std;
    int main()
    {
    	
    	setlocale(LC_ALL, "Russian");
    	multimap<string, int> mp;
    	multimap<string, int>::iterator it;
    	multimap<string, int>::iterator mit;
    	pair<multimap<string,int>::iterator, multimap<string, int>::iterator> pt;
    	set<int>nset;
    
    	string word;
    	char c = ' ';
    	
    
    	char s[256];
    	fstream inOut;
    	inOut.open("text.txt", ios::in);
    	for (int i = 1; i < 500; i++) {
    		inOut.getline(s, 256);
    	
    		char* pch;
    		pch = strtok(s, " ,-:");
    		while (pch != NULL) {
    			word = string(pch);
    			transform(word.begin(), word.end(), word.begin(), ::tolower);
    			mp.insert(pair <string, int>(word, i));
    			//cout « pch «'\t'«i« endl;
    			pch = strtok(NULL, " ,-:");
    		}
    	}
    	inOut.close();
    
    
    
    
    
    	set<string>set;
    
    	string tmp;
    
    	for (mit = mp.begin(); mit != mp.end(); mit++) {
    		tmp = (*mit).first;
    		if (set.find(tmp) != set.end()) {
    			continue;
    		}
    		else {
    
    			set.insert(tmp);
    			cout<<setw(15) << tmp << '\t';
    			pt = mp.equal_range(tmp);
    			
    			for (it = pt.first; it != pt.second; ++it) {
    				nset.insert(it->second);
    				
    			}
    			//cout << nset.size() << "     ";
    			for (it = pt.first; it != pt.second; ++it) {
    				
    				cout << it->second << ' ';
    			}
    			nset.clear();
    			cout << endl;
    		}
    	}
    	system("pause");
    	return 0;
    }

    Программа считывает слова сортирует и выдаёт все номера строк где данное слово встречается

    ArthurMakaev, 10 Апреля 2018

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