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

    В номинации:
    За время:
  2. Куча / Говнокод #28000

    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
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    %% Note: set and unset are not thread-safe.
    -spec set(key(), value()) -> ok.
    set(Key, Value) ->
        case ets:lookup(?status_tab, Key) of
            [{_, {set, _OldValue}}] ->
                ets:insert(?status_tab, {Key, {set, Value}});
            [{_, {unset, Pid}}] ->
                MRef = monitor(process, Pid),
                Pid ! {set, Value},
                receive
                    {'DOWN', MRef, _, _, _} -> ok
                end;
            [] ->
                case ets:insert_new(?status_tab, {Key, {set, Value}}) of
                    true  ->
                        ok;
                    false ->
                        set(Key, Value)
                end
        end,
        ok.
    
    -spec unset(key()) -> ok.
    unset(Key) ->
        case ets:lookup(?status_tab, Key) of
            [{_, {set, _OldValue}}] -> ets:delete(?status_tab, Key);
            _                       -> ok
        end,
        ok.
    
    -spec read(key()) -> value().
    read(Key) ->
        case read_or_wait(Key) of
            {set, Value} ->
                Value;
            {wait, MRef} ->
                receive
                    {'DOWN', MRef, _, _, {cvar_set, Value}} ->
                        Value;
                    {'DOWN', MRef, _, _, noproc} ->
                        read(Key)
                end
        end.
    
    -spec read_or_wait(key()) -> {set, value()} | {wait, reference()}.
    read_or_wait(Key) ->
        case ets:lookup(?status_tab, Key) of
            [] ->
                {Pid, MRef} = spawn_monitor(?MODULE, waker_entrypoint, [Key, self()]),
                receive
                    {Pid, proceed} ->
                        {wait, MRef};
                    {'DOWN', MRef, _, _, Reason} ->
                        cvar_retry = Reason,
                        read_or_wait(Key)
                end;
            [{_, {set, Val}}] ->
                {set, Val};
            [{_, {unset, Pid}}] ->
                {wait, monitor(process, Pid)}
        end.
    
    -spec waker_entrypoint(key(), pid()) -> no_return().
    waker_entrypoint(Key, Parent) ->
        case ets_insert_new({Key, {unset, self()}}) of
            false ->
                exit(cvar_retry);
            true ->
                Parent ! {self(), proceed},
                receive
                    {set, Value} ->
                        ets_insert({Key, {set, Value}}),
                        exit({cvar_set, Value})
                end
        end.

    CHayT, 08 Февраля 2022

    Комментарии (23)
  3. Python / Говнокод #27866

    −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
    #!/usr/bin/python
      
      import sys
      
      cache = {}
      
      def count(start, end):
          if start < end:
              if start not in cache:
                  cache[start] = count(start + 1, end) + count(start * 2, end) + count(start ** 2, end)
              return cache[start]
          elif start == end:
              return 1
          else:
              return 0
    
      print(count(int(sys.argv[1]), int(sys.argv[2])))

    Подсчитать количество путей из a в b с помощью прибавления единицы, умножения на 2 и возведения в квадрат

    Чем формально ограничены возможности преобразовать рекурсию в хвостовую? Вот такое ведь не преобразовать?

    vistefan, 11 Декабря 2021

    Комментарии (23)
  4. Java / Говнокод #27664

    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
    import java.util.Arrays;
    import java.util.Optional;
    
    public class AntiVirus{
      
      private int scanIntensity = 0;
      
      //this method is ready for you.
      public void setScanIntensity(int level){
        scanIntensity = level;
      }
      
      //write this method.
      public String scanFile(File file,VirusDB database){
        String[] signature = database.getSignatures(scanIntensity);
        String fileData = file.getData().toLowerCase();
        
         Optional<String> res = Arrays.stream(signature)
             .map(s -> s.toLowerCase())
             .filter(fileData::contains).findAny();
        
         String scan = " is safe";
        
         if(res.isPresent()) {
            System.out.println(res.get());
            System.out.println("scan: " + scan);
            scan = " is not safe";
            System.out.println("scan after: " + scan);
         }
        
        return file.getName() + scan;
      }
    }

    Не понимаю, почему не работает.

    Задача
    https://www.codewars.com/kata/5b13027eedd62c5216000001

    Test Results:
    AVTest
    checkRandomFiles
    Log
    dos
    scan: is safe
    scan after: is not safe
    dos
    scan: is safe
    scan after: is not safe
    dos
    scan: is safe
    scan after: is not safe
    dos
    scan: is safe
    scan after: is not safe
    dos
    scan: is safe
    scan after: is not safe
    dos
    scan: is safe
    scan after: is not safe
    dos
    scan: is safe
    scan after: is not safe
    dos
    scan: is safe
    scan after: is not safe
    dos
    scan: is safe
    scan after: is not safe
    expected:<f4wpzFoQD is [not ]safe> but was:<f4wpzFoQD is []safe>
    Stack Trace
    Completed in 476ms
    checkSameFilesWithDifferentIntensitySett ings
    Log
    virus
    scan: is safe
    scan after: is not safe
    expected:<file1 is [not ]safe> but was:<file1 is []safe>
    Stack Trace
    Completed in 1ms
    Completed in 496ms

    imrnccc, 14 Сентября 2021

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

    +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
    Ltac destruct_mint_ H := 
       match type of H with
          (MInt_ _ ?z ?t) =>
          lazymatch goal with
            |- ?GOAL =>
            refine (match H in (MInt_ _ z0 t0) return (z = z0 -> t = t0 -> GOAL) with
                    | mint_nil    _  =>
                      fun Heq_z Heq_tt_ =>
                        ltac:(destruct_mint_common Heq_tt_ Heq_z H)
                    | mint_cons   _ te rest l      r   t H =>
                      fun Heq_z Heq_tt_ =>
                        ltac:(destruct_mint_common Heq_tt_ Heq_z H)
                    | mint_cons_l _ te rest l r z t Hz H  =>
                      fun Heq_z Heq_tt_ =>
                        ltac:(destruct_mint_common Heq_tt_ Heq_z H)
                    | mint_cons_r _ te te' rest l r z t Hz Hcomm H =>
                      fun Heq_z Heq_tt_ =>
                        ltac:(destruct_mint_common Heq_tt_ Heq_z H)
                    end (eq_refl z) (eq_refl t))
          end
        end.

    Наебавшись с inversion в механизированным доказательстве, закрыл я очи.

    CHayT, 04 Августа 2021

    Комментарии (23)
  6. JavaScript / Говнокод #27505

    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
    class Animal {
        move(distanceInMeters = 0) {
            print(`Animal moved ${distanceInMeters}m.`);
        }
    }
    
    function main() {
        const dog = new Animal();
        dog.move(10);
    
        const dog2 = Animal();
        dog2.move(11);
    }

    Загадка дня... кто знает что первый вызов конструктора отличается от второго?

    ASD_77, 07 Июля 2021

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

    +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
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    template<typename F, typename... CurryArgs>
    struct curry {
        F func;
        std::tuple<CurryArgs...> tup{};
    
        curry(F f) : func(std::move(f)) {}
    
        template<typename... CtorArgs>
        curry(F f, CtorArgs &&... args) : func(std::move(f)), tup(std::forward<CtorArgs>(args)...) {}
    
        template<typename Tup1, typename Tup2>
        curry(F f, Tup1 && tup1, Tup2 && tup2) : func(std::move(f)), tup(std::tuple_cat(tup1, tup2)) {}
    
        template<typename... Args>
        auto operator()(Args &&... args)
        {
            constexpr size_t have_args = sizeof...(Args) + sizeof...(CurryArgs);
            constexpr size_t need_args = detail::functor_traits<F>::args_count;
            if constexpr (have_args > need_args) {
                static_assert(!sizeof(std::tuple_element_t<0, std::tuple<Args...>>*),
                              "Too many arguments.");
            } else if constexpr (have_args == need_args) {
                return std::apply(func, std::tuple_cat(tup, std::tuple(std::forward<Args>(args)...)));
            } else {
                return curry<decltype(func), CurryArgs..., Args...>(func, tup, std::tuple(std::forward<Args>(args)...));
            }
        }
    };
    
    int main()
    {
        auto f = [](int a, float b, const std::string & c) -> int {
            std::cout << "Functor! a = " << a << ", b = " << b << ", c = " << c << std::endl;
            return a + static_cast<int>(b);
        };
    
        std::cout << f(16, 42.1f, "Hello") << std::endl;
    
        auto c0 = curry(f);
        auto c1 = c0(16);
        auto c2 = c1(42.1f);
    
        c0(16)(42.1f)("Hello");
        c1(42.1f)("Hello");
        c2("Hello");
    
        c0(16, 42.1f)("Hello");
        c0(16, 42.1f, "Hello");
    
        c1(42.1f, "Hello");
    }

    Каррировали-каррировали, да выкаррировали.
    https://wandbox.org/permlink/LPXFUNpWOREcB3wH

    PolinaAksenova, 10 Мая 2021

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

    +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
    std::cout << "Creating ptr1!" << std::endl;
    auto ptr1 = make_nft<Cow>();
    std::cout << "ptr1(" << &ptr1 << "): " << ptr1.get() << std::endl;
    ptr1->MakeSound();
    
    std::cout << "Creating ptr2!" << std::endl;
    nft_ptr<Animal> ptr2;
    std::cout << "ptr2(" << &ptr2 << "): " << ptr2.get() << std::endl;
    std::cout << "Moving: ptr2 = std::move(ptr1)" << std::endl;
    ptr2 = std::move(ptr1);
    std::cout << "Moved: ptr1 = " << ptr1.get() << " ptr2 = " << ptr2.get()
              << std::endl;

    https://github.com/zhuowei/nft_ptr

    "C++ std::unique_ptr that represents each object as an NFT on the Ethereum blockchain."

    PolinaAksenova, 13 Апреля 2021

    Комментарии (23)
  9. Java / Говнокод #27306

    +1

    1. 1
    Class HasThisTypePatternTriedToSneakInSomeGenericOrParameterizedTypePatternMatchingStuffAnywhereVisitor

    https://javadoc.io/doc/org.aspectj/aspectjweaver/1.8.10/org/aspectj/weaver/patterns/HasThisTypePatternTriedToSneakInSomeGene ricOrParameterizedTypePatternMatchingStu ffAnywhereVisitor.html

    6oHo6o, 21 Марта 2021

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

    +2

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    /**
         * Change the zoom level to the specified value. Specify 0.0 to reset the
         * zoom level.
         *
         * @param zoomLevel The zoom level to be set.
         */
        public void setZoomLevel(double zoomLevel);

    Когда-то я думал, что zoom 100% это 1.0. И что на zoom нужно умножать. Но оказалось, что я анскильный.

    DypHuu_niBEHb, 24 Сентября 2020

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

    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
    
    function get_post_id($comment_list_id) {
        $rawdata = file_get_contents("https://govnokod.ru/comments/$comment_list_id/post");
        $rawdata='<?xml encoding="UTF-8">'.$rawdata;
    
        $old_libxml_error = libxml_use_internal_errors(true);
        $dom = new DOMDocument;
        $dom->loadHTML($rawdata);
        libxml_use_internal_errors($old_libxml_error);
    
        $xpath = new DOMXPath($dom);
        $entries = $xpath->query('//*[@id="content"]/ol[@class="posts hatom"]/li[@class="hentry"]/h2/a');
    
        foreach($entries as $entry) {
            $href = $entry->getAttribute('href');
            if(preg_match('#https://govnokod.ru/(\d+)#', $href, $matches)) {
                $post_id = $matches[1];
                break;
            }
        }
        return $post_id;
    }
    
    $outf = fopen('postids.csv', 'w');
    fputcsv($outf, array('post_id','comment_list_id'));
    for($i = 1; $i <= 26663; $i++) {
        fputcsv($outf, array(get_post_id($i), $i));
    }
    fclose($outf);

    Получение списка всех говнокодов, комментарии к которым можно восстановить.

    ropuJIJIa, 19 Мая 2020

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