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

    −113

    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
    def normalize_url(url, preserve_fragment=False):
            url = url.strip()
            if not re.search(r'^\w+:', url):
                url = 'http://' + url.lstrip('/')
    
            if not (url.startswith('http:') or url.startswith('https:')):
                return url
    
            url = list(urlparse.urlsplit(url))
            if url[0] not in ('http', 'https'):
                url[0] = 'http'
            url[1] = url[1].lower().encode('idna')
    
            if type(url[2]) == unicode:
                try:
                    url[2] = url[2].encode('ascii')
                except UnicodeEncodeError:
                    pass
            url[2] = urllib.unquote(url[2])
            if type(url[2]) == unicode:
                url[2] = url[2].encode('utf-8')
            url[2] = urllib.quote(url[2], '/')
    
            if type(url[3]) == unicode:
                try:
                    url[3] = url[3].encode('ascii')
                except UnicodeEncodeError:
                    pass
            cut_params = ('utm_source', 'utm_medium', 'utm_term',
                          'utm_content', 'utm_campaign',
                          'yclid', 'gclid', 'ref')
            new_qsl = []
            for tag in url[3].split('&'):
                if '=' in tag:
                    param, value = tag.split('=', 1)
                    param = urllib.unquote(param)
                    value = urllib.unquote(value)
                    if param in cut_params:
                        continue
                    if type(value) == unicode:
                        value = value.encode('utf-8')
                    new_tag = "%s=%s" % (urllib.quote(param), urllib.quote(value))
                else:
                    new_tag = urllib.unquote(tag)
                    if type(new_tag) == unicode:
                        new_tag = new_tag.encode('utf-8')
                    new_tag = urllib.quote_plus(new_tag)
                new_qsl.append(new_tag)
            url[3] = '&'.join(new_qsl)
            if not preserve_fragment:
                url[4] = ''
            return urlparse.urlunsplit(url)

    Еще немного магии и хватит на сегодня.

    kyzi007, 18 Ноября 2014

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

    −115

    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
    now = timezone.now().astimezone(cur_tz)
    today = now.replace(hour=0, minute=0, second=0, microsecond=0)
    td1day = datetime.timedelta(days=1)
    td7days = datetime.timedelta(days=7)
    td14days = datetime.timedelta(days=14)
    td30days = datetime.timedelta(days=30)
    
    categories = None
    if user is not None:
        try:
            categories = self.categories.restrict_by_acl(
                self.acl.by_user(user, can_enter=True), throw_if_all=True)
        except CampaignProductCategory.NoAclRestriction:
            categories = None
    
    report3_url = reverse('report3', args=[self.pk])
    df = lambda d: d.strftime('%d.%m.%Y')
    
    stats = {'to': now}
    stats['in_1d'] = get_count(today, categories)
    stats['in_1d_from'] = today
    stats['in_1d_url'] = (
        report3_url +
        '#from_date=%s&to_date=%s' % (df(stats['in_1d_from']),
                                      df(stats['to'])))
    stats['in_7d'] = get_count(today-td7days+td1day, categories)
    stats['in_7d_from'] = today - td7days + td1day
    stats['in_7d_url'] = (
        report3_url +
        '#from_date=%s&to_date=%s' % (df(stats['in_7d_from']),
                                      df(stats['to'])))
    stats['in_14d'] = get_count(today-td14days+td1day, categories)
    stats['in_14d_from'] = today - td14days + td1day
    stats['in_14d_url'] = (
        report3_url +
        '#from_date=%s&to_date=%s' % (df(stats['in_14d_from']),
                                      df(stats['to'])))
    stats['in_30d'] = get_count(today-td30days+td1day, categories)
    stats['in_30d_from'] = today - td30days + td1day
    stats['in_30d_url'] = (
        report3_url +
        '#from_date=%s&to_date=%s' % (df(stats['in_30d_from']),
                                      df(stats['to'])))

    Пхп и даты, только питон

    kyzi007, 18 Ноября 2014

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

    −106

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    >>> quit()
    Traceback (most recent call last):
      File "<stdin>", line 1, in ?
    TypeError: 'str' object is not callable
    >>> quit  
    'Use Ctrl-D (i.e. EOF) to exit.'
    >>> type(quit)
    <type 'str'>
    >>> type(exit)
    <type 'str'>

    Первый раз запустил питон 2.4...

    bormand, 14 Ноября 2014

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

    −101

    1. 1
    self.exclude = list(set(list(self.exclude or []) + ['str1', 'str2']))

    american_idiot, 12 Ноября 2014

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

    −106

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    qdev_id, iops = _update_device_iops(instance, device_for_change)
    try:
    	qemu.volumes.set_io_throttle(controller.qemu(), qdev_id, iops)
    except Exception as e:
    	# Check if we turn off this instance? just a moment ago.
    	if "'NoneType' object has no attribute 'connected'" in e:
    		LOG.warning("kemu process seems to be killed")
    	else:
    		raise

    Метод set_io_throttle не бросает exception.
    Мы так проверяем,есть ли connection к qemu или нет.

    gmmephisto, 30 Октября 2014

    Комментарии (1)
  6. Python / Говнокод #16954

    −99

    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
    @login_required
    def datadelivery_stats_report(request, campaign_id):
    
        try:
            start_date = extract_date_to_default_timezone(request, 'start_date')
        except ValidationError:
            return HttpResponseServerError("The %s parameter is invalid." % 'start_date')
        except AttributeError:
            return HttpResponseServerError("The %s parameter is invalid." % 'start_date')
        except KeyError:
            return HttpResponseServerError("The %s parameter is missing." % 'start_date')
    
        try:
            end_date = extract_date_to_default_timezone(request, 'end_date')
        except ValidationError:
            return HttpResponseServerError("The %s parameter is invalid." % 'end_date')
        except AttributeError:
            return HttpResponseServerError("The %s parameter is invalid." % 'end_date')
        except KeyError:
            return HttpResponseServerError("The %s parameter is missing." % 'end_date')

    Джанга такая джанга... Почему же нельзя выбросить ошибку валидации? 404 можно...

    kyzi007, 28 Октября 2014

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

    −106

    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
    import pygame
    
    window = pygame.display.set_mode((600, 600))
    pygame.display.set_caption("GAME")
    screen = pygame.Surface((600, 600))
    
    class Sprite:
        def __init__(self, xpos, ypos, filename):
            self.x=xpos
            self.y=ypos
            self.bitmap=pygame.image.load(filename)
            self.bitmap.set_colorkey((0,0,0))
        def render(self):
            screen.blit(self.bitmap, (self.x,self.y))
    
    laser = Sprite(0, 0, 'laser.png')
    
    done = True
    while done:
        window.fill((50,50,50))
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                done = False
    
        screen.fill((50,50,50))
    
        laser.render()
        window.blit(screen, (0,0))
        pygame.display.flip()

    картинка на черном фоне

    archiwise, 27 Октября 2014

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

    −96

    1. 1
    {% verbatim %}{{ setExpireValue({% endverbatim %}{{ value }}{% verbatim %}) }}{% endverbatim %}

    AngularJS + Django, люди доходят до ручки.

    YourPM, 24 Октября 2014

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

    −97

    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 constant_time_compare(val1, val2):
        """
        Returns True if the two strings are equal, False otherwise.
    
        The time taken is independent of the number of characters that match.
        """
        if len(val1) != len(val2):
            return False
        result = 0
        for x, y in zip(val1, val2):
            result |= ord(x) ^ ord(y)
        return result == 0

    Django.utils.crypto в Django 1.4

    american_idiot, 24 Октября 2014

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

    −93

    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
    # Source: python3.4/distutils/dir_util.py
    
    
    # cache for by mkpath() -- in addition to cheapening redundant calls,
    # eliminates redundant "creating /foo/bar/baz" messages in dry-run mode
    _path_created = {}
    
    # I don't use os.makedirs because a) it's new to Python 1.5.2, and
    # b) it blows up if the directory already exists (I want to silently
    # succeed in that case).
    def mkpath(name, mode=0777, verbose=1, dry_run=0):
        """Create a directory and any missing ancestor directories.
    
        If the directory already exists (or if 'name' is the empty string, which
        means the current directory, which of course exists), then do nothing.
        Raise DistutilsFileError if unable to create some directory along the way
        (eg. some sub-path exists, but is a file rather than a directory).
        If 'verbose' is true, print a one-line summary of each mkdir to stdout.
        Return the list of directories actually created.
        """
    
        global _path_created
    
        # Detect a common bug -- name is None
        if not isinstance(name, basestring):
            raise DistutilsInternalError, \
                  "mkpath: 'name' must be a string (got %r)" % (name,)
    
        # XXX what's the better way to handle verbosity? print as we create
        # each directory in the path (the current behaviour), or only announce
        # the creation of the whole path? (quite easy to do the latter since
        # we're not using a recursive algorithm)
    
        name = os.path.normpath(name)
        created_dirs = [] 
        if os.path.isdir(name) or name == '':
            return created_dirs
        if _path_created.get(os.path.abspath(name)):
            return created_dirs
        ...

    Мало того, что метод жив на основании того, что os.makedirs был добавлен только в Python 1.5.2 (мама родная, 2.7 скоро закопаем, а говно всё тянется), так его ещё и умудрились наиндусить на 60 строк кода, да ещё и ХХХ секцию аккуратно положили. Ладно, чего это я придираюсь... Ах да, оно кеширует уже созданные директории, так что если создать папку и удалить её, второй раз её уже никак не создашь...

    frol, 23 Октября 2014

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