- 1
- 2
- 3
- 4
- 5
- 6
/**
* TODO Document HelloWorld
* <p />
*
* @author Vinod.Jayakumar
*/
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+146
/**
* TODO Document HelloWorld
* <p />
*
* @author Vinod.Jayakumar
*/
Если тебя, любознательный читатель, заинтересовала валидность такого тега, то, чтобы облегчить тебе поиски:
http://www.w3.org/TR/html4/struct/text.html#edef-P
> We discourage authors from using empty P elements. User agents should ignore empty P elements.
+167
#include <windows.h>
struct io
{
io()
{
SetConsoleTitle(__FUNCSIG__);
}
~io()
{
DebugBreak();
}
} io_obj;
int main()
{
}
typedef void(fn_t)();
#pragma comment(linker, "/merge:.CRT=.rdata")
#pragma data_seg(".CRT$XCA")
extern "C" fn_t * start[] = {0};
#pragma data_seg(".CRT$XCZ")
extern "C" fn_t * finish[] = {0};
#pragma data_seg()
void call_dtors();
extern "C" void _initterm()
{
fn_t **p = start, **q = finish;
while (p < q)
{
if (*p)
(*p)();
++p;
}
main();
call_dtors();
}
fn_t * dtors[999];
int c_dtors;
void call_dtors()
{
while (c_dtors--)
dtors[c_dtors]();
}
extern "C" int atexit(void (__cdecl *func )( void ))
{
dtors[c_dtors++] = func;
return !"unspecified";
}
если клепаем что то без CRT и хотим чтоб вызывались
конструкторы деструкторы статических объектов и хотим свое то
вот реализация для тех кто этого еще неделал
https://wasm.ru/forum/viewtopic.php?pid=428250#p428250
+165
//
// Занимательное программирование C++
// С.Симонович, Г.Евсеев, 2001
//
// Глава 12. Программа учится сочинять
//
void __fastcall TForm1::FormCreate
(TObject *Sender)
{
randomize();
ComboBox1->ItemIndex = 0;
ComboBox2->ItemIndex = 0;
ComboBox3->ItemIndex = 0;
}
void __fastcall TForm1::Button1Click
(TObject *Sender)
{
ComboBox1->ItemIndex =
random(ComboBox1->Items->Count);
ComboBox2->ItemIndex =
random(ComboBox2->Items->Count);
ComboBox3->ItemIndex =
random(ComboBox3->Items->Count);
}
Это моя первая книгка по Си++
печалько... тт
+149
//
// mainwindow.h
//
#ifndef MAINMDIWINDOW_H
#define MAINMDIWINDOW_H
/* >:0 Эти инклюды хуже, чем говно, чуть менее, чем полностью */
#include <QMainWindow>
#include <QMdiArea>
#include <QMenu>
#include <QAction>
#include <QMenuBar>
#include <QWebView>
#include <QFile>
#include <QSignalMapper>
#include <QDebug>
#include <QDomDocument>
#include <QToolBar>
#include <QButtonGroup>
#include <QLabel>
#include <QMdiSubWindow>
#include <QApplication>
#include "demoviewer.h"
#include "theoryviewer.h"
class MainMDIWindow : public QMainWindow
{ Q_OBJECT
public:
/* >:0 Кэп?! */
//! Выполняет создание и инициализацию окна приложения.
explicit MainMDIWindow(QWidget *parent = 0);
signals:
public slots:
/* >:0 А ты догадался, что значат эти аргументы? */
void openDocument(int); void loadPage(int);
/* >:0 Это невероятно полезные функции */
void toggleTheoryWindow(bool state) { tw->setVisible(state); }
void toggleDemoWindow(bool state) { dw->setVisible(state); }
protected:
/* >:0 Это на винде не работало, я просто закомментировал.
Вероятно, правильнее было бы воспользоваться средствами сборки под разные платформы,
но я невозбранно комметирую-раскомментирую эту строчку каждый раз при сборке */
inline void paintEvent(QPaintEvent *e)
{ // mdiArea->setBackground(QBrush(QImage(":/images/photo/s200.jpg").scaled(this->size(), Qt::KeepAspectRatioByExpanding)));
e->accept();
}
// ...
/* >:0 ЭтаПять! См. тело конструктора */
QString AppWindowTitle;
// Просмотровщики материала
DemoViewer * dv; QMdiSubWindow* dw;
TheoryViewer* tv; QMdiSubWindow* tw;
bool lockTheory, lockDemo;
// Хранение информации о документах
/* >:0 За такое я впредь обещаю безжалостно резать яйца. Даже себе. */
QVector< QVector< QHash< QString, QString > > > documents;
QVector< QHash< QString, QString > > *currentDocument;
// ...
};
#endif // MAINMDIWINDOW_H
//
// mainwindow.cpp
// Далее следуют отдельные вырезки
//
#include "mainmdiwindow.h"
MainMDIWindow::MainMDIWindow(QWidget *parent) : QMainWindow(parent)
{ /* >:0 Вот зачем нам понадобился атрибут QString AppWindowTitle! */
AppWindowTitle = tr("ЦВМ «Пламя-КВ» ЗРК С-200ВЭ");
setWindowTitle(AppWindowTitle);
// ...
// Инициализация окон просмотровщиков
/* >:0 Вы меня понимаете, не? хД */
tv = new TheoryViewer(); tw = mdiArea->addSubWindow(tv); tw->hide(); tv->setParent(tw); lockTheory = true;
dv = new DemoViewer(); dw = mdiArea->addSubWindow(dv); dw->hide(); dv->setParent(dw); lockDemo = true;
// ...
}
void MainMDIWindow::openDocument(int id)
{ // ...
/* >:0 Нижеследующая конструкция читает HTML файл в UTF-8,
заменяет пути на абсолютные и запихвает получивуюся какуху в QWebView */
QFile in(textLink); bool t = in.open(QIODevice::ReadOnly | QIODevice::Text);
tv->setHtml(QString::fromUtf8(in.readAll()).replace(QString("./"), QApplication::applicationDirPath() + '/'));
in.close();
// ...
}
ИМХО, это МЕГОКОД. И я обещаю больше так никогда не делать ^^
Вбросы говн в потоковых комментариях, начинающихся с православного смайла >:0
+177
// Задача "Сложный XOR", олимпиада ACM контестер Украина.
// Есть множество натуральных чисел от 0 до N. Играют двое игроков. Сначала один убирает из множества число,
// потом второй. Если в множестве есть (осталось) число, равное побитовому XOR двух выбранных чисел, убирают
// и его (в условии задачи битность числа не указана, но сказано, что 1 <= N <= 32). Играют пока в множестве
// есть числа. Проигрывает тот, который не может совершить ход (на ком кончились числа).
// Ввод - число N, вывод - игрок, который выиграл (оба игрока придерживаются выгодной стратегии).
#include <iostream>
#include <time.h>
using namespace std;
int main() {
int n;
cin >> n;
// Это очевидно
if (n==1) {
cout << "First";
return 0;
}
if (n==2) {
cout << "Second";
return 0;
}
// Это было в примере
if (n==3) {
cout << "First";
return 0;
}
int s = clock() % 2; // rand() не работал чето :)
if (s==0) {
cout << "First";
} else {
cout << "Second";
}
return 0;
}
Говноолимпиадам - говнорешения!
Скажете, зачем такое постить, это не говнокод... Фишка в том, что это незамысловатое решение *правильно прошло все тесты с первого раза!* :D
−112
this.iconSrc = iconSrc != '' ? iconSrc : iconSrc;
Очевидно, когда-то это было проверкой на пустую ссылку на картинку.
+126
g.Graphics.DrawLine( p, this.pb.Width / 2 + 126, this.pb.Height / 2 + 176, this.pb.Width / 2 + 126, this.pb.Height / 2 + 176 + 20 );
g.Graphics.DrawLine( p, this.pb.Width / 2 - 126, this.pb.Height / 2 + 176, this.pb.Width / 2 - 126, this.pb.Height / 2 + 176 + 20 );
g.Graphics.DrawLine( new Pen( Color.Black ), this.pb.Width / 2 - 126, this.pb.Height / 2 + 176 + 20, this.pb.Width / 2 + 126, this.pb.Height / 2 + 176 + 20 );
g.Graphics.DrawLine( new Pen( Color.Black ), this.pb.Width / 2 - 126, this.pb.Height / 2 + 176 + 20, this.pb.Width / 2 - 126 + 8, this.pb.Height / 2 + 176 + 15 );
g.Graphics.DrawLine( new Pen( Color.Black ), this.pb.Width / 2 - 126, this.pb.Height / 2 + 176 + 20, this.pb.Width / 2 - 126 + 8, this.pb.Height / 2 + 176 + 25 );
g.Graphics.DrawLine( new Pen( Color.Black ), this.pb.Width / 2 + 126, this.pb.Height / 2 + 176 + 20, this.pb.Width / 2 + 126 - 8, this.pb.Height / 2 + 176 + 15 );
g.Graphics.DrawLine( new Pen( Color.Black ), this.pb.Width / 2 + 126, this.pb.Height / 2 + 176 + 20, this.pb.Width / 2 + 126 - 8, this.pb.Height / 2 + 176 + 25 );
g.Graphics.FillRectangle( Brushes.White, this.pb.Width / 2 - 25, this.pb.Height / 2 + 176 + 10, 50, 20 );
g.Graphics.DrawString( this.textBox1.Text + " mm", new Font( "Arial", 8 ), new SolidBrush( Color.Black ), this.pb.Width / 2 - 21, this.pb.Height / 2 + 176 + 12 );
g.Graphics.DrawLine( new Pen( Color.Black ), this.pb.Width / 2 - (int)paint_nozh_fill / 2, this.pb.Height / 2, this.pb.Width / 2 + (int)paint_nozh_fill / 2, this.pb.Height / 2 );
g.Graphics.DrawLine( new Pen( Color.Black ), this.pb.Width / 2 - (int)paint_nozh_fill / 2, this.pb.Height / 2, this.pb.Width / 2 - (int)paint_nozh_fill / 2 + 8, this.pb.Height / 2 - 5 );
g.Graphics.DrawLine( new Pen( Color.Black ), this.pb.Width / 2 - (int)paint_nozh_fill / 2, this.pb.Height / 2, this.pb.Width / 2 - (int)paint_nozh_fill / 2 + 8, this.pb.Height / 2 + 5 );
g.Graphics.DrawLine( new Pen( Color.Black ), this.pb.Width / 2 + (int)paint_nozh_fill / 2, this.pb.Height / 2, this.pb.Width / 2 + (int)paint_nozh_fill / 2 - 8, this.pb.Height / 2 - 5 );
g.Graphics.DrawLine( new Pen( Color.Black ), this.pb.Width / 2 + (int)paint_nozh_fill / 2, this.pb.Height / 2, this.pb.Width / 2 + (int)paint_nozh_fill / 2 - 8, this.pb.Height / 2 + 5 );
g.Graphics.FillRectangle( Brushes.White, this.pb.Width / 2 - 25, this.pb.Height / 2 - 10, 50, 20 );
g.Graphics.DrawString( this.getNozhFill( ).ToString( ) + " mm", new Font( "Arial", 8 ), new SolidBrush( Color.Black ), this.pb.Width / 2 - 21, this.pb.Height / 2 - 8 );
Человек похоже перепутал визул студию с фотошопом, но закрывать не стал )) Этот код рисует чертеж - примем со стрелочками, с откосами и даже(!) с отбрасывает тень. Понятия не имею как преписывать
+145
//Determine padding for use in allocating new memory
int padding = 0;
while ( (width * 3 + padding) % 4 != 0) padding++;
http://www.cplusplus.com/forum/windows/6353/
Ещё одна история о том, как людям не дано запомнить двоичную природу данных.
Если что, вот корректный шаблон на D:
int packed(int alignment)(int location) {
static assert(alignment == 2 | alignment == 4 | alignment == 8);
const badEnd = alignment - 1; //0b11, 0b111, 0b1111
return location & badEnd ? (location & ~badEnd) + alignment : location;
}
+161
function is_url($url) {
if(preg_match("/\./", $url) && preg_match("/http:\/\//i", $url) && preg_match("/.txt$/i", $url) && preg_match("/\//", str_replace("http://" , "", $url))) return 1;
else return 0; }
function check_value($value) {
if (!is_numeric($value) || $value>20 || $value<1) die ('Количество не число или число учеток превышает 20. Ну, или меньше 1.<br><a href="' . $_SERVER['PHP_SELF'] . '?act=mass">Назад</a>'); }
function regnloc() {
$get = reg();
header("Location: http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . "?" . $get); }
switch ($_GET['act']) {
case 'reg':
regnloc();
break;
case 'mass':
// http://govnokod.ru/6376
break;
case 'file':
if (!$_POST['get']) die ('Отсутствуют данные для записи'.$href);
$content = "Сгенерировано ".date("d.m.y H:i:s")."\n";
if ($_POST['link']) $content .= "Логины взяты по ссылке: ".$_POST['link']."\n";
$content .= $_POST['get'];
file_put_contents('download.txt', $content);
header("Location: download.txt");
break;
default:
if (($_GET['login']) && ($_GET['pass'])) echo $_GET['login'].' - '.$_GET["pass"].'<br><a href="http://сайт.ru/user/search/?a='.rand(1000, 9999).'&age0=&age1=&sex=0&ll=0&online=0&sort=0&login='.$_GET['login'].'" target="_blank">Полюбоваться</a><br><br>';
view_form("?act=reg");
echo '</form><a href="' . $_SERVER['PHP_SELF'] . '?act=mass">Массовая рега</a>'; }
Вариации на тему http://www.snippy.ru/snippet/213/ (http://govnokod.ru/5597)
Вдогонку к предыдущему.
Это - регистратор учетных записей на одной известной мобильной социальность сети.
Что поразительно - спустя полтора года это до сих пор работает.
Бонусом еще немного содомии.
И, да-да, внимательные читатели могли заметить еще в 6376 parse_str(reg()).
reg() возвращает результаты строкой вида return "login=$login&pass=$pass";
+158
case 'mass':
$href = '<br><a href="' . $_SERVER['PHP_SELF'] . '?act=mass">Назад</a>';
if ($_GET['step']) {
if (($_POST['step']) && ($_POST['link'])) die ('Пожалуйста, введите только что-то одно - кол-во или ссылку'.$href);
if ((!$_POST['step']) && (!$_POST['link']) && ($_GET['step'] == 1)) {
if ($_POST['code']) regnloc();
die ('Пожалуйста, введите что-нибудь - кол-во или ссылку'.$href);}
if ($_POST['step']) $mode = 'steps';
if ($_POST['link']) $mode = 'link';
if ($_GET['mode']) $mode = $_GET['mode'];
if (!$mode) die ('Привет юным хакерам!'.$href);
check_value($_GET['step']);
$step = $_GET['step'];
if ($mode == 'steps') {
if ($_POST['step']) {
check_value($_POST['step']);
$end = $_POST['step']; }
else {
check_value($_GET['end']);
$end = $_GET['end'];}
parse_str(reg());
$get = "$login - $pass\n".$_POST['get']; }
if ($mode == 'link') {
if (is_url($_POST['link'])) {
$strings = file($_POST['link']);
$end = count($strings);
check_value($end);
$arrstep = $step - 1;
if (strlen(trim($strings[$arrstep])) <= 15) { parse_str(reg(trim($strings[$arrstep])));
$get = "$login - $pass\n".$_POST['get']; }
else { $error = 1; $get = $_POST['get']; }}
else { die ('Ссылка неверна или указывает не на .txt файл'.$href);} }
$step++;
if ($step <= $end) {
if ($error) echo '<div style="color:red;">Предыдущая учетка не была зарегана - ник более 15-ти символов</div><br>';
echo "Учетка $step из $end<br>";
view_form("?act=mass&mode=$mode&step=$step&end=$end"); }
else {
echo '<b>Завершено!</b><br><a href="' . $_SERVER['PHP_SELF'] . '?act=mass">Повторить</a><br><br><form action="?act=file" method="post">Ваши учетки:<br><input type="submit" value="Скачать файлом">'; }
echo '<br><textarea name="get" rows="10" cols="33">'.$get.'</textarea><input type="hidden" name="link" value="'.$_POST['link'].'"></form>';}
else {
view_form("?act=mass&step=1");
echo '<br><br><b>Опции массреги</b><br>Введите кол-во учеток: <input type="text" name="step" size="2" maxlength="2"><br>или ссылку на txt-файл с никами:<br><input type="text" name="link"><br><br><a href="' . $_SERVER['PHP_SELF'] . '">Обычная рега</a></form>'; }
break;
7ion. Начало.
Написано примерно летом 2009 года.
Помнится, я еще недоумевал - почему мой код называют страшным.