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

    +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
    #include <ppl.h>
    #include <windows.h>
    #include <ppltasks.h>
    #include <iostream>
    #include <vector>
    
    using namespace Concurrency;
    using namespace std;
    
    CRITICAL_SECTION cs6;
    
    int main(int argc, char* argv[])
    {
    	size_t concurentThreadsSupported = std::thread::hardware_concurrency();
    	cout << concurentThreadsSupported << endl;
    	//deadlock hazard increased with concurentThreadsSupported decreasing
    
    	size_t taskAmountForWasteVirtualCores = concurentThreadsSupported - 1;//must be equal to (virtual processor thread amount from Concurrency::IResourceManager) - 1
    	vector<task<void>> t;
    	for (size_t i = 0; i<taskAmountForWasteVirtualCores; ++i)
    		t.push_back(create_task([]{
    			Sleep(INFINITE);//some very long IO operation or deadlocked by EnterCriticalSection or sql transaction or other
    		}));
    	Sleep(1000);
        cout << "another way:" << endl;
        InitializeCriticalSection(&cs6);
        auto locker = create_task([]{
            cout << "locker" << endl;
            EnterCriticalSection(&cs6);//same as begin sql transaction
            cout << "locker entered cs 6" << endl;
            Concurrency::wait(500);//Deadlock by any concurrency context switching directly or indirectly by std or MFC (events, mutex, etc)
            cout << "locker played" << endl;
            LeaveCriticalSection(&cs6);//same as end sql transaction
            cout << "~locker ok" << endl;
        });
        auto locked = create_task([]{
            cout << "locked" << endl;
            EnterCriticalSection(&cs6);//same as begin sql transaction
            cout << "locked entered cs 6" << endl;
            Concurrency::wait(500);
            cout << "locked played" << endl;
            LeaveCriticalSection(&cs6);//same as end sql transaction
            cout << "~locked ok" << endl;
        });
    	Sleep(1000);
    	cout << "FAIL" << endl;
    	return 0;
    }

    Нашел дидлок)
    http://rextester.com/KHC72232
    http://rextester.com/EMG65441

    laMer007, 04 Марта 2015

    Комментарии (11)
  2. PHP / Говнокод #17724

    +170

    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
    public function action_ajaxlogin()
    	{
    		// Если запрос поступил не через AJAX, то шлем нахуй
    		if ( ! $this->request->is_ajax())
    		{
    			throw new HTTP_Exception_404(NULL);
    		}
    
    		// Вырубаем авто-рендер, ибо это хуев аякс запрос
    		$this->auto_render = false;
    
    		// Собираем информацию и пользователе в ёбанный массив
    		$user_data = $this->request->post('user_data');
    
    		// Если пользователь авторизирован, то заебато, и возвращаем статус 200!
    		if (Auth::instance()->login($user_data['username'], $user_data['password'], (bool) isset($user_data['remember_me'])))
    			return $this->response->status(200);
    
    		// Если нет, то "Вася, все хуйня! Давай по новой!"
    		return $this->response->status(400);
    	}
    
    	public function action_logout()
    	{
    		// Если запрос поступил не через AJAX, то шлем нахуй
    		if ( ! $this->request->is_ajax())
    		{
    			throw new HTTP_Exception_404(NULL);
    		}
    
    		// Вырубаем сучий авто-рендер, нахуй, в пизду блядь
    		$this->auto_render = false;
    
    		// Выходим из аккаунта, если вышли, то ахуенно, 200-ый статус)
    		if (Auth::instance()->logout())
    			return $this->response->status(200);
    
    		// Если все хуйня, то "Вася, давай по новой!"
    		return $this->response->status(400);
    	}

    Kohana фреймворк, и таких комментариев по проекту тьма :)

    proweber1, 03 Марта 2015

    Комментарии (130)
  3. JavaScript / Говнокод #17723

    +155

    1. 1
    logs.splice.apply(logs, [j, 1].concat(line.split("\n")));

    strax, 03 Марта 2015

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

    +168

    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
    98. 98
    generator=function(a,q){m=Math;no='';nb=' ';
    rnd=function(r,w){return((m.round(((+new Date)*m.random())%r)||0)+(w||0));};
    ff=function(ff){ma=function(ma1,ma2){return(m.max(ma1,ma2));};return(ma(ma(rnd(rnd(ff)),rnd(rnd(ff))),ma(rnd(rnd(ff)),rnd(rnd(ff)))));};
    sumb=function(x,y){return(String.fromCharCode(rnd(m.abs((y||1)-1),m.abs(x||32))));};
    sor=function(o){return(o.sort(function(){return(0.5-m.random())}));};
    a=Number(a||0);
    q=q||[];
    
    
    
    
    
    
    
    
    
    
    q=function(z){r=0;for(j=0;j<z.length;j++){r+=z[j]};return(r);}(q)?q:(Array(4+4+4+4+4+4+4+4
    
    		+4+4+4		+4+4+4
    
    +1).join('1').split(no));sx=function(p,u){g=q.length;return(Number(q[p>g?g:p])?u:no);};len=Array();for(r=0;r<rnd(a,a*5);r++){e=[
    
    
    
    
    	sumb(958)
    
    	,sumb(97,26)
    	,sumb(945,25)
    
    
    
    	,sumb(97,26)
    	,sumb(97,26)
    	,sumb(97,26)
    	,sumb(97,26)
    
    
    			,sumb(97,26)
    			,sumb(97,26)
    			,sumb(97,26)
    			,sumb(97,26)
    
    
    
    
    
    
    			,sumb(97,26)
    			,sumb(97,26)
    			,sumb(97,26)
    			,sumb(97,26)
    
    
    
    	,sumb(97,26)
    	,sumb(945,25)
    	,sumb(97,26)
    	,sumb(945,25)
    	,sumb(97,26)
    	,sumb(945,25)
    	,sumb(97,26)
    	,sumb(945,25)
    
    
    
    			,sumb(97,26)
    			,sumb(97,26)
    			,sumb(97,26)
    			,sumb(97,26)
    
    
    
    
    	,sumb(223)
    	,sumb(228)
    	,sumb(230)
    	,sumb(231)
    
    
    
    
    
    	,sumb(239)
    	,sumb(240)
    	,sumb(241)
    	,sumb(235)
    
    
    
    
    
    
    
    
    
    	,sumb(246)

    И это было написано ручками, не использовался никакой uglify
    И этот проект мне достался в наследство на новой работе.
    КМП.

    JSMastaRolu, 03 Марта 2015

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

    +52

    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
    void ArmInterface::dispatchMessage(QString name, QJsonArray args)
    {
        //флаг того что мы не смогли обработать
        bool notCallbacks = true;
        //проходим по всем методам( которые кстати можно создать в рантайме )
        for( int i = 0; i < metaObject()->methodCount() ; i++ )
        {
            QMetaMethod method = metaObject()->method( i);        
            
            //имя метода подходит под имя под сообщение от сервера? Прекрасно проверяем дальше.
            if ( method.name() != name )
            {
                qWarning() << "method.name() != name" << " -> " <<method.name() << " != " << name;
                //так как метод не найден мы просто выйдем отсюда, не дожидаясь ничего плохого
                continue;            
            }
            //метод у нас публичный? Если да то можно запускать обработку иначе заявим что низя
            if ( method.access() != QMetaMethod::Public )
            {
                qWarning() << "Method " << method.name()<< " not public!";
    #ifdef IGNORE_NOT_PUBLIC_METHOD
                continue;
    #endif
            }
            //несовдатает количество аргументов? Хватит это терпеть пишем warning, и если надо выходим из этого диспатчера
            int countParams = method.parameterCount();
            if ( args.count() != method.parameterCount() )
            {
                qWarning() << "Method " << method.name() << " params count = " << method.parameterCount() << " and received args params count =  "  << args.count();
    #ifndef IGNORE_METHOD_PARAMS_COUNT
                continue;
    #endif
                //берем наименьшее количество параметров
                countParams = countParams > args.count() ? countParams : args.count();
            }
            
            //создание валидного QGenericArgument 
            auto genericArg = [ this, method, args ]( int index ) -> QGenericArgument{
                //out of range? 
                if ( args.count() <= index || 
                     method.parameterCount() <= index )
                    return QGenericArgument();
                void * data = 0;
                //сохраняем временный QVariant для дальнейшей более удобной работы с ним
                QVariant  temp = args.at( index ).toVariant();
                //попытка конвертирования типов. Если что-то не получается, пишем в лог. Мб надо будет сделать преждевременный выход, если сконвертировать не получается.
                if ( !temp.convert( method.parameterType( index) ) )
                {
                    qWarning()<< objectName() << " method : " << method.name() <<
                                 " Not convert " << method.parameterNames().at( index ) << args.at( index ).toVariant().typeName() << 
                                 " from " << args.at( index ).toVariant().typeName() << 
                                 " to " << QMetaType::typeName( method.parameterType( index) )  ;
                };
                //у нас есть такой аргумент? Если нет - то ничего не делаем
                if ( args.count() > index )
                {
                    data = QMetaType::create( method.parameterType( index ) , temp.data() );
                }
                const char * name = 0;
                //у нас есть имя аргумента и аргумент в него? Если чего-то нет - то ничего и не будем ничего делать
                if ( method.parameterNames().count() > index && data)
                    name = method.parameterNames().at( index ).data();
    
                return QGenericArgument(
                            name, 
                            data);
            };
            
            //тут можно вызывать! 
            method.invoke( this, 
                           //генерируем аргументы
                           genericArg(0),
                           genericArg(1),
                           genericArg(2),
                           genericArg(3),
                           genericArg(4),
                           genericArg(5),
                           genericArg(6),
                           genericArg(7),
                           genericArg(8),
                           genericArg(9));
            notCallbacks = false;
            //раз вызвали значит нашли подходящий callback, а следовательно искать дальше ненадо. Выходим нафиг.
            break;
        }
        //вызвали что -нить? Если вызвали то не вызываем ничего. А иначе идем в другую функцию - которая разбирается как раз с такими сообщениями.
        //Если надо перехватить совершенно все сообщения - перегружать функцию в которой находимся.
        if ( !notCallbacks )
            dispathUndefinedMessage( name, args );
    }

    Написал и мучаюсь - гавнокод или все таки нет.

    ахда, мне надо выучить русский )

    Dart_Sergius, 02 Марта 2015

    Комментарии (22)
  6. Си / Говнокод #17719

    +133

    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
    int start()
      {
     string filename = "GBPJPY.hst";
     int i_unused[30];
       
     int FILE = FileOpenHistory(filename, FILE_READ|FILE_BIN);
     FileSeek(FILE, 0, SEEK_SET);
     
     int version    = FileReadInteger (FILE, LONG_VALUE);
     string c_copyright  = FileReadString (FILE, 64);
     string name    = FileReadString (FILE, 12);
     int period     = FileReadInteger (FILE, LONG_VALUE);
     int i_digits   = FileReadInteger (FILE, LONG_VALUE);
     int timesign    = FileReadInteger (FILE, LONG_VALUE);       //timesign
     datetime last_sync   = FileReadInteger (FILE, LONG_VALUE);       //last_sync
     FileReadArray (FILE, i_unused, 0, 13);
     
     Print("Version = ", version);
     Print("c_copyright = ", c_copyright);
     Print("Equity = ", name);
     Print("period = ", period);
     Print("i_digits = ", i_digits);
     Print("timesign = ", TimeToStr(timesign, TIME_DATE|TIME_SECONDS));
     Print("last_sync = ", last_sync);
     Print("i_unused = ", i_unused[0]);
     Print("i_unused = ", i_unused[1]);
     Print("i_unused = ", i_unused[2]);
     Print("i_unused = ", i_unused[3]);
     Print("i_unused = ", i_unused[4]);
     Print("i_unused = ", i_unused[5]);
     Print("i_unused = ", i_unused[6]);
     Print("i_unused = ", i_unused[7]);
     Print("i_unused = ", i_unused[8]);
     Print("i_unused = ", i_unused[9]);
     Print("i_unused = ", i_unused[0]);
     Print("i_unused = ", i_unused[11]);
     Print("i_unused = ", i_unused[12]);
     Print("Time    = ", FileReadInteger (FILE, LONG_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Volume   = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Time    = ", FileReadInteger (FILE, LONG_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Volume   = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Time    = ", FileReadInteger (FILE, LONG_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Volume   = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Time    = ", FileReadInteger (FILE, LONG_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Price    = ", FileReadDouble (FILE, DOUBLE_VALUE));
     Print("Volume   = ", FileReadDouble (FILE, DOUBLE_VALUE));
     FileClose(FILE);   
     return(0);
    }

    Язык программирования торгового терминала MetaTrader 4 - MQL 4 - имеет C-нотацию. Многое роднит его с языком C, поэтому пример размещаю сюда.
    У меня складывается мнение, что, как и Forex - дно (днище) в мире электронной торговли, так и основная масса кода, написанного на MQL4 - образец того, как
    НЕ нужно программировать! Чего стоит одна только вырвиглазная разметка вкупе с корявым непоследовательным именованием... характерная, в том числе,
    и для официально поставляемых с терминалом примеров кода. Заранее прошу прощения за многострочный пример

    AndreySt, 02 Марта 2015

    Комментарии (31)
  7. PHP / Говнокод #17718

    +156

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    if (count($GRoleData['base']['forbid']) == 4 && isset($GRoleData['base']['forbid']['type']))
    							{
    								$temp = $GRoleData['base']['forbid'];
    								unset($GRoleData['base']['forbid']);
    								$GRoleData['base']['forbid'][0] = $temp;
    							}

    Класс преобразует XML в массив. Если элемент встречается более одного раза, то внутрь элемента суется еще один массив. В некоторых местах должен быть всегда массив, но если элемент один, класс положит его в корень. Код выше "исправляет" это. 4 - количество дочерей дочерей дочерей дочерей дочерей дочки родителя.

    DesmondHume, 02 Марта 2015

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

    +60

    1. 1
    std::string s = "a" /* + */ "b";

    bormand, 02 Марта 2015

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

    +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
    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
    if (!isset($_GET['outbox']) and !isset($_GET['deleted']) and !isset($_GET['verification'])){
    				$res2 = mysql_query("SELECT l.* FROM letters l LEFT JOIN `customers` ct ON ct.id=l.from_user WHERE l.deleted<>1 AND ct.`Sex` = 'male' {$addon_sql} ORDER BY l.time_insert DESC");
    				for($arr=array(); $t = mysql_fetch_assoc($res2); $arr[]=$t);
    
    				smarty_put_var('zagolovok', 'Входящие письма');
    		}
    
    		if (isset($_GET['verification'])) {
    		$res2 = mysql_query("SELECT * FROM `letters` where `deleted` != 1 AND `checked` = 'N' {$addon_sql} order by `time_insert` DESC");
    		for($arr = array(); $t = mysql_fetch_assoc($res2); $arr[] = $t);
    
    		smarty_put_var('zagolovok', 'Ожидающие проверку');
    		}
    
    		if (isset($_GET['outbox'])) {
        	$res2 = mysql_query("SELECT l.* FROM `letters` l
    		    	LEFT JOIN `customers` ct ON ct.`id`=l.from_user
    		    	WHERE l.deleted != 1 AND ct.`Sex` = 'female' {$addon_sql}
    		    	ORDER BY l.time_insert DESC LIMIT 200");
    		    	for ($arr = array(); $t = mysql_fetch_assoc($res2); $arr[]=$t);
    
    		    	smarty_put_var('zagolovok', 'Исходящие письма');
    		}
    
    		    	if (isset($_GET['deleted'])){
        	$res2 = mysql_query("SELECT * FROM `letters` WHERE `deleted` = 1
    		    	{$addon_sql} ORDER BY `time_insert` DESC");
    		    	for($arr=array(); $t=mysql_fetch_assoc($res2); $arr[]=$t);
    
    		    	smarty_put_var('deleted', true);
    		    	smarty_put_var('zagolovok', 'Удаленные письма');
    		    	}
    
    		    	$letters = array_slice($arr, $first, $limit);
    
    		foreach ($letters as &$letter) {
    			$letter['from_user_details'] = Model_Table_Customers::model()
    				->fetchByPk($letter['from_user']);
    			$letter['to_user_details'] = Model_Table_Customers::model()
    				->fetchByPk($letter['to_user']);
    		}
    
    if (isset($_GET['outbox'])){smarty_put_var('pages', pages_admin("?module=admin_letters&outbox&page=", $arr, $page, $limit)); smarty_put_var('type', 'outbox');}
    elseif (isset($_GET['verification'])){smarty_put_var('pages', pages_admin("?module=admin_letters&verification&page=", $arr, $page, $limit)); smarty_put_var('type', 'verification');}
    elseif (isset($_GET['deleted'])){smarty_put_var('pages', pages_admin("?module=admin_letters&deleted&page=", $arr, $page, $limit)); smarty_put_var('type', 'deleted');}
    else {smarty_put_var('pages', pages_admin("?module=admin_letters&page=", $arr, $page, $limit)); smarty_put_var('type', '');}
    
    ...
    
    function pages_admin($link, $arr, $page, $vis)
    {
        $radius=4;
        $pages=floor(count($arr)/$vis);
        $return="";
        $str='<table cellpadding="0" cellspacing=3 border="0">
        <tr><td height=7></td></tr>
        <tr>';
    
        if ($pages > 1) {
            $first = 'First';
            $prev = 'Prev';
            $next = 'Next';
            $last = 'Last';
    
            if($page<$radius*2){
               .....
          трэшак в том же духе

    Очередной шедевр с сохранением авторского стиля и табуляции. Это подготовка для smarty представления таблицы с постраничной разбивкой. Возможны 4 типа писем - 4 вкладки. pages_admin() - возвращает пагинатор в виде готового html кода.

    Клиент жаловался, что страница сильно тормозит. Там более 150 000 писем. Я догадывался, что код можно чутка оптимизирвоать, но не думал, что существенно. А когда посмотрел вижу - п-ц ))) Интересно насколько получить ускорить?

    stechkh, 01 Марта 2015

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

    +76

    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
    private void spreadBullets() {
            bulletItemsWip.clear();
            for (AbstractInventoryItem item : inventoryItemsSortedByValue) {
                if (item instanceof RangeBulletItem) {
                    bulletItemsWip.add((RangeBulletItem) item);
                }
            }
    
            rangeUnitsQueueWip.clear();
            for (Unit unit : areaObject.getUnits()) {
                if (unit.getSpecialization().equals(Unit.UnitSpecialization.RANGE)) {
                    rangeUnitsQueueWip.add(unit);
                }
            }
    
            while (rangeUnitsQueueWip.size > 0 && bulletItemsWip.size > 0) {
                Iterator<Unit> unitsIterator = rangeUnitsQueueWip.iterator();
                while (unitsIterator.hasNext()) {
                    // find suitable bullets or remove unit from queue
                    Unit rangeUnit = unitsIterator.next();
    
                    RangeBulletItem foundBulletItemInInventoryForUnit = searchBulletFor(rangeUnit);
                    if (foundBulletItemInInventoryForUnit == null) {
                        // remove unit from bullets queue
                        unitsIterator.remove();
                    } else {
                        //  bullet was found
                        RangeBulletItem unitBulletsItem = rangeUnit.getEquipment().getRangeBulletsItem();
                        if (unitBulletsItem == null) {
                            unitBulletsItem = foundBulletItemInInventoryForUnit.split(1);
                            rangeUnit.getEquipment().setRangeBulletsItem(unitBulletsItem);
                        } else {
                            if (unitBulletsItem.getClass().equals(foundBulletItemInInventoryForUnit.getClass())){
                                if (!unitBulletsItem.isFull()) {
                                    foundBulletItemInInventoryForUnit.moveQuantity(1, unitBulletsItem);
                                } 
                            } else {
                                rangeUnit.getEquipment().dropRangeBullets();
                                unitBulletsItem = foundBulletItemInInventoryForUnit.split(1);
                                rangeUnit.getEquipment().setRangeBulletsItem(unitBulletsItem);
                            }
                        }
    
                        if (foundBulletItemInInventoryForUnit.isEmpty()) {
                            // remove item from inventory
                            bulletItemsWip.removeValue(foundBulletItemInInventoryForUnit, true);
                            remove(foundBulletItemInInventoryForUnit);
                        }
    
                        if (unitBulletsItem.isFull()) {
                            // remove unit from bullets queue
                            unitsIterator.remove();
                        }
    
                        if (bulletItemsWip.size == 0) {
                            // stop spreading
                            break;
                        }
                    }
                }
            }
    
            // sync quantities to inventory
            for (AbstractInventoryItem item : bulletItemsWip) {
                getItem(item.getClass()).setQuantity(item.getQuantity());
            }
        }

    Раздать пули отряду...

    dmli, 01 Марта 2015

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