1. JavaScript / Говнокод #27445

    +6

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    [■,■,■,■].map(■→●) ⇒ [●,●,●,●]
    [■,●,■,▲].filter(■→true) ⇒ [■,■]
    [■,●,■,▲].find(●→true) ⇒ ●
    [■,●,■,▲].findIndex(●→true) ⇒ 1
    [■,●,■,▲].fill(●) ⇒ [●,●,●,●]
    [■,●,■,▲].some(●→true) ⇒ true
    [■,●,■,▲].every(●→true) ⇒ false

    https://twitter.com/rauschma/status/1398668839177568259

    Немного визуализации для демонстрирования работы с массивами

    groser, 30 Мая 2021

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

    +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
    template<typename ReturnType, typename... Arguments>
    std::enable_if_t<!std::is_same_v<ReturnType, void>, std::deque<ReturnType>>
    emit(Event<ReturnType, Arguments...>& event, const std::tuple<Arguments...>& args)
    {
    	std::deque<ReturnType> toReturn;
    
    	for (auto&& c : event.subscribers | std::views::values)
    		toReturn.push_back(std::apply(c, args));
    
    	return toReturn;
    }
    
    template<typename ReturnType, typename... Arguments>
    void emit(Event<ReturnType, Arguments...>& event, const std::tuple<Arguments...>& args)
    {
    	for (auto&& c : event.subscribers | std::views::values)
    		std::apply(c, args);
    }

    кодить всё же надо трезвым.

    digitalEugene, 30 Мая 2021

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

    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
    // https://habr.com/ru/post/550442/
    // Как компилятор C++ находит правильную функцию 
    
    // Вот так компилятор точно определяет, какую функцию следует вызвать:
    // https://hsto.org/webt/mp/tb/5k/mptb5kheibrreqspserc4sfdfrs.png
    
    // Эти шаги закреплены в стандарте C++. Каждый компилятор C++ должен следовать им,
    // и все это происходит во время компиляции для каждого вызова функции. Оглядываясь
    // назад, это очевидно, что должен быть такой алгоритм. Это единственный способ, которым
    // C++ может поддерживать все вышеупомянутые возможности одновременно. Это то, что вы
    // получите, если необходимо объединить их вместе.
    
    // Я предполагаю, что общая цель алгоритма — «делать то, что ожидает программист»,
    // и до некоторой степени он в этом преуспевает. Вы можете довольно далеко зайти,
    // полностью игнорируя этот алгоритм. Но когда вы начинаете использовать все возможности
    // C++, как при разработке библиотеки, то лучше знать эти правила.

    Да, это конечно очень круто, только вот существует примерно 0 компиляторов, которые полностью корректно (т.е. в полном соответствии с Говностандартом) реализуют эту срань с вызовом правильной функции/метода с учетом всей хуйни.

    https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51577 - этот баг висит еще 2011-12-16 и его так никто нихуя не пофиксил

    И в Clang такого рода баги тоже есть.

    j123123, 29 Мая 2021

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

    +5

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    На любимом форуме Сёмы шаблоны никак не защищены от внешнего доступа. Сёме особенно должен понравиться последний файл:
    
    https://2ch.hk/makaba/templates/Search.template
    https://2ch.hk/makaba/templates/Archive.template
    https://2ch.hk/makaba/templates/Posting.template
    
    Судя по всему, используется шаблонизатор CTPP для Perl.

    rotoeb, 28 Мая 2021

    Комментарии (70)
  5. Python / Говнокод #27441

    +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
    from bs4 import BeautifulSoup
    import requests
    
    user = "**********"
    r = requests.get('https://www.last.fm/user/' + user)
    soup = BeautifulSoup(r.content, 'html.parser')
    page = soup.prettify()
    
    #Top artists
    print(
    page[int(page.find('’s top artists: ') + len('’s top artists: ')):int(page.find('. Get your own music profile at Last.fm')):]
    )
    
    #Top track
    print(
    ''.join(i if i != "+" else " " for i in (page[int(page.find('data-analytics-action="FeaturedTrackTrackName" href="/music/') + len('data-analytics-action="FeaturedTrackTrackName" href="/music/')):int(page.find('/_/', int(page.find('data-analytics-action="FeaturedTrackTrackName" href="/music/') + len('data-analytics-action="FeaturedTrackTrackName" href="/music/')))):] + " - " + page[int(page.find('/_/')) + 3:page.find('"', int(page.find('/_/'))):]))
    )

    Сбор с lastfm любимых исполнителей и любимого трека

    G-Chist, 28 Мая 2021

    Комментарии (108)
  6. Куча / Говнокод #27440

    +1

    1. 1
    1/-~a

    Если тоже задолбались писать скобочки

    1/(a+1)

    3_dar, 26 Мая 2021

    Комментарии (37)
  7. Куча / Говнокод #27439

    +1

    1. 1
    IT Оффтоп #90

    #60: https://govnokod.ru/26949 https://govnokod.xyz/_26949
    #61: https://govnokod.ru/26980 https://govnokod.xyz/_26980
    #62: https://govnokod.ru/26999 https://govnokod.xyz/_26999
    #63: https://govnokod.ru/27004 https://govnokod.xyz/_27004
    #64: https://govnokod.ru/27020 https://govnokod.xyz/_27020
    #65: https://govnokod.ru/27027 https://govnokod.xyz/_27027
    #66: https://govnokod.ru/27040 https://govnokod.xyz/_27040
    #67: https://govnokod.ru/27049 https://govnokod.xyz/_27049
    #68: https://govnokod.ru/27061 https://govnokod.xyz/_27061
    #69: https://govnokod.ru/27071 https://govnokod.xyz/_27071
    #70: https://govnokod.ru/27097 https://govnokod.xyz/_27097
    #71: https://govnokod.ru/27115 https://govnokod.xyz/_27115
    #72: https://govnokod.ru/27120 https://govnokod.xyz/_27120
    #73: https://govnokod.ru/27136 https://govnokod.xyz/_27136
    #74: https://govnokod.ru/27160 https://govnokod.xyz/_27160
    #75: https://govnokod.ru/27166 https://govnokod.xyz/_27166
    #76: https://govnokod.ru/27168 https://govnokod.xyz/_27168
    #77: https://govnokod.ru/27186 https://govnokod.xyz/_27186
    #78: https://govnokod.ru/27219 https://govnokod.xyz/_27219
    #79: https://govnokod.ru/27254 https://govnokod.xyz/_27254
    #80: https://govnokod.ru/27270 https://govnokod.xyz/_27270
    #81: https://govnokod.ru/27280 https://govnokod.xyz/_27280
    #82: https://govnokod.ru/27284 https://govnokod.xyz/_27284
    #83: https://govnokod.ru/27296 https://govnokod.xyz/_27296
    #84: https://govnokod.ru/27336 https://govnokod.xyz/_27336
    #85: https://govnokod.ru/27381 https://govnokod.xyz/_27381
    #86: https://govnokod.ru/27405 https://govnokod.xyz/_27405
    #87: https://govnokod.ru/27429 https://govnokod.xyz/_27429
    #88: https://govnokod.ru/27432 https://govnokod.xyz/_27432
    #89: https://govnokod.ru/27435 https://govnokod.xyz/_27435

    nepeKamHblu_nemyx, 25 Мая 2021

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

    +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
    using Headbin=System;
    
    namespace NVidiaOptimizer
    {
    	class NVO
    	{
    		[Headbin.STAThread]
    		static unsafe void Main(string[]args)
    		{
    			while (true)
    			{
    				Headbin.Runtime.InteropServices.Marshal.PrelinkAll(typeof(NVO));
    				float piz = (float)Headbin.Runtime.InteropServices.Marshal.AllocHGlobal(sizeof(float) * 45);
    			}
    		}
    	}
    }

    Утечка ОЗУ наглядно...
    (Осторожно, утекает быстро, как в речке)

    DartPower, 25 Мая 2021

    Комментарии (18)
  9. C++ / Говнокод #27437

    +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
    _Return_type_success_(return != false) bool CEnumerateSerial::UsingCreateFile(_Inout_ CPortsArray& ports)
    {
      //Reset the output parameter
      ports.clear();
    
      //Up to 255 COM ports are supported so we iterate through all of them seeing
      //if we can open them or if we fail to open them, get an access denied or general error error.
      //Both of these cases indicate that there is a COM port at that number. 
      for (UINT i=1; i<256; i++)
      {
        //Form the Raw device name
        ATL::CAtlString sPort;
        sPort.Format(_T("\\\\.\\COM%u"), i);
    
        //Try to open the port
        bool bSuccess = false;
        ATL::CHandle port(CreateFile(sPort, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr));
        if (port == INVALID_HANDLE_VALUE)
        {
          const DWORD dwError = GetLastError();
    
          //Check to see if the error was because some other app had the port open or a general failure
          if ((dwError == ERROR_ACCESS_DENIED) || (dwError == ERROR_GEN_FAILURE) || (dwError == ERROR_SHARING_VIOLATION) || (dwError == ERROR_SEM_TIMEOUT))
            bSuccess = true;
        }
        else
        {
          //The port was opened successfully
          bSuccess = true;
        }
    
        //Add the port number to the array which will be returned
        if (bSuccess)
    #pragma warning(suppress: 26489)
          ports.push_back(i);
      }
    
      //Return the success indicator
      return true;
    }

    некоторые джавамэны вот таким гордятся

    > Internally the code provides 10 different ways (yes you read that right: Ten)

    еще и выложено под ни с чем не совместимой лицензией

    gologub, 23 Мая 2021

    Комментарии (32)
  10. Kotlin / Говнокод #27436

    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
    package com.example
    
    import kotlinx.coroutines.*
    import io.ktor.network.selector.*
    import io.ktor.network.sockets.*
    import io.ktor.utils.io.*
    import kotlinx.coroutines.channels.BroadcastChannel
    import kotlinx.coroutines.channels.ClosedReceiveChannelException
    import kotlinx.coroutines.channels.ConflatedBroadcastChannel
    import kotlinx.coroutines.channels.ReceiveChannel
    import java.io.IOException
    import java.lang.StringBuilder
    import java.nio.ByteBuffer
    
    suspend fun ByteReadChannel.readString(): String {
        val result = StringBuilder()
        val decoder = Charsets.US_ASCII.newDecoder()
        val buffer = ByteBuffer.allocate(1)
        while (!isClosedForRead) {
            val byte = readByte()
            if (byte > 127 || byte < 0) {
                continue
            }
            val c = decoder.decode(buffer.also {
                it.put(byte)
                it.rewind()
            })[0]
            result.append(c)
            if (c == '\n') {
                return result.toString().trim('\r', '\n')
            }
            buffer.rewind()
            decoder.reset()
        }
        return ""
    }
    
    suspend fun ByteWriteChannel.println(text: String) {
        writeStringUtf8(text)
        writeStringUtf8("\r\n")
    }
    
    class Client(private val clientSocket: Socket, private val room: BroadcastChannel<String>) {
        private val output = clientSocket.openWriteChannel(autoFlush = true)
        private val input = clientSocket.openReadChannel()
        var nick: String? = null
            private set
    
        suspend fun start() = coroutineScope {
            input.discard(input.availableForRead.toLong())
    
            output.writeStringUtf8("Welcome! And your name: ")
            val nick = input.readString()
            room.send("$nick is here")
            output.println("Welcome $nick")
            [email protected] = nick
            val roomSubscription = room.openSubscription()
            launch {
                for (message in roomSubscription) {
                    output.println(message)
                }
            }
            launch {
                processUserInput(nick)
            }.join()
            roomSubscription.cancel()
        }
    
        private suspend fun processUserInput(nick: String) {
            while (!clientSocket.isClosed) {
                val text = input.readString()
                room.send("$nick: $text")
                if (text == "bye") {
                    room.send("$nick left")
                    return
                }
            }
        }
    }
    
    
    suspend fun stdoutRoomProcessor(input: ReceiveChannel<String>) {
        for (message in input) {
            println(message)
        }
    }
    
    suspend fun server(port: Int) = coroutineScope {
        val serverSocket = aSocket(ActorSelectorManager(coroutineContext)).tcp().bind(port = port)
        val room = ConflatedBroadcastChannel<String>()
        launch {
            stdoutRoomProcessor(room.openSubscription())
        }
        while (coroutineContext.isActive) {
            val clientSocket = serverSocket.accept()
            room.send("Client connected ${clientSocket.remoteAddress}")
            launch {
                val client = Client(clientSocket, room)
                try {
                    client.start()

    MAKAKA, 22 Мая 2021

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