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

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

    +1

    1. 1
    2. 2
    3. 3
    Вы уронили продуктовое приложение и SSH-доступ изнутри виртуалки к нему,
    все сессии потеряны. Доступ к виртуалке надо просить через заказчика, и это косяк.
    Ваши действия?

    vistefan, 23 Июля 2020

    Комментарии (203)
  3. Куча / Говнокод #26810

    +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
    // Это означает что, например, поведение следующего кода не определено:
    
    fn cast(x: f32) -> u8 {
        x as u8
    }
    
    fn main() {
        let f = 300.0;
    
        let x = cast(f);
    
        println!("x: {}", x);
    }

    https://habr.com/ru/post/511546/
    > Это мы называем ошибкой «корректности» (ведь unsafe кода тут нет) — то есть ошибка, когда компилятор делает неправильные вещи. Мы отмечаем их в нашем трекере как I-unsound, и относимся к ним очень серьёзно.

    gost, 18 Июля 2020

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

    +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
    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
    import java.util.concurrent.TimeUnit;
    import java.util.regex.Pattern;
    import static java.lang.System.*;
    import static java.util.concurrent.TimeUnit.NANOSECONDS;
    
    public class Rep implements CharSequence
    {
        String str = null;
        int    len;
        char  base;
    
        public Rep(char x, int count)
        {
            this.len  = count;
            this.base = x;
        }
    
        @Override
        public int length()
        {
            return len;
        }
    
        @Override
        public char charAt(int index)
        {
            return base;
        }
    
        @Override
        public CharSequence subSequence(int beginIndex, int endIndex)
        {
            if (beginIndex < 0) {
                throw new StringIndexOutOfBoundsException(beginIndex);
            }
            if (endIndex > this.len) {
                throw new StringIndexOutOfBoundsException(endIndex);
            }
            int subLen = endIndex - beginIndex;
            if (subLen < 0) {
                throw new StringIndexOutOfBoundsException(subLen);
            }
            return ((beginIndex == 0) && (endIndex == this.len)) ? this
                    : new Rep(this.base, subLen);
        }
    
        @Override
        public String toString()
        {
            return null!=str ?  str : (this.str  = new String(new char[]{base}).repeat(len));
        }
    
        public static void main(String... args)
        {
            long ns = 0L;
            Pattern lazy   = Pattern.compile("^(11+?)\\1+$");
            Pattern greedy = Pattern.compile("^(11+?)\\1+$");
            ns=nanoTime();  lazy  .matcher(new Rep('1',100160079)).matches(); out.println( NANOSECONDS.toMillis(nanoTime()-ns));
            ns=nanoTime();  greedy.matcher(new Rep('1',100160079)).matches();out.println( NANOSECONDS.toMillis(nanoTime()-ns));
            ns=nanoTime();  greedy.matcher(new Rep('1',1165139)).matches();out.println( NANOSECONDS.toMillis(nanoTime()-ns));
    
            ns=nanoTime(); "1".repeat( 100160079 ).matches("^(11+?)\\1+$") ; out.println("Lazy String:"+ NANOSECONDS.toMillis(nanoTime()-ns));
            ns=nanoTime(); "1".repeat( 100160079 ).matches("^(11+)\\1+$") ; out.println("Greedy String:"+ NANOSECONDS.toMillis(nanoTime()-ns)); 
        }
    
    }

    Так как в «Йажа» регулярки работают не на строках, а на интерфейсе CharSequence https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/CharSequence.html

    Решил что можно сделать тупую реализацию CharSequence для строк из повторяющегося символа.

    https://ideone.com/8eYFU7

    3.14159265, 16 Июля 2020

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

    +1

    1. 1
    2. 2
    3. 3
    4. 4
    SIGRed (CVE-2020-1350) is a wormable, critical vulnerability (CVSS base score of 10.0) in the Windows DNS server
    that affects Windows Server versions 2003 to 2019, and can be triggered by a malicious DNS response.
    As the service is running in elevated privileges (SYSTEM), if exploited successfully, an attacker is granted Domain Administrator
    rights, effectively compromising the entire corporate infrastructure.

    https://research.checkpoint.com/2020/resolving-your-way-into-domain-admin-exploiting-a-17-year-old-bug-in-windows-dns-servers/

    gost, 15 Июля 2020

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

    +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
    IT Оффтоп #50
    
    
    #1: https://govnokod.ru/18142 https://govnokod.xyz/_18142
    #2: https://govnokod.ru/18378 https://govnokod.xyz/_18378
    #3: https://govnokod.ru/19667 https://govnokod.xyz/_19667
    #4: https://govnokod.ru/21160 https://govnokod.xyz/_21160
    #5: https://govnokod.ru/21772 https://govnokod.xyz/_21772
    #6: (vanished) https://govnokod.xyz/_24063
    #7: https://govnokod.ru/24538 https://govnokod.xyz/_24538
    #8: (vanished) https://govnokod.xyz/_24815
    #9: https://govnokod.ru/24867 https://govnokod.xyz/_24867
    #10: https://govnokod.ru/25328 https://govnokod.xyz/_25328	
    #11: (vanished) https://govnokod.xyz/_25436
    #12: (vanished) https://govnokod.xyz/_25471
    #13: (vanished) https://govnokod.xyz/_25590
    #14: https://govnokod.ru/25684 https://govnokod.xyz/_25684
    #15: https://govnokod.ru/25694 https://govnokod.xyz/_25694
    #16: https://govnokod.ru/25725 https://govnokod.xyz/_25725
    #17: https://govnokod.ru/25731 https://govnokod.xyz/_25731
    #18: https://govnokod.ru/25762 https://govnokod.xyz/_25762
    #19: https://govnokod.ru/25767 https://govnokod.xyz/_25767
    #20: https://govnokod.ru/25776 https://govnokod.xyz/_25776
    #21: https://govnokod.ru/25798 https://govnokod.xyz/_25798
    #22: https://govnokod.ru/25811 https://govnokod.xyz/_25811
    #23: https://govnokod.ru/25863 https://govnokod.xyz/_25863

    #24: https://govnokod.ru/25941 https://govnokod.xyz/_25941
    #25: https://govnokod.ru/26026 https://govnokod.xyz/_26026
    #26: https://govnokod.ru/26050 https://govnokod.xyz/_26050
    #27: https://govnokod.ru/26340 https://govnokod.xyz/_26340
    #28: https://govnokod.ru/26372 https://govnokod.xyz/_26372
    #29: https://govnokod.ru/26385 https://govnokod.xyz/_26385
    #30: https://govnokod.ru/26413 https://govnokod.xyz/_26413
    #31: https://govnokod.ru/26423 https://govnokod.xyz/_26423
    #32: https://govnokod.ru/26440 https://govnokod.xyz/_26440
    #33: https://govnokod.ru/26449 https://govnokod.xyz/_26449
    #34: https://govnokod.ru/26456 https://govnokod.xyz/_26456
    #35: https://govnokod.ru/26463 https://govnokod.xyz/_26463
    #36: https://govnokod.ru/26508 https://govnokod.xyz/_26508
    #37: https://govnokod.ru/26524 https://govnokod.xyz/_26524
    #38: https://govnokod.ru/26539 https://govnokod.xyz/_26539
    #39: https://govnokod.ru/26556 https://govnokod.xyz/_26556
    #40: https://govnokod.ru/26568 https://govnokod.xyz/_26568
    #41: https://govnokod.ru/26589 https://govnokod.xyz/_26589
    #42: https://govnokod.ru/26600 https://govnokod.xyz/_26600
    #43: https://govnokod.ru/26604 https://govnokod.xyz/_26604
    #44: https://govnokod.ru/26627 https://govnokod.xyz/_26627
    #45: https://govnokod.ru/26635 https://govnokod.xyz/_26635
    #46: (vanished) https://govnokod.xyz/_26646
    #46: (vanished) https://govnokod.xyz/_26654
    #47: https://govnokod.ru/26671 https://govnokod.xyz/_26671
    #48: https://govnokod.ru/26707 https://govnokod.xyz/_26707
    #49: https://govnokod.ru/26750 https://govnokod.xyz/_26750
    #49: https://govnokod.ru/26776 https://govnokod.xyz/_26776

    guestinxo, 12 Июля 2020

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

    +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
    44. 44
    45. 45
    private void checkButton_Click(object sender, EventArgs e)
        {
          if (this.passportTextbox.Text.Trim() == "")
          {
            int num1 = (int) MessageBox.Show("Введите серию и номер паспорта");
          }
          else
          {
            string rawData = this.passportTextbox.Text.Trim().Replace(" ", string.Empty);
            if (rawData.Length < 10)
            {
              this.textResult.Text = "Неверный формат серии или номера паспорта";
            }
            else
            {
              string commandText = string.Format("select * from passports where num='{0}' limit 1;", (object) Form1.ComputeSha256Hash(rawData));
              string connectionString = string.Format("Data Source=" + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\db.sqlite");
              try
              {
                SQLiteConnection connection = new SQLiteConnection(connectionString);
                connection.Open();
                SQLiteDataAdapter sqLiteDataAdapter = new SQLiteDataAdapter(new SQLiteCommand(commandText, connection));
                DataTable dataTable1 = new DataTable();
                DataTable dataTable2 = dataTable1;
                sqLiteDataAdapter.Fill(dataTable2);
                if (dataTable1.Rows.Count > 0)
                {
                  if (Convert.ToBoolean(dataTable1.Rows[0].ItemArray[1]))
                    this.textResult.Text = "По паспорту «" + this.passportTextbox.Text + "» доступ к бюллетеню на дистанционном электронном голосовании ПРЕДОСТАВЛЕН";
                  else
                    this.textResult.Text = "По паспорту «" + this.passportTextbox.Text + "» доступ к бюллетеню на дистанционном электронном голосовании НЕ ПРЕДОСТАВЛЯЛСЯ";
                }
                else
                  this.textResult.Text = "Паспорт «" + this.passportTextbox.Text + "» в списке участников дистанционного голосования НЕ НАЙДЕН";
                connection.Close();
              }
              catch (SQLiteException ex)
              {
                if (ex.ErrorCode != 1)
                  return;
                int num2 = (int) MessageBox.Show("Файл db.sqlite не найден. Положите файл в папку вместе с exe.");
              }
            }
          }
        }

    https://habr.com/post/510512/
    Медуза, паспорта и говнокод — почему номера паспортов всех участников интернет-голосования попали в Интернет

    gost, 11 Июля 2020

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

    +1

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    public static bool found13 = false;
    public static bool found11 = false;
    // ...
    public List<int> Children = new List<int>(); //index of children
    public List<int> Children13 = new List<int>(); //index of children

    Код бота-автора подавляющего большинства статей на нескольких языках. В основном Шведский (автор бота — швед) и, наверное, Себуанский, не знаю как правильно по-русски, короче язык океании, где-то на Филиппинах на нем говорят. На последнем, между прочим, бот нахерачил столько, что вывел себуанскую Википедию на второе место по количеству статей вообще.

    Потрясающий пример говнокода, написанного учёным для дела, и приемлемо решающий свою задачу. На основе отрытых баз знаний о таксонах биологических видов и географических объектах (реки, горы, населенные пункты), генерит статьи-заглушки с краткой информационной сводкой.

    https://sv.wikipedia.org/wiki/Wikipedia:Projekt_DotNetWikiBot_Framewor k/Lsjbot/Makespecies

    Сори, если баян.

    vistefan, 06 Июля 2020

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

    +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
    if (feet_yaw <= 58)
    	{
    		if (-58 > feet_yaw)
    			player->EyeAngles()->y = body_max_rotation + player->EyeAngles()->y;
    	}
    	else
    	{
    		player->EyeAngles()->y = body_max_rotation - player->EyeAngles()->y;
    	}
    	if (player->GetAnimOverlay(6)->m_flPlaybackRate > 0.1)
    	{
    		for (int resolve_delta = 58.f; resolve_delta < -58.f; resolve_delta = resolve_delta - 20.f)
    		{
    			player->EyeAngles()->y = resolve_delta;
    		}
    	}

    ресольвер

    esoterik, 04 Июля 2020

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

    +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
    if (UpdateLBY)
    			{
    				auto m_flDelta = csgo->local->GetPlayerAnimState()->m_flGoalFeetYaw - csgo->local->GetPlayerAnimState()->m_flEyeYaw;
    
    				if (m_flDelta >= 35.0 && m_flDelta <= -35.0) {
    					// the first lby break is left.
    					csgo->cmd->viewangles.y -= 122.f;
    				}
    				else {
    					if (m_flDelta <= -35.0) {
    						// the second lby break is right.
    						csgo->cmd->viewangles.y += 122.f;
    					}
    					if (m_flDelta >= 35.0) {
    						// the loop.
    						csgo->cmd->viewangles.y -= 122.f;
    					}
    				}
    				csgo->send_packet = false;
    				return;
    			}

    esoterik, 03 Июля 2020

    Комментарии (8)
  11. Java / Говнокод #26791

    +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
    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
    package literatePrimes;
    
    import java.util.ArrayList;
    
    public class PrimeGenerator {
      private static int[] primes;
      private static ArrayList<Integer> multiplesOfPrimeFactors;
    
      protected static int[] generate(int n) {
        primes = new int[n];
        multiplesOfPrimeFactors = new ArrayList<Integer>();
        set2AsFirstPrime();
        checkOddNumbersForSubsequentPrimes();
        return primes;
      }
    
      private static void set2AsFirstPrime() {
        primes[0] = 2;
        multiplesOfPrimeFactors.add(2);
      }
    
      private static void checkOddNumbersForSubsequentPrimes() {
        int primeIndex = 1;
        for (int candidate = 3;
             primeIndex < primes.length;
             candidate += 2) {
          if (isPrime(candidate))
            primes[primeIndex++] = candidate;
        }
      }
    
      private static boolean isPrime(int candidate) {
        if (isLeastRelevantMultipleOfNextLargerPrimeFactor(candidate)) {
          multiplesOfPrimeFactors.add(candidate);
          return false;
        }
        return isNotMultipleOfAnyPreviousPrimeFactor(candidate);
      }
    
      private static boolean
      isLeastRelevantMultipleOfNextLargerPrimeFactor(int candidate) {
        int nextLargerPrimeFactor = primes[multiplesOfPrimeFactors.size()];
        int leastRelevantMultiple = nextLargerPrimeFactor * nextLargerPrimeFactor;
        return candidate == leastRelevantMultiple;
      }
    
      private static boolean
      isNotMultipleOfAnyPreviousPrimeFactor(int candidate) {
        for (int n = 1; n < multiplesOfPrimeFactors.size(); n++) {
          if (isMultipleOfNthPrimeFactor(candidate, n))
            return false;
        }
        return true;
      }
    
      private static boolean
      isMultipleOfNthPrimeFactor(int candidate, int n) {
       return
         candidate == smallestOddNthMultipleNotLessThanCandidate(candidate, n);
      }
    
      private static int
      smallestOddNthMultipleNotLessThanCandidate(int candidate, int n) {
        int multiple = multiplesOfPrimeFactors.get(n);
        while (multiple < candidate)
          multiple += 2 * primes[n];
        multiplesOfPrimeFactors.set(n, multiple);
        return multiple;
      }
    }

    https://habr.com/ru/post/508876/
    Вероятно, хватит рекомендовать «Чистый код»
    > Я остановлюсь на ещё одном вопиющем примере кода. Это генератор простых чисел из главы 8:

    gost, 03 Июля 2020

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