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

    +43

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    /*
     * encoding.cpp
     *
     *  Created on: Oct 25, 2012
     *      Author: root
     */

    falsting, 17 Февраля 2014

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

    +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
    92. 92
    93. 93
    94. 94
    95. 95
    96. 96
    97. 97
    void KateQuickOpen::update () {
      // пропущено
      QModelIndex idxToSelect;
      int linecount = 0;
      QMapIterator<qint64, KTextEditor::View *> i2(sortedViews);
      while (i2.hasNext()) {
            i2.next();
    
            KTextEditor::Document *doc = i2.value()->document();
    
            if (alreadySeenDocs.contains(doc))
              continue;
    
            alreadySeenDocs.insert (doc);
    
            QStandardItem *itemName = new QStandardItem(doc->documentName());
    
            itemName->setData(qVariantFromValue(QPointer<KTextEditor::Document> (doc)), DocumentRole);
            itemName->setData(QString("%1: %2").arg(doc->documentName()).arg(doc->url().pathOrUrl()), SortFilterRole);
            itemName->setEditable(false);
            QFont font = itemName->font();
            font.setBold(true);
            itemName->setFont(font);
    
            QStandardItem *itemUrl = new QStandardItem(doc->url().pathOrUrl());
            itemUrl->setEditable(false);
            base_model->setItem(linecount, 0, itemName);
            base_model->setItem(linecount, 1, itemUrl);
            linecount++;
    
            if (!doc->url().isEmpty() && doc->url().isLocalFile())
              alreadySeenFiles.insert (doc->url().toLocalFile());
    
            // select second document, that is the last used (beside the active one)
            if (linecount == 2)
              idxToSelect = itemName->index();
        }
    
      // get all open documents
      QList<KTextEditor::Document*> docs = Kate::application()->documentManager()->documents();
        foreach(KTextEditor::Document *doc, docs) {
            // skip docs already open
            if (alreadySeenDocs.contains (doc))
              continue;
    
            QStandardItem *itemName = new QStandardItem(doc->documentName());
    
            itemName->setData(qVariantFromValue(QPointer<KTextEditor::Document> (doc)), DocumentRole);
            itemName->setData(QString("%1: %2").arg(doc->documentName()).arg(doc->url().pathOrUrl()), SortFilterRole);
            itemName->setEditable(false);
            QFont font = itemName->font();
            font.setBold(true);
            itemName->setFont(font);
    
            QStandardItem *itemUrl = new QStandardItem(doc->url().pathOrUrl());
            itemUrl->setEditable(false);
            base_model->setItem(linecount, 0, itemName);
            base_model->setItem(linecount, 1, itemUrl);
            linecount++;
    
            if (!doc->url().isEmpty() && doc->url().isLocalFile())
              alreadySeenFiles.insert (doc->url().toLocalFile());
        }
    
        // insert all project files, if any project around
        if (Kate::PluginView *projectView = m_mainWindow->mainWindow()->pluginView ("kateprojectplugin")) {
          QStringList projectFiles = projectView->property ("projectFiles").toStringList();
          foreach (const QString &file, projectFiles) {
            // skip files already open
            if (alreadySeenFiles.contains (file))
              continue;
    
            QFileInfo fi (file);
            QStandardItem *itemName = new QStandardItem(fi.fileName());
    
            itemName->setData(qVariantFromValue(KUrl::fromPath (file)), UrlRole);
            itemName->setData(QString("%1: %2").arg(fi.fileName()).arg(file), SortFilterRole);
            itemName->setEditable(false);
            QFont font = itemName->font();
            font.setBold(true);
            itemName->setFont(font);
    
            QStandardItem *itemUrl = new QStandardItem(file);
            itemUrl->setEditable(false);
            base_model->setItem(linecount, 0, itemName);
            base_model->setItem(linecount, 1, itemUrl);
            linecount++;
          }
        }
    
        // swap models and kill old one
        m_model->setSourceModel (base_model);
        delete m_base_model;
        m_base_model = base_model;
    
        // пропущено
    }

    Адская копипаста. У меня мозг сегфолтится при попытке ее формализировать.

    https://projects.kde.org/projects/kde/applications/kate/repository/revisions/master/entry/kate/app/katequickopen.cpp#L135

    Elvenfighter, 16 Февраля 2014

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

    +58

    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
    template <typename T>
    class MySharedPtr{
    public:
      explicit MySharedPtr(T* obj) : _obj(obj){}
      // --> я дописал
      MySharedPtr(const MySharedPtr& other) : _obj(other._obj){ inc_ref_count(_obj);}
      // <-- я дописал
      MySharedPtr& operator=(const MySharedPtr& other) {
        // --> я дописал
        if (this == &other)
          return *this;
        // <-- я дописал
        _obj = other._obj;
        inc_ref_count(_obj);
      }
      ~MySharedPtr(){
        dec_ref_count(_obj);
      }
    
    private:
      static void inc_ref_count(T* obj){
        std::lock_guard<std::mutex> lock(_mutex);
        _ref_count[obj] ++ ;
      }
    
      static void dec_ref_count(T* obj){
        std::lock_guard<std::mutex> lock(_mutex);
        if (--_ref_count[obj]){
          delete obj;
          _ref_count.erase(_ref_count.find(obj));
        }
      }
    
      T* _obj;
    
      static std::mutex MySharedPtr<T>::_mutex;
      static std::map<T*,int> MySharedPtr<T>::_ref_count;
    };
    
    
    template <typename T>
    std::map<T*,int> MySharedPtr<T>::_ref_count;
    
    
    template <typename T>
    std::mutex MySharedPtr<T>::_mutex;

    сегодня приходил чел-выпускник, написал на листочке shared_ptr, какое ваше мнение?

    LispGovno, 14 Февраля 2014

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

    +51

    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
    template <class T> class return_1_t: public std::unary_function<T, T> {
    public:
    	return_1_t(const T & Ret) : _ret(Ret) {}
    	T operator()(T Arg) const { return _ret; }
    private:
    	T _ret;
    };
    template <class Arg1, class Arg2> class project1st: public std::binary_function<Arg1, Arg2, Arg1> {
    public:
    	Arg1 operator()(const Arg1 & X, const Arg2 & Y) { return X; }
    };
    template <class Arg1, class Arg2> class project2nd: public std::binary_function<Arg1, Arg2, Arg2> {
    public:
    	Arg2 operator()(const Arg1 & X, const Arg2 & Y) { return Y; }
    };
    template <class T> class identity: public std::unary_function<T, T> {
    public:
    	T operator()(const T & Arg) const { return Arg; }
    };
    template <class To, class From> class static_cast_t: public std::unary_function<To, From> {
    public:
    	To operator()(From obj) const {	return static_cast<To>(obj); }
    };
    template <class T> class take_address: public std::unary_function<T&, T*> {
    public:
    	result_type operator()(argument_type arg) const { return &(arg); }
    };
    template <class T> class take_const_address: public std::unary_function<const T&, const T*> {
    public:
    	result_type operator()(argument_type arg) const { return &(arg); }
    };
    template <class T> class creator: public std::unary_function<void, T*> {
    public:
    	result_type operator()(void) const { return new T(); }
    };
    template <class T, class Arg1> class creator_1_par: public std::unary_function<Arg1, T*> {
    public:
    	result_type operator()(argument_type arg) const { return new T(arg); }
    };
    template <class T, class Arg1, class Arg2> class creator_2_par: public std::binary_function<Arg1, Arg2, T*> {
    public:
    	result_type operator()(first_argument_type arg1, second_argument_type arg2) const	{ return new T(arg1, arg2);	}
    };
    template <class T> class maker: public std::unary_function<void, T> {
    public:
    	result_type operator()(void) const { return T(); }
    };
    template <class T, class Arg1> class maker_1_par: public std::unary_function<Arg1, T> {
    public:
    	result_type operator()(argument_type arg) const { return T(arg); }
    };
    template <class T, class Arg1, class Arg2> class maker_2_par: public std::binary_function<Arg1, Arg2, T> {

    Вот до чего доводит людей отсутствие частичного применения и лямбд.

    laMer007, 13 Февраля 2014

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

    +55

    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
    #include <iostream>
    #include <thread>
    #include <cmath>
    #include <cstdlib>
    #include <algorithm>
    #include <iterator>
    #include <future>
    
    constexpr std::size_t array_size = 1e7;
    constexpr std::size_t chunks_number = 1e3;
    
    double local_pi(const std::size_t array_length)
    {
        std::vector<std::pair<double, double>> array_xy;       
        array_xy.reserve(array_length);      
        std::generate_n(std::back_inserter(array_xy), array_length, [](){
          return std::make_pair(rand()/static_cast<double>(RAND_MAX), 
    			    rand()/static_cast<double>(RAND_MAX));
          });
        std::vector<bool> bool_z;
        bool_z.reserve(array_length);
        auto bool_z_insterter = std::back_inserter(bool_z);
        std::for_each(array_xy.cbegin(), array_xy.cend(), [&](const std::pair<double, double>& ref){
          const auto func = [](const std::pair<double, double>& ref){
    	return sqrt(pow(ref.first, 2) + pow(ref.second, 2)) <= 1.0;
          };
          bool_z_insterter = func(ref);
        });
        const auto sum = 4.0 * (std::accumulate(bool_z.cbegin(), bool_z.cend(), 0.0)/array_length);
        return sum;
    }
    int main(){
      const auto concurrency_level = std::thread::hardware_concurrency();
      std::vector< double > chunks_vector;
      chunks_vector.reserve(chunks_number);
      for (std::size_t j = 0; j < chunks_number; ++j) {
        std::vector<std::future<double>> futures;
        futures.reserve(concurrency_level-1);
        for (std::size_t i = 0; i < concurrency_level-1; ++i){
          auto f = std::async(std::launch::async, local_pi, array_size/concurrency_level);
          futures.push_back(std::move(f));
        }
        auto pi = local_pi(array_size/concurrency_level);
        for (auto&& x : futures ){
          pi += x.get();
        }
        pi /= concurrency_level;
        chunks_vector.push_back(pi);
      }
      const auto total_pi = std::accumulate(chunks_vector.cbegin(), chunks_vector.cend(), 0.0)/chunks_vector.size();
      std::cout << "Pi equals = " << std::scientific << total_pi << std::endl;
      return 0;
    }

    Вычисляем pi методом Монте-Карло

    Abbath, 10 Февраля 2014

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

    +45

    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
    for (int i=0; i<N-1; ++i) for (int j=0; j<N-1; ++j)
    		{
    			int& 
    				f1=fields[i  ][j  ].index,
    				f2=fields[i+1][j  ].index,
    				f3=fields[i  ][j+1].index,
    				f4=fields[i+1][j+1].index;
    			if (f1<=0 && f2<=0 && f3<=0 && f4<=0) 
    			{
    				f1=-1;
    				f2=-1;
    				f3=-1;
    				f4=-1; 
    			}				
    		}

    несколько минут пырился в код и не мог понять, где ошибка
    БЛЯДСКАЯ КРЕСТОПИДЕРАСТИЧНАЯ СИСТЕМА ИМЕНОВАНИЯ ТИПОВ ПЕРЕМЕННЫХ

    TarasB, 10 Февраля 2014

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

    +63

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    #include <iostream>
    using namespace std;
    
    int main() {
    	// your code goes here
    	float f = 267.0f;
    	unsigned char c = f;
    	cout << (int)c << endl;
    	return 0;
    }

    Кресты помогают обнаруживать ошибки в логике программы. За это Страуструпу респект и уважуха.

    http://ideone.com/V9rgSC

    LispGovno, 09 Февраля 2014

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

    +63

    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
    int main()
    {
    	server::CServer();
    	return 0;
    }
    
    class CServer {
    public:
        CServer()
        {
            SOCKET listen_sd = socket (AF_INET, SOCK_STREAM, 0);	  CHK_ERR(listen_sd, "socket");
            SET_NONBLOCK(listen_sd);
    
            struct sockaddr_in sa_serv;
            memset (&sa_serv, '\0', sizeof(sa_serv));
            sa_serv.sin_family      = AF_INET;
            sa_serv.sin_addr.s_addr = INADDR_ANY;
            sa_serv.sin_port        = htons (1111);          /* Server Port number */
    
            int err = ::bind(listen_sd, (struct sockaddr*) &sa_serv, sizeof (sa_serv));      CHK_ERR(err, "bind");
            
            err = listen (listen_sd, 5);            CHK_ERR(err, "listen");
    
            while(true)
            {
                    Sleep(1);
    
                    struct sockaddr_in sa_cli;  
                    size_t client_len = sizeof(sa_cli);
    #ifdef WIN32
                    const SOCKET sd = accept (listen_sd, (struct sockaddr*) &sa_cli, (int *)&client_len);
    #else
                    const SOCKET sd = accept (listen_sd, (struct sockaddr*) &sa_cli, &client_len);
    #endif  
                    Callback(sd);
            }
        }
    };

    http://habrahabr.ru/post/211853/

    Бесконечный цикл (event loop) в конструкторе.

    Опущены неинтересные строчки инициализации всякой фигни.

    Про Sleep вместо select/epoll/etc. я вовсе молчу.

    WGH, 08 Февраля 2014

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

    +56

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    #include <iostream>
    using namespace std;
    
    int main() {
    	int i = 5;
    	int* p1 = &i;
    	volatile int* p2 = &i;
    	cout << p1 << endl;
    	cout << p2 << endl;
    	return 0;
    }

    http://ideone.com/hpw4CB

    LispGovno, 08 Февраля 2014

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

    +51

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    #include <iostream>
    using namespace std;
    
    int main() {
        const int ci = 42;
        auto f = [ci]() mutable { std::cout << ++ci << '\n'; };
        f();
        return 0;
    }

    http://ideone.com/0P72sN
    А слона то я и не приметил.

    LispGovno, 07 Февраля 2014

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