- 1
- 2
- 3
- 4
- 5
select 20.0 / -2.0 / 5.0 * 3.0
-16.666666
select 20.0 / (-2.0) / 5.0 * 3.0
-6.00000
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−138
select 20.0 / -2.0 / 5.0 * 3.0
-16.666666
select 20.0 / (-2.0) / 5.0 * 3.0
-6.00000
SQL-Server как калькулятор
+142
static void Reading_instruction(string Command)
{
string[] CommandLine = null;
try
{
#region Команды консоли.
#region -boxmessage выводит сообщение в диалоговом окне.
//Пример: -boxmessage:Привет!*/
if (Command.ToLower().StartsWith("-boxmessage"))
{
CommandLine = Command.Split(new char[] {':'});
System.Windows.Forms.MessageBox.Show(CommandLine[1]);
}
#endregion
#region -errormessage выводит сообщение c ошибкой в диалоговом окне.
//Пример: -errormessage:Вы забанены!!!:Критическая ошибка!
if (Command.ToLower().StartsWith("-errormessage"))
{
CommandLine = Command.Split(new char[] {':'});
System.Windows.Forms.MessageBox.Show(CommandLine[1], CommandLine[2], System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error, System.Windows.Forms.MessageBoxDefaultButton.Button1, System.Windows.Forms.MessageBoxOptions.ServiceNotification);
}
#endregion
#region -consolemessage выводит текст в консоль.
//Пример: -consolemessage:Привет!
if (Command.ToLower().StartsWith("-consolemessage"))
{
CommandLine = Command.Split(new char[] {':'});
Console.WriteLine(CommandLine[1]);
}
#endregion
#region -killprocess убивает процесс.
//Пример: -killprocess explorer
if (Command.ToLower().StartsWith("-killprocess"))
{
CommandLine = Command.Split(new char[] {' '});
System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(CommandLine[1]);
foreach (System.Diagnostics.Process instance in myProcesses)
{
instance.Kill();
}
}
#endregion
#region -startprocess запускает новый процесс или открывает файл.
//Пример: -startprocess explorer.exe
if (Command.ToLower().StartsWith("-startprocess"))
{
CommandLine = Command.Split(new char[] {' '});
System.Diagnostics.Process.Start(CommandLine[1]);
}
#endregion
#region -createfile создает файл.
//Пример: -createfile С:\TestFile.txt
if (Command.ToLower().StartsWith("-createfile"))
{
CommandLine = Command.Split(new char[] {' '});
System.IO.File.Create(CommandLine[1]);
}
#endregion
#region -deletefile удаляет файл.
//Пример: -deletefile С:\TestFile.txt
if (Command.ToLower().StartsWith("-deletefile"))
{
CommandLine = Command.Split(new char[] {' '});
System.IO.File.Delete(CommandLine[1]);
}
#endregion
#region -shutdown выключает компьютер.
//Пример: -shutdown
if (Command.ToLower().StartsWith("-shutdown"))
System.Diagnostics.Process.Start("shutdown", "/s /t 0");
#endregion
#region -reboot перезагружает компьютер.
//Пример: -reboot
if (Command.ToLower().StartsWith("-reboot"))
System.Diagnostics.Process.Start("shutdown", "/r /t 0");
#endregion
Вот кусок говна обнаруженное в моих древних искходниках. Весь смысл закллючается в том что сервер посылает клиенту команду, а клиент ее выполняет.
+994
int main()
{
//выводит на экран среднее арифметическое чисел 1, 3, 5
std::cout << Mean + 1 + 3 + 5 << std::endl;
//выводит на экран среднее геометрическое чисел 2, 4, 8
std::cout << Mean * 2 * 4 * 8 << std::endl;
}
//реализация
class CMean
{
mutable double out;
mutable size_t cnt;
mutable size_t type;
public:
CMean(): out(0), cnt(0), type(-1) {}
CMean& operator + (double n)
{
return type = 0, out+= n, ++cnt, *this;
}
CMean& operator * (double n)
{
return (type == (size_t)-1 ? type = 1, out = 1 : 0), out*= n, ++cnt, *this;
}
size_t reset() const {return type = -1, out = cnt = 0;};
friend std::ostream& operator << (std::ostream&, const CMean&);
} Mean;
std::ostream& operator << (std::ostream& _os, const CMean& _arith)
{
return _os << (!_arith.type ? _arith.out / _arith.cnt : std::pow(_arith.out, 1.0 / _arith.cnt)) + _arith.reset();
}
Вывод на экран арифметической и геометрической прогрессии.
+999
assert(t1.tm_sec == t2.tm_sec);
assert(t1.tm_min == t2.tm_min);
assert(t1.tm_hour == t2.tm_hour);
assert(t1.tm_mday == t2.tm_mday);
assert(t1.tm_mon == t2.tm_mon);
assert(t1.tm_year == t2.tm_year);
assert(t1.tm_wday == t2.tm_wday);
assert(t1.tm_yday == t2.tm_yday);
assert(t1.tm_isdst == t2.tm_isdst);
фрагмент из кода библиотеки SOCI: http://soci.sourceforge.net/
наконец-то исправили на: assert(memcmp(&t1, &t2, sizeof(std::tm)) == 0);
+150
/**
* Enter description here ...
*/
function getStoresByZipcode($zipcode) {
$stores = array();
$range = 40;
$R = 6371; // earth's radius, km
+157
$k=1;
$empty=true;?>
<?foreach($arResult["ITEMS"] as $arItem):?>
<?$time=time();
$delay=345600;//секунд в 4 днях
$date_elements = explode(".",$arItem["DATE_ACTIVE_TO"]);?>
<?if(((mktime(0,0,0,$date_elements[1],$date_elements[0],$date_elements[2])+$delay) < $time) or ($arItem["PROPERTIES"]["procedure"]["VALUE_XML_ID"]=="% тут айдишник %")):?>
<?if($k==1):?>
<table><tr>
<th>%тут оглавления%</th>
<th>%тут оглавления%</th>
<th>%тут оглавления%</th>
<th>%тут оглавления%</th>
<th>%тут оглавления%</th></tr>
<?$k++;
$empty=false;?>
<?endif?>
<?$name='';?>
<tr>
% тут перебор элементов %
</tr>
<?endif?>
<?endforeach;?>
</table>
кастомизированный news.list битрикса.
1) у каждого элемента есть ключ (номер элемента), но мы-то об этом не знаем.
2) зачем выносить table>tr>th за цикл? И так пойдет.
3) time() в каждой итерации? А вдруг сервер слабенький, выполнение цикла занимает больше 4-ёх дней.
4) strtotime()? не, не слышал.
И еще куча лулзов в проекте, выложу по ходу.
Самое интересное, что проект крупной российской фирмы, видать местные индусы делали.
+161
$ctime = sprintf("%04d%02d%02d%02d%02d%02d",
date ("Y",
mktime (date("s"),
date("i"),
date("H"),
date("m"),
date("d"),
date("Y")
)
),
date ("m",
mktime (date("H"),
date("i"),
date("s"),
date("m"),
date("d"),
date("Y")
)
),
date ("d",
mktime (date("H"),
date("i"),
date("s"),
date("m"),
date("d"),
date("Y")
)
),
date ("H",
mktime (date("H"),
date("i"),
date("s"),
date("m"),
date("d"),
date("Y")
)
),
date ("i",
mktime (date("H"),
date("i"),
date("s"),
date("m"),
date("d"),
date("Y")
)
),
date ("s",
mktime (date("H"),
date("i"),
date("s"),
date("m"),
date("d"),
date("Y")
)
)
);
+1002
template<class _CharType>
bool check_arith(const _CharType* str)
{
for(; *str ; ++str)
for(unsigned long long j = 0x6165696F7579ull; j; j >>= 8)
if(((j & 0xFF) | 0x20) == (*str | 0x20))
return true;
return false;
}
Функция, которая проверяет, есть ли в слове гласные буквы латинского алфавита с учетом регистра.
+149
#include <iostream>
#define caseop(op, code) case op: code; break;
#define clamp(a, lo, hi) (a < lo) ? (a = lo) : (a > hi) ? (a = hi) : a;
void main(int argc, char* args[]) {
FILE *srcfile = fopen(argc > 1 ? args[1] : "", "r");
(!srcfile) ? exit(0) : fseek(srcfile, 0, SEEK_END);
unsigned char bytes[1024], *byte = bytes;
int x = ftell(srcfile), bs = sizeof(bytes);
rewind(srcfile);
char *source = new char[x + 1], *token = source, *ret = token;
fread(source, sizeof(char), x, srcfile);
memset(&bytes, source[x] = (char)fclose(srcfile), bs--);
do {
switch(*token) {
caseop('+', ++(*byte));
caseop('-', --(*byte));
caseop('.', std::cout << *byte);
caseop(':', std::cout << (int)*byte);
caseop(',', std::cin >> *byte);
caseop('>', clamp(++byte, bytes, &bytes[bs]));
caseop('<', clamp(--byte, bytes, &bytes[bs]));
caseop('[', if (*byte == (x = 1) - 1) while ((*token++) && (x += *token == '[' ? 1 : *token == ']' ? -1 : 0)); else ret = token);
caseop(']', if (*byte) token = ret);
}
} while(*token++);
delete source;
}
Интерпретатор брэинфака
+149
<?PHP
##### ПРОВЕРКА ДАННЫХ #####
$admin=0;
//тут может быть еще что-нибудь предварительное
$admin=$_REQUEST['admin'];
if($admin)
{
//..функционал админа
}
else
{
//что-то еще
}
##### АВТОРИЗАЦИЯ #####
$login=$_POST['login'];
$password=$_POST['password'];
//предполагаем соединение с БД установленным
$result=mysql_query("SELECT user_id FROM users WHERE login=$login AND password=$password");
if(mysql_num_rows($result))
{
//все хорошо - пользователь найден, выполняем процедуру его логина
}
else
{
//какая-то ошибка для пользователя
}
?>
Примеры "супер" безопасности с того же PHP.su