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

    −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
    from random import random
    from math import log
    
    def championship(champions = 16):
        space = '          '
        count_of_laps = int(log(champions,2))
        koef = [i for i in range(count_of_laps)]
    
        nummer = 1
        num_of_champions = []
        for i in range(champions):
            num_of_champions.append(nummer)
            nummer += 2
        value_of_champions = [("%.4f" % (random())) for i in range(champions)]
    
        lap0 = []
        for i in range(champions):
            lap0.append([num_of_champions[i], value_of_champions[i], space*koef[0]])
        koef.append(koef[-1]+1)
        count_lap = 1
    
        laps = []
        for i in range(count_of_laps):
            fighter1 = 0
            fighter2 = 1
            exec(f'lap{count_lap} = []')
    
            while fighter2 <= eval(f'len(lap{count_lap - 1})'):
                num_winner = (eval(f'lap{count_lap - 1}[{fighter1}][0]') + eval(f'lap{count_lap - 1}[{fighter2}][0]'))//2
                value_winner = max(eval(f'lap{count_lap - 1}[{fighter1}][1]'), eval(f'lap{count_lap - 1}[{fighter2}][1]'))
                probel = space*koef[i+1]
                winner = [num_winner, value_winner, probel]
                exec(f'lap{count_lap}.append({winner})')
                fighter1 += 2
                fighter2 += 2
            count_lap += 1
    
        laps = []
        for i in range(count_of_laps+1):
            exec(f'laps += lap{i}')
        laps.sort()
    
        for i in range(nummer-2):
            print(laps[i][2] + str(laps[i][1]))
    
    if __name__ == "__main__":
        while True:
            value = int(input('Write power of two: '))
            print()
            if (value & (value - 1)) == 0:
                championship(value)
                print()
            else:
                print('not power of two')

    Прога воспроизводит турнир между цифрами от 0 до 1. Самое большое побеждает

    Fantoner, 02 Января 2020

    Комментарии (0)
  2. Python / Говнокод #26299

    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
    """ASCII art generator braille only.
    
    To start, put this and the image (you need to rename it to input.jpg) in one folder.
    
    The main problem of the algorithm:
    Due to the fact that the 8 empty dots symbol and any other Braille symbol have different widths,
    the picture may 'float'.
    
    """
    from PIL import Image, ImageDraw
    
    # Change scale of image.
    scale = int(input('% of scale: ')) / 100
    imgForScale = Image.open('input.jpg')
    widthOldForScale, heightOldForScale = imgForScale.size
    widthNewForScale, heightNewForScale = int(widthOldForScale * scale), int(heightOldForScale * scale)
    scaleImg = imgForScale.resize((widthNewForScale, heightNewForScale), Image.ANTIALIAS)
    scaleImg.save('inputScale.jpg')
    # -------------
    
    # Makes the image BW.
    factor = int(input('factor: '))  # The more, the darker.
    imgForBW = Image.open('inputScale.jpg')
    draw = ImageDraw.Draw(imgForBW)
    widthForBW, heightForBW = imgForBW.size
    pix = imgForBW.load()
    for i in range(widthForBW):
        for j in range(heightForBW):
            a = pix[i, j][0]
            b = pix[i, j][1]
            c = pix[i, j][2]
            S = a + b + c
            if S > (((255 + factor) * 3) // 2):
                a, b, c = 255, 255, 255
            else:
                a, b, c = 0, 0, 0
            draw.point((i, j), (a, b, c))
    imgForBW.save("inputScaleBW.jpg")
    # -------------
    
    # The image should be divided by 2 horizontally, by 4 vertically. Otherwise, the extra pixels will be removed.
    img = Image.open('inputScaleBW.jpg')
    size = w, h = img.size
    if (w % 2) == 0:
        pass
    else:
        w -= 1
    hCut = h % 4
    if hCut == 0:
        pass
    else:
        h -= hCut
    # -------------
    
    data = img.load()
    yStart, yEnd = 0, 4
    xStart, xEnd = 0, 2
    valueOfPixNow = []
    b = w // 2  # I don`t remember.
    a = b - 1   # The same thing.
    i = 0
    
    while (yEnd <= h) and (xEnd <= w):
        # Getting data from a image.
        valueOfPixNow = []
        for y in range(yStart, yEnd):
            for x in range(xStart, xEnd):
                if not ((230 <= data[x, y][0] <= 255) and (230 <= data[x, y][1] <= 255) and (230 <= data[x, y][2] <= 255)):
                    valueOfPixNow.append(1)
                else:
                    valueOfPixNow.append(0)
        # -------------------
        # Convert data from image.
        normalBinaryReversed = [valueOfPixNow[0], valueOfPixNow[2], valueOfPixNow[4], valueOfPixNow[1], valueOfPixNow[3],
                                valueOfPixNow[5], valueOfPixNow[6], valueOfPixNow[7]]
        normalBinary = list(reversed(normalBinaryReversed))
        strBinary = ''.join(map(str, normalBinary))
        strHex = hex(int(strBinary, 2))
        twoLastNum = strHex[2:]
        if len(twoLastNum) == 1:
            twoLastNum = '0' + twoLastNum
        hexStrBraille = '28' + twoLastNum
        decimalBraille = int(hexStrBraille, 16)
        answer = chr(decimalBraille)
        # -------------------
        if i == a:
            a += b
            print(answer)
        else:
            print(answer, end='')
        i += 1
    
        if xEnd < w:
            xStart += 2
            xEnd += 2
        else:
            xStart = 0
            xEnd = 2
            yStart += 4
            yEnd += 4

    Fantoner, 02 Января 2020

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

    −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
    def raboficate(sents: Sequence[Sequence[str]]) -> Sequence[str]:
        RABOWORDS = (
            ('много', '.'),
            ('малость', '.'),
            ('зачем', '?')
        )
    
        sents_rab = []
        for sent in sents:
            raboword = random.choice(RABOWORDS)
            sents_rab.append([raboword[0]] + sent + [raboword[1]])
        return sents_rab

    Массовое зомбирование сознания при помощи «Python».
    https://github.com/gost-gk/raboscript

    В помощь начинающим рабомантам и кобенаторам нашим отделом по датамайнингу бигдаты был надатамайнен, почищен и приведён к удобоваримому виду (все слова/знаки препинания разделены пробелами, мусор убран) самый длинный фанфик по «Mass Effect»: https://mega.nz/#!XdFyzahR!_rXcsCBWyyrnl69feQMpCi238ACNp euO-Zz9nn2E-FQ (сорок мегабайт отборной психозы!).
    Также аналитическим отделом был найден пакет «pymorphy2», с помощью которого наши инженеры надеются довести рабоскрипт до идеала.

    gost, 15 Декабря 2019

    Комментарии (135)
  4. Python / Говнокод #26091

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    import random
    
    UPCHK = ["СЕМ", "ОДИН", "БЛЭЦК", "ОЛОЛО", "БЖЫБЖА", "ЖУЧЛО", "ВЗДРЪЖНИ ЭФФЕКТ", "ВИДЕ", "ДВА МРЕОКЛЯ", "ДЕНИСЕ", "ДУПЯЧКА", "ГЛАГНЕ", "ГЛАНДЭ", "ГАЛАКТЕКО ОПАСНОСТЕ", "ЖАЖА", "ЕБИ ГУСЕЙ, СУКА!!11111", "ЖЕПЬ ЕБРИЛО", "ЖНЕЖНЕ", "ЖРАЧНЕ", "ПЯПЯЩЬ", "ЖЫВТОНЕ", "ЖУЙЧНИ", "ЖИВЛОБАРЕ", "ЖЪРЧИК", "ЗАРЯД УПЯЧКИ", "КЕЙГУШЕГИ", "КОЛЛАЙДРЕ", "КОТЭ", "КРАБЕ", "КРЕО", "ЛЕОНИДЕ", "ЛУЧИ ПОНОСА", "МЖВЯЧНИ", "ОНОТОЛЕ", "ПЯНИ", "ОТАКЕ!!!!1111", "ОЯЕБУ", "ПЕПЯКА", "ПЕПЯКОДЭНС", "ПЕПЯКОМЭН", "ПОПЯЧТСА", "ПОТС ЗОХВАЧЕН", "ПРДУНЬ-ПРДУНЬ", "ПТСО", "ПЫЩЬ!!!!111одинодин1", "РАЗУПЛОТНЕНИЕ", "РАЗРАЗИ МЕНЯ КРОТЫ", "РИАЛЬНИ", "САКИРМАХРЕПЯКА", "СКОЛОПЕНДРЕ", "СМОТРИ БАЛЕТ, СУКА!1", "СУЧЕЧКЕ", "С. Р. У!!!", "СТОПИЦОТ", "ТУПАК", "ТУТСЯ", "УГ", "ХУРЬ", "ХУЙС", "ЧАКЕ", "ЧОЧО", "ЧОЧОЧКИ", "ЧПЯКИ-ЧПЯКИ", "ШМЕЛЕ", "ЩАЧЛО КАРПА", "ЭЕКСТЕЛР ТЫЕОЙ ЯЕБАНЕЙУ КОТУ", "GSOM", "ЧЯПЬ-ЧЯПЬ", "ЪЖСЛО", "ЪЕЧОЖЖА", "ЪПРШУТЕ", "ЬШТУК", "ШТЫРНЕ", "ЯСХИЩАЧУ", "ГЪЛБЬ", "СГОМОНЬ", "JEPEBRILO", "АБЗЪДУКА", "АНГАНАСЕ", "АНТИКРАБЕРИАЛЬНЕ ЪМЛО", "БЖНИ", "БЖНИНА", "БЖНЬТУКИ", "БЛЪВАРИЯ", "БЪРЩЕ", "ВЪРДКЭ", "ГЖЪН’КИ", "ГАЗОДОРЫЖНИ", "ЖВЯЧНИ", "ЖРАЧНЕ", "ЖУЙЧНИ", "ЖЪРЧИК", "ЖЛЯЦНИ", "КВИТКИ ПИЖМЫ", "КРАКЛЕ", "МЕНСТО", "МРАЗЬ", "МУРА", "МЭБЛНИ", "НОКЛА", "ОГУДОРОПОМИРЕЦ", "ПДКЯЖЦЫ", "ПРЯСНО СВИНСКО", "ПЪДГРЪЗНИ", "ПЪРЖОЛИ", "ПЫЩИНЪ", "КВАСОЭ", "ПЯНИ", "РЪГАЕЛЛО", "СГУЩНИ МОЛОЛО", "СКЛИВЗЧНЕ МАСЛОЭ", "СТРИТ ФАЙТРЕ", "СЪРНЕ", "ТЪШНИК", "ХЛЯПНИ", "LЪЙS", "ЧИСПЫ", "ЧЯПИЙ", "ЩЯЩЬ-ЩЯЩЬ", "ШТЫРНЕ", "ЪТСО", "ЪПШРОТЭ", "ЫРЧНИ"]
    def upchka(u, sigma, words=100):
        res = []
        for word in [random.choice(UPCHK) for _ in range(words)]:
            res += [word for _ in range(max(abs(int(random.normalvariate(u, sigma))), 1))]
        return ' '.join(res)
    
    upchka(1, 3, 100)

    ЖЕПЬ ЕБРИЛО ЖЕПЬ ЕБРИЛО ЩАЧЛО КАРПА ПЫЩЬ!!!!111одинодин1

    gost, 11 Декабря 2019

    Комментарии (55)
  5. 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)
  6. 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)
  7. Python / Говнокод #26017

    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
    Building on that example, the new syntax for function definitions would look like:
    
    def name(positional_only_parameters, /, positional_or_keyword_parameters,
             *, keyword_only_parameters):
    
    Therefore the following would be valid function definitions:
    
    def name(p1, p2, /, p_or_kw, *, kw):
    def name(p1, p2=None, /, p_or_kw=None, *, kw):
    def name(p1, p2=None, /, *, kw):
    def name(p1, p2=None, /):
    def name(p1, p2, /, p_or_kw):

    https://www.python.org/dev/peps/pep-0570

    3.14159265, 07 Ноября 2019

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

    +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
    x = 0; y = 0
     
    def gcd(a, b):
    #{
        global x, y
        if (a == 0):
        #{
            x = 0; y = 1;
            return b;
        #}
        d = gcd(b%a, a);
        t = x
        x = y - (b // a) * x;
        y = t;
        return d;
    #}
     
    #int main()
    #{
    #ios_base::sync_with_stdio(0); in.tie(0);
    #I n, p, w, d, dd, ww;
    #in >> n >> p >> w >> d;
    n, p, w, d = map(int, input().split())
    gc = gcd(d, w);
    dd = x; ww = y
    g = w * d // gc;
    if (p % gc):
        print(-1); exit(0)
    dd *= p // gc;
    ww *= p // gc;
    if (ww < 0):
    #{
        di = (-ww + g // w - 1) // (g // w);
        ww += g // w * di;
        dd -= g // d * di;
        if (dd < 0):
            print(-1); exit(0)
    #}
    elif (dd < 0):
    #{
        di = (-dd + g // d - 1) // (g // d);
        dd += g // d * di;
        ww -= g // w * di;
        if (dd < 0):
            print(-1); exit(0)
    #}
    if (ww < 0 or dd < 0):
        print(-1); exit(0)
    di = dd // (g // d);
    dd -= g // d * di;
    ww += g // w * di;
    if (ww + dd <= n):
        print(ww, dd, n - ww - dd)
    else:
        print(-1);
    #}

    Когда на соревновании по спортивному программированию пишешь код на C++ и внезапно понимаешь, что int64_t тебе недостаточно.

    fyodor95, 04 Ноября 2019

    Комментарии (52)
  9. Python / Говнокод #26001

    +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
    import re, copy, json
    
    config = {}
    
    
    def domain_mapper(domain):
    	def injector(f):
    		if domain not in config:
    			config[domain] = []
    		config[domain].append(f)
    	return injector
    
    def default(f):
    	config['default'] = [f]
    	return f
    
    @domain_mapper("gmail.com")
    @default
    def google_filter(content):
    	regex = r"([^\!\?\.]*?offer.*?[\!\?\.])"
    	repl = r""
    	return re.sub(regex, repl, content, re.M)
    
    @domain_mapper("gmail.com")
    def another_google_filter(content):
    	return content
    
    @domain_mapper("yandex.ru")
    def yandex_filter(content):
    	regex = r"<img src=[\"'](.+?)[\"'].*/>"
    	repl = r"\1"
    	return re.sub(regex, repl, content, re.M)
    
    @domain_mapper("mail.ru")
    def mail_filter(content):
    	regex = r"<img src=[\"'](.+?)\.gif[\"'].*/>"
    	repl = r"<img src='\1.png'/>"
    	return re.sub(regex, repl, content, re.M)

    Говно или нет?

    miwomare, 28 Октября 2019

    Комментарии (85)
  10. Python / Говнокод #25986

    +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
    class Container:
        def __init__(self, liquid):
            self.liquid = liquid
    
        def look_inside(self):
            return f"{self.liquid} in container"
    
        @classmethod
        def create_with(cls, liquid):
            return cls(liquid)
    
    
    class Bottle(Container):
        def look_inside(self):
            return f"bottle full of {self.liquid}"
    
    
    class Glass(Container):
        def look_inside(self):
            return f"A glass of {self.liquid}"
    
    
    for c in (c.create_with("beer") for c in [Glass, Bottle]):
        print(c.look_inside())

    ми маємо class polymorphism

    DypHuu_niBEHb, 23 Октября 2019

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