- 1
- 2
- 3
- 4
- 5
- 6
CharT getline(std::istream& i, string& s, const CharT* delim) {
...
if (!i.operator void*())
break;
...
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+2
CharT getline(std::istream& i, string& s, const CharT* delim) {
...
if (!i.operator void*())
break;
...
}
Библиотека Apache UIMA-CPP.
Что могло заставить написать так, вместо обычного if (i)? Какой-то древний компилятор, который не использует каст к указателю в условии?
Ну и, разумеется, в C++11 ios::operator void*() заменили на explicit ios::operator bool(), так что работать перестало.
+8
public TD GetColumn(int i) {
try {
return this.Columns[i];
} catch {
return this.Columns[i - 1];
}
}
в продолжение парсера
−126
def price_request(self, response):
# ебануцо
t = TakeFirst()
magic_data = {'__ASYNCPOST': 'true'}
# --- забираю зашитые данные из форм
keys = [
'__BOOKMARKERbmTabs',
'__VIEWSTATE',
'__VIEWSTATEGENERATOR',
'__EVENTVALIDATION',
'HiddenField'
]
for k in keys:
val = response.xpath('//input[contains(@id, "%s")]/@value' % k).extract()
key = response.xpath('//input[contains(@id, "%s")]/@name' % k).extract()
if key:
magic_data[t(key)] = t(val) or ''
val = response.xpath('//input[contains(@value, "btnGetPrice")]/@value').extract()
key = response.xpath('//input[contains(@value, "btnGetPrice")]/@name').extract()
if key:
magic_data[t(key)] = t(val) or ''
# --- неведомая херня из js
# вызов получения цены
js = response.xpath(u'//script[contains(text(), "$(document).ready(function ()")][contains(text(), "__doPostBack")]').re(
"__doPostBack\('([^']+)','([^']*)'\)")
# [\$\w0]+btnGetPrice
magic_data['__EVENTTARGET'] = js[0]
# обычно ''
magic_data['__EVENTARGUMENT'] = js[1]
# ключ от сервера, скорее всего он связан с сессией
js = response.xpath(u'//script[contains(text(), "Sys.Application.setServerId")]').re('\("([^"]+)", "([^"]*)"\)')
super_magic_key = js[1]
# --- опять данные из формы которые туда должны при ините странице соваться
js = response.xpath(u'//script[contains(text(), "Sys.WebForms.PageRequestManager._initialize")]').re("'form1', \[([^\]]+)\]")[0]
super_magic_values = re.findall("'([^']+)'", js)
super_magic_value_1 = super_magic_values[0]
for m in super_magic_values[1:len(super_magic_values)]:
if m:
magic_data[m] = ''
# хер его знает почему, но первую букву надо откусить, обычно это t
super_magic_value1 = super_magic_value_1[1:len(super_magic_value_1)]
# составное значение вида [\$\w0]+=[\$\w0]+$updPrice|[\$\w0]+btnGetPrice
magic_data[super_magic_key] = super_magic_value1 + '|' + magic_data['__EVENTTARGET']
return FormRequest(url=response.url,
formdata=magic_data,
dont_filter=True,
meta=response.meta,
callback=self.parse_price,
method='post',
headers={'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest',
'X-MicrosoftAjax': 'Delta=true',
'Origin': 'http://www.exist.ru',
'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate',
'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; en-gb) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27'
})
То что случается если жалко ресурсов на запуск js при парсинге )
−119
import inspect
def phpformat(fmt):
return fmt.format(**inspect.getouterframes(inspect.currentframe())[1][0].f_locals)
surname = "Бонд"
name = "Джеймс"
num = 7
print(phpformat("{surname}. {name} {surname}. Агент {num:03d}."))
PHP'шная интерполяция строк теперь и в питоне.
Родилось в http://govnokod.ru/18147#comment285697
−170
CREATE TRIGGER TR_Table1 ON Table1
INSTEAD OF INSERT
AS
INSERT INTO Table1
SELECT * FROM INSERTED
Диалект MS SQL
INSTEAD OF INSERT - триггер, отменяющий вставку и передающий список значений, указанных в запросе в псевдотаблице INSERTED.
т.е. автор вместо того чтобы позволить северу вставлять строк решил каждый раз вставлять их лично.
+144
#include <stdio.h>
int main(void)
{
puts("1\n3\n5\n7\n9\n11\n13\n15\n17\n19\n21\n23\n25\n27\n29\n31\n33\n35\n37\n39\n41\n43\n45\n47\n49\n51\n53\n55\n57\n59\n61\n63\n65\n67\n69\n71\n73\n75\n77\n79\n81\n83\n85\n87\n89\n91\n93\n95\n97\n99");
return 0;
}
Выводим все нечетные числа от 0 до 100. Одно число - одна строка.
−117
class DictOfLists(defaultdict): # it's possible to use dict instead
def __init__(self, *args, **kwds):
__args=self.__check_args(*args)
self.__check_kwds(**kwds)
defaultdict.__init__(self,(lambda:[]), *__args, **kwds)
# dict.__init__(self, *__args, **kwds)
def __is_valid_item(self,item):
if len(item)==2 and not hasattr(item[0],"__iter__") and hasattr(item[1],"__iter__"):
return True
return False
def __check_args(self,*args):
if len(args)>1:
if type(args) == tuple and self.__is_valid_item(args):
return [args,] # tuple of key and list of values
else:
raise TypeError("Item of %s must be a tuple of (key,IterableValue) but %s=%s is not"%\
(self.__class__.__name__,
args.__class__.__name__,
repr(args)))
if len(args) != 1: return args
if isinstance(args[0], DictOfLists): return args
if hasattr(args[0],"__iter__"):
if len(args[0]) == 0: return args # empty iterator
items = args[0].items() if type(args[0]) == dict else args[0]
if self.__is_valid_item(items):
return [args,] # tuple of key and list of values
for v in items:
if not (type(v) == tuple and len(v)==2):
raise TypeError("Item of %s must be a tuple of (key, IterableValue) but %s=%s is not"%\
(self.__class__.__name__,
v.__class__.__name__,
v))
if not hasattr(v[1],"__iter__"):
raise TypeError("Value of %s must be iterable but %s(%s) is not"%\
(self.__class__.__name__,
v[1].__class__.__name__,
repr(v[1])))
else: raise TypeError(" %s must be initialized by {},[],() or %s but %s is not"%\
(self.__class__.__name__,
self.__class__.__name__,
args[0].__class__.__name__))
return args
def __check_kwds(self, **kwds):
for v in kwds.itervalues():
if not hasattr(v,"__iter__"):
raise TypeError("Value of %s must be iterable but %s(%s) is not"%\
(self.__class__.__name__,
v.__class__.__name__,
repr(v)))
def walk(self):
for k, v in self.iteritems():
for x in v:
yield k, v, x
raise StopIteration
def __setitem__(self, *args, **kwargs):
self.__check_args(*args)
self.__check_kwds(**kwargs)
return dict.__setitem__(self, *args, **kwargs)
def update(self, *args, **kwds):
_args=self.__check_args(*args)
self.__check_kwds(**kwds)
dict.update(self,*_args, **kwds)
correct = [ {}, [], (), # empty iterable
{'k2':[], 'k22':[]}, # multipe items dict
[('k3',[]),('k32',[])], # array tuples key list val
(('k4',[]),('k42',[])), # tuple of tuples key list val
('k5',[]) # tuple of key list val
]
strange = [('e0','12'), ('e1','123')]
import inspect
def init_tester(dict_class,t_array,cs):
print "\n%s %s %s"%( inspect.currentframe().f_code.co_name, dict_class().__class__.__name__, cs )
for i in t_array:
try:
print repr(i).ljust(26), repr(dict_class(i)).ljust(74),
print ' work '.ljust(8)
except Exception,e:
print "dosn't work ",
print e
continue
print "------------------------------"
if __name__ == '__main__':
init_tester( DictOfLists, correct, "correct")
init_tester( dict, correct, "correct")
init_tester( DictOfLists, strange, "strange")
init_tester( dict, strange, "strange")
Вот такой вот словарь, значениями элементов которого могут быть только списки. В принципе легко его доделать, чтобы знаечениями были все iterable, но не строки. Кроме этого, он внимательнее проверяет агрументы. Например если ему послать ('k5',[]), он воспримет это как: k5 - key, [] - value. Build-in dict например воспринимает ('12','34') как 1 - key, 2 - value, 3 - key, 4 - value. Соответственно если ему послать ('12','345'), он ругнется. Мне показалось, что это немного странное поведение, трактовать 2-х символьные строки, как key-value. Покритикуйте please. В том числе "стиль" и "красоту".
+155
<? if($sess_gr==1||$sess_gr==7||$sess_gr==11||$sess_gr==2||$sess_gr==3){?>
<? if($sess_gr==1||$sess_gr==7||$sess_gr==11||$sess_gr==2||$sess_gr==3){?><td rowspan="2"></td><?}?><td rowspan="2"></td>
<? }?>
Контрольный IF, на случай, если PHP с первого раза не понял
+138
if ("A" == Key.ToUpper().Substring(startIndex, 1))
num = 11L;
else if ("B" == Key.ToUpper().Substring(startIndex, 1))
num = 12L;
else if ("C" == Key.ToUpper().Substring(startIndex, 1))
num = 13L;
else if ("D" == Key.ToUpper().Substring(startIndex, 1))
num = 14L;
else if ("E" == Key.ToUpper().Substring(startIndex, 1))
num = 15L;
else if ("F" == Key.ToUpper().Substring(startIndex, 1))
num = 16L;
else if ("0" == Key.ToUpper().Substring(startIndex, 1))
num = 0L;
else if ("1" == Key.ToUpper().Substring(startIndex, 1))
num = 1L;
else if ("2" == Key.ToUpper().Substring(startIndex, 1))
num = 2L;
else if ("3" == Key.ToUpper().Substring(startIndex, 1))
num = 3L;
else if ("4" == Key.ToUpper().Substring(startIndex, 1))
num = 4L;
else if ("5" == Key.ToUpper().Substring(startIndex, 1))
num = 5L;
else if ("6" == Key.ToUpper().Substring(startIndex, 1))
num = 6L;
else if ("7" == Key.ToUpper().Substring(startIndex, 1))
num = 7L;
else if ("8" == Key.ToUpper().Substring(startIndex, 1))
num = 8L;
else if ("9" == Key.ToUpper().Substring(startIndex, 1))
{
num = 9L;
}
Программист, писавший ЭТО считал себя очень большим талантом и был даже тех.диром, пока не уволили....))
+116
string pattern = @"\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?";
Регулярка для IP //_*)