1. Python / Говнокод #26052

    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
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    86. 86
    87. 87
    88. 88
    89. 89
    90. 90
    91. 91
    92. 92
    93. 93
    94. 94
    95. 95
    96. 96
    97. 97
    98. 98
    99. 99
    from datetime import datetime, timedelta
    from dateutil import parser
    import os
    import pytest
    
    from tests.db_support import psg_db
    
    
    intake_iot_mapper = [('sourceId', 'DEVICE_ID', str),
                         ('altitude', 'ALTITUDE', int),
                         ('odometer', 'ODOMETER', int),
                         ('battery', 'BATTERY_LEVEL', int),
                         ('speed', 'SPEED', int),
                         ('satCount', 'SAT_COUNT', float),
                         ('gpsQuality', 'GPSQUALITY', float),
                         ('lat', 'LAT', float),
                         ('lon', 'LON', float),
                         ('radius', 'RADIUS', int),
                         ('objectId', 'OBJECT_ID', str),
                         ('direction', 'DIRECTION', int)]
    
    
    @pytest.fixture(scope='module')
    def device_ids():
        sql_device = """SELECT
                          dvc.id,
                          dvc.source_id device_id,
                          dvc_m.object_id
                        FROM iot_platform.iot_device_mecomo dvc_m
                          JOIN iot_platform.iot_device dvc on dvc.id = dvc_m.id
                        WHERE dvc_m.object_id is not NULL ORDER BY dvc_m.object_id"""
    
        ids = psg_db(sql=sql_device)
    
        ids_dict = [(row['device_id'], row['id'], row['object_id']) for row in ids]
    
        return ids_dict
    
    
    @pytest.mark.parametrize('device_id, uuid, object_id', device_ids())
    @pytest.mark.parametrize('check_date', [str((datetime.now() - timedelta(days=1)).date())])
    def test_telemetry_all(device_id, uuid, object_id, get_intake_data, devices_list, get_iot_data, check_date, expect):
    
        _from = parser.parse(check_date)
        _to = _from + timedelta(hours=23, minutes=59, seconds=59)
    
        intake_from = _from.strftime('%Y/%m/%d %H:%M:%S')
        intake_to = _to.strftime('%Y/%m/%d %H:%M:%S')
    
        # take wider period from Dymano (+24 hours)
        dynamo_from = _from.timestamp()*1000
        dynamo_to = (_to + timedelta(hours=24)).timestamp()*1000
    
        xml_file_name = '%s/IntakeRaw/device_telemetry/telemetry_device_%s_%s.xml' % (os.path.dirname(__file__), device_id, _from.date())
    
        # write response data to file if there is no file saved
        if not os.path.isfile(xml_file_name):
    
            params = {'objectId': object_id, 'startIndex': 1, 'startDate': intake_from, 'endDate': intake_to}
            content = get_intake_data('positions_report', **params)
    
            # create dir, get intake data and write it to the file
            os.makedirs(os.path.dirname(xml_file_name), exist_ok=True)
            with open(xml_file_name, 'w') as f_xml:
                f_xml.write(content.decode('utf-8'))
    
        telemetry_in = devices_list(xml_file_name, 'POSITION')
        telemetry_out = get_iot_data(uuid, dynamo_from, dynamo_to, 'telemetry')
    
        # check if IOT data is empty but there are entries in the intake, go no further if this fails
        if telemetry_in:
            assert telemetry_out, \
                'Fail: empty data received for device %s, period %s - %s: Entries count: Intake %s != %s Dynamo DB' \
                % (uuid, dynamo_from, dynamo_to, len(telemetry_in), len(telemetry_out))
    
        for pos_id in telemetry_in:
            # check if the position id was saved in Dynamo
            if pos_id in telemetry_out:
                for key_out, key_in, to_type in intake_iot_mapper:
    
                    # check if the parameter is in the intake and it is not null
                    if key_in in telemetry_in[pos_id] and telemetry_in[pos_id][key_in] is not None:
    
                        if key_out in telemetry_out[pos_id]:
    
                            if key_in in ('LAT', 'LON'):
                                expect(
                                    to_type(telemetry_out[pos_id]['location'][key_out]) == to_type(float(telemetry_in[pos_id][key_in])),
                                    'Fail: position id %s, %s: in %s != %s out' % (pos_id, key_out, telemetry_in[pos_id][key_in],
                                                                                   telemetry_out[pos_id]['location'][key_out]))
                            else:
                                expect(str(telemetry_out[pos_id][key_out]) == telemetry_in[pos_id][key_in],
                                       'Fail: position id %s, %s: in %s != %s out' %
                                       (pos_id, key_out, telemetry_in[pos_id][key_in], telemetry_out[pos_id][key_out]))
    
                        else:
                            expect(key_out in telemetry_out[pos_id],
                                   'Fail: record time %s, device id: %s:%s: %s in %s != None %s out'
                                   % (pos_id, device_id, uuid, key_in, telemetry_in[pos_id][key_in], key_out))

    интеграционный тест одной тупой педовки

    gvkdgvkd, 27 Ноября 2019

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

    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
    public static long NextTimestamp()
    {
    	if (initTimestamp == null)
    	{
    		lock (syncRoot)
    		{
    			if (initTimestamp == null)
    			{
    				initTimestamp = false;
    				var sessionProvider = Locator.GetServiceNotNull<ISessionProvider>();
    				TimestampService.GetTimestamp();
    				sessionProvider.CloseSession("");
    				initTimestamp = true;
    			}
    		}
    	}
    
    	return initTimestamp.Value ? TimestampService.GetTimestamp() : 0;
    }

    Нельзя просто взять и вызвать TimestampService.GetTimestamp() - StackOverflowException получишь. Вот как надо!

    scrappyabc, 27 Ноября 2019

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

    0

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

    #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: https://govnokod.ru/24063 (потёр пидор сракер) https://govnokod.xyz/_24063
    #7: https://govnokod.ru/24538 https://govnokod.xyz/_24538
    #8: https://govnokod.ru/24815 (потёр пидор сракер) https://govnokod.xyz/_24815
    #9: https://govnokod.ru/24867 https://govnokod.xyz/_24867
    #10: https://govnokod.ru/25328 https://govnokod.xyz/_25328
    #11: https://govnokod.xyz/_25436 https://govnokod.ru/25436 (потёр пидор сракер)
    #12: https://govnokod.xyz/_25471
    #13: https://govnokod.xyz/_25590 (потёр пидор сракер)
    #14: https://govnokod.xyz/_25684
    #15: https://govnokod.xyz/_25694
    #16: https://govnokod.xyz/_25725
    #17: https://govnokod.xyz/_25731
    #18: https://govnokod.xyz/_25762
    #19: https://govnokod.xyz/_25767
    #20: https://govnokod.xyz/_25776
    #21: https://govnokod.xyz/_25798
    #22: https://govnokod.xyz/_25811
    #23: https://govnokod.xyz/_25863
    #24: https://govnokod.xyz/_25941
    #25: https://govnokod.xyz/_26026

    syoma, 27 Ноября 2019

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

    +1

    1. 1
    Segmentation fault

    Я против «неинформативных ошибок».

    gost, 26 Ноября 2019

    Комментарии (17)
  5. bash / Говнокод #26048

    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
    # Если вы желаете ограничить диапазон "снизу",
    # то просто производите генерацию псевдослучайных чисел в цикле до тех пор,
    # пока не получите число большее нижней границы.
    
    FLOOR=200
    
    number=0   # инициализация
    while [ "$number" -le $FLOOR ]
    do
      number=$RANDOM
    done
    echo "Случайное число, большее $FLOOR ---  $number"

    https://www.opennet.ru/docs/RUS/bash_scripting_guide/x4812.html

    groser, 26 Ноября 2019

    Комментарии (24)
  6. PHP / Говнокод #26047

    0

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    foreach ($cart = LaraCart::getItems() as $product) {         
        $product->id;      
           $product->name;      
           $product->title_slug;       
          $product->price;         
        $product->qty;      
           $product->photo;     
            $product->item_type;  
           }

    А не прогнать бы нам просто данные ммм?

    ARTWIN_PRO, 26 Ноября 2019

    Комментарии (18)
  7. Python / Говнокод #26046

    +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
    >>> from heapq import heappush, heappop
    >>> heap = []
    >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
    >>> for item in data:
    ...     heappush(heap, item)
    ...
    >>> ordered = []
    >>> while heap:
    ...     ordered.append(heappop(heap))
    ...
    >>> ordered
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> data.sort()
    >>> data == ordered
    True

    В «Python» есть стандартный модуль «heapq» с процедурками, которые делают из обычного листа очередь с приоритетом: https://docs.python.org/3.8/library/heapq.html. Всё просто, понятно, удобно и без этих ваших «классов» с «наследованиями». Именно поэтому я за «Python».

    gost, 26 Ноября 2019

    Комментарии (32)
  8. Куча / Говнокод #26045

    0

    1. 1
    https://upload.wikimedia.org/wikipedia/commons/b/b5/Hexadecimal-counting.jpg

    Просто оставлю это здесь

    CEMEH, 25 Ноября 2019

    Комментарии (39)
  9. Куча / Говнокод #26044

    0

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    https://stackoverflow.com/questions/33569457/pymysql-returning-old-snapshot-values-not-rerunning-query
    
    
    > Thanks. This saved my day.
    > You are a hero to me, my country and the world in general. This saved my whole week. Also I did not found any other way to prevent this bug.
    > Thanks a lot, this saved my day

    Столкнулся с ровно такой же хуетой, как у стековерфлововца, но я делаю commit, и вижу изменения.
    Кто-то скажет, что не надо было ставить "MySQL".

    BJlADuMuPCKuu_nemyx, 25 Ноября 2019

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

    +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
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    class HTMLCheapRedactor
    {
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Form a = new Form() { Text = "HTML Doc" },
                b = new Form() { Text = "HTML Code" };
            var web = new WebBrowser() { Dock = DockStyle.Fill };
            var txt = new TextBox()
            {
                Multiline = true,
                Dock = DockStyle.Fill,
                ScrollBars = ScrollBars.Both,
                Font = new Font("Consolas", 12f),
                WordWrap = false,
                AcceptsTab = true
            };
            web.DataBindings.Add(new Binding("DocumentText", txt, "Text"));
            a.Controls.Add(web);
            b.Controls.Add(txt);
            b.Show();
            b.AddOwnedForm(a);
            txt.Text = @"<html>
    <head>
         <title>Hello World!</title>
    </head>
    <body>
         Hello World!
    </body>
    </html>";
            Application.Run(a);
        }
    }

    groser, 24 Ноября 2019

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