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

    В номинации:
    За время:
  2. 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)
  3. 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)
  4. 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)
  5. 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)
  6. 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)
  7. 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)
  8. 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)
  9. 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)
  10. C# / Говнокод #6952

    +126

    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
    public static bool ValidateEmailAddress(string emailAddress)
            {
                try
                {
                    string TextToValidate = emailAddress;
                    // test email address with expression
                    if (emailExpression.IsMatch(TextToValidate))
                    {
                        // is valid email address
                        return true;
                    }
                    else
                    {
                        // is not valid email address
                        return false;
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }

    public static bool ValidateEmailAddress(string emailAddress)
    {
    if(string.IsNullOrEmpty(emailAddress))
    return false;
    return emailExpression.IsMatch(TextToValidate);
    }

    jenik15, 14 Июня 2011

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

    +197

    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
    ; загрузка из cfg-файла переменной Gravity
    seg011:06CA         fld     [dbl_45A48]   ; 0.2
    seg011:06CF         add     sp, -8
    seg011:06D2         fstp    [bp+var_16]   ; default=0.2
    seg011:06D6         push    ds
    seg011:06D7         mov     ax, offset aGravity
    seg011:06DA         push    ax            ; key="GRAVITY"
    seg011:06DB         wait
    seg011:06DD         push    cs
    seg011:06DE         call    near ptr cfg_ReadDbl
    seg011:06E1         add     sp, 12
    seg011:06E4         fstp    [curGravity]  ; cur=cfg_ReadDbl()
    ; проверка загруженного значения на диапазон [0,05..10,0]
    seg011:06E9         fld     [flt10]
    seg011:06EE         add     sp, -8
    seg011:06F1         fstp    [bp+var_16]   ; max = 10.0
    seg011:06F5         fld     [minGravity]
    seg011:06FA         add     sp, -8
    seg011:06FD         fstp    [bp+var_1E]   ; min = 0.05
    seg011:0701         fld     [curGravity]
    seg011:0706         add     sp, -8
    seg011:0709         fstp    [bp+var_26]   ; cur
    seg011:070D         wait
    seg011:070F         push    cs
    seg011:0710         call    near ptr CheckRangeDbl
    seg011:0713         fstp    st            ; результат нах...
    seg011:0716         add     sp, 24
    <....cut....>
    
    ; double CheckRangeDbl(double cur, double min, double max)
    seg011:0077 proc    CheckRangeDbl far
    seg011:0077 var_2   = word ptr -2
    seg011:0077 @@cur   = qword ptr  6
    seg011:0077 @@min   = qword ptr  0Eh
    seg011:0077 @@max   = qword ptr  16h
    seg011:0077         push    bp
    seg011:0078         mov     bp, sp
    seg011:007A         dec     sp
    seg011:007B         dec     sp
    seg011:007C         fld     [bp+@@cur]
    seg011:0080         fcomp   [bp+@@min]
    seg011:0084         fnstsw  [bp+var_2]
    seg011:0088         wait
    seg011:008A         mov     ax, [bp+var_2]
    seg011:008D         sahf
    seg011:008E         jnb     @@chk_max     ; if (cur < min)
    seg011:0090         fld     [bp+@@min]    ;     st(0) = min
    seg011:0094         jmp     @@exit
    seg011:0096 @@chk_max:                    ; else
    seg011:0096         fld     [bp+@@cur]
    seg011:009A         fcomp   [bp+@@max]
    seg011:009E         fnstsw  [bp+var_2]
    seg011:00A2         wait
    seg011:00A4         mov     ax, [bp+var_2]
    seg011:00A7         sahf
    seg011:00A8         jbe     @@ret_cur     ; if (cur > max)
    seg011:00AA         fld     [bp+@@max]    ;     st(0) = max
    seg011:00AE         jmp     @@exit
    seg011:00B0 @@ret_cur:                    ; else
    seg011:00B0         fld     [bp+@@cur]    ;     st(0) = cur
    seg011:00B4 @@exit:
    seg011:00B4         fst     [bp+@@cur]
    seg011:00B8         wait
    seg011:00BA         mov     sp, bp
    seg011:00BC         pop     bp
    seg011:00BD         retf                  ; return st(0)
    seg011:00BD endp    CheckRangeDbl

    Из старой, очень популярной игрухи (Scorshed Earth). Все как положено, подгружаемые из cfg-файла данные проходят проверку. Только вот результаты проверок (для double, для int и прочих типов) попросту отбрасываются :) Даже не знаю, как такое можно было накодить, на невнимательность непохоже - такого кода довольно много.

    DemonId7, 12 Июня 2011

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