- 1
- 2
- 3
- 4
- 5
- 6
- 7
if($atributId){
$sql = "UPDATE directory_atributes SET name = '$newName' WHERE id = $atributId LIMIT 1";
$db-> Query($sql);
die();
} else{
die();
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+57
if($atributId){
$sql = "UPDATE directory_atributes SET name = '$newName' WHERE id = $atributId LIMIT 1";
$db-> Query($sql);
die();
} else{
die();
}
Депрессивное программирование. В любом случае ты умрёшь.
+126
double fact(int value)
{
switch (value)
{
case 0:
return 1;
break;
case 1:
return 1;
break;
default:
return value * fact(value - 1);
break;
}
}
Вычисление факториала
+997
Can you think of an algorithm that performs the below:
“The Big Brown Fox” => “Fox Brown Big The”
“How are you?” => “you? are How”
std::string reverse_words( const std::string& str )
{
std::string result;
result.reserve( str.length() );
size_t word_begin = 0;
while( word_begin < str.length() )
{
const size_t pos = str.find_first_of( ' ', word_begin );
pos = (pos != string::npos) ? pos : str.length();
std::string word = str.substr( word_begin, pos-word_begin );
word_begin = pos + 1;
if (result.length() > 0)
{
word.append( 1, ' ');
}
result.insert( 0, word );
}
return result;
}
высрал буквально 5 минут назад
inplace версию чего-то влом писать для домашнего теста, да и кода в ней будет больше, но работать она должна быстрее за счет отсутствия аллокаций
но писать надо, так как отправлять такое как-то стыдно
+997
class fileOutBuf : public streambuf
{
public:
// ...
typedef char char_type;
typedef int int_type;
typedef int streamsize;
// ...
int printf( const char * fpFormat, ... );
inline int vprintf( const char * fpFormat, va_list fvaList )
{
if ( NULL != dpFileDescriptor )
{
if ( true == sdVerboseFlag && false == dSkipVerboseOutput)
vfprintf( dpVerboseFileDescriptor, fpFormat, fvaList );
return vfprintf( dpFileDescriptor, fpFormat, fvaList );
}
else
{
if ( NULL != dpOutputFuncPtr )
return (*dpOutputFuncPtr)( fpFormat, fvaList );
}
return 0;
}
// ....
virtual int_type overflow( int_type c = EOF );
virtual streamsize xsputn( const char_type *s, streamsize n );
// ....
};
int fileOutBuf::printf( const char * fpFormat, ... )
{
va_list lvaList;
int lRet;
va_start( lvaList, fpFormat );
if ( NULL != dpFileDescriptor )
{
if ( true == sdVerboseFlag && false == dSkipVerboseOutput)
vfprintf( dpVerboseFileDescriptor, fpFormat, lvaList );
lRet = vfprintf( dpFileDescriptor, fpFormat, lvaList );
}
else
{
if ( NULL != dpOutputFuncPtr )
lRet = (*dpOutputFuncPtr)( fpFormat, lvaList );
}
va_end( lvaList );
return lRet;
}
fileOutBuf::int_type fileOutBuf::overflow( int_type c )
{
if ( NULL != dpFileDescriptor )
{
if ( true == sdVerboseFlag && false == dSkipVerboseOutput)
fputc( c, dpVerboseFileDescriptor );
return fputc( c, dpFileDescriptor );
}
else
return fileOutBuf::printf( "%c", c );
}
fileOutBuf::streamsize fileOutBuf::xsputn( const fileOutBuf::char_type *s, fileOutBuf::streamsize n )
{
if ( NULL != dpFileDescriptor )
{
if ( true == sdVerboseFlag && false == dSkipVerboseOutput)
fwrite( s, sizeof( char_type ), n, dpVerboseFileDescriptor );
return fwrite( s, sizeof( char_type ), n, dpFileDescriptor );
}
else
return fileOutBuf::printf( "%*s", n, s );
}
нетривиальная капипаста или делаем из мухи слона.
ЗЫ после удаления всей капипасты, от класа в целом осталось что-то около 50 строк.
+170
private function _________close ($param_name)
private function __________open ($param_name)
"это для того чтобы видно было в коде"
−106
if (_start > _end) _start = _end;
if (_end < _start) _end = _start;
c пламенным приветом = )
+154
class Allocator
{
public:
virtual void *Alloc (size_t) = 0;
virtual void Dealloc (void *) = 0;
struct Allocation
{
Allocator *m_pAllocator[1];
static void Dealloc (void *ptr)
{
if (ptr)
((Allocator **)ptr)[-1]->Dealloc (((Allocator **)ptr)-1);
}
};
};
class UsesAllocator
{
public:
void *operator new (size_t aSize,Allocator &aAllocator)
{
Allocator::Allocation *pResult =
(Allocator::Allocation *)
aAllocator.Alloc (aSize+sizeof (Allocator::Allocation));
if (!pResult) throw std::bad_alloc ();
pResult->m_pAllocator[0] = &aAllocator;
return pResult->m_pAllocator+1;
}
void *operator new [] (size_t aSize,Allocator &aAllocator)
{
Allocator::Allocation *pResult =
(Allocator::Allocation *)
aAllocator.Alloc (aSize+sizeof (Allocator::Allocation));
if (!pResult) throw std::bad_alloc ();
pResult->m_pAllocator[0] = &aAllocator;
return pResult->m_pAllocator+1;
}
void operator delete (void *ptr,Allocator &)
{ Allocator::Allocation::Dealloc (ptr); }
void operator delete (void *ptr)
{ Allocator::Allocation::Dealloc (ptr); }
void operator delete [] (void *ptr,Allocator &)
{ Allocator::Allocation::Dealloc (ptr); }
void operator delete [] (void *ptr)
{ Allocator::Allocation::Dealloc (ptr); }
};
...
class MyClass: /*virtual*/ public UsesAllocator
{
public:
...
};
...
MyClass *PROFIT = new (allocatorOfOurInterest) MyClass (...);
http://www.gamedev.ru/flame/forum/?id=153274+156
(function () {
var backgroundPosition = getComputedStyle(document.querySelector('a.comment-vote-on')).backgroundPosition;
Array.prototype.forEach.call(
document.querySelectorAll('span.comment-vote-on'),
function (element) {
element.style.backgroundPosition = backgroundPosition;
}
);
})()
По просьбам телезрителей публикуется букмарклет невинности,
который избавляет от необходимости фотошопить скриншот для иллюстрации заявлений типа "Это не я мину совал!".
Я ленив, поэтому говнокод тоже присутствует.
+168
function WikiExtractArticleUrl($str) { // Декодирование кирилицы из урла
ErrorsOff(); // отключаем вывод ошибок нашего обработчика, дабы iconv не сорил
try { // пытаемся с помощью iconv перекодировать кирилицу из утф8 в сп1251, подсунув декодированную кирилицу (из %12%%2D и т.д.)
$text = iconv('UTF-8', 'CP1251', rawurldecode($str));
throw new Exception(''); // создаем новое исключение, дабы похапэ отстал от нас
} catch(Exception $e) { // ловим ошибку iconv, типа перекодировать не надо
$text = urldecode($str); // тупо декодируем
}
ErrorsOn(); // выключаем ошибки и возвращаем результ
return $text;
}
Функция для получения крилицы из ЧПУ урла (сайт в кодировке win1251).
+154
include "./include/db.conf.php";
$con = mysql_connect($DB["host"],$DB["user"],$DB["pass"]) or die ("could not connect:".mysql_error());
mysql_set_charset('utf8');
mysql_select_db($DB["dbName"]) or die ("could not connect:".mysql_error());
$hash = $_GET['hash'];
$login = $_GET['login'];
echo "SELECT id FROM reg WHERE log = '".$login."' AND hash = '".$hash."'";
$query = mysql_query("SELECT id FROM reg WHERE log = '".$login."' AND hash = '".$hash."'") or die ("MYSQL error".mysql_error());
if ($query) {
while($row = mysql_fetch_array($query)) {
echo row['id'];}
$query = mysql_query("UPDATE reg SET commit=1 WHERE id=".row['id'])
or die ("MYSQL error".mysql_error());}
Знакомая поделилась шедевром. Так, конечно, можно... но в общем комментарии излишни.
Да, форматирование оригинала сохранено.