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

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

    +2

    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
    //Модуль основной формы внешней обработки
    
    &НаКлиенте
    Процедура ПродатьСлона(Оферта)
    	
    	Перем Акцепт;
    	
    	Если ПустаяСтрока(Оферта) Тогда
    		
    		Оферта = "Купи слона!";
    		
    	Иначе
    		
    		Оферта = "Все говорят """+Оферта+""" а ты купи слона!";
    		
    	КонецЕсли;	
    		
    	ВвестиСтроку(Акцепт,Оферта,0, Истина); 	
    		
        ПродатьСлона(Акцепт);
    	
    КонецПроцедуры	
    
    &НаКлиенте
    Процедура ПриОткрытии(Отказ)
    	
    	ПродатьСлона("");
    	
    КонецПроцедуры

    Продаём слона!

    informatikmarazmatik, 30 Мая 2017

    Комментарии (11)
  3. Си / Говнокод #23073

    +2

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    for(uint64_t i = 0ULL; i <= 999999999ULL; i+= 1)
    {
        long double a =  0.00005l * i; // это чтоб в плавучке не накапливались ошибки.
        somefunction(a);
        ....
    }

    j123123, 26 Мая 2017

    Комментарии (11)
  4. Python / Говнокод #23006

    +3

    1. 1
    2. 2
    if str(type(date))!="<class 'datetime.date'>":
        date=date.date()

    Решил перевести datetime.datetime в datetime.date

    peterder72, 10 Мая 2017

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

    +10

    1. 1
    if ($invitationType == '1' || '2') {}

    Indian validation. WHYYYYY?

    madfishGovnokod, 06 Июля 2016

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

    +5

    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
    $sql = mysql_query("SELECT * FROM `news` ORDER BY `id` DESC LIMIT 1");
    while($sql1 = mysql_fetch_assoc($sql))
    {
    echo ''.smile(bb($sql1['text'])).'<br />
    Добавил: '.nick($sql1['avtor']).'<br />
    <a href="/news/comment'.$sql1['id'].'">Комментарии:</a> ('.mysql_result(mysql_query('select count(`id`) from `news_com` where `news` = "'.$sql1['id'].'"'),0).')';
    if($user['id']) {
    echo '<br /><a href="?news='.$sql1['id'].'">Скрыть новость</a>';}
    if(isset($_GET['news']))
    {
    $news= trim(intval($_GET['news']));
     mysql_query("UPDATE `users` SET `news` = '".$news."' WHERE `id` = '".$user['id']."'");
    header('Location: '.$HOME.'');
    }
    }

    Исходники супер сильной cms 2016 ! Встречайте StrongCMS! Версия движка 1.1. Скачать можно на strongcms.ru :)

    eskrano, 05 Июля 2016

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

    +5

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    $number_of_posts = 1;
    $page_id = $_GET['page'];
    $all_posts_query = "SELECT * FROM `posts` WHERE status = 'publish'";
    $all_posts_run = mysqli_query($con, $all_posts_query);
    $all_posts = mysqli_num_rows($all_posts_run);
    $total_pages = ceil($all_posts / $number_of_posts);
    $posts_start_from = ($page_id - 1) * $number_of_posts;
    
    $query = "SELECT * FROM `posts` WHERE `status` = 'publish' ORDER BY id DESC LIMIT $posts_start_from, $number_of_posts";

    Задача: сделать паджинацию, выжрав максимум ресурсов сервера :))
    Сверхзадача: реализовать выборку по id с помощью LIMIT'а

    DDDeeper, 11 Июня 2016

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

    +2

    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
    while (s != null)
                {
                    s = fs.ReadLine();
    
                    //arr  line example <rect x="0" y="0" rgba(92,41,235,0.9921568627451 
    
                    String[] arr = s.Split('(');
                    arr = arr[1].Split(',');
    
                    int fourPart = (int)(float.Parse(arr[3].Replace('.',',')) * 0xFF);
                    var binaryFour =  Convert.ToString(fourPart, 2);
    
                    while(binaryFour.Length < 8)
                    {
                        binaryFour = "0" + binaryFour;
                    }
    
                    int threePart = int.Parse(arr[2]);
                    var binaryThree = Convert.ToString(threePart, 2);
    
                    while (binaryThree.Length < 8)
                    {
                        binaryThree = "0" + binaryThree;
                    }
    
                    int twoPart = int.Parse(arr[1]);
                    var binaryTwo = Convert.ToString(twoPart, 2);
    
                    while (binaryTwo.Length < 8)
                    {
                        binaryTwo = "0" + binaryTwo;
                    }
    
                    int firstPart = int.Parse(arr[0]);
                    var binaryfirst = Convert.ToString(firstPart, 2);
    
                    number = Convert.ToInt32((binaryfirst + binaryTwo + binaryThree + binaryFour),2);
    
                    Write("number", number.ToString());
                }

    Хз как такое вообще появляется в голове

    partizanes, 31 Мая 2016

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

    0

    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
    Нам нужно больше запросов в БД!!!!111 строим дерево меню:
        private function Stack($PageCategory) {
          $Menu = NULL;
          $Q = 'SELECT * FROM '.$this->table.' WHERE pageCategory = '.$PageCategory.' ORDER BY pagePosition;';
          $Result = $this->Result($Q);
          while($Row = mysql_fetch_assoc($Result)) {
            $Row['pageChilds'] = $this->Stack($Row['pageID']);
            $Menu[$Row['pageID']] = $Row;
          }
          return $Menu;
        }
    
    AUTOINCREMENT PHP-way:
        private function CurrentID() {
          $Q = 'SELECT MAX(pageID) as maxID FROM '.$this->table.';';
          $Row = $this->Row($Q);
          return ++$Row['maxID'];
        }
    
    Так форматируем даты:
        private function FormatDate() {
          $Year = substr($this->publication['publicationDate'], 0, 4);
          $Month = substr($this->publication['publicationDate'], 5, 2);
          $Day = substr($this->publication['publicationDate'], 8, 2);
          return $Day.'.'.$Month.'.'.$Year;
        }
    
    Просто контроллер:) А чо?
    <?php
      
      class Slider extends DataBase {
        
        private $slides;
        
        public function GetSlides() {
          $Q = 'SELECT * FROM slide ORDER BY slidePosition;';
          $this->slides = $this->Rows($Q);
        }
        
        public function ViewSlides() {
          $Slides = '';
          if($this->slides) {
            foreach($this->slides as $SlideStack) {
              $Slides .= $this->ViewSlide($SlideStack);
            }
          }
          return $Slides;
        }
        
        private function ViewSlide($SlideStack) {
          $A = '<a href="'.$SlideStack['slideLink'].'">';
          $A .= '  <div class="BannerSlide">';
          $A .= '    <img src="'.I.'/slides/'.$SlideStack['slideImage'].'.jpg">';
          $A .= '    <div class="BannerSlideText">';
          $A .= '      <div class="BannerSlideTextInner">'.$SlideStack['slideName'].'<br>';
          $A .= '        <span>'.$SlideStack['slideText'].'</span>';
          $A .= '      </div>';
          $A .= '    </div>';
          $A .= '  </div>';
          $A .= '</a>';
          return $A;
        }
        
      } // End class
      
    ?>

    Окунулся в велосипедную CMS, на которой ваяет контора http://fn85.ru/

    nik757, 18 Мая 2016

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

    +3

    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
    function pluralize($num) {
            switch ($num) {
                case 1:
                case 21:
                    $word = "товар";
                    break;
                case 2:
                case 3:
                case 4:
                case 22:
                case 23:
                case 24:
                case 32:
                case 33:
                case 34:
                    $word = "товара";
                    break;
                default:
                    $word = "товаров";
                    break;
            }
            return $word;
    }

    На продакшене.

    dgkj, 18 Мая 2016

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

    +9

    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
    <?
    	if(/*!get($conf, 'settings', 'canonical') &&*/ !array_key_exists("null", $_GET) && !array_key_exists("p", $_GET) && ($conf['settings']['theme/*:admin'] != $conf['settings']['theme']) && !array_search($arg['fn'], ['', 'ajax', 'json', '404', 'img'])){ # Нет перезагрузки страницы адреса
    		if(!($diff = array_diff_key($_GET, array_filter($_GET)))){
    			if($alias = "{$arg['modpath']}:{$arg['fn']}". (($keys = array_keys(array_diff_key($_GET, array_flip(["m", "id"])))) ? "/". implode("/", $keys) : "")){
    				if($seo_cat = fk("{$conf['db']['prefix']}seo_cat", $w = array("alias"=>$alias), $w += array("name"=>$conf['modules'][$arg['modpath']]['name']. " » ". (get($conf, 'settings', "{$arg['modpath']}_{$arg['fn']}") ?: $arg['fn']))/*, $w*/)){
    					if(empty($seo_cat['hide'])){
    						if($settings = mpzam($conf['settings'], "settings")){
    							if($characters_lang = rb("{$conf['db']['prefix']}seo_characters_lang", "name", $w = "[". ((strpos($_SERVER['HTTP_HOST'], "xn--") === 0) ? "Русские" : "Английские"). "]")){
    								if($characters = array_column(rb("{$conf['db']['prefix']}seo_characters", "characters_lang_id", "id", array_flip([$characters_lang['id'],0])), "to", "from")){
    									if($seo_cat['href'] && ("/" == substr($seo_cat['href'], 0, 1)) /*&& ("/" == substr($seo_cat['href'], -1, 1))*/){
    										if(get($_GET, 'id')){ # Проверка и формирование методанных объекта
    											if(($default = rb($arg['fn'], "id", $_GET['id']))){
    												foreach(array_intersect_key($seo_cat, array_flip(array('title', 'description', 'keywords', "href"))) as $n){
    													if(preg_match_all("#{([\w-_]+):(\w+)}#", $n, $match)){ mpre($n, $match);
    														foreach($match[0] as $n=>$m){
    															if(empty($e) || !rb($e, "table", "field", "[{$match[1][$n]}]", "[{$match[2][$n]}]")){
    																$e[] = array("id"=>(empty($e) ? 0 : count($e)), "table"=>$match[1][$n], "field"=>$match[2][$n]);
    															}
    														}
    													}//else{ mpre($n, $match); }
    												} if(!empty($e)){
    													foreach($e as $t){
    														if(strpos($t['table'], "-")){
    															if($id = get($_GET, $t['table'])){
    																$data[$t['table']] = rb($t['table'], "id", (int)$id);
    															}else{ mpre("Ключ не найден"); }
    														}
    													} while(($tabs = array_intersect_key((empty($d) ? ($d = $default) : $d), array_flip(array_map(function($v){ return "{$v}_id"; }, array_column($e, "table"))))) && (($loop = /*mpre*/(empty($loop) ? 1 : $loop+1)) < 10 /* Максимальное количество итераций */)){ # Если есть ключи от требующихся тегов
    														foreach($tabs as $k=>$id){
    															$data[$t = substr($k, 0, -3)] = rb($t, "id", $id);
    															$d += $data[$t = substr($k, 0, -3)];
    															$e = array_diff_key($e, rb($e, "table", "id", "[{$t}]"));
    														}
    													}
    												} if($mpzam = mpzam(empty($data) ? $default : array(""=>$default)+$data)){// exit(mpre($mpzam));
    													foreach(array_intersect_key($seo_cat, array_flip(array('title', 'description', 'keywords'))) as $k=>$m){
    														if($m){ $meta[$k] = strtr(strtr($m, $settings), $mpzam); }
    													} if($src = htmlspecialchars_decode(mb_strtolower(strtr($seo_cat['href'], $mpzam+$settings), 'UTF-8'))){
    														if(!preg_match_all("#{(.*):?(.*?)}#", $src. implode("", $meta), $match) && (substr($src, -1) != "/")){
    															if($meta && ($meta = meta(array(urldecode($_SERVER['REQUEST_URI']), strtr($src, $characters)), $meta += array("cat_id"=>$seo_cat['id'])))){
    																exit(header("Location: {$meta[0]}"));
    															}else{ mpre("Мета информация не установлена"); }
    														}else{ mpre("В адресе категории <a href='/seo:admin/r:{$conf['db']['prefix']}seo_cat?&where[id]={$seo_cat['id']}'>{$seo_cat['name']}</a> и метаинформации заменены не все теги", $src, $meta); }
    													}else{ mpre("Ошибка формирования адреса страницы"); }
    												}else{ mpre("Таблица языка перекодировки не найдена <a href='/seo:admin/r:mp_seo_characters_lang'>{$w}</a>"); }
    											}else{ mpre("Элемент с указанных номером не найден", $_GET['id']); }
    										}else if($src = htmlspecialchars_decode(mb_strtolower(strtr(implode("/", array_slice(explode("/", $seo_cat['href']), 0, 2)), $settings), 'UTF-8'))){ // mpre($src); # Список элементов
    											if(!preg_match_all("#{(.*):?(.*?)}#", $src. implode("", $seo_cat), $match) && (substr($src, -1) != "/")){// exit(mpre($src, $match));
    												if($meta = meta(array(urldecode($_SERVER['REQUEST_URI']), strtr($src, $characters)), $seo_cat + array("cat_id"=>$seo_cat['id']))){
    													exit(header("Location: {$meta[0]}"));
    												}else{ mpre("Мета информация не установлена"); }
    											}else{ mpre("В адресе и метаинформации заменены не все теги <a href='/seo:admin/r:{$conf['db']['prefix']}seo_cat?&where[id]={$seo_cat['id']}'>{$seo_cat['name']}</a>", $src, $seo_cat); }
    										}else{ mpre("Элемент не найден и адрес списка не верный"); }
    									}else{ mpre("Не верный формат seo адреса <a href='/seo:admin/r:{$conf['db']['prefix']}seo_cat?&where[id]={$seo_cat['id']}'>{$seo_cat['name']}</a>"); }
    								}else{ mpre("Не установлена таблица перекодировки <a href='/seo:admin/r:mp_seo_characters'>seo_characters</a>"); }
    							}else{ mpre("Не найдены данные перекодировки"); }
    						}else{ mpre("Ошибка формирования системных переменных"); }
    					}else{ /*mpre("Категория отмечена как скрытая");*/ }
    				}else{ mpre("Не найдена категория переадресации"); }
    			}else{ mpre("Алиас сфоримрован ошибочно"); }
    		}else{ mpre("Входящие параметры содержат пустые значения", $diff); }
    	}else{ /*mpre(get($conf, "settings", "canonical"));*/ }

    Больше веселухи тут https://github.com/mpak2/mpak.su

    geph, 10 Мая 2016

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