- 1
- 2
- 3
- 4
- 5
CREATE TRIGGER TR_Table1 ON Table1
INSTEAD OF INSERT
AS
INSERT INTO Table1
SELECT * FROM INSERTED
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−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 //_*)
+6
list* down_if_valid_me(void)
{
return this ? this->down() : NULL;
}
+31
for (int i = 1; i++; i <= 20) {
if (ExecSQL(...) >= 0) {
Ok_rekord=true;
break;
}
if (i == 20) {
if (ExecSQL(...) < 0) {
// показываем сообщение об ошибке
} else {
Ok_rekord=true;
}
}
}
Вот такой вот цикл для повтора при дедлоке...
−148
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
sub get0 { print("get0\n"); return 0; }
sub get2 { print("get2\n"); return 2; }
my ($a, $b) = (1, 1);
$a ? $b = get0() : $b = get2();
print Dumper({
'a' => $a,
'b' => $b,
});
Результат несколько обескураживает :)
http://ideone.com/V60Y1L
+156
private static BigInteger result = 0;
static BigInteger F1 = 1;
static BigInteger F2 = 1;
static BigInteger provv;
static BigInteger provv2;
static void Main(string[] args)
{
for (BigInteger number = 3; result == 0; number++)
{
provv2 = F2;
F2 = F2 + F1;
F1 = provv2; ;
if (HasProperty(F2.ToString()))
result = number;
}
}
private static bool HasProperty(string number)
{
if (number.Length < 9)
return false;
if (IsPandigital(number.Substring(0, 9)))
if (IsPandigital(number.Substring(number.Length - 9, 9)))
return true;
return false;
}
private static bool IsPandigital(string result)
{
int repetitions;
for (int count = 0; count < 9; count++)
{
repetitions = 0;
for (int count2 = 0; count2 < 9; count2++)
{
if (result.ElementAt(count).ToString() == "0")
return false;
if (result.ElementAt(count).ToString() == result.ElementAt(count2).ToString())
{
repetitions++;
if (repetitions == 2)
return false;
}
}
}
return true;
}
http://projecteuler.net/problem=104
http://projecteuler.net/thread=104;page=6
>brute force approach,solved aproximately in 24 hours
>solved aproximately in 24 hours
>24 hours
>24
>hours
Терпеливый, сука!