- 1
- 2
if (dbg)
printf("2\n");
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+133
if (dbg)
printf("2\n");
// This is debug mode
+157
function run()
{
var test = [60, 1, 5, 70, 8];
var biggest = 100;
var biggest_index = 0;
for (var i = 0; i < test.length; i++)
{
if (test[i] < test[i + 1])
{
biggest = test[i + 1];
test[biggest - [i + 1]] = [biggest];
}
}
test[test.length] = biggest;
}
run();
таск был найти наибольшего эллемента масива [60, 1, 5, 70, 8]; во что получилось у коллеги новобранца. это был его 20-ты опыт ;)
+133
//......................................
void DlPortWritePortUshort(WORD addr, WORD data) {
DWORD br;
(&addr)[1]=data;
DeviceIoControl(hdriver,IOCTL_WRITE_PORT_USHORT,&addr,4,NULL,0,&br,NULL);
}
DWORD DlPortReadPortUlong(WORD addr) {
DWORD br;
DeviceIoControl(hdriver,IOCTL_READ_PORT_ULONG,&addr,2,&addr,4,&br,NULL);
return *(DWORD*)&addr;
}
void DlPortWritePortUlong(WORD addr, DWORD data) {
DWORD br;
DeviceIoControl(hdriver,IOCTL_WRITE_PORT_ULONG,&addr,8,NULL,0,&br,NULL);
}
//......................................
Кусок очередного форка dll-ки для работы с очередным, мать его, форком драйвера inpout32.sys.
Попался в поисках исправленного драйвера и dll-обёртки для него.
+95
public static class ColorExtension
{
public static bool IsDarkColor(this Color color)
{
return (color.R & 255) + (color.G & 255) + (color.B & 255) < 3*256/2;
}
}
x & 255 = ?, где x типа byte
+74
private static File getTmpOutputFile(VirtualFile file) {
String origPath = file.getRealFile().getAbsolutePath();
File tmp = new File(origPath + ".tmp");
// If the temp file already exists
if (tmp.exists()) {
long tmpLastModified = tmp.lastModified();
long now = System.currentTimeMillis();
// If the temp file is older than the destination file, or if it is
// older than the allowed compression time, it must be a remnant of
// a previous server crash so we can overwrite it
if (tmpLastModified < file.lastModified()) {
return tmp;
}
if (now - tmpLastModified > PluginConfig.maxCompressionTimeMillis) {
return tmp;
}
// Otherwise it must be currently being written by another thread,
// so wait for it to finish
while (tmp.exists()) {
if (System.currentTimeMillis() - now > PluginConfig.maxCompressionTimeMillis) {
throw new PressException("Timeout waiting for compressed file to be generated");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
// Return null to indicate that the file was already generated by
// another thread
return null;
}
return tmp;
}
Самый вредный говнокод, который я встречал за последний год.
При определённых условиях может так случиться, что он ждёт (до 60 секунд!), пока предыдущий временный файл не исчезнет. Он не пытается его удалить, не пытается создать новый файл, ничего не логирует - он просто ждёт, пока файл сам исчезнет.
И у меня как раз так и случилось - из-за совпадения разных событий файл не удалялся, метод ждал 60 секунд, но за это время валились совсем другие вещи по таймауту, и ушло много времени на то, чтобы понять, где же настоящая проблема.
И весь этот геморрой можно было бы благополучно заменить всего-навсего одной сточкой:
return File.createTempFile(origPath, "tmp");
Исходник - плагин play-press:
https://github.com/dirkmc/press/blob/master/app/press/io/OnDiskCompressedFile.java
+95
double[,] ThreadMatrixMult(int size, double[,] m1, double[,] m2)
{
double[,] result = new double[size, size];
var threads = new List<Thread>(size);
for (int i = 0; i < size; i++)
{
var t = new Thread( ti =>
{
int ii = (int)ti;
for (int j = 0; j < size; j++)
{
result[ii, j] = 0;
for (int k = 0; k < size; k++)
{
result[ii, j] += m1[ii, k] * m2[k, j];
}
}
});
threads.Add(t);
t.Start(i);
}
foreach (Thread thread in threads)
thread.Join();
return result;
}
+59
if ( number % 10 == 0 ) {
number %= 10;
}
мне кажется, или...
−109
class QuerysetResponse(object):
"""
вариант респонса для фильтрации гридов или диктселекфилдов
используя механизм инструкций
"""
def __init__(self, queryset, application, root=None):
self.root = root or "data"
def __new__(cls, *args, **kwargs):
return super(cls, cls).__new__(cls)(*args, **kwargs)
def __call__(self, queryset, application):
dict_list = []
pack = get_pack_instance(application)
for item in pack.list_columns:
if isinstance(item, (list, tuple)):
dict_list.append(item[0])
elif isinstance(item, dict) and item.get('data_index'):
dict_list.append(item['data_index'])
self.dict_ = dict_list
if not queryset:
queryset = []
return PreJsonResult(dict(rows=list(queryset),
total=len(queryset)), dict_list=self.dict_).get_http_response()
self.root не используется, ну, это видно. QuerysetResponse "инстанцируется" во всем проекте один раз.
Мне бы такое даже в голову не пришло.
+157
if ( diffYear < 5 ) {
document.getElementById('yearsText').innerHTML = "года |";
} else if ( diffYear > 1 ){
document.getElementById('yearsText').innerHTML = "лет |";
} else {
document.getElementById('yearsText').innerHTML = "год |";
}
if ( diffMonth > 4 ) {
document.getElementById('monthText').innerHTML = "месяцев |";
} else if ( diffMonth > 1 ){
document.getElementById('monthText').innerHTML = "месяца |";
} else {
document.getElementById('monthText').innerHTML = "месяц |";
}
if ( diffDay > 5 ) {
document.getElementById('monthText').innerHTML = "дней |";
} else if ( diffDay > 1 ){
document.getElementById('monthText').innerHTML = "дня |";
} else {
document.getElementById('monthText').innerHTML = "день |";
}
}
очередная кака с датой
−161
my @arr = (1,2,3,4);
foreach (@arr)
{
threads->new(\&doSomething, $_)->join;
}
Цикл на 4...? Запуск потоков.