1. Лучший говнокод

    В номинации:
    За время:
  2. Assembler / Говнокод #7302

    +132

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    movq	(%rdi), %rdi	# this.11_6->_M_impl._M_start, D.49210
    	testq	%rdi, %rdi	# D.49210
    	je	.L1	#,
    	jmp	_ZdlPv	#
    	.p2align 5,,7
    	.p2align 3
    .L1:
    	rep
    	ret

    Говнокод от компилятора g++-4.5.2

    Почему нельзя было сделать так:
    movq (%rdi), %rdi # this.11_6->_M_impl._M_start, D.49210
    testq %rdi, %rdi # D.49210
    jne _ZdlPv #,
    rep
    ret

    Не понимаю...

    wecanstoptrain, 21 Июля 2011

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

    +171

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    if (@$_REQUEST['send'])
    {
    	Header("Location: /index.php");
    	exit();
    	$username = $_REQUEST['username'];
    	$message = $_REQUEST['message'];
    	$a = new message();
    	$a->connectdb();
    	$a->addpost($username, $message) or die(mysql_error());
    	$a->view();
    
    }

    "Поправил вот так, работает вроде нормально", - автор.
    Источник: http://www.askdev.ru/question/6646/%D0%9F%D0%BE%D1%87%D0%B5%D0%BC%D1%83-%D0%BD%D0%B5-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%D0% B5%D1%82-%D1%80%D0%B5%D0%B4%D0%B8%D1%80%D0%B5%D0% BA%D1%82/new/#answer12608,comment21490

    Bazzin_Frog, 20 Июля 2011

    Комментарии (21)
  4. Pascal / Говнокод #7250

    +154

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    type
    число=ineger;
    плюс_число=word;
    эконом=shortint;
    плюс_эконом=byte;
    моар=longint;
    граммар=real;
    йцукен=char;
    йцуукеен=string;
    холивар=boolean;

    dos, 15 Июля 2011

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

    +163

    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
    99. 99
    Файл 1 :
    <?php
    for ($i=0; $i<10; $i++) // Моё примечение - вонять начинает отсюда
    {
    include "delstr.php";
    include "razdel2.php";
    include "gendat.php";
    include "dopismain.php";
    }
    Файл delstr.php:
    <?php
    $num_stroka = 7; //Удалим 7 строку из файла
    $file = file("gendat.php"); // Считываем весь файл в массив
    for($i = 0; $i < sizeof($file); $i++)
    if($i == $num_stroka) unset($file[$i]);
    $fp = fopen("gendat.php", "w");
    fputs($fp, implode("", $file));
    fclose($fp);
    ?>
    Файл razdel2.php:
    <?php
    $sl = file('ancorrzd.txt');
    $sm = $sl[array_rand($sl, 1)];
    $datam = $sm;
    $file = fopen ("rzd.txt","w");
    $str = "$datam";
    fputs ( $file, $str);
    fclose ($file);
    $dataC = trim(file_get_contents ("rzd.txt"));
    $data="\$dataCata='$dataC';";
    $file = 'gendat.php';
    $array=file( $file );
    $array[7]= $data; //строка в которой нужно изменить значение $data
    file_put_contents( $file, $array );
    ?>
    Файл gendat.php:
    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', 'On');
    ini_set('session.auto_start', '1');
    //ini_set('upload_tmp_dir', 'c:\tmp');
    set_time_limit(120);
    @session_start();
    $dataCata='xfgjcfyi';
    $txtFile = 'result.txt'; // файл с текстом
    $ancorFile = 'ancor.txt'; // файл с заголовками
    $tplFile = 'template.txt'; // файл шаблона .dat файлов
    $mainTplFile= 'maintemplate.txt'; // Шаблон файла со ссылками
    $datDir = "articles/$dataCata"; // директория для .dat файлов
    $datExt = 'dat'; // расширение .dat файлов
    $mainFile = 'main.dat'; // Файл со ссылками на .dat файлы
    $srcCharset = 'cp1251'; // Кодировка исходных файлов
    $destCharset = 'cp1251'; // Кодировка файлов на выходе
    $scriptCharset = 'utf-8'; // Кодировка скрипта
    $blockLength = 4000; // Максимальный размер блока в байтах из файла с текстом
    $file = fopen ("engine/menu.php","a");
    $str = "<li><a href=\"/$dataCata/\">$dataCata</a></li>";
    if ( !$file )
    {
    echo("Ошибка открытия файла");
    }
    else
    {
    fputs ( $file, $str);
    }
    fclose ($file);
    if ($srcCharset == 'utf-8') $blockLength *= 2;
    $blockLength = $blockLength % 2 > 0 ? $blockLength+1 : $blockLength;
    if ( !is_dir($datDir) ) mkdir($datDir, 0777, true);
    $hMain = NULL;
    if ( !(@$hMain = fopen($mainFile, 'w+')) ) die("Невозможно создать файл $mainFile<br/>\b");
    $hText = fopen($txtFile, 'r');
    $ancors = explode("\n", $srcCharset == $scriptCharset ? file_get_contents($ancorFile) : iconv($srcCharset, $scriptCharset, file_get_contents($ancorFile)));
    $template = $srcCharset == $scriptCharset ? file_get_contents($tplFile, 'r') : iconv( $srcCharset, $scriptCharset, file_get_contents($tplFile, 'r') ); // читаем шаблон
    $content = '';
    while ($content = fread($hText, $blockLength)) {
    $fname = genName();
    if (@$hDat = fopen("$datDir/$fname.$datExt", 'w')) {
    $ancor = trim($ancors[rand(0, count($ancors)-1)]);
    $content = $srcCharset == $scriptCharset ? trim($content) : iconv($srcCharset, $scriptCharset, trim($content));
    // Генерим dat файлы по шаблону
    $thisTpl = preg_replace("/(<!--.*?Kan_title.*?-->).*?(<!--.*?Kan_title.*?-->)/uism", "$1\n$ancor\n$2", $template);
    $thisTpl = preg_replace("/(<!--.*?Kan_content.*?-->).*?(<!--.*?Kan_content.*?-->)/uism", "$1\n$content\n$2", $thisTpl);
    $thisTpl = $scriptCharset == $destCharset ? $thisTpl : iconv( $scriptCharset, $destCharset, $thisTpl );
    if (fwrite($hDat, $thisTpl)) {
    echo "Файл $dataCata/$fname.$datExt записан<br/>\n";
    $html = "
    <loc><a href=\"/$dataCata/$fname.html\">$ancor</a></loc>\n";
    fwrite($hMain, iconv($scriptCharset, $destCharset, $html));
    } else { echo "Ошибка записи в файл $dataCata/$fname.$datExt<br/>\n"; }
    } else {
    echo "Не могу записать в файл $dataCata/$fname.$datExt<br/>\n";
    }
    }
    // Генерация уникального имени
    function genName() {
    return substr(md5(uniqid(rand(), true)), 0, rand(7, 13));
    }
    ?>

    Человек интересуется, почему цикл выполняется только 1 раз. Ему посоветовали разместить лучше свой код тут, но по-моему, делать это самостоятельно у него желания нет, решил помочь. Пруфлинк - http://forum.searchengines.ru/showthread.php?t=643176

    Nemoden, 12 Июля 2011

    Комментарии (21)
  6. Python / Говнокод #7153

    −96

    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
    import os
    import codecs
    from xml.dom import minidom
    
    dir = 'C:\\Users\\pee\\AppData\\Roaming\\Thunderbird\\Profiles\\your_profile_here.default\\extensions'
    target = 'install.rdf'
    TB_id = '{3550f703-e582-4d05-9a08-453d09bdfdc6}'
    maxVer = '5.*'
    
    # open file, parse xml, find Thunderbird ID, change maxVersion, save file
    def verchanger(rdf):
        found = False
        print(rdf)
        xmldoc = minidom.parse(rdf)
        idlist = xmldoc.getElementsByTagName("em:id")
        for i in idlist:
            if i._get_firstChild().nodeValue == TB_id:
                print('Thunderbird ID was founded in em:id node with index ', idlist.index(i)+1)
                print(i.parentNode.getElementsByTagName("em:maxVersion")[0]._get_firstChild().nodeValue)
                if i.parentNode.getElementsByTagName("em:maxVersion")[0]._get_firstChild().nodeValue == maxVer:
                    print('file already updated, skipping')
                    break
                else:
                    found = True
                    i.parentNode.getElementsByTagName("em:maxVersion")[0]._get_firstChild().nodeValue = maxVer
                print('new value is: ', i.parentNode.getElementsByTagName("em:maxVersion")[0]._get_firstChild().nodeValue )
        if found:
            xmldoc.writexml(codecs.open(rdf,'w','utf-8'), encoding='utf-8')
    
    
    # get list of files with full paths
    filelist = [dir + '\\' + x + '\\' + target for x in os.listdir(dir)]
    
    for i in filelist:
        verchanger(i)

    Мой первый говнокод :)

    Проходит по папке с расширениями Thunderbird, изменяя требуемую минимальную версию плагина на железно заданную maxVer. Вынужденно наговнокодено после обновления ТБ на версию 5.

    Прошу разобрать по косточкам, я Питон только изучаю. Дочитал Лутца до классов, почти всё накопал с помощью Гугля .

    omgiafs, 05 Июля 2011

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

    −120

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    if( (ori == UIInterfaceOrientationLandscapeLeft) || (ori == UIInterfaceOrientationLandscapeRight))
    {
        // Some code
    }
    else if(ori==UIInterfaceOrientationPortrait || ori==UIInterfaceOrientationPortraitUpsideDown)
    {
        // Some other code
    }
    else {
        // God mode on!
    }

    Реальный проект после индусов... Что движет этими людьми я не понимаю...

    makadaw, 02 Июля 2011

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

    +109

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    if (File.Exists(local)) {
                        if (Connect()) {
                            if (ftpConnection.Exists(remote)) {
    //code
                            }
                        }
                    }

    Irdis, 27 Июня 2011

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

    +147

    1. 1
    2. 2
    3. 3
    uint32_t getuint32(char *p){
      return (*p<<24)|(*(p+1)<<16)|(*(p+2)<<8)|(*(p+3));
    }

    yasosiska, 27 Июня 2011

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

    +153

    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
    try
    			{
    				sw = gcnew StreamWriter(GetIniFileName());
    			}
    			catch(UnauthorizedAccessException^ e)
    			{
    				MessageBox::Show( "Access is denied.", "Ошибка", MessageBoxButtons::OK, MessageBoxIcon::Error );
    				ShowException(dynamic_cast<System::Exception^>(e));
    				return;
    			}
    			catch(ArgumentNullException^ e)
    			{
    				MessageBox::Show( e->ParamName + ": File path is null.", "Ошибка", MessageBoxButtons::OK, MessageBoxIcon::Error );
    				ShowException(dynamic_cast<System::Exception^>(e));
    				return;
    			}
    			catch(ArgumentException^ e)
    			{
    				MessageBox::Show( e->ParamName + ": Wrong file path.", "Ошибка", MessageBoxButtons::OK, MessageBoxIcon::Error );
    				ShowException(dynamic_cast<System::Exception^>(e));
    				return;
    			}
    			catch(DirectoryNotFoundException^ e)
    			{
    				MessageBox::Show( "The specified path is invalid, such as being on an unmapped drive.", "Ошибка", MessageBoxButtons::OK, MessageBoxIcon::Error );
    				ShowException(dynamic_cast<System::Exception^>(e));
    				return;
    			}
    			catch(PathTooLongException^ e)
    			{
    				MessageBox::Show( "The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. ", "Ошибка", MessageBoxButtons::OK, MessageBoxIcon::Error );
    				ShowException(dynamic_cast<System::Exception^>(e));
    				return;
    			}
    			catch(IOException^ e)
    			{
    				MessageBox::Show( "File path includes an incorrect or invalid syntax for file name, directory name, or volume label syntax. ", "Ошибка", MessageBoxButtons::OK, MessageBoxIcon::Error );
    				ShowException(dynamic_cast<System::Exception^>(e));
    				return;
    			}
    			catch(SecurityException^ e)
    			{
    				MessageBox::Show( "The caller does not have the required permission." + e->ToString(), "Ошибка", MessageBoxButtons::OK, MessageBoxIcon::Error );
    				ShowException(dynamic_cast<System::Exception^>(e));
    				return;
    			}
    			catch(System::Exception^ e)
    			{
    				ShowException(e);
    				return;
    			}

    Обработка исключений.

    ScumCoder, 22 Июня 2011

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

    +154

    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
    <?php
     if (isset($_POST['update'])) {
    			 $kolcen=mysql_real_escape_string($_POST['kolcen']);
    			 $tovar=mysql_real_escape_string($_POST['tovar']);
    			 $descr=mysql_real_escape_string($_POST['descr']);
    			 $price=intval($_POST['price']);
    			 $price2=intval($_POST['price2']);
    			 $price3=intval($_POST['price3']);
    			 $id=intval($_POST['update']); 
    			 $zag1=mysql_real_escape_string($_POST['zag1']);
    			 $zag2=mysql_real_escape_string($_POST['zag2']);
    			 $zag3=mysql_real_escape_string($_POST['zag3']);
    			 
    			  switch($kolcen){ 
    		 case '3':$updatetovar = mysql_query ("UPDATE `tovar3` SET `tovar`='$tovar',`descr`='$descr',`price`='$price',`price2`='$price2',`price3`='$price3' WHERE `id`='$id' and `id`='$serv'");
    		 break; 
    		 case '2': $updatetovar = mysql_query ("UPDATE `tovar2` SET `tovar`='$tovar',`descr`='$descr',`price`='$price',`price2`='$price2' WHERE `id`='$id' and `id`='$serv'");
    		 break; 
    		 case '1':$updatetovar = mysql_query ("UPDATE `tovar` SET `tovar`='$tovar',`descr`='$descr',`price`='$price' WHERE `id`='$id' and `pizzaid`='$service'");
    		 break;
    		 case '2images': $updatetovar = mysql_query ("UPDATE `2images` SET `tovar`='$tovar',`descr`='$descr',`price`='$price',`price2`='$price2',`price3`='$price3',`img`='$img',`zag1`='$zag1',`zag2`='$zag2',`zag3`='$zag3' WHERE `id`='$id' and `id`='$serv'");
    		 break;
    		 }
    ?>

    Народ зацените мой код плиз на предмет говнокода, и если чето не так то дайте совет . Этот код для админки добавления товаров. Есть 4 типа категорий, товар с одной ценой, с двумя, с тремя, и товар с двумя картинками. В зависимости от типа категории делаем запрос к базе

    frie, 21 Июня 2011

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