1. Куча / Говнокод #8043

    +145

    1. 1
    http://open-life.org/blog/algorithm/1627.html

    Красивое наглядное видео алгоритмов сортировки.
    Новичкам может быть полезно, да и просто эстетически приятно.

    CKrestKrestGovno, 30 Сентября 2011

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

    +162

    1. 1
    if(!empty($arResult["Post"])>0)

    Как вы думаете, что это? Правильно, Битрикс!

    maxru, 30 Сентября 2011

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

    +134

    1. 1
    2. 2
    if (!(string.IsNullOrEmpty("")))
    ...

    HellMaster_HaiL, 30 Сентября 2011

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

    +155

    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 <iostream>
    #include <memory>
    #include <assert.h>
    using namespace std;
     
    template <class T>
    class megaClass
    {
    public:
     
        void hello()
        {
            assert(dynamic_cast<T*>(this)!=NULL);
            static_cast<T*>(this)->hello();
        }
        virtual ~megaClass() {}
    };
     
    class cleft : public megaClass<cleft>
    {
    public:
     
        void hello()
        {
            std::cout << "left::hello()" << std::endl;
        }
    };
     
    class cright : public megaClass<cright>
    {
    public:
     
        void hello()
        {
            std::cout << "right::hello()" << std::endl;
        }
    };
     
     
    int main()
    {
        scoped_ptr<megaClass<cleft> > a1=new cleft;
        a1->hello();
        scoped_ptr<megaClass<cright> > a2=new cright;
        a2->hello();
        
        return 0;
    }

    Пытался продемонстрировать статический полиморфизм TarasB и получилась такая какашка. Кто действительно крут и может сабдж продемонстрировать? Я где-то видел пример, но не помню где...

    Ещё продемонстрировал статический полиморфизм через стратегии:

    struct Strategy1
    {
    static void do(){printf("Lol1");}
    };
    struct Strategy2
    {
    static void do(){printf("Lol2");}
    };
    template<class Strategy>
    class MegaClass
    {public:
    void do()
    {
    printf("Mega");
    Strategy::do();//Класс Strategy можно было и создать для хранения состояния.
    printf("/n\");
    }
    };
    //...

    Дальше в разных частях кода создаем:
    MegaClass<Strategy1> o;
    o.do();
    //...
    MegaClass<Strategy2> o;
    o.do();
    "Один" класс ведёт себя по разному. Понятно, что это не совсем полиморфизм. Но очень часто именно в таком контексте используют динамический полиморфизм, хотя такого статического здесь достаточно выше крыши.
    Плюсы этого подхода :
    1)Создаётся объект в стеке, значит быстро, а не в куче. Хотя можно и не в стеке.
    2)Используется шаблон, значит компиль будет инлайнить.

    Минус:
    1)Если понадобится резкой перейти от статического полиморфизма к динамическому - придётся переписывать на виртуальные функции или на истинный статический полиморфизм.

    Обсуждения здесь:
    http://govnokod.ru/8025#comment110773


    Сразу исключим детсадовский вариант статического функционального полиморфизма c перегрузкой функций:
    Class1 o1;
    foo(o1);
    Class2 o2;
    foo(o2);

    void foo(Class1 o){/*...*/};
    void foo(Class2 o){/*...*/};



    Кто-нибудь реально умеет can into нормальный статический полиморфизм?

    CPPGovno, 30 Сентября 2011

    Комментарии (116)
  5. PHP / Говнокод #8039

    +30

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    $files = file_scan_directory(dirname(__FILE__) .'/modes/', '^([^\.].*)\.inc$', array('.', '..', 'CVS'), 0, FALSE);
        foreach ($files as $file) {
          require_once($file->filename);
          $mode = $file->name;
          if (function_exists('advpoll_info_'. $mode)) {
            $advpoll_modes[$mode] = call_user_func('advpoll_info_'. $mode);
          }
        }

    brainstorm, 30 Сентября 2011

    Комментарии (2)
  6. JavaScript / Говнокод #8038

    +169

    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
    function echeck(str) {
      var at="@"
      var dot="."
      var lat=str.indexOf(at)
      var lstr=str.length
      //  var ldot=str.indexOf(dot)
      if (str.indexOf(at)==-1){
        alert("Invalid E-mail ID");
        return false;
      }
      if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
        alert("Invalid E-mail ID");
        return false;
      }
      if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
        alert("Invalid E-mail ID");
        return false;
      }
      if (str.indexOf(at,(lat+1))!=-1){
        alert("Invalid E-mail ID");
        return false;
      }
      if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        alert("Invalid E-mail ID");
        return false;
      }
      if (str.indexOf(dot,(lat+2))==-1){
        alert("Invalid E-mail ID");
        return false;
      }
      if (str.indexOf(" ")!=-1){
        alert("Invalid E-mail ID");
        return false;
      }
      return true;
    }

    если честно, дочитал где-то только до 15 строки

    marg, 30 Сентября 2011

    Комментарии (13)
  7. JavaScript / Говнокод #8037

    +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
    var resizeTimer,calWidth,$BlockPath,widthLeftPart,widthRightPart,count;
    var $headBlock = $('div.hdr');
    var $rightBlock = $('li.userFullName');
    var $leftBlock = $('li.subMenu-title');
    
    $(document).ready(resizeLabels);
    $(window).resize(resizeLabels);
    
    function doResizeLabels($typeBlock) {
            count = 2;
            resultWidth = 0;
            if ($typeBlock==$leftBlock) {
                    $BlockPath=$('ul.subMenu li:not(.subMenu-title)');
            } else {
                    $BlockPath=$('ul.usersLink li:not(.userFullName)');
            };    
            $BlockPath.each(function() {
            eachPosition = $(this).position(); 
            eachWidth = $(this).width();  
            eachOuterWidth = $(this).outerWidth();
            count++;
            if ($typeBlock==$leftBlock) {
                    widthLeftPart = eachPosition.left + eachWidth;
                    widthPadding = eachOuterWidth - eachWidth;
            } else {
                    if (count==3) widthPadding = eachPosition.left;
                    widthRightPart = widthRightPart + eachOuterWidth;
            };              
            });    
            if ($typeBlock==$leftBlock) {
                    widthLeftPart = widthLeftPart + ((widthPadding / 2) * count);
                    resultWidth = headWidth/2 - widthLeftPart;
            } else {
                    rightWidth = headWidth/2 - widthRightPart;
                    resultWidth = rightWidth-(headWidth/2-widthPadding/2)/2;
            };        
            $typeBlock.width(resultWidth);
    }
    function resizeLabels() {
            $leftBlock.width(0);
            $rightBlock.width(0);
            headWidth = $headBlock.width();
            widthLeftPart = widthRightPart = 0;        
            headWidth = $headBlock.width();
            
            doResizeLabels($leftBlock);
            doResizeLabels($rightBlock);				
    };

    Serious_Andy, 30 Сентября 2011

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

    +158

    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
    <?php
    function bkconnect($login=FALSE,$update=FALSE){
    	function get_bk_inf($content){
    		if (strlen($content) > 0){
                        preg_match("#align=(.*)#i", $content, $returnarray['align']);
                        preg_match("#gamecity=(.*)#i", $content, $returnarray['gamecity']);
                        preg_match("#room_name=(.*)#i", $content, $returnarray['room_name']);
                        preg_match("#gamecity_url=(.*)#i", $content, $returnarray['gamecity_url']);
                        preg_match("#level=(.*)#i", $content, $returnarray['level']);
                        preg_match("#klan=(.*)#i", $content, $returnarray['klan']);
                        preg_match("#login_online=(.*)#i", $content, $returnarray['login_online']);
                        foreach($returnarray as $array_name => $array_data){
                                $returnarray[$array_name] = $returnarray[$array_name][1];
                                        }
                        }
                        return $returnarray;
                        }
    	function bklogin($login){
    		$tmp=rawurlencode(trim(strip_tags($login)));
    		$url="http://sandcity.combats.com/inf.pl?login=".$tmp."&short=1";
    		$response=get_headers($url,1);
    		if (strpos($response[0],'302'))
    		{$url=str_replace(" ","%20",$login);
    		 return file_get_contents($url);}
    		elseif (strpos($response[0],'200'))
    		{return file_get_contents($url);}
    		else {return"";}
    		return file_get_contents($url);
    		}
    	if($update==TRUE){
    		$myrow = mysql_query("select id,bk_login FROM black_list");
    		if(mysql_num_rows($myrow)){
    			while($result = mysql_fetch_array($myrow)){
    				$contents = bklogin($login);
    				$info = get_bk_inf($contents);
    				if(is_array($info)){
    				$sql="UPDATE `newblacklist` SET
                                                                align ='".$info['align']."',
                                                                gamecity ='".$info['gamecity']."',
                                                                room_name='".$info['room_name']."',
                                                                gamecity_url='".$info['gamecity_url']."',
                                                                level='".$info['level']."',
                                                                klan='".$info['klan']."',
                                                                login_online='".$info['login_online']."'
                                                                WHERE `id`='".$result['id']."'";
    				$myrow2 = mysql_query($sql);
    				}else{echo'error';}
    				}
    			}else{return;}
    		}else{
    			$contents = bklogin($login);
    			$info = get_bk_inf($contents);
    			if(is_array($info)){
    				return $info;}else{
    					return 'Чтото не так';}
    			}
    	}
    function liginviev($inf){
    function align($align){if($align>0){return '<img src="http://img.combats.com/i/align'.$align.'.gif" border="0px">';}else{return '&nbsp';}}
    function klan($klan){if(strlen($klan)>0){
    	return "<a href='http://capitalcity.combats.com/clans_inf.pl?".$klan."' target='_blank'>
    	<img src='http://img.combats.com/i/klan/".$klan.".gif' title='".$klan."'></a>";}else{
    		return '&nbsp';}}
    function room($rooms){if(strlen($rooms)>0){return $rooms;}else{return' ';}}
    function online($online){
    	if($online==1){return'<img src="/i/user_online.gif" />';}else{return'<img src="/i/user_offline.gif" />';}
    	return $on;}
    	}
    function Logs($id){
    $myrow = mysql_query("SELECT * FROM newblacklistlogs WHERE blackId='".$id."'");
    $crow['loc'] = mysql_num_rows($myrow);
    if($crow['loc']>0){
    	while($result = mysql_fetch_array($myrow)){
    		$crow['logs'] .='<a href="'.$result['file'].'" target="_blank"><img src="/i/fighttype6.gif" /></a>';
    		}
    		return $crow=array('col'=>$crow['loc'],'logs'=>$crow['logs']);
    	}else{return $crow=array('col'=>$crow['loc'],'logs'=>' ');}
    	}
    ?>

    Один ЧС для клан сайта игры combats.ru

    lans8097, 30 Сентября 2011

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

    +169

    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
    if(this->connectionState)
        {
            db_Model->clear();
            db_Model->setTable("lh_chat_archive");
            db_Model->setRelation(6, QSqlRelation("lh_profiles", "id", "last_name"));
            db_Model->setEditStrategy(QSqlRelationalTableModel::OnManualSubmit);
            db_Model->removeColumn(0);
            db_Model->removeColumn(0);
            db_Model->removeColumn(0);
            db_Model->removeColumn(0);
            db_Model->removeColumn(0);
            db_Model->removeColumn(2);
            db_Model->removeColumn(2);
            db_Model->removeColumn(2);
            db_Model->removeColumn(3);
            db_Model->removeColumn(3);
            db_Model->removeColumn(3);
            db_Model->removeColumn(3);
            db_Model->removeColumn(3);
            db_Model->removeColumn(3);
            db_Model->removeColumn(3);
            db_Model->removeColumn(3);
            db_Model->removeColumn(3);
            db_Model->removeColumn(3);
            db_Model->removeColumn(3);
            db_Model->select();
            db_Model->setHeaderData(0, Qt::Horizontal, trUtf8("Клиент"));
            db_Model->setHeaderData(1, Qt::Horizontal, trUtf8("Менеджер"));
    
            mapper->setModel(db_Model);
            mapper->setItemDelegate(new QSqlRelationalDelegate(this));
        }

    Сотрудник фирмы таким образом избавился от ненужных столбцов в выборке. На вопрос: "А как быть если столбцов много?", ответа не последовало...

    inbush, 30 Сентября 2011

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

    +146

    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
    <?php
    function curl($url='', $post='') {
    	$cl = curl_init();
    	curl_setopt($cl, CURLOPT_URL, $url);
    	curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
    	curl_setopt($cl, CURLOPT_HEADER, 1);
    	curl_setopt($cl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1) Gecko/20090624 Firefox/3.5');
    	curl_setopt($cl, CURLOPT_COOKIEJAR, 'cookie.txt');
    	curl_setopt($cl, CURLOPT_COOKIEFILE, 'cookie.txt');
    	if(!empty($post)) {
    		curl_setopt($cl, CURLOPT_POST, 1); 
    		curl_setopt($cl, CURLOPT_POSTFIELDS, $post);
    	} else curl_setopt($cl, CURLOPT_POST, 0);
    	$ex = curl_exec($cl);
    	curl_close($cl);
    	return $ex;
    }
    $wall_id = 'wallxxx_xxx';
    $hash = 'a2069bb43c20769e9';
    
    curl('http://vkontakte.ru/login.php?act=login&q=&[email protected]&pass=xxx&captcha_sid=&captcha_key=');
    echo curl('http://vkontakte.ru/like.php', "act=a_do_like&object={$wall_id}&hash={$hash}&wall=1");
    ?>

    Ребят, сервер отдаёт: HTTP/1.1 302 Found Server: nginx/0.7.59 Date: Thu, 29 Sep 2011 18:42:58 GMT Content-Type: text/html; charset=windows-1251 ..., но почему то "лайк" не ставит.
    В чём может быть проблема?

    substr, 29 Сентября 2011

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