- 1
- 2
- 3
- 4
- 5
if(object)
if(object->isSolid)
event.isCancelled = true;
;else //<
throw NullEventArgumentException("object == nullptr");
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
if(object)
if(object->isSolid)
event.isCancelled = true;
;else //<
throw NullEventArgumentException("object == nullptr");
Новый токен в C++ про который знает только 0.6% говнокодеров
+1
IT Оффтоп #47
#1: https://govnokod.ru/18142 https://govnokod.xyz/_18142
#2: https://govnokod.ru/18378 https://govnokod.xyz/_18378
#3: https://govnokod.ru/19667 https://govnokod.xyz/_19667
#4: https://govnokod.ru/21160 https://govnokod.xyz/_21160
#5: https://govnokod.ru/21772 https://govnokod.xyz/_21772
#6: (vanished) https://govnokod.xyz/_24063
#7: https://govnokod.ru/24538 https://govnokod.xyz/_24538
#8: (vanished) https://govnokod.xyz/_24815
#9: https://govnokod.ru/24867 https://govnokod.xyz/_24867
#10: https://govnokod.ru/25328 https://govnokod.xyz/_25328
#11: (vanished) https://govnokod.xyz/_25436
#12: (vanished) https://govnokod.xyz/_25471
#13: (vanished) https://govnokod.xyz/_25590
#14: https://govnokod.ru/25684 https://govnokod.xyz/_25684
#15: https://govnokod.ru/25694 https://govnokod.xyz/_25694
#16: https://govnokod.ru/25725 https://govnokod.xyz/_25725
#17: https://govnokod.ru/25731 https://govnokod.xyz/_25731
#18: https://govnokod.ru/25762 https://govnokod.xyz/_25762
#19: https://govnokod.ru/25767 https://govnokod.xyz/_25767
#20: https://govnokod.ru/25776 https://govnokod.xyz/_25776
#21: https://govnokod.ru/25798 https://govnokod.xyz/_25798
#22: https://govnokod.ru/25811 https://govnokod.xyz/_25811
#23: https://govnokod.ru/25863 https://govnokod.xyz/_25863
#24: https://govnokod.ru/25941 https://govnokod.xyz/_25941
#25: https://govnokod.ru/26026 https://govnokod.xyz/_26026
#26: https://govnokod.ru/26050 https://govnokod.xyz/_26050
#27: https://govnokod.ru/26340 https://govnokod.xyz/_26340
#28: https://govnokod.ru/26372 https://govnokod.xyz/_26372
#29: https://govnokod.ru/26385 https://govnokod.xyz/_26385
#30: https://govnokod.ru/26413 https://govnokod.xyz/_26413
#31: https://govnokod.ru/26423 https://govnokod.xyz/_26423
#32: https://govnokod.ru/26440 https://govnokod.xyz/_26440
#33: https://govnokod.ru/26449 https://govnokod.xyz/_26449
#34: https://govnokod.ru/26456 https://govnokod.xyz/_26456
#35: https://govnokod.ru/26463 https://govnokod.xyz/_26463
#36: https://govnokod.ru/26508 https://govnokod.xyz/_26508
#37: https://govnokod.ru/26524 https://govnokod.xyz/_26524
#38: https://govnokod.ru/26539 https://govnokod.xyz/_26539
#39: https://govnokod.ru/26556 https://govnokod.xyz/_26556
#40: https://govnokod.ru/26568 https://govnokod.xyz/_26568
#41: https://govnokod.ru/26589 https://govnokod.xyz/_26589
#42: https://govnokod.ru/26600 https://govnokod.xyz/_26600
#43: https://govnokod.ru/26604 https://govnokod.xyz/_26604
#44: https://govnokod.ru/26627 https://govnokod.xyz/_26627
#45: https://govnokod.ru/26635 https://govnokod.xyz/_26635
#46: (vanished) https://govnokod.xyz/_26646
#46: (vanished) https://govnokod.xyz/_26654
+1
public function isSpecial()
{
$special_ids = array(
2222,
3028,
3333,
5555,
5702,
6666,
6700,
7654,
7777,
8451,
11225
);
return in_array((int)$this->getId(), $special_ids);
//return $this->getId() == 2222 || $this->getId() == 3028 || $this->getId() == 3333 || $this->getId() == 5555 || $this->getId() == 5702;
}
https://github.com/wiistriker/govnokod_legacy/blob/master/modules/quoter/models/quote.php
Рекурсивный говнокод.
+1
from tkinter import *
from random import randint
f = randint(2, 10)
s = randint(2, 10)
r = f * s
def main_f():
global f
global s
global r
if r == int(inp.get()):
ls.configure(text='да! Вы правы')
f = randint(2, 10)
s = randint(2, 10)
r = f * s
l.configure(text=f'сколько будет {f} * {s}?')
else:
ls.configure(text='нет, вы не правы')
l.configure(text=f'сколько будет {f} * {s}?')
win = Tk()
win.title('math')
l = Label(win, text=f'сколько будет {f} * {s}?')
l.grid(column=0 , row=0)
ls = Label(win, text=' ')
ls.grid(column=0, row=1)
inp = Entry(win, width=10)
inp.grid(column=1, row=0)
but = Button(win, text='проверить', command=main_f, fg='red')
but.grid(column=2, row=0)
win.mainloop()
третьиклассник решил выучить таблицу умножения
+1
from vk_bot.vk_config import GROUP_ID, TOKEN
import vk_api
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
import random
from vk_bot.db_session import *
from vk_bot.__all_models import BugReport, Comment
import datetime
from vk_bot.vacancies import get_vacancies, ServerError
def main():
global_init("feedback/feedback.sqlite")
vk_session = vk_api.VkApi(
token=TOKEN)
vk = vk_session.get_api()
longpoll = VkBotLongPoll(vk_session, GROUP_ID)
bot_state = {}
def send_msg(msg):
vk.messages.send(user_id=event.obj.message['from_id'],
message=msg,
random_id=random.randint(0, 2 ** 64))
for event in longpoll.listen():
if event.type == VkBotEventType.MESSAGE_NEW:
if event.obj.message['from_id'] in bot_state and bot_state[event.obj.message['from_id']]:
state = bot_state[event.obj.message['from_id']]
if state == 1:
send_msg('Спасибо, ваше мнение для нас очень важно.')
Comment().new(event.obj.message['from_id'], datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
event.obj.message['text'])
bot_state[event.obj.message['from_id']] = 0
elif state == 2:
BugReport().new(event.obj.message['from_id'], datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
event.obj.message['text'])
send_msg('Спасибо за ваш отзыв, мы постараемся исправить проблему в ближайшем будущем.')
bot_state[event.obj.message['from_id']] = 0
elif state == 4:
parameters = [r.strip() for r in event.obj.message['text'].split(',')]
try:
vacancies = get_vacancies(parameters[0], parameters[1])
except ServerError:
send_msg('Не удалось получить ответ от сервера, попробуйте позже')
bot_state[event.obj.message['from_id']] = 0
except Exception:
send_msg('Данные введены некорректно, попробуйте заново.')
send_msg('Формат: <должность>, <мин. зарплата>')
else:
if len(vacancies) == 0:
send_msg('По данным критериям ничего не найдено')
else:
vacancy_list = [f"{i}) {v['title']}, {v['salary']}" for i, v in enumerate(vacancies)]
send_msg('\n'.join(vacancy_list))
if bot_state[event.obj.message['from_id']] == 0:
send_msg('1 - написать отзыв или предложение\n 2 - сообщить о неправильной работе сайта\n 3 - документация к api\n 4 - посмотреть список доступных вакансий\n иначе напишите сообщение и модератор вскоре на него ответит')
elif event.obj.message['from_id'] not in bot_state:
send_msg('1 - написать отзыв или предложение\n 2 - сообщить о неправильной работе сайта\n 3 - документация к api\n 4 - посмотреть список доступных вакансий\n иначе напишите сообщение и модератор вскоре на него ответит')
bot_state[event.obj.message['from_id']] = 0
else:
key = event.obj.message['text'][0]
if key == '1':
send_msg('Пожалуйста, поделитесь вашим мнением по поводу сайта.')
bot_state[event.obj.message['from_id']] = 1
elif key == '2':
send_msg('Пожалуйста, максимально подробно опишите вашу проблему.')
bot_state[event.obj.message['from_id']] = 2
elif key == '3':
send_msg('https://www.youtube.com/watch?v=dQw4w9WgXcQ')
elif key == '4':
send_msg('Введите название должности и минимальную желаемую зарплату по образцу:<должность>, <мин. зарплата>')
bot_state[event.obj.message['from_id']] = 4
else:
send_msg('Модератор вам скоро ответит, пожалуйста подождите.')
if __name__ == '__main__':
main()
Код бота поддержки.
Один из товарищей по проекту ничего в нем не делал,
а потом чтобы его не выгоняли попросил дать ему хотя бы бота.
Вот результат.
Модели и вспомогательные файлы оставлять думаю не имеет смысла, все и так очевидно
+1
template <class... Args>
void log(Args&&... args)
{
auto dummy = { (std::clog << args, 0)... };
std::clog << std::endl;
}
новый printf на с++
+1
https://github.com/oskusalerma/trelby/issues/85
Сорян за пост-ссылку, но я тут валяюсь под столом просто.
Есть тулза для написания сценариев (для чего только нет тулзы, правда?). Она опенсурсная и при этом выглядит не как говно. Но, когда начинаешь её щупать, ВНЕЗАПНО оказывается, что буквы кириллицы в ней тупо не набираются. Лезешь в FAQ, там лежит ссылка на issue из поста. А уже там просто сказка!
Короч, автор примерно в 2007 году сходил почитал спеку пдф, обнаружил, что "PDF spec is oriented towards Latin-1" и решил, что это даёт ему моральное право забить болт на Unicode, а заодно utf-8 и унтерменш, которые не осилили самый тривиальный сабсет латиницы.
В 2012-ом после, судя по всему, многочисленных недоумённых вопросов автор снова появился на горизонте с тикетом на гитхабе и объяснениями в духе "Unicode нет и не будет, потому что не для тебя моя черешня цвела". Цитата для понимания майндсета чувака: "That's how it was 5 years ago anyway when I last looked at it; maybe the spec has improved since then?"
В общем, выглядело так, будто дядя устал и решил, что пора бы всю эту хуйню переложить на чужие хрупкие плечи, у нас тут опенсурс тем более и все дела.
Но, когда в 2015-ом году появился некий анон с предложением все починить и даже какими-то наработками, автор ему сказал, что иди сука гоняй тесты (видимо, руками, потому что CI настроить он тоже не смог) на всех платформах, а то, вишь, "the old "I'll do the fun bits and let others do the boring bits" strategy. Good luck with that."
Короч чуваки ещё немного поспорили с этим аутистом, после чего съебались в туман, а тулза так кириллицу и не поддерживает.
Смешно и грустно.
+1
private IDictionary<string, Value> valueIndex;
...
var result = this.valueIndex
.Where(v => v.Key == prefix + hashCode.ToString())
.Select(v => new
{
path = v.Value.Path,
field = v.Value.Field
})
.FirstOrDefault();
Трушный способ достать значение из словаря.
В словаре 10000 записей, за каждой полезут хотя бы раз
+1
template<typename CharType>
class Formatter
{
private:
static int _ToString(Int32 Value){
return CString<CharType>::Snprintf(
(CharType*)GSupportToStringBuffer,
TO_STRING_BUFFER_SIZE,
"%" PRId32,
Value);
}
static int _ToString(float Value){
return CString<CharType>::Snprintf(
(CharType*)GSupportToStringBuffer,
TO_STRING_BUFFER_SIZE,
"%f",
Value);
}
template<typename First, typename ... Args>
static void _ConvertArgs(Array<GenericString<CharType>>& _ArgBuffer, const First& _First, const Args& ... _Args) {
_ArgBuffer.Add(ToString(_First));
_ConvertArgs(_ArgBuffer, _Args ...);
}
template<typename First>
static void _ConvertArgs(Array<GenericString<CharType>>& _ArgBuffer, const First& _First) {
_ArgBuffer.Add(ToString(_First));
}
static bool _ScanPlaceholder(const CharType* Format, size_t Index, size_t Length, size_t& Placeholder, size_t& LastIndex) {
size_t i = Index;
size_t j = 0;
while (i < Length && Format[i] != FormatterPlaceholder<CharType>::End)
{
if (!Char<CharType>::IsDigit(Format[i]))
{
return false;
}
else
{
GSupportToStringBuffer[j] = Format[i];
j++;
}
i++;
}
if (i == Length)
return false;
GSupportToStringBuffer[j] = 0;
#if defined(64BIT)
Placeholder = CString<CharType>::Atoi64((const CharType*)GSupportToStringBuffer);
#else
Placeholder = CString<CharType>::Atoi((const CharType*)GSupportToStringBuffer);
#endif
LastIndex = i;
return true;
}
public:
template<typename T>
static GenericString<CharType> ToString(const T& Value) {
int Length = Formatter<CharType>::_ToString(Value);
return GenericString<CharType>((char*)GSupportToStringBuffer, Length);
}
template<typename ... Args>
static GenericString<CharType> Format(const CharType* Format, const Args& ... _Args) {
Array<GenericString<CharType>> _FormatedArgs;
_FormatedArgs.Reserve(sizeof...(Args));
Formatter<CharType>::_ConvertArgs(_FormatedArgs, _Args ...);
const size_t _Length = CString<CharType>::Strlen(Format);
size_t Index = 0;
for (size_t i = 0; i < _Length; i++)
{
if (Format[i] == FormatterPlaceholder<CharType>::Begin)
{
size_t Placeholder = 0;
size_t LastIndex = 0;
if (_ScanPlaceholder(Format, i + 1, _Length, Placeholder, LastIndex) && Placeholder < sizeof...(Args))
{
Memory::Copy(GSupportFormatBuffer + Index, _FormatedArgs[Placeholder].Data(), _FormatedArgs[Placeholder].Length() * sizeof(CharType));
Index += _FormatedArgs[Placeholder].Length();
i = LastIndex;
}
}
else
{
GSupportFormatBuffer[Index] = Format[i];
Index++;
}
}
GSupportFormatBuffer[Index] = 0;
return GenericString<CharType>((const CharType*)GSupportFormatBuffer);
}
};
template<typename T>
forceinline String ToString(const T& Value){
return Formatter<char>::ToString<T>(Value);
}
template<typename ... Args>
forceinline String Format(const char* Format, const Args& ... _Args){
return Formatter<char>::Format(Format, _Args ...);
}
Три года назад писал printf аля Console.WriteLine в C#. Тут порезал до ста строк. https://pastebin.com/8BCLuBEm
+1
(() => {
const urlPrefix = 'https://distrochooser.de/en/';
const msgs = [];
let msg = '';
for (let i = 479076; i > 0; --i) {
const url = urlPrefix + i;
if (msg.length + url.length + 1 < 2000) {
msg += '\n';
msg += url;
} else {
msgs.push(msg);
msg = url;
}
}
return msgs;
})()
Проходим мимо, не обращаем внимания.
Ведутся SEO-работы.