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

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

    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
    #include<iostream>
    #include<fstream>
    #include<vector>
    using namespace std;
    string rec(const string str, char c){return str;} //syntax error : missing ';' before identifier 'rec', ')' before 'const',  ')', ';' before '{', 
                                                                                    //'str' : undeclared identifier, 'rec': identifier not found
    
    void cer(){}                                                            //'cer' : local function definitions are illegal
    
    main(){                                                                  //'main': identifier not found
    
    	string s, d="Math.cos",a;                  //missing '}' before identifier 's',  ';' before identifier 's', 's', 'd', 'a' : undeclared identifier
    	
            ifstream fin;
    	vector<string> mas; // 'std::vector' : 'string' is not a valid template type argument for parameter '_Ty', 'mas' : unknown size
                                                  //'std::vector' : no appropriate default constructor available
    
    fin.open(mDocWrite); //'void std::basic_ifstream<char,std::char_traits<char>>::open(const char *,std::ios_base::open_mode)' : 
                                            //cannot convert argument 1 from 'nsAutoPtr<nsHtml5Tokenizer>' to 'const wchar_t *'
                         //No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
    
    //if (fin.is_open()) cout<<"1";else	cout<<"0";
    while(fin>>s)    //'s' : undeclared identifier, fatal error C1903: unable to recover from previous error(s); stopping compilation
    	{bool f=0;
    		for(int i=0; i<s.size(); ++i)
    			if (s[i]==d[0])
    				{
    					f=1;
    					for (int j=0; j<s.size()&&j<d.size(); ++j)
    						if (d[j]!=s[i+j]) f=0;
    					if (f)
    						{
    							a.clear();
    							for (int j=0; j<i; ++j)
    								a=a+s[j];
    							a=a+"0.5*";
    							for (int j=i; j<s.size(); ++j)
    								a=a+s[j];
    						}
    				}
    						if (f)	{mas.push_back("\n");mas.push_back(a);mas.push_back("\n");}
    			else mas.push_back(s);
    			s=rec(s,'0');
    	}
    	ofstream fout;
    fout.open(mDocWrite);
    for (int i=0; i<mas.size(); ++i) fout<<mas[i]<<"\t";
    }

    предполагалось, что код будет уменьшать cos угла в два раза, но при компиляции выдает ошибки, логику большинства которых не могу понять. Ошибки указал в коде. Подскажите, что не так.

    DrAli, 04 Сентября 2018

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

    +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
    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
    #include <iostream>
    #include <type_traits>
    #include <utility>
    #include <array>
    
    template<size_t Size, typename T, typename FunctorType, size_t... idx>
    constexpr std::array<decltype(std::declval<FunctorType>().operator()(std::declval<T>())), Size>
                  map_impl(const std::array<T, Size> & arr, FunctorType && f, std::index_sequence<idx...>)
    {
        return std::array{ f(std::get<idx>(arr))... };
    }
    
    template<size_t Size, typename T, typename FunctorType>
    constexpr std::array<decltype(std::declval<FunctorType>().operator()(std::declval<T>())), Size>
                  map(const std::array<T, Size> & arr, FunctorType && f)
    {
        return map_impl(arr, f, std::make_index_sequence<Size>{});
    }
    
    struct MyFunctor {
        constexpr float operator()(int arg)
        {
            return static_cast<float>(arg * arg) / 2.0f;
        }
    };
    
    int main()
    {
        constexpr std::array arr{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    
        auto arrMappedFunctor = map(arr, MyFunctor{});
        auto arrMappedLambda = map(arr, [](int x) constexpr { return static_cast<float>(x * x) / 2.0f; });
    
        for (auto && x : arrMappedFunctor) {
            std::cout << x << ' ';
        }
        std::cout << std::endl;
        for (auto && x : arrMappedLambda ) {
            std::cout << x << ' ';
        }
        std::cout << std::endl;
        return 0;
    }

    0.5 2 4.5 8 12.5 18 24.5 32 40.5 50
    0.5 2 4.5 8 12.5 18 24.5 32 40.5 50


    Метушня выходит на новый уровень: полноценный map в compile-time. Поддерживает как ручные функторы с перегруженным operator(), так и constexpr-лямбды. При помощи небольшой модификации возможно реализовать поддержку кортежей с произвольными типами.

    gost, 18 Августа 2018

    Комментарии (28)
  4. Куча / Говнокод #24623

    0

    1. 1
    Ну как вы тут, потомки? Борманд еще живой?

    nihau, 14 Августа 2018

    Комментарии (28)
  5. Куча / Говнокод #24358

    0

    1. 1
    2. 2
    3. 3
    Кококо
    "Microsoft" купил "GitHub" 
    Кококо

    guestinxo, 04 Июня 2018

    Комментарии (28)
  6. Python / Говнокод #24318

    −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
    24. 24
    from random import choice
     
    noun = ['пони', 'анус', 'синхрофазатрон', 'погромист', 'хуй', 'шланг', 'гцц', 'соснолька', 'хуита', 'говно', 'питушня', 'лалка', 'питон', 'енот', 'ватник', 'пидорашка', 'шиндос', 'линупс', 'жопа', 'дед мороз']
    verb = ['срёт', 'падает', 'бесит', 'пиздит', 'летает', 'сосёт', 'бегает']
    adj = ['сраный', 'ёбаный', 'розовый', 'коричневый', 'охуенный', 'пиздатый', 'тупой', 'ебучий', '']
     
    templates = [
        [adj, noun, verb],
        [adj, noun],
        [noun, ['говно']],
        [['У тебя'], adj, noun, verb],
        [['У тебя'], adj, noun],
        [['Какого хуя'], adj, noun, verb, ['\b?']],
        [['Почему'], noun, verb, ['\b?']],
        [['Что такое'], noun, ['\b?']],
        [adj, noun, verb, 'и', verb],
        [noun, verb, ['\b, a'], noun, verb],
    ]
     
    bububu = lambda: (lambda s: s[0].capitalize() + s[1:] + (choice('.!?') if s[-1] not in '.!?' else ''))(' '.join(i for i in map(choice, choice(templates)) if i))
     
     
    for _ in range(30):
        print(bububu())

    https://ideone.com/oOwyzI
    Просто от неча делать...

    666_N33D135, 24 Мая 2018

    Комментарии (28)
  7. C++ / Говнокод #23545

    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
    PrefixAllocator::PrefixAllocator(
        const std::string& myNodeName,
        const KvStoreLocalCmdUrl& kvStoreLocalCmdUrl,
        const KvStoreLocalPubUrl& kvStoreLocalPubUrl,
        const PrefixManagerLocalCmdUrl& prefixManagerLocalCmdUrl,
        const MonitorSubmitUrl& monitorSubmitUrl,
        const AllocPrefixMarker& allocPrefixMarker,
        const folly::Optional<folly::CIDRNetwork> seedPrefix,
        uint32_t allocPrefixLen,
        bool setLoopbackAddress,
        bool overrideGlobalAddress,
        const std::string& loopbackIfaceName,
        std::chrono::milliseconds syncInterval,
        PersistentStoreUrl const& configStoreUrl,
        fbzmq::Context& zmqContext)
        : myNodeName_(myNodeName),
          allocPrefixMarker_(allocPrefixMarker),
          seedPrefix_(seedPrefix),
          allocPrefixLen_(allocPrefixLen),
          setLoopbackAddress_(setLoopbackAddress),
          overrideGlobalAddress_(overrideGlobalAddress),
          loopbackIfaceName_(loopbackIfaceName),
          syncInterval_(syncInterval),
          configStoreClient_(configStoreUrl, zmqContext),
          zmqMonitorClient_(zmqContext, monitorSubmitUrl) {

    Фейсбук выложил какую-то хуйню https://github.com/facebook/openr/blob/master/openr/allocators/PrefixAllocator.cpp#L61

    g0cTb, 16 Ноября 2017

    Комментарии (28)
  8. Си / Говнокод #23426

    +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
    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
    // https://github.com/vk-com/kphp-kdb/blob/ce6dead5b3345f4b38487cc9e45d55ced3dd7139/bayes/bayes-data.c#L1966
    
    int init_all (kfs_file_handle_t Index) {
      int i;
    
      log_ts_exact_interval = 1;
    
      ltbl_init (&user_table);
    
      bl_head = qmalloc (sizeof (black_list));
      black_list_init (bl_head);
    
      int f = load_header (Index);
    
      jump_log_ts = header.log_timestamp;
      jump_log_pos = header.log_pos1;
      jump_log_crc32 = header.log_pos1_crc32;
    
      int user_cnt = index_users = header.user_cnt;
    
      if (user_cnt < 1000000) {
        user_cnt = 1000000;
      }
    
      assert (user_cnt >= 1000000);
      user_cnt *= 1.1;
    
      while (user_cnt % 2 == 0 || user_cnt % 5 == 0) {
        user_cnt++;
      }
    
      ltbl_set_size (&user_table, user_cnt);
      users = qmalloc (sizeof (user) * user_cnt);
    
      for (i = 0; i < user_cnt; i++) {
        user_init (&users[i]);
      }
    
      LRU_head = users;
      LRU_head->next_used = LRU_head->prev_used = LRU_head;
    
      if (f) {
        try_init_local_uid();
      }
    
      if (index_mode) {
        buff = qmalloc (max_words * sizeof (entry_t));
        new_buff = qmalloc (4000000 * sizeof (entry_t));
      }
    
      return f;
    }

    http://govnokod.ru/23357#comment390273
    > Говорят что в ВК в начале была такая херь: "уже зарегистрировано N" и это N увеличивалось джаваскриптом со случайной скоростью вообще без связи с сервером

    Если я правильно понял, вконтакт продолжает пиздеть по поводу фактического количества зареганых на нем пользовалелей, но теперь делает это на бэкенде

    user_cnt *= 1.1;

    cunt

    j123123, 17 Октября 2017

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

    −93

    1. 1
    2. 2
    3. 3
    4. 4
    Функция ПеревестиДеньги(СчетИсточник, СчетПолучатель, Сумма)
            СнятьСоСчета(СчетИсточник, Сумма);
            ПополнитьСчет(СчетПолучатель, Сумма);
    КонецФункции

    Как написать эту функцию безопасно? Что делать, если ПополнитьСчет упадет с исключением, например?

    LispGovno, 03 Августа 2016

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

    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
    /**
         * Sets the user in the token.
         *
         * The user can be a UserInterface instance, or an object implementing
         * a __toString method or the username as a regular string.
         *
         * @param string|object $user The user
         *
         * @throws \InvalidArgumentException
         */
        public function setUser($user)
        {
            if (!($user instanceof UserInterface || (is_object($user) && method_exists($user, '__toString')) || is_string($user))) {
                throw new \InvalidArgumentException('$user must be an instanceof UserInterface, an object implementing a __toString method, or a primitive string.');
            }
            if (null === $this->user) {
                $changed = false;
            } elseif ($this->user instanceof UserInterface) {
                if (!$user instanceof UserInterface) {
                    $changed = true;
                } else {
                    $changed = $this->hasUserChanged($user);
                }
            } elseif ($user instanceof UserInterface) {
                $changed = true;
            } else {
                $changed = (string) $this->user !== (string) $user;
            }
            if ($changed) {
                $this->setAuthenticated(false);
            }
            $this->user = $user;
        }

    https://github.com/symfony/security-core/blob/master/Authentication/Token/AbstractToken.php#L93

    craaazy19, 26 Июля 2016

    Комментарии (28)
  11. Куча / Говнокод #19746

    +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
    16. 16
    17. 17
    18. 18
    type asynchronizer struct {
    	payload interface{}
    }
    
    func (as *asynchronizer) MarshalJSON() ([]byte, error) {
    	insert := []byte("\"async\":true,")
    	if as.payload == nil {
    		as.payload = struct{}{}
    	}
    	raw, err := json.Marshal(as.payload)
    	if err != nil {
    		return raw, err
    	}
    	if raw[1] == '}' {
    		insert = insert[:len(insert)-2]
    	}
    	return append(append(raw[0:1], insert...), raw[1:]...), nil
    }

    Чем дальше в лес, тем больше Го напоминает ПХП.

    wvxvw, 03 Апреля 2016

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