1. C++ / Говнокод #19967

    0

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    #include <iostream>
    #include <string>
    #include <fstream>
    #include <locale>
    #include <windows.h>
    #include <conio.h>
    #include <cstdlib>
    
    using namespace std;
    
    struct Book
    {
    string author;
    string name;
    string year;
    };
    
    struct toolstruct
    {
    string filename;
    ifstream file_for_read;
    ofstream file_for_write;
    unsigned int struct_cnt = 0;
    HANDLE stdouthandle = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;
    Book * shelfptr;
    };
    
    enum SSORT_TYPE
    {
    SSORT_INC = 1,
    SSORT_DEC = -1
    };
    
    void Display(toolstruct*);
    void Edit(toolstruct*);
    void Sort(toolstruct*, SSORT_TYPE);
    void Write(toolstruct*);
    
    int main()
    {
    
    setlocale(LC_ALL, "Russian");
    
    toolstruct ftool;
    char buff;
    unsigned int i = 0;
    
    do
    {
    cout<<"Введите имя каталога:"<<endl;
    getline(cin, ftool.filename);
    ftool.file_for_read.open(ftool.filename.c_str(), ios_base::in);
    }while(!ftool.file_for_read.is_open());
    
    
    while(!ftool.file_for_read.eof() && ftool.struct_cnt<20)
       {
       ftool.file_for_read>>buff;
       if(buff=='~'){ftool.struct_cnt++;}
       };
    ftool.shelfptr = new Book[ftool.struct_cnt];
    ftool.file_for_read.clear();
    ftool.file_for_read.seekg(0);
    ftool.shelfptr = new Book[ftool.struct_cnt];
    do
       {
       ftool.file_for_read>>buff;
       if(buff=='~')
          {
          getline(ftool.file_for_read, ftool.shelfptr[i].author);
          getline(ftool.file_for_read, ftool.shelfptr[i].name);
          getline(ftool.file_for_read, ftool.shelfptr[i].year);
          i++;
          }
       }while(!ftool.file_for_read.eof());
    ftool.file_for_read.close();
    Display(&ftool);
    }
    
    void Display(toolstruct* ts)
    {
    //void (*callback_ptr)(toolstruct*) = Display;
    system("cls");
    cout<<"Содержимое файла "<<ts->filename<<":"<<endl
        <<"   Автор            "<<"Название            "<<"Год публикации"<<endl;
    if(ts->struct_cnt != 0)
    {
    for(unsigned short j = 0; j<ts->struct_cnt; j++)
    {
    ts->pos.X = 0;
    ts->pos.Y = j+2;
    SetConsoleCursorPosition(ts->stdouthandle, ts->pos);
    cout<<j+1<<". ";
    if(ts->shelfptr[j].author.length()<=20)
        {cout<<ts->shelfptr[j].author;}
    else{cout<<ts->shelfptr[j].author.substr(0,16)+"...";}
    ts->pos.X = 20;
    SetConsoleCursorPosition(ts->stdouthandle, ts->pos);
    if(ts->shelfptr[j].name.length()<=20)

    Взято из паблика втентакле, где собираются студни со своими неординарными решениями лабораторных. Задача была реализовать чтение-запись структур в файл/из файла, а также сортировку по убыванию/возрастанию одного из полей.

    Fluttie, 10 Мая 2016

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

    +7

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    private function checkPlaces(){
        $popups = array();
        foreach($this->popups as $popup){
            if($popup->showOnThisPage()){
                $popups[] = $popup;
            }
        }
        $this->popups = $popups;
    }
    
    private function checkExcludes(){
        $popups = array();
        foreach($this->popups as $popup){
            if(!$popup->excludeOnThisPage()){
                $popups[] = $popup;
            }
        }
        $this->popups = $popups;
    }
    
    private function checkPage(){
        $popups = array();
        foreach($this->popups as $popup){
            if($popup->checkPageCount($this->user_info['popup_page'])){
                $popups[] = $popup;
            }
        }
        $this->popups = $popups;
    }
    private function checkReferer(){
        $popups = array();
        foreach($this->popups as $popup){
            if($popup->checkReferer()){
                $popups[] = $popup;
            }
        }
        $this->popups = $popups;
    }
    private function checkGETParams(){
        $popups = array();
        foreach($this->popups as $popup){
            if($popup->checkGETParams()){
                $popups[] = $popup;
            }
        }
        $this->popups = $popups;
    }
    private function checkVisitCount(){
        $popups = array();
        foreach($this->popups as $popup){
            if($popup->checkVisitCount($this->user_info['visit_count'])){
                $popups[] = $popup;
            }
        }
        $this->popups = $popups;
    }
    private function checkFirstVisitDate(){
        $popups = array();
        foreach($this->popups as $popup){
            if($popup->checkFirstVisitDate()){
                $popups[] = $popup;
            }
        }
        $this->popups = $popups;
    }
    private function checkLastVisitDate(){
        $popups = array();
        foreach($this->popups as $popup){
            if($popup->checkLastVisitDate()){
                $popups[] = $popup;
            }
        }
        $this->popups = $popups;
    }
    private function checkCustom(){
        $popups = array();
        foreach($this->popups as $popup){
            if($popup->checkCustom()){
                $popups[] = $popup;
            }
        }
        $this->popups = $popups;
    }
    private function checkDate(){
        $popups = array();
        foreach($this->popups as $popup){
            if($popup->checkDate()){
                $popups[] = $popup;
            }
        }
        $this->popups = $popups;
    }
    private function checkDevice(){
        $popups = array();
        foreach($this->popups as $popup){
            if($popup->checkDevice()){
                $popups[] = $popup;
            }
        }
        $this->popups = $popups;

    Скилл Ctrl+C - Ctrl+V прокачан до 80го уровня.

    strax, 09 Мая 2016

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

    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
    struct Base // ñòðóêòóðà äàííûõ 
    
    {
    	char tiker[50];
    	char per[50];
    	//int dateymd;
    	float openPrice;
    	float maxPrice;
    	float minPrice;
    	float closePrice;
    	float volume;
    	float war;
    	float Doch;
    	float Risk;
    
    	//	
    };
    
    
    struct Analys
    
    {
    	char tiker[35];
    	float OgDoh;
    	float Risk;
    	float kov;
    
    	
    
    };for ( int i= 0; i<k; i++)
    	{ if ( vec[i].OgDoh <0)
    	{ vec[i].OgDoh = 0;
    	for (int j=0;j<kol;j++)
    	{VecBase[i+j].Doch = 1000;}
    	}
    	};
    	vec.erase(remove_if(vec.begin(), vec.end(), remover(0) ),
    	vec.end());
    	VecBase.erase(remove_if(VecBase.begin(), VecBase.end(), Remover(1000) ),
    	VecBase.end());
    	vec.shrink_to_fit();
    	VecBase.shrink_to_fit();

    Я подвисла на создании Remover-а

    vec строится на основе VecBase и оба вектора используются в дальнейшем
    да-да, эта штуковина должна удалить все, что связано с vec[i].OgDoh <0

    Ragnareka, 09 Мая 2016

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

    −1

    1. 1
    2. 2
    3. 3
    ID_tables_vec[arg1.get_extra_value()]
         [ID_tables_vec[arg1.get_extra_value()][arg1.get_value()].get_value()]
         .set_name(tmp_str);

    Это один оператор. Из кода интерпретатора модельного языка (задание в универе). Периодически в коде начали возникать подобные вещи, связанные с особенностями таблиц имен. Буду рад, если кто-то предложит эквивалентные, но более читаемые конструкции.

    DrCodeMonkey, 07 Мая 2016

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

    −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
    41. 41
    42. 42
    <? require 'config/bd.php'; ?>
    <?
    if($_POST["title"]){
    $id = intval($_POST["id"]);
    $title = intval($_POST["title"]);
    $num = mysql_num_rows(mysql_query("SELECT id FROM banner WHERE id = '".$id."'"));
    if($num>0){
    mysql_query("UPDATE banner SET url = '$url', img = '$img', title = '$title', day = '$day', active = '".$_POST["active"]."', active_to = '$active_to' WHERE id = '".$id."'");
    ?>
    <div class="color='red'">Баннер отредактирован</div>
    <?
    }
    }
    if($_POST["id"]){
    $id = intval($_POST["id"]);
    $title = intval($_POST["title"]);
    $num = mysql_num_rows(mysql_query("SELECT id FROM banner WHERE id = '".$id."'"));
    if($num>0){
    $row = mysql_fetch_array(mysql_query("SELECT * FROM banner WHERE id = '".$id."'"));
    ?>
    <form method="post" action="">
    <strong>ID:</strong> <?=$row['id'];?><br>
    <strong>Ссылка перехода:</strong> <?=$row['url'];?><br>
    <strong>Ссылка на баннер:</strong> <?=$row['img'];?><br>
    <strong>Заголовок:</strong> <?=$row['title'];?><br>
    <strong>Дней:</strong> <input type="text" size="5" name="id" value="<?=$row['day'];?>">
    <strong>Активен?:</strong><select name="active"><option value="1" <? if($row["active"]==1){?>selected="selected"<? }?>>Да</option><option value="0" <? if($row["active"]==0){?>selected="selected"<? }?>>Нет</option></select><br>
    <strong>Активен до:</strong> <input type="text" size="10" name="id" value="<?=$row['active_to'];?>">
    <input type="hidden" name="id" value="<?=$row['id'];?>">
    <input type="submit" value="Сохранить">
    </form>
    <?
    }else{
    ?>
    Баннер не найден
    <?
    }
    }?>
    <form method="post" action="">
    Введите ID баннера: <input type="text" name="id">
    <input type="submit" value="Поиск">
    </form>

    Что здесь не так? Первую часть поиск по ID проходит! Дале выскакивает форма редактирования, ввел данные нажимаю Сохранить но ничего не происходит! Просто игнор! Исправьте пж!

    Andriu, 07 Мая 2016

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

    +2

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    DWORD GetDriveSpaceMB(char* drive)
    {
        DWORD nsc, nbs, nfc, ncu;
        double FreeB;
        DWORD FreeM;
        string diskname = format_x("%s:\\",drive);
        GetDiskFreeSpace((char*)diskname.c_str(), &nsc, &nbs, &nfc, &ncu );
        FreeB = (double) nfc * (double) nsc * (double) nbs;
        FreeM = FreeB / 1024.0 / 1024;
        return FreeM;
    }

    lomer, 07 Мая 2016

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

    +1

    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
    // новый тестовый экшн в контроллере
            public function actionNew($alias)
        {
            $model=Partners::model()->model()->findByAttributes(array('alias'=>$alias));
                   
                    if($model==null)
                throw new CHttpException(404,'The requested page does not exist.');
                           
                    $this->render('view',array(
                'model'=>$this->loadModel($model->id),
            ));
           
        }
     
    // правило в конфиге
    // '<module:\w+>/<controller:\w+>/<alias:\w+>' => '<module>/<controller>/new',

    https://vk.com/echo_php?w=wall-175_189930%2Fall

    Уи1

    Keeper, 07 Мая 2016

    Комментарии (1)
  8. Куча / Говнокод #19949

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    <ol ng-init="citationsLimit = 3" ng-model="citationsLimit">
    	<li class="citation citationList" ng-repeat="citation in answerFact.citations | limitTo: citationsLimit as citationsResult">
    		<i class="fa ic-marker fa-circle" aria-hidden="true"></i>
    		<div class="citation-text">
    			<span ng-bind-html="citation.highlightedSentenceString"></span>
    			<span ng-if="citation.source">
    				(<a  href="{{citation.source}}" target="_blank">{{citation.source}}</a>)
    			</span>
    		</div>
    	</li>
    </ol>

    ifmy, 06 Мая 2016

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

    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
    <?php
    namespace DoctrineExtensions;
    use \Doctrine\ORM\Event\LoadClassMetadataEventArgs;
    /**
     * Расширение для Doctrine ORM
     * Позволяет отслеживать и работать не со всей базой, а только с таблицами с префиксом
     * Необходимо для уживания с битриксом
     *
     * Class TablePrefix
     * @package DoctrineExtensions
     */
    class TablePrefix
    {
        protected $prefix = '';
        public function __construct($prefix)
        {
            $this->prefix = (string) $prefix;
        }
        public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
        {
            $classMetadata = $eventArgs->getClassMetadata();
            $classMetadata->setTableName($this->prefix . $classMetadata->getTableName());
            foreach ($classMetadata->getAssociationMappings() as $fieldName => $mapping) {
                if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadataInfo::MANY_TO_MANY) {
                    $mappedTableName = $classMetadata->associationMappings[$fieldName]['joinTable']['name'];
                    $classMetadata->associationMappings[$fieldName]['joinTable']['name'] = $this->prefix . $mappedTableName;
                }
            }
        }
    }

    Адепты битрикса добрались до Doctrine ORM. И вот что из этого получилось.
    Заставь дурака ORM подключать, он и events задрочит.

    Keeper, 06 Мая 2016

    Комментарии (1)
  10. JavaScript / Говнокод #19946

    −2

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    this.params.IsCellEditable = function(rowNumber, cellNumber) {
    	cellNumber == 1;
    	this.params.ButtonList = this.params.ButtonList.filter(b=>b[0] === "OnRefresh");
    
    	let textContr = new CTextArea('textContr');
    	textContr.SourceName = "value";
    	textContr.ViewName = "Params";
    	textContr.ComEdit = true;
    	this.params.arrEditObj[1] = textContr;
    
    }

    Найдено в нашем проекте в старом модуле, в авторстве никто не признаётся.
    Во-первых, строка 2 бессмысленна. Во-вторых, всё последующее имело бы хоть какой-то смысл _вне_ этой функции, а внутри уже на строке 3 выкидывает ошибку, потому что контекст там и есть this.param из первой строчки. В-третьих, строка 3 призвана выкидывать из тулбара виджета this.param все кнопки, кроме OnRefresh, но на самом деле она там только одна и есть. В-четвёртых, строчки 7 и 8 просто лишние (ну, это из логики используемого в проекте движка следует). В-пятых, из названия метода можно предположить (и это действительно так), что он должен бы возвращать булевское значение, но он всегда возвращает только undefined и, таким образом, все ячейки виджета оказываются нередактируемыми — что совсем лишает смысла создание контрола для редактирования в строках 5—9.
    Редкостная бредятина. Кто-то в полном затмении писал, и даже десяти секунд не потратил на тестирование.

    torbasow, 06 Мая 2016

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