- 1
name = name.replace(u'c', u'с') # this is magia
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
Всего: 128
−118
name = name.replace(u'c', u'с') # this is magia
−116
df[df['reason']=='in-in error sequence']['spider'].value_counts().to_csv('spiders_out-out-seq.csv')
Страшно?
−115
def _make_parser_function(name, sep=','):
def parser_f(filepath_or_buffer,
sep=sep,
dialect=None,
compression=None,
doublequote=True,
escapechar=None,
quotechar='"',
quoting=csv.QUOTE_MINIMAL,
skipinitialspace=False,
lineterminator=None,
header='infer',
index_col=None,
names=None,
prefix=None,
skiprows=None,
skipfooter=None,
skip_footer=0,
na_values=None,
na_fvalues=None,
true_values=None,
false_values=None,
delimiter=None,
converters=None,
dtype=None,
usecols=None,
engine='c',
delim_whitespace=False,
as_recarray=False,
na_filter=True,
compact_ints=False,
use_unsigned=False,
low_memory=_c_parser_defaults['low_memory'],
buffer_lines=None,
warn_bad_lines=True,
error_bad_lines=True,
keep_default_na=True,
thousands=None,
comment=None,
decimal=b'.',
parse_dates=False,
keep_date_col=False,
dayfirst=False,
date_parser=None,
memory_map=False,
nrows=None,
iterator=False,
chunksize=None,
verbose=False,
encoding=None,
squeeze=False,
mangle_dupe_cols=True,
tupleize_cols=True,
):
# Alias sep -> delimiter.
if delimiter is None:
delimiter = sep
kwds = dict(delimiter=delimiter,
engine=engine,
dialect=dialect,
compression=compression,
doublequote=doublequote,
escapechar=escapechar,
quotechar=quotechar,
quoting=quoting,
skipinitialspace=skipinitialspace,
lineterminator=lineterminator,
header=header,
index_col=index_col,
names=names,
prefix=prefix,
skiprows=skiprows,
na_values=na_values,
na_fvalues=na_fvalues,
true_values=true_values,
false_values=false_values,
keep_default_na=keep_default_na,
thousands=thousands,
comment=comment,
decimal=decimal,
parse_dates=parse_dates,
keep_date_col=keep_date_col,
dayfirst=dayfirst,
date_parser=date_parser,
nrows=nrows,
iterator=iterator, ....
На самом деле оно в общем не такое уж и страшное потому что в питоне можно по имени аргументы в метод, но флешер в мне нервно икнул
+135
<html class=" js flexbox flexboxlegacy hashchange history rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity flash no-touch no-opera cssanimations csscolumns cssgradients no-cssreflections csstransforms csstransforms3d csstransitions fontface generatedcontent video audio localstorage applicationcache performance mediaqueries" lang="ru-RU" xml:lang="ru-RU" style="">
−97
//на фрагмент ролика
s130.addEventListener(MouseEvent.MOUSE_DOWN, fs130);
function fs130(event:MouseEvent):void
{
s130.startDrag();
}
stage.addEventListener(MouseEvent.MOUSE_UP, fs1302);
function fs1302(event:MouseEvent):void
{
s130.stopDrag();
}
//на кнопку
prov30.addEventListener(MouseEvent.CLICK, fprov30);
function fprov30(event:MouseEvent):void
{
if ((Math.abs(s130.x-zon330.x) < (zon330.width/2-s130.width/2))&&(Math.abs(s130.y-zon330.y) < (zon330.height/2-s130.height/2)))
{
t30.text = "Верно!";
}
else
{
t30.text = "Неверно!";
}
}
Это то чем собираются учить детей. Пример кода.
−113
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)
Еще немного магии и хватит на сегодня.
−115
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'])))
Пхп и даты, только питон
−99
@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 можно...
−102
obj['query'] = urllib.unquote(str(obj['meta']['search_words'].decode('utf-8'))).decode('utf-8')
−99
def str_to_weight(val, format_str_max, format_str_min=None, separator=u",", long=3):
"""
%fgr (full gr) %cgr (cut gr) %kg
example
>>> str_to_weight('0.120', u'%kg%fgr kg', u'%kg%fgr kg', ',', 3)
u'0,120 kg'
>>> str_to_weight('0.120', u'%kg%fgr kg', u'%fgr gr', ',', 3)
u'120 gr'
>>> str_to_weight('0.120', u'%kg%fgr kg', u'%cgr gr', ',', 3)
u'12 gr'
"""
if isinstance(val, basestring):
try:
num = float(val.replace(',', '.'))
except ValueError:
return None
elif isinstance(val, float):
num = val
else:
return None
format_str = format_str_min if num < 1 and format_str_min else format_str_max
kg = u'%.f' % int(num)
fgr = re.sub(u'^\d+.', u'', (u'%.' + str(long) + u'f') % num)
if num < 1:
fgr = re.sub('^0+', '', fgr)
cgr = re.sub(u'0+$', u'', fgr)
if fgr and '%kg' in format_str:
fgr = separator + fgr
if cgr and '%kg' in format_str:
cgr = separator + cgr
return format_str.replace(u'%fgr', fgr).replace(u'%cgr', cgr).replace(u'%kg', kg)
def create_ru_weight_patterns(weight):
res = [
str_to_weight(weight, u'^%kg%cgr.?кг|%kg%cgr.?л', u'^%fgr.?г|%fgr.?мл', separator=u'[\.|,]'),
str_to_weight(weight, u'[ |\t|\n]%kg%cgr.?кг|%kg%cgr.?л', u'[ |\t|\n]%fgr.?г|%fgr.?мл', separator=u'[\.|,]'),
str_to_weight(weight, u'%kg%cgr.?кг|%kg%cgr.?л', u'%fgr.?г|%fgr.?мл', separator=u'[\.|,]'),
str_to_weight(weight, u'%kg%cgr.?кг|%kg%cgr.?л', separator=u'[\.|,]')
]
return filter(lambda x: x, res)
Чо айдишники, есть вес, я легко его найду в товаре
Через месяц...