1. C# / Говнокод #14234

    +137

    1. 1
    var romans = "I II III IV".Split(' ');

    Rez, 17 Декабря 2013

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

    +10

    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
    #include <iostream>
    #include <list>
    #include <queue>
    #include <memory>
    #include <mutex>
    #include <condition_variable>
    #include <type_traits>
    #include <assert.h>
    using namespace std;
    
    template<class Data>
    class UnboundedQueueForNonThrowMovable
    {
    	static_assert(std::is_nothrow_move_constructible<Data>::value, "Data must be nonthrow movable type.");
    	static_assert(!std::is_array<Data>::value, "Data must not be c-array.");
    	
    public:
    	typedef Data value_type;
    	
    private:
    	typedef std::queue<Data, std::list<Data>> Queue;
    	typedef std::unique_lock<std::mutex> Lock;
    	Queue _queue;
    	std::mutex _lockQueue;
    	std::condition_variable _pushToQueue;
    	
    	UnboundedQueueForNonThrowMovable(const UnboundedQueueForNonThrowMovable&) = delete;
    	UnboundedQueueForNonThrowMovable(UnboundedQueueForNonThrowMovable&&) = delete;
    	UnboundedQueueForNonThrowMovable& operator=(const UnboundedQueueForNonThrowMovable&) = delete;
    	UnboundedQueueForNonThrowMovable& operator=(UnboundedQueueForNonThrowMovable&&) = delete;
    public:
    	UnboundedQueueForNonThrowMovable(void){}
    	
    	void push(Data&& data)
    	{
    		Lock lockerQueue(this->_lockQueue);
    		this->_queue.push(std::move(data));
    		this->_pushToQueue.notify_all();//_condition.notify_one(); most optimal, but can cause deadlock.
    	}
    	
    	void push(Data& data)
    	{
    		this->push(std::move(data));
    	}
    	
    	bool emptyUnstable(void) const
    	{
    		Lock lockerQueue(this->_lockQueue);
    		return this->_queue.empty();
    	}
    	
    	Data pop(void)
    	{
    		Lock lockerQueue(this->_lockQueue);
    		this->_pushToQueue.wait(lockerQueue, [this](void){return !this->_queue.empty();});
    		assert(!this->_queue.empty());
    		Data result = std::move(this->_queue.front());
    		this->_queue.pop();
    		return result;
    	}
    	
    	template< class Rep, class Period>
    	Data pop(const std::chrono::duration<Rep, Period> WaitDuration)
    	{
    		Lock lockerQueue(this->_lockQueue);
    		if(!this->_pushToQueue.wait(lockerQueue, WaitDuration, [this](void){return !this->_queue.empty();}))
    			return Data();
    		assert(!this->_queue.empty());
    		Data result = std::move(this->_queue.front());
    		this->_queue.pop();
    		return result;
    	}
    };
    
    template<class Data>	
    using UnboundedQueueForUniquePtr = UnboundedQueueForNonThrowMovable<std::unique_ptr<Data>>;
    template<class Data>
    using UnboundedQueueForSharedPtr = UnboundedQueueForNonThrowMovable<std::shared_ptr<const Data>>;
    template<class Data>
    using UnboundedQueue = UnboundedQueueForUniquePtr<Data>;
    
    int main() {
    	cout<<"ok"<<endl;
    	{
    		//UnboundedQueueForSharedPtr<int>::value_type == std::shared_ptr<const int>
    		UnboundedQueueForSharedPtr<int> queueSharedPtr;
    		//auto a = std::make_shared<const int>(45);
    		auto a = std::make_shared<int>(45);
    		assert(a);
    		queueSharedPtr.push(a);
    		assert(!a);//Fired if you use "auto a = std::make_shared<int>(45)" below. It is compiler bug, I think, because previus code line must cause compile error.
    		auto b = queueSharedPtr.pop();//std::shared_ptr<const int>
    		assert(b);
    		cout<<*b<<endl;
    		assert(*b==45);

    http://ideone.com/qdsWJi
    Немного глупый вопрос, почему в 90 строчке не получаем ошибку компиляции если закомментировать 87-ую строку и разкомментировать 88-ую?

    laMer007, 16 Декабря 2013

    Комментарии (15)
  3. PHP / Говнокод #14231

    +161

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    //надо показать элемент каталога во всей красе
    $_CENTER="show_category_item(".$newParts[0].");";
    eval($_CENTER);
    
    // ...
    $_LEFT='get_main_category($cat_id, $new_path);';
    $_CENTER="show_category_item_list($".'newParts'.");";

    Вот с таким адом мне приходится работать.

    oooZinka, 16 Декабря 2013

    Комментарии (15)
  4. Java / Говнокод #14230

    +74

    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
    for (int i = 0; i != nl.length(); i++)
    {
        out.write(nl.charAt(i));
    }
    
    for (int i = 0; i != footerStart.length(); i++)
    {
        out.write(footerStart.charAt(i));
    }
    
    for (int i = 0; i != type.length(); i++)
    {
        out.write(type.charAt(i));
    }
    
    for (int i = 0; i != footerTail.length(); i++)
    {
        out.write(footerTail.charAt(i));
    }
    
    for (int i = 0; i != nl.length(); i++)
    {
        out.write(nl.charAt(i));
    }

    Зачем писать функцию, когда можно успешно копипастить циклы

    http://grepcode.com/file/repo1.maven.org/maven2/org.bouncycastle/bcpg-jdk16/1.45/org/bouncycastle/bcpg/ArmoredOutputStream.java

    roman-kashitsyn, 15 Декабря 2013

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

    +7

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    auto r = [&](){
    for(auto i: a)
      if(i==k)
        return f(i);
    }();

    Однажды мне знакомый рассказывал, что во многих языках плохие грязные циклы. Мол настоящие чистые циклы должны возвращать значение. Я написал ему вот это. Он многозначительно подумал и замолчал. Через две с половиной недели он уволился.

    LispGovno, 14 Декабря 2013

    Комментарии (19)
  6. Java / Говнокод #14228

    +72

    1. 1
    2. 2
    3. 3
    4. 4
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWITHMD5ANDTRIPLEDES");
    PBEKeySpec spec = new PBEKeySpec(password, salt, 1024, 128);
    SecretKey key = factory.generateSecret(spec);
    hexdump(key.getEncoded());

    http://ideone.com/bVElQG

    Не, ну я все понимаю, PKCS #5 1.5 аля PBE, MD5 и DES не считаются безопасными алгоритмами... но не настолько же...

    bormand, 14 Декабря 2013

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

    +137

    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
    if (!string.IsNullOrEmpty(date))
    			{
    				var result = date.Split('.');
    				filter.TenderDate.Start = new DateTime(
    					Convert.ToInt16(result[2]),
    					Convert.ToInt16(result[1]),
    					Convert.ToInt16(result[0]),
    					0,
    					0,
    					0);
    				filter.TenderDate.End = new DateTime(
    					Convert.ToInt16(result[2]),
    					Convert.ToInt16(result[1]),
    					Convert.ToInt16(result[0]),
    					23,
    					59,
    					59);
    			}

    Парсинг дат? Не, не слышал.

    xumix, 14 Декабря 2013

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

    +135

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    $(function () {
    		var objects = [
    		@foreach (var item in Model.PlannedObjectSet)
      {
    			<text>{ Address: '@item.Address', Name: '@item.Name', Id: @item.Id, date: '@item.PlannedStartDate', type: @item.ObjectType, Coords: @(item.Coords ?? "null") }@(item == Model.PlannedObjectSet.Last() ? "" : ",")</text>
      }
    		];
    		$('#map').tenderMap({mode:'p', zoom:10, center:[55.83, 37.58]});
    		$('#map').tenderMap('showData', objects);
    	});

    Вот такая вот сериализация в JSON встретилась мне сегодня в коде Razor view

    xumix, 14 Декабря 2013

    Комментарии (58)
  9. Assembler / Говнокод #14225

    +143

    1. 1
    2. 2
    .686
    .model tiny

    Весьма специфичная ошибка при использовании masm32.

    laMer007, 14 Декабря 2013

    Комментарии (56)
  10. Си / Говнокод #14224

    +135

    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
    void permutate(int a[10], int n) {
        // God bless mr. Donald E. Knuth;
        // Tons of oil to English bell ringers!
    
        // WARNING: It's dangerous to go alone, take this^H read this shit
        int c[10], o[10], j, s, q;
        for (j = 1; j <= n; j++) {
            c[j] = 0;
            o[j] = 1;
        }
        while (1) {
            check(a, n);
            j = n;
            s = 0;
            while (1) {
                do {
                    q = c[j] + o[j];
                    if (q < 0) { o[j] = -o[j]; --j; }
                } while (q < 0);
                if (q == j) {
                    if (j == 1) return; else ++s;
                    o[j] = -o[j];
                    --j;
                    continue;
                }
                int t = a[j - c[j] + s];
                a[j - c[j] + s] = a[j - q + s];
                a[j - q + s] = t;
                c[j] = q;
                break;
            }
        }
    }

    Реализация алгоратма "простых изменений" по описанию из Кнута (т4. Комбинаторный поиск, генерация всех перестановок).
    Напрашивающиеся goto раздражают, было бы приятно увидеть менее пахучие реализации. Не смог нагуглить, забугорного названия этого алгоритма не знаю, а про "простые изменения" тинай вики молчит.

    vistefan, 13 Декабря 2013

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