1. PHP / Говнокод #11646

    +62

    1. 1
    2. 2
    3. 3
    4. 4
    $date = substr($row[date], 0, 16);
    $dat1 = explode(" ", $date);
    $dat = explode("-", $dat1[0]);
    $date = "$dat[2]/$dat[1]/$dat[0]";

    Изящно

    kindofbear, 24 Августа 2012

    Комментарии (12)
  2. Java / Говнокод #11645

    +69

    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
    public static void main(String[] args) throws Exception {
    	// ProblemFactory in action...
    	DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    	docBuilderFactory.setValidating(false);
    	docBuilderFactory.setNamespaceAware(false);
    	DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    
    	// I really don't want to download that stupid DTD from w3c.org
    	docBuilder.setEntityResolver(new EntityResolver() {
    		public InputSource resolveEntity(String publicId, String systemId)
    				throws SAXException, IOException {
    			return new InputSource(new StringReader(""));
    		}
    	});
    
    	// Just fine
    	Document doc = docBuilder.parse("http://govnokod.ru/comments");
    
    	// ProblemFactory again
    	XPathFactory xpathFactory = XPathFactory.newInstance();
    	XPath xpath = xpathFactory.newXPath();
    
    	// Just fine
    	NodeList nodes = (NodeList)xpath.evaluate("//li[@class='hentry']", doc, XPathConstants.NODESET);
    	Pattern topicUriRegex = Pattern.compile("^.*/(\\d+)$");
    
    	// This is Java, not C. Why I need to write that shitty loop?!
    	for (int i=0, n=nodes.getLength(); i<n; i++) {
    		Node node = nodes.item(i);
    		String author = xpath.evaluate(".//strong[@class='entry-author']/a/text()", node);
    		String language = xpath.evaluate(".//a[@rel='chapter']/text()", node);
    		String topicUri = xpath.evaluate(".//a[@rel='bookmark'][@class='entry-title']/@href", node);
    		Matcher m = topicUriRegex.matcher(topicUri);
    		String topicId = m.matches() ? m.group(1) : "неизвестный говнокод";
    		String text = xpath.evaluate(".//div[@class='entry-comment']", node);
    		
    		System.out.println("==== " + author + " наложил в " + topicId + " (" + language + ") ====");
    		System.out.println(text);
    		System.out.println("");
    	}
    }

    Треш угар и содомия.Java, DOM и парсер уютненького.

    bormand, 24 Августа 2012

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

    +39

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    extern const TSafeFloat Pi;//Не использовать до входа в main!!! Возможно она ещё не инициализированна!!!
    //#define PI		3.14159265358979323846
    
    #ifndef M_PI
                             #define M_PI		3.14159265358979323846
    #endif

    Форматирование сохранено. Файл PiConsts.h

    HaskellGovno, 24 Августа 2012

    Комментарии (67)
  4. Ruby / Говнокод #11643

    −160

    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
    <div class="comment-content">
      		<% if comment.body.include?('[/quote]') %>
      			<% @text = Array.new %>
      			<% summ = '' %>
      			<% @text = simple_format(comment.body).split(' ') %>
      			<% namecheck = false %>
      			<% contentcheck = false %>
      			<% quotestart = false %>
      			<% donothing = true %>
      			<% quotecount = 0 %>
      			<% count_quotes = 0 %>
      			<% @text.each do |t| %>
      				<% if t.include?('[/quote]') %>
      					<% count_quotes ||= 0 %>
      					<% count_quotes += 1 %>
      				<% end %>
      			<% end %>
      			<% @text.each do |t| %>
      				<% if t.include?('[/quote]') %>
      					<% contentcheck = false %>
      					<% namecheck = false %>
      					<% t = t.gsub('[/quote]', '</div></div>') %>
      				<% elsif t.include?('[quote=') %>
      					<% namecheck = true %>
      					<% donothing = false %>
      					<% t = t.gsub('[quote=', '') %>
      				<% elsif t.include?(']') %>
      					<% t = t.gsub(']', '') %>
      				<% end %>
      				<% if donothing == false %>
      					<% if contentcheck == true and namecheck == true and t != '' and t != '<p>' and t != '</p>' %>
      						<% t = '<div class=quotecontent>' + '<div class=quotestart>' + '<div class=quotename>' + 'Цитата - ' + t + '</div>' %>
      						<% contentcheck = true %>
      						<% namecheck = false %>
      					<% elsif contentcheck == true and t != '' and t != '<p>' and t != '</p>' %>
      						<% t = '<div class=quotecontent>' + t %>
      						<% contentcheck = false %>
      					<% elsif namecheck == true and t != '' and t != '<p>' and t != '</p>' %>
      						<% t = '<div class=quotestart>' + '<div class=quotename>' + 'Цитата - ' + t + '</div>' %>
      						<% namecheck = false %>
      						<% contentcheck = true %>
      					<% end %>
      				<% end %>
      				<% summ = summ + t + ' ' %>
      			<% end %>
      		<% else %>
      			<% summ = comment.body %>
      		<% end %>
        	<%=raw simple_format(summ) %>
        </div>

    Вьюха списка комментариев. Когда это попало к верстальщику - он был мягко говоря шокирован.

    ruby-code, 24 Августа 2012

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

    −102

    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
    -(void)tableView:(UITableView*)tableViewTable didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        switch (indexPath.row) {
            case 0:
            {
                ViewControllerFavorites *contoller = [[ViewControllerFavorites alloc] initWithNibName:nil bundle:nil];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]];
            }
                break;
            case 1:
            {
                ViewControllerMyAccount *contoller = [[ViewControllerMyAccount alloc] initWithNibName:nil bundle:nil];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]];            
            }
                break;            
            case 2:
            {
                ViewControllerParts *contoller = [[ViewControllerParts alloc] initWithNibName:nil bundle:nil];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]];            
            }
                break;            
            case 3:
            {
                ViewControllerFinancing *contoller = [[ViewControllerFinancing alloc] initWithNibName:nil bundle:nil];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]];            
            }
                break;            
            case 4:
            {
                ViewControllerWebView *contoller = [[ViewControllerWebView alloc] initWithNibName:nil bundle:nil link:@"http://www.facebook.com"];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]];    
            }
                break;            
            case 5:
            {
                ViewControllerWebView *contoller = [[ViewControllerWebView alloc] initWithNibName:nil bundle:nil link:@"http://twitter.com"];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]]; 
            }
                break;            
            case 6:
            {
                ViewControllerWebView *contoller = [[ViewControllerWebView alloc] initWithNibName:nil bundle:nil link:@"http://plus.google.com"];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]]; 
            }
                break;            
            case 7:
            {
                ViewControllerLiveChat *contoller = [[ViewControllerLiveChat alloc] initWithNibName:nil bundle:nil];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]];           
            }
                break;            
            case 8:
            {
                ViewControllerGasStations *contoller = [[ViewControllerGasStations alloc] initWithNibName:nil bundle:nil];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]];            
            }
                break;            
            case 9:
            {
                ViewControllerVinScanner *contoller = [[ViewControllerVinScanner alloc] initWithNibName:nil bundle:nil];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]];           
            }
                break;            
            case 10:
            {
                ViewControllerQRScanner *contoller = [[ViewControllerQRScanner alloc] initWithNibName:nil bundle:nil];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]];            
            }
                break;            
            case 11:
            {
                ViewControllerNewsletter *contoller = [[ViewControllerNewsletter alloc] initWithNibName:nil bundle:nil];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]];            
            }
                break;            
            case 12:
           {
                ViewControllerSettings *contoller = [[ViewControllerSettings alloc] initWithNibName:nil bundle:nil];
                [contoller setNavigationController:navigationController];
                [navigationController pushUIViewController:contoller WithName:[[[row getData] objectForKey:@"description"] uppercaseString]];           
            }
                break;        
            default:
                break;
        }

    Вот так в коммерческих проектах реализуют навигацию.

    GK2012, 23 Августа 2012

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

    +142

    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
    main()
       {
       j=atol("776677"); c=0;
      gb=65500;  /*гран буф не>65500!*/
      gp=gb+65500;
       c=PA();
       vm = v_mod(0x0f00)&0x00ff;
       if((vm!=2) && (vm!=3) && (vm!=7))   v_mod(3);
       if(vm==7) v_m=MK_FP(0xB000,0); /* присвоить адр в-памяти */
       else   v_m=MK_FP(0xB800,0);
       if(c==0) {printf("Самопроверка программы неудачна."); dely(9);}
       gek=calloc(1000,sizeof(int));
       bufa=farcalloc(4000,sizeof(long));
       bfk=calloc(4000,sizeof(int));
       ok=calloc(800,sizeof(char));
       st=calloc(10,sizeof(char));
       bufv=calloc(4000,sizeof(char));
     if((gek==NULL)||(bufa==NULL)||(bfk==NULL)||(ok==NULL)||(st==NULL)||(bufv==NULL))
    	  {
      printf(" Неудачное выделение памяти для основных буферов.\n");
      printf(" Программа не выполняется.");
    	 dely(9); exit(1);   }
       for(x=0;x<4000;x++) {bufa[x]=0L;bfk[x]=0; /*занул буф адресов и кодов */
       if(x<10) st[x]=0x00; /*буф для выв чисел на экр*/
       if(x<26) urov[x]=1;
       if(x<20) {abn[x]=1; aba[x]=2L;}} /*мин адресa абс ном строк и нач загр буф*/
       if(x<128) B0[x]=0;
       ur=vv=avt=in=0; i=N=0; zap=0;x_=1;
       ifm=10;/*10,01,11,12,21 - 1:п/панель записей,0-инф п/панель,12,21-2 базы*/
     /*  vctp(3);*/
       mou(0);   kur(0);
      okn=0; /*сбр инд сохр-х окон*/
      v_mod(0);
       nok1=16;
      SET();   ch=pal[0];
      textbackground(BLACK);
       clrscr();
      okno(0,2,ch,ch);
      window(1,1,80,25);
      okno(16,2,ch,ch);
      nstr(1);
      baz=1;
      nfl="0.cry ";
      F_place("10.cry");
      kzo();
      prx=3; /*нейтраль*/
      for(vm=4000;vm<8000;vm++) v_m[vm]=0; vm=0;
      /*vm-далее кол-во стр загр буф*/
      ppan(0,0);
      form_kod(2);/*чт genko*/
       attr=pal[5];  vdl(a+1,y_,a+36,y_,0,0);    /*сох атр  бывш стр*/
       vctp(0);
      tit();
      if(zap!=0) nstr(2);
      ZA[0]='\0';
      za=strlen(MPR);
      strcat(ZA,MPR);if(za>3) strcat(ZA,"\\");  strcat(ZA,"save.com");
      za=0; if((access(ZA,0)!=-1))  za=1; /*ZA-путь savera*/
      /**************/
      for(;;)
          {
          mou(1);
           ch=get_char(1);
    	if((ch<48)||(ch>57))  /*кроме цифр*/
    	 if((ch!=0xfe)&&(ch>0x20)&&(f_kl==0)) {printf("\7"); ch=0;}
    	mou(2); mus(a); /*ориен мыши*/
    	if((ch==TAB)||(ch==RIGHT)||(ch==LEFT))
    	  tab();/*порядок не менять*/
    	if(ch==15) { ctrl(); tab();}
    	mus(a); mus(101);
    	if(ch==F7)   gl_poisk(0);
    	if(ch==AF7)  gl_poisk(1);
    	if(ch==F1) hlp();
    	if(ch==CTRL) ctrl();
    	if((ch==AF1)&&(Pp==1)) ctrl();
    	if((ch==AF2)&&(Pp==0)) ctrl();
    	if(ch==32) exr(0);
    	if(ch==AF3) exb();
    	if(ch==AF4) exr(1);
    	if(ch==UP)   { cm=0; up(1);}
    	if(ch==DOWN) { cm=0; down(1); }
    	if(ch==PGUP) { cm=0;scroll(0,0);}
    	if(ch==PGDN) { cm=0;scroll(1,0);}
    	if(ch==HOME) { cm=0;scroll(0,4000);}
    	if(ch==END)  { cm=0;scroll(1,4000);}
    	if(ch==F5)   kon(1);
    	if(zap==0) /*ес зп разреш*/
    	{
    	if(ch==INS)  { s=0;
        if((chkm(3)!=0)||(chkm(4)!=0)) {s=1;
     coo(0,0x4E,0xCF,"","Предельная длина файла!",
     "Разрешено только удаление!",""," Выход");}
        if((chkm(1)!=0)||(chkm(2)!=0)) {s=1;
     coo(0,0x4E,0xCF,"","Исчерпана длина буфера!",
     "Сохраните набранную информацию,","после чего можно продолжить.",
     " Выход");}
    	 if(vm==4000)
    {coo(0,0x7f,0x70,"Количество записей в списке достигло 4000.",
    "","В данном случае возможно только удаление",

    Это один знакомый слесарь ЭВМ писал прогу для создания/редактирования/просмотра самопальной древовидной БД, для своих нужд, с тем условием, что работать она должна была чуть ли не на i286, и грузилась не более 2х секунд. Недавно он обратился ко мне с просьбой перенести её под линь, но увидев это я решил что такое жить не должно, поэтому просто писал аналог с нуля, на плюсах, но справедливости ради, замечу что моя прога вышла чуть тормознее:).
    Полный код к сожалению не влез, вот он: http://ideone.com/3sLsa.
    P.S. Авторское форматирование сохранено.

    suc-daniil, 23 Августа 2012

    Комментарии (67)
  7. Java / Говнокод #11640

    +60

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    class Test {
        private int m_field;
    
        int getField() {
            return m_field;
        }
    
        void setField(int field) {
            m_field = field;
        }
    }

    Дискасс.

    bormand, 23 Августа 2012

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

    +58

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    // Дополняем недостающие данные товаров
    foreach($product_data as $p_key => $p_dat) {
      		if(!isset($p_dat['product_id'])) {
      			unset($product_data[$p_key]);
      			$this->remove($p_dat['def_key']);
      			continue;
      		}
    }

    Фееричный комментарий!

    zima, 23 Августа 2012

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

    +56

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    //Получение направления сортировки новостей
    $order_desc = (Input::getVar('desc') == 'down') ? 'down' : 'up';
    
    //Дальнейшее использование 
    $news = NewsManager::getNews($category, $page_id, $order, ($order_desc == 'up') ? 0 : 1);

    кручу верчу...

    Edward, 23 Августа 2012

    Комментарии (7)
  10. Java / Говнокод #11637

    +120

    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
    // See where we currently are in a calendar quarter.
    // In Java, JANUARY == 0.
    // Yes, I could just write (3 - currentMonth % 3),
    // but this is clearer
    switch (currentMonth % 3) {
    case 0: // January, April, July, October
    	monthsToInclude = 3; // include whole last quarter
    	break;
    case 1: // February, May, August, November
    	monthsToInclude = 2; // include first two months of this quarter
    	break;
    default: // March, June, September, December
    	monthsToInclude = 1; // include first month of this quarter
    	break;
    }

    Или всё-таки наплевать на читаемость и заменить короткой версией?

    someone, 23 Августа 2012

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