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

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

    +167

    1. 1
    while(!file_exists(getcwd()."/.htroot")){chdir('..');}

    http://www.php.net/manual/en/function.require.php

    if you want always include, require, open files using some 'root' folder based path you may may put file '.htroot' in 'root' folder and use this.

    while(!file_exists(getcwd()."/.htroot")){chdir('..');}

    This code change current dir to dir where '.htroot' file located and everywhere you can use relative to 'root' paths.

    Please avoid absent of '.htroot' file.

    qbasic, 12 Декабря 2010

    Комментарии (13)
  3. Куча / Говнокод #4857

    +131

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    <div class="pg_content"><br>  <div id="pg_title" class="pg_title"><br>      <h1 style="display:block;top:25px;"><br>
              Shape Company Website Design        </h1><br>     <h1>Summer of Love</h1>     ... </div>    <div id="pg_preview"><br>
         <img class="pg_thumb" style="display:block;z-index:9999;" src="images/medium/1.jpg" alt="images/large/1.jpg"/><br>   
         <img class="pg_thumb" src="images/medium/2.jpg" alt="images/large/2.jpg"/>        ... </div>  
      <div id="pg_desc1" class="pg_description"><br>        <div style="display:block;left:250px;">       <br>    
    <h2>Project Description</h2>        <br>    <p>A description comes here</p><br>     </div>        <div><br>         <h2>Project Description</h2><br>            <p>A description comes here</p> <br>    </div>
            ... </div>    <div id="pg_desc2" class="pg_description"><br>        <div style="display:block;left:250px;"><br>  
             <h2>Technologies Used</h2><br>          <p>A text comes here</p><br>        </div>        <div> <br> 
           <h2>Technologies Used</h2><br>          <p>A text comes here</p>    <br>    </div>        ... </div></div>

    Собственно теги переноса вперемешку с блоками. Ересь :)

    Код, соответственно, не мой. Слава Богу))

    Scr1pt1k, 08 Декабря 2010

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

    +161

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    $uploaddir = '../foto/'.$img_name_clean.'/';
    $uploadfile = $uploaddir . basename($_FILES[$key]['name']);
    $img_name = $_FILES[$key]['name'];
    
    if (file_exists("../foto/".$img_name_clean."/".$img_name."")){echo "Внимание! Ошибка, в папке ".$img_name_clean." уже существует файл ".$img_name."! Пожалуста, переименуте загружаемый файл."; exit;}
    if (move_uploaded_file($_FILES[$key]['tmp_name'], $uploadfile)) {
    chmod('../foto/'.$img_name_clean.'/' . $img_name, 0666);
    echo "Файл ".$_FILES[$key]['name']." загружен в папку ".$img_name_clean.".\n<br>";
    } else {
    echo "Файл ".$_FILES[$key]['name']." не загружен в папку ".$img_name_clean.".\n<br>";exit;
    }

    Эх, не удержался таки! Продолжение предыдущего.

    Uchkuma, 08 Декабря 2010

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

    +145

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    <ZORG2> Как грамотно хранить PHP код в базе????
    <neko> как строку
    <ZORG2> я имею в виду фильтровать его как то?? возможность добавления PHP кода в базу будет только у админа сайта.
    <neko> скастуй в строку!
    <ZORG2> и этот код будет подключаться в некоторые страницы сайта для выполнения

    привет от #php на irc.by

    robot, 07 Декабря 2010

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

    +119

    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
    public void SendCommand(string command, bool fake)
    {
        ...
        for (var tries = 0; tries < 2; tries++)
        {
            for (var i = 0; i < 2; i++)
                try
                {
                    sended = m_Socket.Send(sendBytes);
                    break;
                }
                catch (Exception e)
                {
                    Log.Error(LogSys, "SendCommand: Xception on send command to server: {0}", e.Message);
                    Thread.Sleep(m_Socket.SendTimeout);
                    if (i == 10)
                    {
                        Log.Error(LogSys, "SendCommand: cant send command in 10 tries.");
                        return;
                    }
                    continue;
                }
            ...
        }
        ...
    }

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

    banderror, 04 Декабря 2010

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

    +145

    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
    function parseHTML(text)
    {
        var t = text;
        var a = new Array();
    	var b = new Array();
        var cur = 0;
        var waiting_open_tag = true;
    	var last_cut = 0;
        for (var i = 0; i < t.length; i++)
        {
            cur = t.charAt(i);
            if (waiting_open_tag)
            {
                if (cur == '<')
    			{
    				a.push(t.substring(last_cut, i));
    				waiting_open_tag = false;
    				last_cut = i;
    			}
            }
    		else
    		{
                if (cur == '>')
    			{
    				a.push(t.substring(last_cut, i+1));
    				waiting_open_tag = true;
    				last_cut = i+1;
    			}
    		}
    		if (i == t.length-1)
    		{
    			a.push(t.substring(last_cut, i+1));
    		}
    
        }
    	// now reparse DOT"."
    	for (i = 0; i < a.length; i++)
    	{
    		y = a[i];
    		last_cut = 0;
    		for (z = 0; z < y.length; z++)
    		{
    			cur = y.charAt(z);
    			if (z == 0)
    			{
    				if ((cur == '<') || (cur == '&') || (cur == '\n'))
    				{
    					z = y.length + 981;
    					b.push(y.substring(last_cut, z+1));
    					continue;
    				}
    			}
    			if (cur == '.')
    			{
    				b.push(y.substring(last_cut, z+1));
    				last_cut = z+1;
    			}
    			if (z == y.length-1)
    			{
    				b.push(y.substring(last_cut, z+1));
    			}
    		}
    	}
        return b;
    }

    Эта функция разбивает строку на элементы массива. Граница разделения - это HTML tags ( < >) и точка (.)
    Функция сделана для подготовки текста к автоматическому переводу в Гугле - кто работал тот знает что запихнув большую строку ничего не получите.
    Я уже знаю ваши сопливые комментарии: RegExp. Собственно по этому это можно считать говнокодом ибо изобретен велосипед (но такого велосипеда в интернете нет). Ну а кто не Noob, прошу предоставить рабочий RegExp.

    increazon, 02 Декабря 2010

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

    +145

    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
    #include <iostream>
    #include <fstream>
    #include <conio.h>
    using namespace std;
    
    int main()
    {
    	int wc,cnt=0,maxp=0,minp=2147483647,maxn=-2147483648,minn=0,pos=0,neg=0,zf=0;
    	fstream(f);
    	f.open("input.txt",ios::in);
    
    	while (!f.eof())
    	{
    		if(!zf) zf--;
    		wc=0;
    		f >>wc;
    		if (wc>0) { if (maxp<wc) maxp=wc;  if (minp>wc) minp=wc; pos++; }
    		else {if (minn>wc) minn=wc;  if (maxn<wc&&wc)maxn=wc; if (!wc) zf+=2; else neg++; }
    	}
    	if (pos>1 && neg>1)
    		if ((float)maxp/minp > (float)minn/maxn) cout<<maxp<<"/"<<minp<<"="<<(float)maxp/minp;
    			else cout<<minn<<"/"<<maxn<<"="<<(float)minn/maxn;
    
    	if (pos>1 && neg<2)	cout<<maxp<<"/"<<minp<<"="<<(float)maxp/minp;
    	if (pos<2 && neg>1)	cout<<minn<<"/"<<maxn<<"="<<(float)minn/maxn;
    
    		if (pos<=1 && neg<=1)
    			if(zf) if(pos) cout<<"0/"<<minp<<"=0";else cout<<"0/"<<minn<<"=0";
    				else if ((float)maxp/maxn>(float)maxn/maxp)cout<<maxp<<"/"<<maxn<<"="<<(float)maxp/maxn; 
                                  else cout<<maxn<<"/"<<maxp<<"="<<(float)maxn/maxp;
    
    	if (pos+neg+zf<=1) cout<<"No solution!";
    
    	f.close();
     getch();
    	
    return 0;
    }

    Задача 2-ого курса: "в массиве целых числел найти два таких числа, чтобы их частное было максимальным ( O(n) )"
    И ее решение -.- Особо доставляет название переменных

    bulka, 29 Ноября 2010

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

    +165

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    function loadtitle($array) { //Функция установки meta-параметров в массив
    	$meta = array(); //Устанавливаем массив
    	$meta['title']=$array['title']; //Присваиваем метаданные
    	$meta['description'] =  $array['description'];				
    	$meta['author'] = $array['author'];				
    	$meta['keywords'] = $array['keywords'];	
    	return $meta; //Возвращаем массив метаданных
    }

    обнаружил в своем проекте 3 летней давности. сижу и тихо офигеваю)

    kindofbear, 28 Ноября 2010

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

    +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
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    /*фрагмент из компонента*/
    $arProps = array(
    "NAMES"=>$props["NAMES"]["VALUE"],
    "DESCRIPTIONS"=>$props["DESCRIPTIONS"]["VALUE"],
    "LINKS"=>$props["LINKS"]["VALUE"],
    "IMAGES"=>$props["PICTURES"]["VALUE"],
    "URLS" => array(
    "0"=>CFile::GetPath($props["PICTURES"]["VALUE"][0]),
    "1"=>CFile::GetPath($props["PICTURES"]["VALUE"][1]),
    "2"=>CFile::GetPath($props["PICTURES"]["VALUE"][2]),
    "3"=>CFile::GetPath($props["PICTURES"]["VALUE"][3]),
    "4"=>CFile::GetPath($props["PICTURES"]["VALUE"][4]),
    ),
    );
    
    /*код из шаблона*/
    <div class="text-blocks">
    <?if($arResult["PROPS"]["DESCRIPTIONS"][0]["TEXT"]):?>
      <div id="banner_text_1" class="text curr" style="left:92px; opacity:0.8; display: block">
    <table border="0" cellpadding="0" cellspacing="0"><tr><td>
        <a href="<?=$arResult["PROPS"]["LINKS"][0]?>"><?=$arResult["PROPS"]["DESCRIPTIONS"][0]["TEXT"]?></a>
    </td></tr></table>
      </div>
    <?endif;?>
    <?if($arResult["PROPS"]["DESCRIPTIONS"][1]["TEXT"]):?>
      <div id="banner_text_2" class="text" style="left:156px; opacity:0; display: none">
    <table border="0" cellpadding="0" cellspacing="0"><tr><td>
        <a href="<?=$arResult["PROPS"]["LINKS"][1]?>"><?=$arResult["PROPS"]["DESCRIPTIONS"][1]["TEXT"]?></a>
    </td></tr></table>
      </div>
    <?endif;?>
    <?if($arResult["PROPS"]["DESCRIPTIONS"][2]["TEXT"]):?>
      <div id="banner_text_3" class="text" style="left:220px; opacity:0; display: none">
    <table border="0" cellpadding="0" cellspacing="0"><tr><td>
        <a href="<?=$arResult["PROPS"]["LINKS"][2]?>"><?=$arResult["PROPS"]["DESCRIPTIONS"][2]["TEXT"]?></a>
    </td></tr></table>
      </div>
    <?endif;?>
    <?if($arResult["PROPS"]["DESCRIPTIONS"][3]["TEXT"]):?>
      <div id="banner_text_4" class="text" style="left:284px; opacity:0; display: none">
    <table border="0" cellpadding="0" cellspacing="0"><tr><td>
        <a href="<?=$arResult["PROPS"]["LINKS"][3]?>"><?=$arResult["PROPS"]["DESCRIPTIONS"][3]["TEXT"]?></a>
    </td></tr></table>
      </div>
    <?endif;?>
    <?if($arResult["PROPS"]["DESCRIPTIONS"][4]["TEXT"]):?>
      <div id="banner_text_4" class="text" style="left:284px; opacity:0; display: none">
    <table border="0" cellpadding="0" cellspacing="0"><tr><td>
        <a href="<?=$arResult["PROPS"]["LINKS"][4]?>"><?=$arResult["PROPS"]["DESCRIPTIONS"][3]["TEXT"]?></a>
    </td></tr></table>
      </div>
    <?endif;?>
    </div>

    Выборка свойств картинок и последующий вывод в шаблоне (выдернуто из самописного компонента Битрикс). Писал это очень давно, вот возникла необходимость править, открыл - посмотрел - случилась истерика!!! Очевидно что такое циклы я тогда еще не подозревал))

    akovalenko, 26 Ноября 2010

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

    +179

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    if(
        (s.Find("/0")!=-1)||
        (s.Find("Log10(-")!=-1)||
        (s.Find("Log10(0")!=-1))//stupid user error
    {
    }

    Проверка, есть ли в формуле, введенной пользователем, деление на 0, логарифм от отрицательного числа или логарифм от нуля. Стиль и комментарии автора сохранены.

    Shumway, 23 Ноября 2010

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