- 1
- 2
- 3
- 4
- 5
int a, b ;
//some code
int numCount = 0;
while ((a + numCount++) < b) // посчитать кол-во чисел между a и b, включая a и b
;
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+68
int a, b ;
//some code
int numCount = 0;
while ((a + numCount++) < b) // посчитать кол-во чисел между a и b, включая a и b
;
это великолепно!
+54
void Game::initialize()
{
if (SDL_Init(SDL_INIT_VIDEO))
exit(1);
window = new Window("Game", 640, 480);
try
{
window->create();
}
catch (const Exception& exception)
{
std::cout << exception.getError() << '\n';
delete window;
exit(1);
}
canvas = new Canvas();
try
{
canvas->initialize(window->getWindow());
}
catch (const Exception& exception)
{
std::cout << exception.getError() << '\n';
delete canvas;
exit(1);
}
}
+59
LPVOID lpInfo = NULL;;
UINT unInfoLen = 0;
DWORD dwLangCode = 0;
if (!GetTranslationId(lpInfo, unInfoLen, GetUserDefaultLangID(), dwLangCode, FALSE))
{
if (!GetTranslationId(lpInfo, unInfoLen, GetUserDefaultLangID(), dwLangCode, TRUE))
{
if (!GetTranslationId(lpInfo, unInfoLen, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), dwLangCode, TRUE))
{
if (!GetTranslationId(lpInfo, unInfoLen, MAKELANGID(LANG_ENGLISH, SUBLANG_NEUTRAL), dwLangCode, TRUE))
// use the first one we can get
dwLangCode = *((DWORD*)lpInfo);
}
}
}
докомментировались, ебанатики...
+62
void f(bool *ok = 0)
{
//тут возникла ошибка
if (ok)
*ok = false;
return;
}
//далее в коде
bool ok = false;
f(&ok);
не, ну заебок, чо
+51
#if defined(alignas) /* check C++ keywords */ \
|| defined(alignof) \
|| defined(asm) \
|| defined(auto) \
|| defined(bool) \
<...snip...>
|| defined(virtual) \
|| defined(void) \
|| defined(volatile) \
|| defined(wchar_t) \
|| defined(while)
#error keyword defined before including C++ standard header
#endif /* defined... */
Из заголовочных файлов VS 2012.
http://www.viva64.com/en/b/0146/
+51
#include <ppl.h>
#include <windows.h>
#include <ppltasks.h>
#include <iostream>
#include <vector>
using namespace Concurrency;
using namespace std;
CRITICAL_SECTION cs6;
int main(int argc, char* argv[])
{
size_t concurentThreadsSupported = std::thread::hardware_concurrency();
cout << concurentThreadsSupported << endl;
//deadlock hazard increased with concurentThreadsSupported decreasing
size_t taskAmountForWasteVirtualCores = concurentThreadsSupported - 1;//must be equal to (virtual processor thread amount from Concurrency::IResourceManager) - 1
vector<task<void>> t;
for (size_t i = 0; i<taskAmountForWasteVirtualCores; ++i)
t.push_back(create_task([]{
Sleep(INFINITE);//some very long IO operation or deadlocked by EnterCriticalSection or sql transaction or other
}));
Sleep(1000);
cout << "another way:" << endl;
InitializeCriticalSection(&cs6);
auto locker = create_task([]{
cout << "locker" << endl;
EnterCriticalSection(&cs6);//same as begin sql transaction
cout << "locker entered cs 6" << endl;
Concurrency::wait(500);//Deadlock by any concurrency context switching directly or indirectly by std or MFC (events, mutex, etc)
cout << "locker played" << endl;
LeaveCriticalSection(&cs6);//same as end sql transaction
cout << "~locker ok" << endl;
});
auto locked = create_task([]{
cout << "locked" << endl;
EnterCriticalSection(&cs6);//same as begin sql transaction
cout << "locked entered cs 6" << endl;
Concurrency::wait(500);
cout << "locked played" << endl;
LeaveCriticalSection(&cs6);//same as end sql transaction
cout << "~locked ok" << endl;
});
Sleep(1000);
cout << "FAIL" << endl;
return 0;
}
Нашел дидлок)
http://rextester.com/KHC72232
http://rextester.com/EMG65441
+52
void ArmInterface::dispatchMessage(QString name, QJsonArray args)
{
//флаг того что мы не смогли обработать
bool notCallbacks = true;
//проходим по всем методам( которые кстати можно создать в рантайме )
for( int i = 0; i < metaObject()->methodCount() ; i++ )
{
QMetaMethod method = metaObject()->method( i);
//имя метода подходит под имя под сообщение от сервера? Прекрасно проверяем дальше.
if ( method.name() != name )
{
qWarning() << "method.name() != name" << " -> " <<method.name() << " != " << name;
//так как метод не найден мы просто выйдем отсюда, не дожидаясь ничего плохого
continue;
}
//метод у нас публичный? Если да то можно запускать обработку иначе заявим что низя
if ( method.access() != QMetaMethod::Public )
{
qWarning() << "Method " << method.name()<< " not public!";
#ifdef IGNORE_NOT_PUBLIC_METHOD
continue;
#endif
}
//несовдатает количество аргументов? Хватит это терпеть пишем warning, и если надо выходим из этого диспатчера
int countParams = method.parameterCount();
if ( args.count() != method.parameterCount() )
{
qWarning() << "Method " << method.name() << " params count = " << method.parameterCount() << " and received args params count = " << args.count();
#ifndef IGNORE_METHOD_PARAMS_COUNT
continue;
#endif
//берем наименьшее количество параметров
countParams = countParams > args.count() ? countParams : args.count();
}
//создание валидного QGenericArgument
auto genericArg = [ this, method, args ]( int index ) -> QGenericArgument{
//out of range?
if ( args.count() <= index ||
method.parameterCount() <= index )
return QGenericArgument();
void * data = 0;
//сохраняем временный QVariant для дальнейшей более удобной работы с ним
QVariant temp = args.at( index ).toVariant();
//попытка конвертирования типов. Если что-то не получается, пишем в лог. Мб надо будет сделать преждевременный выход, если сконвертировать не получается.
if ( !temp.convert( method.parameterType( index) ) )
{
qWarning()<< objectName() << " method : " << method.name() <<
" Not convert " << method.parameterNames().at( index ) << args.at( index ).toVariant().typeName() <<
" from " << args.at( index ).toVariant().typeName() <<
" to " << QMetaType::typeName( method.parameterType( index) ) ;
};
//у нас есть такой аргумент? Если нет - то ничего не делаем
if ( args.count() > index )
{
data = QMetaType::create( method.parameterType( index ) , temp.data() );
}
const char * name = 0;
//у нас есть имя аргумента и аргумент в него? Если чего-то нет - то ничего и не будем ничего делать
if ( method.parameterNames().count() > index && data)
name = method.parameterNames().at( index ).data();
return QGenericArgument(
name,
data);
};
//тут можно вызывать!
method.invoke( this,
//генерируем аргументы
genericArg(0),
genericArg(1),
genericArg(2),
genericArg(3),
genericArg(4),
genericArg(5),
genericArg(6),
genericArg(7),
genericArg(8),
genericArg(9));
notCallbacks = false;
//раз вызвали значит нашли подходящий callback, а следовательно искать дальше ненадо. Выходим нафиг.
break;
}
//вызвали что -нить? Если вызвали то не вызываем ничего. А иначе идем в другую функцию - которая разбирается как раз с такими сообщениями.
//Если надо перехватить совершенно все сообщения - перегружать функцию в которой находимся.
if ( !notCallbacks )
dispathUndefinedMessage( name, args );
}
Написал и мучаюсь - гавнокод или все таки нет.
ахда, мне надо выучить русский )
+60
std::string s = "a" /* + */ "b";
+59
#include <iostream>
#include <time.h>
#include <cmath>
#include <windows.h>
using namespace std;
int main()
{
Hashtable^ hat = gcnew Hashtable();
hat->Add(1,"|");
hat->Add(2,"||");
hat->Add(3,"|||");
hat->Add(4,"||||");
hat->Add(5,"|||||");
hat->Add(6,"||||||");
hat->Add(7,"|||||||");
hat->Add(8,"||||||||");
hat->Add(9,"|||||||||");
hat->Add(10,"||||||||||");
hat->Add(11,"|||||||||||");
hat->Add(12,"||||||||||||");
hat->Add(13,"|||||||||||||");
hat->Add(14,"||||||||||||||");
hat->Add(15,"|||||||||||||||");
hat->Add(16,"||||||||||||||||");
hat->Add(17,"|||||||||||||||||");
hat->Add(18,"||||||||||||||||||");
hat->Add(19,"|||||||||||||||||||");
hat->Add(20,"||||||||||||||||||||");
hat->Add(21,"|||||||||||||||||||||");
hat->Add(22,"||||||||||||||||||||||");
hat->Add(23,"|||||||||||||||||||||||");
hat->Add(24,"||||||||||||||||||||||||");
hat->Add(25,"|||||||||||||||||||||||||");
hat->Add(26,"||||||||||||||||||||||||||");
hat->Add(27,"|||||||||||||||||||||||||||");
hat->Add(28,"||||||||||||||||||||||||||||");
hat->Add(29,"|||||||||||||||||||||||||||||");
hat->Add(30,"||||||||||||||||||||||||||||||");
hat->Add(31,"|||||||||||||||||||||||||||||||");
hat->Add(32,"||||||||||||||||||||||||||||||||");
hat->Add(33,"|||||||||||||||||||||||||||||||||");
hat->Add(34,"||||||||||||||||||||||||||||||||||");
hat->Add(35,"|||||||||||||||||||||||||||||||||||");
hat->Add(36,"||||||||||||||||||||||||||||||||||||");
hat->Add(37,"|||||||||||||||||||||||||||||||||||||");
hat->Add(38,"||||||||||||||||||||||||||||||||||||||");
hat->Add(39,"|||||||||||||||||||||||||||||||||||||||");
hat->Add(40,"||||||||||||||||||||||||||||||||||||||||");
hat->Add(41,"|||||||||||||||||||||||||||||||||||||||||");
hat->Add(42,"||||||||||||||||||||||||||||||||||||||||||");
hat->Add(43,"|||||||||||||||||||||||||||||||||||||||||||");
hat->Add(44,"||||||||||||||||||||||||||||||||||||||||||||");
hat->Add(45,"|||||||||||||||||||||||||||||||||||||||||||||");
hat->Add(46,"||||||||||||||||||||||||||||||||||||||||||||||");
hat->Add(47,"|||||||||||||||||||||||||||||||||||||||||||||||");
hat->Add(48,"||||||||||||||||||||||||||||||||||||||||||||||||");
hat->Add(49,"|||||||||||||||||||||||||||||||||||||||||||||||||");
hat->Add(50,"||||||||||||||||||||||||||||||||||||||||||||||||||");
srand(time(0));
for(int i = 1; i<50; i++)
{
int r = rand() % 1000;
String^ s = hat[i]->ToString();
Console::WriteLine("\r"+i*2+"% completed:"+s);
}
cout << endl << "Operation completed successfully.\n" << flush;
return 0;
}
// http://stackoverflow.com/questions/16635787/making-a-console-progress-bar-windows/19589370#19589370
// Рисуем прогресс бар на С++
+51
{
INT TextTickIdx(-1), MinorCnt( m_AxisX->GetMinorTick() || m_AxisX->GetDisplayMinorGrid() ? (INT)m_AxisX->GetMinorTickSpace() : 0 );
std::vector<std::pair<RectF,INT>>::iterator SLRit = SavedLabelRects.begin();
std::vector<std::pair<SizeF,SizeF>>::iterator STSit = SavedTextSizes.begin();
if(SLRit != SavedLabelRects.end())
TextTickIdx = NotEmptyIdxs[SLRit->second];
BOOL ShowCatLines(m_AxisX->GetShowCategoryLines());
std::map<REAL, PointF> CatPts;
if(ShowCatLines)
{
// берём все возможные по всей длине оси
REAL CatOff(0);
if(m_AxisXPlacement == CAXP_ONTICK)
CatOff = CalcScaleIntervalW/2.0f;
INT CatLnsCnt = (m_AxisXPlacement == CAXP_ONTICK) ? PointsCount : PointsCount + 1;
for(INT i(0);i < CatLnsCnt;i++)
{
PointF Pt;
REAL SecCoord;
switch(Position)
{
case AA_TOP:
case AA_BOTTOM:
SecCoord = AxisXSelfRect.X + CatOff + i*CalcScaleIntervalW;
Pt.X = SecCoord;
break;
case AA_LEFT:
case AA_RIGHT:
SecCoord = AxisXSelfRect.Y + CatOff + i*CalcScaleIntervalW;
Pt.Y = SecCoord;
break;
}
CatPts.insert(std::make_pair(SecCoord, Pt));
}
}
PointF TickOff(0,0);
BOOL TicksBetweenCategories(m_AxisX->GetTicksBetweenCategories());
if(TicksBetweenCategories)
{
switch(Position)
{
case AA_TOP:
case AA_BOTTOM:
TickOff.X = ReversedAxisX ? -CalcScaleIntervalW*0.5f : CalcScaleIntervalW*0.5f;
break;
case AA_LEFT:
case AA_RIGHT:
TickOff.Y = ReversedAxisX ? CalcScaleIntervalW*0.5f : -CalcScaleIntervalW*0.5f;
break;
}
}
std::vector<CDgmAxisTickTextDrawCacheItem>& AxisXTickCache = m_AxisX->GetDrawTickTextCache();
long TickInterval = IsDateAxis ? m_AxisX->GetDateAxisSettings()->GetMajorTickUnitInterval() : m_AxisX->GetTickMarksInterval();
if(TickInterval < 1)
TickInterval = 1;
INT TickStartAt = (m_AxisXPlacement == CAXP_ONTICK && !TicksBetweenCategories ? 0 : 1);
DATE DateMajorTickStartAt = m_AxisX->GetDateAxisSettings()->GetMajorTickStartAt();
INT CategoryMajorTickStartAt = m_Owner->GetCategoryFromDate(DateMajorTickStartAt) - 1;
if (CategoryMajorTickStartAt < 0)
{
CategoryMajorTickStartAt = 0;
}
CDgmDateAxisUnit MinorLabelTickUnits(DAU_AUTO);
if(IsDateAxis)
{
CDgmDateAxisSettings* ds = m_AxisX->GetDateAxisSettings();
MinorLabelTickUnits = ds->GetMinorTickUnit();
if(MinorLabelTickUnits == DAU_AUTO)
MinorLabelTickUnits = m_CalculatedDateAxisAutoMajorTickUnit;
MinorCnt = ds->GetMinorTickUnitInterval();
if(MinorCnt < 1)
MinorCnt = 1;
}
INT _k(0);
for (INT i(0), Cnt(Names.size());i < Cnt;i++)
{
CDgmAxisTickTextDrawCacheItem CacheItem;
BYTE nShow(0);
CacheItem.TickDrawPoint = Names[i].first + TickOff;
CacheItem.SetTextVisible(i == TextTickIdx);
if(i == TextTickIdx) // метка с текстом
{
CacheItem.TextDrawCenter = Names[i].first; // именно тик, т.к. одная координата у них общая, а вторая
// координата тика, ректа и центра после будет
// скорректирована по оси Х, из-за того, что ее
// размер и положение изменятся
CacheItem.PointIdx = Names[i].second.second;
if(CacheItem.PointIdx < 0)
CacheItem.TextValue = Names[i].second.first->m_text.GetPlainText();
CacheItem.TextDrawSize = SLRit->first;
CacheItem.FontSize = FontHeight;
CacheItem.m_sizefDrawBounds = STSit->first;
CacheItem.m_sizefTextBounds = STSit->second;
if (CacheItem.TextDrawCenter.X + CacheItem.TextDrawSize.Width * 0.5f > Max)
{
CacheItem.TextDrawCenter.X = Max - CacheItem.TextDrawSize.Width * 0.5f;
Маааленький фрагментик большущего метода расчета координат для вывода подписей на оси Х на диаграмме. Так принято говнокодить в одной очень крупной российской ИТ-компании, занимающейся разработкой BI-продуктов.