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

    +18

    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
    #include <iostream>
    #include <memory>
    #include <mutex>
    #include <condition_variable>
    #include <atomic>
    
    
    typedef ::std::unique_lock<::std::mutex> TLock;
    
    using namespace std;
    template<typename T>
    class TQueueElement
    {
    public:
    	T _data;
    	std::shared_ptr<TQueueElement<T> > _prev;
    	mutable ::std::mutex _lockElem;
    
    public:
    	TQueueElement(T data):_data(data),_prev(nullptr){};
    	virtual ~TQueueElement(){};
    
    
    };
    
    template<typename T>
    class TQueue
    {
    private:
    	mutable ::std::mutex _lockHead;
    	mutable ::std::mutex _lockTail;
    	::std::condition_variable _pushToQueue;
    	std::atomic<bool> _isEmpty;
    	std::shared_ptr<TQueueElement<T> > _tail;
    	std::shared_ptr<TQueueElement<T> > _head;
    
    public:
    	TQueue():_lockHead(),_isEmpty(true){};
    	virtual ~TQueue(){};
    
    ///получаем элемент из очереди
    	T pop()
    	{
    		TLock lock(_lockTail);//блокируем все получения из очереди
    		if (_tail==nullptr) 
    			{_isEmpty=true; _pushToQueue.wait(lock,[this](){return !_isEmpty;});} //если очередь пуста ожидаем пока в ней чтото появиться 
    		{
    			TLock lockTail(_tail->_lockElem); //блокируем последний элемент в очереди возможно к нему попробуют обратиться во время запихивания в очередь
    			auto data=_tail->_data;
    			_tail=_tail->_prev;
    			return data;
    		}
    		
    	}
    
    	void push(T data)
    	{
    		auto el=std::shared_ptr<TQueueElement<T> >(new TQueueElement<T>(data));//заранее создаем элемент очереди 
    		TLock lock(_lockHead);
    		if (_isEmpty)//если очередь пуста говорим что наш элемент пока первый и последний
    		{
    			_head=el;
    			_tail=el;
    			_isEmpty=false;
    			_pushToQueue.notify_all();
    		}else//если очередь не пуста 
    		{
    			{
    				TLock lockHead(_head->_lockElem); //блокируем голову от возможного обращения с хвоста
    				_head->_prev=el; //выставляем ссылку на новую голову у старой
    			}
    			_head=el;//выставляем новую голову
    		}
    	}
    
    
    	
    };
    
    
    int main() {
    	TQueue<int> q;
    	q.push(7);
    	q.pop();
    	// your code goes here
    	return 0;
    }

    https://ideone.com/uGX56M
    Ничего не забыл ? Пытался написать очередь для межпоточной синхронизации.

    IKing, 02 Июля 2014

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

    +26

    1. 1
    2. 2
    private:
      GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator);

    Корпорация добра.

    tirinox, 02 Июля 2014

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

    +157

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    class WP_Post {
    	public static function get_instance( $post_id ) {
    		...
            }
    	public function __construct( $post ) {
    		foreach ( get_object_vars( $post ) as $key => $value )
    			$this->$key = $value;
    	}

    Вордпресс 3.9.1. Создать объект можно только из объекта. Ну или передав айдишник записи (что само по себе еще логично), но называется эта хуйня почему-то get_instance(), словно это синглтон.

    Fike, 02 Июля 2014

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

    +159

    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
    function redirect(){
            setTimeout("redirect1();", 60000)
    }
    
    function redirect1(){
            if(parent.lan_ipaddr == "192.168.1.1")
                    if(navigator.appName.indexOf("Microsoft") >= 0){
                            parent.location.reload();                       
                            //parent.location.href = "http://192.168.1.1/index.asp?t="+new Date().getTime();
                    }
                    else{
                            //parent.location.href = "http://192.168.1.1/";
                            parent.parent.location.href = parent.parent.location.href;
                    }
            else{
                    parent.$('drword').innerHTML = "<#Setting_factorydefault_iphint#><br/>";
                    setTimeout("parent.hideLoading()",1000);
                    setTimeout("parent.dr_advise();",1000);
            }
    }

    Решил тут посмотреть сорцы вебморды роутера

    Fike, 02 Июля 2014

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

    +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
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    public static List<string[]> Compose(List<string> list_eng, List<string> list_tar, string divider = ";")
            {
                List<string[]> composed = new List<string[]>();
                for (int i = 0; i < list_eng.Count - 1; i++)
                {
                    string[] tokens = new string[3];
                    string[] temp = list_eng[i].Split(new string[] { divider }, StringSplitOptions.None);
    
                    if (temp.Length != 2)
                    {
                        Console.WriteLine("1." + i + " : expected 2 tokens, found " + temp.Length);
                        continue;
                    }
    
                    tokens[0] = temp[0];
                    tokens[1] = temp[1];
    
                    composed.Add(tokens);
                }
    
                for (int i = 0; i < list_tar.Count - 1; i++)
                {
                    string[] tokens = list_tar[i].Split(new string[] { divider }, StringSplitOptions.None);
    
                    if (tokens.Length != 2)
                    {
                        Console.WriteLine("2." + i + " : expected 2 tokens, found " + tokens.Length);
                        continue;
                    }
    
                    int eq = composed.FindIndex(a => a[0] == tokens[0]);
    
                    if (eq == -1)
                        continue;
                    else
                        composed[eq][2] = tokens[1];
                }
                return composed;
            }

    Парсит csv в колонки.

    chebyrashka, 01 Июля 2014

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

    +134

    1. 1
    IEventDetails evt = logger.GetEvent((Int32)((Object[])msg.ID)[0], (Int64)((Object[])msg.ID)[1]);

    Нашёл свой код бородатой давности в одном решении, в котором присутсвует дедлок, а лезть в код не хотелось.
    Вот теперь думаю, ковырять компонент дальше или пусть себе с дедлоком живёт.....

    TauSigma, 01 Июля 2014

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

    +14

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    std::string MakeString(const char* ch) 
    { 
       stringstream ss; 
       for (int i = 0; i < strlen(ch); i++) { 
          ss<<ch[i]; 
       } 
       string result = ss.str(); 
       return result; 
    }

    Создание строки

    absolut, 01 Июля 2014

    Комментарии (20)
  8. PHP / Говнокод #16263

    +158

    1. 1
    for($month = 1 ; $month <= intval(12); $month ++)

    clauclauclau, 01 Июля 2014

    Комментарии (33)
  9. PHP / Говнокод #16262

    +159

    1. 1
    2. 2
    3. 3
    if ($_POST['category']===1){ //Визначаємо яку категорію вибрав користувач ...
        "INSERT INTO `advertisement` (category) VALUES ('Квартира')";
    }

    Пришло время выполнить запрос. Запрос сам не выполнится...

    Взято отсюда: http://govnokod.ru/16259

    bormand, 30 Июня 2014

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

    +155

    1. 1
    (isset($presetFilters)) ? ((in_array($object->id,$presetFilters)) ? $object->avatar('-s') : $object->avatar('-gs-s')) : $object->avatar('-gs-s')

    код для получение префикса аватарки

    v1m, 30 Июня 2014

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