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

    0

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    // Since C++20
    
    struct A {
      int&& r;
    };
    A a1{7}; // OK, lifetime is extended
    A a2(7); // well-formed, but dangling reference

    Удачной отладки!

    PolinaAksenova, 06 Мая 2021

    Комментарии (57)
  2. Си / Говнокод #27393

    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
    //glsl vertex shader
    attribute float mass;
    uniform vec3 center;
    
    #define RAD 10.0
    const float D = RAD * 2.0;
    
    ///////////////////THIS///////////////////
    float repeat(float x, float z) {
      float dx = distance(x, z);
      while(dx > RAD) {
        if (x > z) {
          x -= D;
        } else {
          x += D;
        }
        dx = distance(x, z);
      }
      return x;
    }
    ///////////////////////////////////////////
    
    vec3 repeat(vec3 x, vec3 y) {
      return vec3(dr(x.x, y.x), dr(x.y, y.y), dr(x.z, y.z));
    }
    
    void main() {
      vec3 pos = position;
      pos.z += time;
      pos = repeat(pos, center);
      
      vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
      gl_PointSize = 70.0 * mass;
      gl_Position = projectionMatrix * mvPosition;
    }

    По сути функция repeat должна повторять текстуру (как background-repeat: repeat в css) в зависимости от положения точки центра, короче: двигается центр, двигается и текстура за ним. Мне даже ума не хватает описать это, поэтому формулу сам искал, хватило ума только на это говно. Спустя несколько недель додумался до следующего говна, уже без цикла:
    float repeat(float x, float z) {
    float mp = x > z ? -1.0 : 1.0;
    z += RAD * mp;
    float dx = distance(x, z);
    float n = floor(dx / D) * D;
    x += n*mp;
    return x;
    }
    Тяжело не знать математики. Может местные шизы подскажут как называется такое поведение и как нормальную формулу?

    sobakapavlova, 06 Мая 2021

    Комментарии (15)
  3. JavaScript / Говнокод #27392

    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
    function test3()
    {
    		const a = 10.5
    	        switch (a) 
    		{                                            
    		    case 10.5:
            	        print("cool. 10.5");                          
    			break;                                          
    	        }
    }
    
    function test3()
    {		
    	        switch ("kokoko") 
    		{                                            
    		    case "kokoko":
            	        print("pituh");                          
    			break;                                          
    	        }
    }

    Продолжаем говнокомпилить...

    А ваш С такое прокомпилирует? мой - запросто :)

    ASD_77, 05 Мая 2021

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

    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
    template<typename T>
    class SharedPtr {
        T* value;
        int* ref_count;
    
    public:
        SharedPtr(T* value) : value(value) {
            ref_count = new int;
            *ref_count = 1;
        }
    
        SharedPtr(const SharedPtr& other) {
            value = other.value;
            ref_count = other.ref_count;
            (*ref_count)++;
        }
    
        SharedPtr(SharedPtr&& other) {
            value = other.value;
            ref_count = other.ref_count;
            other.ref_count = nullptr;
        }
    
        ~SharedPtr() {
            if (ref_count == nullptr) {
                return;
            }
    
            if (*ref_count == 1) {
                delete value;
                delete ref_count;
            } else {
                (*ref_count)--;
            }
        }
    
        T& operator *() const {
            return *value;
        }
    
        T* operator ->() const {
            return value;
        }
    };

    Реалейзовал минимальную версию shared_ptr. Есть ошибки/замечания?

    https://ideone.com/g7gqBM

    3_dar, 04 Мая 2021

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

    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
    class MediaWiki {
    // Поля, другие методы
    
    private function performRequest() {
    		global $wgTitle;
    
    		$request = $this->context->getRequest();
    		$requestTitle = $title = $this->context->getTitle();
    		$output = $this->context->getOutput();
    		$user = $this->context->getUser();
    
    		if ( $request->getVal( 'printable' ) === 'yes' ) {
    			$output->setPrintable();
    		}
    
    		$this->getHookRunner()->onBeforeInitialize( $title, null, $output, $user, $request, $this );
    
    		// Invalid titles. T23776: The interwikis must redirect even if the page name is empty.
    		if ( $title === null || ( $title->getDBkey() == '' && !$title->isExternal() )
    			|| $title->isSpecial( 'Badtitle' )
    		) {
    			$this->context->setTitle( SpecialPage::getTitleFor( 'Badtitle' ) );
    			try {
    				$this->parseTitle();
    			} catch ( MalformedTitleException $ex ) {
    				throw new BadTitleError( $ex );
    			}
    			throw new BadTitleError();
    		}
    
                    // Check user's permissions to read this page.
    		// We have to check here to catch special pages etc.
    		// We will check again in Article::view().
    		$permissionStatus = PermissionStatus::newEmpty();
    		if ( !$this->context->getAuthority()->authorizeRead( 'read', $title, $permissionStatus ) ) {
    			// T34276: allowing the skin to generate output with $wgTitle or
    			// $this->context->title set to the input title would allow anonymous users to
    			// determine whether a page exists, potentially leaking private data. In fact, the
    			// curid and oldid request  parameters would allow page titles to be enumerated even
    			// when they are not guessable. So we reset the title to Special:Badtitle before the
    			// permissions error is displayed.
    
    			// The skin mostly uses $this->context->getTitle() these days, but some extensions
    			// still use $wgTitle.
    			$badTitle = SpecialPage::getTitleFor( 'Badtitle' );
    			$this->context->setTitle( $badTitle );
    			$wgTitle = $badTitle;
    
    			throw new PermissionsError( 'read', $permissionStatus );
    		}
    
                    // Еще какая-то логика для хандлинга редиректов по заголовкам страниц
    }
    // ...
    }
    
    // ...
    
    class MessageCache implements LoggerAwareInterface {
    // ...
    public function parse( $text, $title = null, $linestart = true,
    		$interface = false, $language = null
    	) {
    		global $wgTitle;
    
    		if ( $this->mInParser ) {
    			return htmlspecialchars( $text );
    		}
    
    		$parser = $this->getParser();
    		$popts = $this->getParserOptions();
    		$popts->setInterfaceMessage( $interface );
    
    		if ( is_string( $language ) ) {
    			$language = $this->langFactory->getLanguage( $language );
    		}
    		$popts->setTargetLanguage( $language );
    
    		if ( !$title || !$title instanceof Title ) {
    			$logger = LoggerFactory::getInstance( 'GlobalTitleFail' );
    			$logger->info(
    				__METHOD__ . ' called with no title set.',
    				[ 'exception' => new Exception ]
    			);
    			$title = $wgTitle;
    		}
    		// Sometimes $wgTitle isn't set either...
    		if ( !$title ) {
    			# It's not uncommon having a null $wgTitle in scripts. See r80898
    			# Create a ghost title in such case
    			$title = Title::makeTitle( NS_SPECIAL, 'Badtitle/title not set in ' . __METHOD__ );
    		}
    
    		$this->mInParser = true;
    		$res = $parser->parse( $text, $title, $popts, $linestart );
    		$this->mInParser = false;
    
    		return $res;
    	} // ...
    }

    Зачем в методах класса вообще использовать глобальные изменяемые состояния, если это нарушает принцип инкапсуляции (для обеспечения чего и была введена абстракция класса в языки)? И сидишь гадаешь, при вызове какого метода у какого объекта у тебя слетела верстка, контент и пр. Это усложняет написание безопасных расширений для системы.

    JaneBurt, 03 Мая 2021

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

    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
    76. 76
    // В одном файле
    
    // Getting gif by url
    const getGifUrl = (searchQuery, gifRating) => {
      const fullUrl = `${giphyUrl}${giphyApiKey}&tag=${searchQuery}&rating=${gifRating}`;
      let gifSource;
      let girSourceOriginal;
    
      fetch(fullUrl).then(response => {
        return response.json();
      }, networkError => {
        console.log(networkError);
      }).then(jsonResponse => {
        if (!jsonResponse)
          gifSource = '';
        else {
          gifSource = jsonResponse.data.images.preview_gif.url;
          gifSoucreOriginal = jsonResponse.data.image_original_url;
        }
    
        renderGif(gifSource, gifSoucreOriginal);
      });
    };
    
    // Где-то в другом файле
    
    // incapsulating image
    const incapsulateImage = (gifUrl, gifUrlOriginal) => {
      // creating gif preview tile
      const image = document.createElement('img');
      image.src = gifUrl;
    
      // create link to the original gif
      const linkOriginal = document.createElement('a');
      linkOriginal.href = gifUrlOriginal;
    
      // incapsulating gif tile into link
      linkOriginal.appendChild(image);
    
      // create container-tile
      const tile = document.createElement('div');
      tile.className = "container-tile";
    
      // incapsulating linked gif into tile
      tile.appendChild(linkOriginal);
    
      return tile;
    }
    
    // Rendering one gif image
    const renderGif = (gifUrl, gifUrlOriginal) => {
      if (gifUrl) {
        const imageTile = incapsulateImage(gifUrl, gifUrlOriginal);
        $gifContainer.append(imageTile);
      } else if (!$gifContainer.html()) {
        const notFoundHeading = document.createElement('h1');
        notFoundHeading.innerHTML = NOT_FOUND_TEXT;
        $gifContainer.append(notFoundHeading);
      }
    };
    
    const render = () => {
       // Rendering whole block of gifs
      const renderContainer = (searchQuery, gifCount, gifRating) => {
        for (let i = 0; i < gifCount; i++) {
          getGifUrl(searchQuery, gifRating);
    
          const heading = $gifContainer.find('h1');
          if (heading && heading.text() == NOT_FOUND_TEXT) {
            break;
          }
        }
      }
    
      // ...Сетап всяких обработчиков событий на элементы...
    }

    Когда толком не знал про промисы (а уж тем более про модули), городил такую дичь.

    JaneBurt, 02 Мая 2021

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

    +2

    1. 1
    Мир! Труд! Май!

    С праздником, питухи!

    MAuCKuu_nemyx, 01 Мая 2021

    Комментарии (114)
  8. Python / Говнокод #27387

    +1

    1. 1
    2. 2
    3. 3
    4. 4
    def main():
        pipe(int(input('Введите неотрицательное целое число: ')),   
             lambda n: (n, reduce(lambda x, y: x * y, range(1, n + 1))),   
             lambda tup: print(f'Факториал числа {tup[0]} равняется {tup[1]}'))

    Из https://habr.com/ru/post/555370/ (Функциональное ядро на Python).

    PolinaAksenova, 01 Мая 2021

    Комментарии (13)
  9. JavaScript / Говнокод #27386

    +1

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    function main() {    
    	(function () {
    		print("Hello World!");
    	})();
    }

    а ваш С компилятор может так говнокодить? а мой компилятор может :)

    ASD_77, 30 Апреля 2021

    Комментарии (20)
  10. Куча / Говнокод #27385

    +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
    var proto = $new(null);
    proto.foo = function() { 
      $print(this.msg) 
    }
    
    var o = $new(null);
    o.msg = "hello";
    $objsetproto(o,proto);
    o.foo(); // print "hello"
    
    $objsetproto(o,null); // remove proto
    o.foo(); // exception

    Давайте писать ня Neko!
    https://nekovm.org

    PolinaAksenova, 29 Апреля 2021

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