Каков лучший комментарий в исходном коде, с которым Вы когда-либо встречались? [закрытый]

360
задан 14 revs, 11 users 61% 17 September 2011 в 14:54
поделиться

518 ответов

/////////////////////////////////////// this is a well commented line
291
ответ дан sage386 23 November 2019 в 00:15
поделиться
// I don't know why I need this, but it stops the people being upside-down

x = -x;
269
ответ дан 2 revs, 2 users 80% 23 November 2019 в 00:15
поделиться
// I know the line below is wrong, but it came that way from our IP vendor, and 
// the driver won't work if you "fix" it. I've had to revert this change 4 times
// now. Leave it alone, or I will hunt you down and hurt you
if (r = 0) {
    /* bunch of code here */
}
else
{
   /* even more code here */
}
109
ответ дан 2 revs 23 November 2019 в 00:15
поделиться
  mov si, pCard      ; captain?
117
ответ дан Hafthor 23 November 2019 в 00:15
поделиться
int MyFunction()
{
    // There once was a man named Dave
    int Result = 0;

    // Whose code just wouldn't behave
    MyObject *Ptr = new MyObject();

    // He left to go to a meetin'
    Result = Ptr->DoSomething();

    // And left his memory a leakin'
    return Result;
}

Комментарий

C++
128
ответ дан 2 revs, 2 users 97% 23 November 2019 в 00:15
поделиться
if(m_measures =/*=*/ --index)
{
    ....
128
ответ дан NeilDurant 23 November 2019 в 00:15
поделиться

Кто-то жаловался, что "лучший" комментарий поднимал худшие комментарии. По моему скромному мнению, они более забавны, и настолько "лучше", но вот честный лучший комментарий, который я имею когда-либо , читает :

/*
Major subtleties ahead:  Most hash schemes depend on having a "good" hash
function, in the sense of simulating randomness.  Python doesn't:  its most
important hash functions (for strings and ints) are very regular in common
cases:

>>> map(hash, (0, 1, 2, 3))
[0, 1, 2, 3]
>>> map(hash, ("namea", "nameb", "namec", "named"))
[-1658398457, -1658398460, -1658398459, -1658398462]
>>>

This isn't necessarily bad!  To the contrary, in a table of size 2**i, taking
the low-order i bits as the initial table index is extremely fast, and there
are no collisions at all for dicts indexed by a contiguous range of ints.
The same is approximately true when keys are "consecutive" strings.  So this
gives better-than-random behavior in common cases, and that's very desirable.

OTOH, when collisions occur, the tendency to fill contiguous slices of the
hash table makes a good collision resolution strategy crucial.  Taking only
the last i bits of the hash code is also vulnerable:  for example, consider
[i << 16 for i in range(20000)] as a set of keys.  Since ints are their own
hash codes, and this fits in a dict of size 2**15, the last 15 bits of every
hash code are all 0:  they *all* map to the same table index.

But catering to unusual cases should not slow the usual ones, so we just take
the last i bits anyway.  It's up to collision resolution to do the rest.  If
we *usually* find the key we're looking for on the first try (and, it turns
out, we usually do -- the table load factor is kept under 2/3, so the odds
are solidly in our favor), then it makes best sense to keep the initial index
computation dirt cheap.

The first half of collision resolution is to visit table indices via this
recurrence:

    j = ((5*j) + 1) mod 2**i

For any initial j in range(2**i), repeating that 2**i times generates each
int in range(2**i) exactly once (see any text on random-number generation for
proof).  By itself, this doesn't help much:  like linear probing (setting
j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
order.  This would be bad, except that's not the only thing we do, and it's
actually *good* in the common cases where hash keys are consecutive.  In an
example that's really too small to make this entirely clear, for a table of
size 2**3 the order of indices is:

    0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]

If two things come in at index 5, the first place we look after is index 2,
not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
Linear probing is deadly in this case because there the fixed probe order
is the *same* as the order consecutive keys are likely to arrive.  But it's
extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
and certain that consecutive hash codes do not.

The other half of the strategy is to get the other bits of the hash code
into play.  This is done by initializing a (unsigned) vrbl "perturb" to the
full hash code, and changing the recurrence to:

    j = (5*j) + 1 + perturb;
    perturb >>= PERTURB_SHIFT;
    use j % 2**i as the next table index;

Now the probe sequence depends (eventually) on every bit in the hash code,
and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
because it quickly magnifies small differences in the bits that didn't affect
the initial index.  Note that because perturb is unsigned, if the recurrence
is executed often enough perturb eventually becomes and remains 0.  At that
point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
that's certain to find an empty slot eventually (since it generates every int
in range(2**i), and we make sure there's always at least one empty slot).

Selecting a good value for PERTURB_SHIFT is a balancing act.  You want it
small so that the high bits of the hash code continue to affect the probe
sequence across iterations; but you want it large so that in really bad cases
the high-order hash bits have an effect on early iterations.  5 was "the
best" in minimizing total collisions across experiments Tim Peters ran (on
both normal and pathological cases), but 4 and 6 weren't significantly worse.

Historical:  Reimer Behrends contributed the idea of using a polynomial-based
approach, using repeated multiplication by x in GF(2**n) where an irreducible
polynomial for each table size was chosen such that x was a primitive root.
Christian Tismer later extended that to use division by x instead, as an
efficient way to get the high bits of the hash code into play.  This scheme
also gave excellent collision statistics, but was more expensive:  two
if-tests were required inside the loop; computing "the next" index took about
the same number of operations but without as much potential parallelism
(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
above, and then shifting perturb can be done while the table index is being
masked); and the dictobject struct required a member to hold the table's
polynomial.  In Tim's experiments the current scheme ran faster, produced
equally good collision statistics, needed less code & used less memory.

Theoretical Python 2.5 headache:  hash codes are only C "long", but
sizeof(Py_ssize_t) > sizeof(long) may be possible.  In that case, and if a
dict is genuinely huge, then only the slots directly reachable via indexing
by a C long can be the first slot in a probe sequence.  The probe sequence
will still eventually reach every slot in the table, but the collision rate
on initial probes may be much higher than this scheme was designed for.
Getting a hash code as fat as Py_ssize_t is the only real cure.  But in
practice, this probably won't make a lick of difference for many years (at
which point everyone will have terabytes of RAM on 64-bit boxes).
*/
145
ответ дан llimllib 23 November 2019 в 00:15
поделиться

На инициализации связанного списка:

last = first; /* Biblical reference */

Succint и веселый.

146
ответ дан Brian Clapper 23 November 2019 в 00:15
поделиться

Попытайтесь ввести свою любимую профанацию в поиск кода Google , это коротает много тусклых часов. Некоторые мои любимые примеры:

/* These magic numbers are fucking stupid. */

/* Dear free software world, do you NOW see we are fucking
   things up?! This is insane! */

/* We will NOT put a fucking timestamp in the header here. Every
   time you put it back, I will come in and take it out again. */

# However, this only works if there are MULTIPLE checkboxes!
# The fucking JS DOM *changes* based on one or multiple boxes!?!?!
# Damn damn damn I hate the JavaScript DOM so damn much!!!!!!

/* TODO: this is obviously not right ... this whole fucking module
   sucks anyway */

/* FIXME: please god, when will the hurting stop? Thus function is so
   fucking broken it's not even funny. */

и мой любимый

 # code below replaces code above - any problems?
 # yeah, it doesn't fucking work.
147
ответ дан 2 revs, 2 users 90% 23 November 2019 в 00:15
поделиться

... или умрите//сука

149
ответ дан namata 23 November 2019 в 00:15
поделиться
/* Emits a 7-Hz tone for 10 seconds.
  True story: 7 Hz is the resonant frequency of a
  chicken's skull cavity. This was determined
  empirically in Australia, where a new factory
  generating 7-Hz tones was located too close to a
  chicken ranch: When the factory started up, all the
  chickens died.
  Your PC may not be able to emit a 7-Hz tone. */

main()
{
    sound(7);
    delay(10000);
    nosound();
}

(звуковая функция в Справочнике версии 2.0 Turbo C)

155
ответ дан 2 revs, 2 users 84% 23 November 2019 в 00:15
поделиться

на коде js:

// hack for ie browser (assuming that ie is a browser)
171
ответ дан 2 revs, 2 users 67% 23 November 2019 в 00:15
поделиться
// I have to find a better job
172
ответ дан 2 revs, 2 users 67% 23 November 2019 в 00:15
поделиться
options.BatchSize = 300; //Madness? THIS IS SPARTA!
178
ответ дан jumpinjackie 23 November 2019 в 00:15
поделиться
/* Halley's comment */
178
ответ дан 2 revs 23 November 2019 в 00:15
поделиться
//I am not sure why this works but it fixes the problem. 

Это было перед рядом кода, который технически решал проблему, к которой это было предназначено, но повредило 3 других вещи....

192
ответ дан 3 revs, 2 users 83% 23 November 2019 в 00:15
поделиться
/* You are not meant to understand this */ 
207
ответ дан 3 revs, 3 users 50% 23 November 2019 в 00:15
поделиться
/* Please work */
216
ответ дан 3 revs, 2 users 75% 23 November 2019 в 00:15
поделиться

Много лет назад (приблизительно в 1994) я работал над приложением PRO*C Oracle для крупной многонациональной компании-разработчика программного обеспечения, о которой Вы услышите. Приложение я продолжал работать, было крупным приложением Oracle, и у них была утилита, которая выполнила в течение ночи убирающиеся данные и выполнение всех видов совокупных вычислений. Каждый раз, когда чему-либо было нужно выполнение как пакетное задание, его пихнули в эту утилиту и поскольку можно предположить, что это стало абсолютным чудовищем. Это было также известно крошечному количеству комментариев, что это имело для такой крупной программы.

Один из нескольких комментариев, которые это действительно имело, остается самым прекрасным комментарием, я когда-либо видел чистый WTF'ness... Я пытался найти ошибку в функции, которая была сотнями строк долго, и прямо в середине его был [только 114] комментарий в функции:

/* I did this the other way */

По сей день это - все еще самый прекрасный комментарий, который я когда-либо видел.

217
ответ дан Dave Verwer 23 November 2019 в 00:15
поделиться

Я прошел лишенное сна кодирование выполненные и запущенные только пишущие комментарии, которые были кавычками из Бойцовского клуба.

Все еще траление через код несколько лет спустя я нахожу комментарий, который заставляет меня смеяться. Большинство из них просто случайные мысли. Я действительно однако сохранял свои комментарии к отношению строк довольно хорошими!

// This shouldn't happen. The only way this can happen is if the
// <code>JFileChooser</code> has returned a <code>File</code> that doesn't exist
// on the system. If this happens we can't recover, and there is more than likely
// a rip in the space time continuum that the user is too distracted by to notice
// anything else.
<час>
 /**
   * This method leverages collective synergy to drive "outside of the box"
   * thinking and formulate key objectives into a win-win game plan with a
   * quality-driven approach that focuses on empowering key players to drive-up
   * their core competencies and increase expectations with an all-around
   * initiative to drive down the bottom-line. I really wanted to work the word
   * "mandrolic" in there, but that word always makes me want to punch myself in
   * the face.
   */
private void updateFileCountLabel() {
219
ответ дан 2 revs, 2 users 72% 23 November 2019 в 00:15
поделиться

Этот был живым доказательством, в производственном коде, эффектов микроуправления в нашей команде:

// I am not responsible of this code.
// They made me write it, against my will.

... сопровождаемый меньше, чем оптимальным кодом, задуманным нашим любимым техническим директором, который довольно любил снижение и код и кодирование инструкций в горла разработчиков (*).

, Конечно, когда руководитель проекта искал причину ошибки и нашел, это было в "меньше, чем оптимальный код", он был меньше, чем удивлен...

(*) я, конечно, упоминаю Могущественный Король VB ... Если Вы хотите оценить полную величину питания Могущественный Король VB , можно считать следующее ТАК сообщение: , Что самое странное кодировало стандарт, постановляют, что Вы были вынуждены следовать? ...

223
ответ дан 4 revs 23 November 2019 в 00:15
поделиться
# To understand recursion, see the bottom of this file 

У основания файла:

# To understand recursion, see the top of this file
230
ответ дан 2 revs, 2 users 89% 23 November 2019 в 00:15
поделиться

От Java 1.2 SwingUtilities:

doRun.run();  // ... "a doo run run".
233
ответ дан Josh Segall 23 November 2019 в 00:15
поделиться
// I am not sure if we need this, but too scared to delete. 
254
ответ дан 2 revs, 2 users 67% 23 November 2019 в 00:15
поделиться

Один из самых классических является комментарием, сделанным Pierre de Fermat о его известной "Последней теореме": "Поле этой страницы является немного слишком маленьким для записи доказательства".

Это взяло больше чем за 350 лет до того, как доказательство было найдено...

(Согласно Википедия это - оригинальный текст:)

Cubum autem в дуэтах cubos, AUT quadratoquadratum в дуэтах quadratoquadratos, и generaliter nullam в infinitum крайнем quadratum potestatem в дуэтах eiusdem nominis оценка фаса dividere cuius rei demonstrationem mirabilem нормальный detexi. Hanc marginis exiguitas не caperet.

... и переведенный на английский язык:

(Невозможно разделить куб на два куба или четвертое питание в два четвертых полномочия, или в целом, любое питание выше, чем второе в два как полномочия. Я обнаружил действительно изумительное доказательство этого, которое это поле является слишком узким для содержания.)

254
ответ дан 3 revs, 2 users 94% 23 November 2019 в 00:15
поделиться
//Dear future me. Please forgive me. 
//I can't even begin to express how sorry I am.  

И сегодня я просто нашел этого:

//private instance variable for storing age
public static int age;
212
ответ дан 4 revs, 3 users 67% 23 November 2019 в 00:15
поделиться
double penetration; // ouch
296
ответ дан 23 November 2019 в 00:15
поделиться

Наш администратор БД обнаружил это в середине хранимой процедуры в 3000 строк, написанной третьей стороной.

/* IF DOLPHINS ARE SO SMART, HOW COME THEY LIVE IN IGLOOS? */
172
ответ дан 23 November 2019 в 00:15
поделиться
/*
This isn't the right way to deal with this, but today is my last day, Ron
just spilled coffee on my desk, and I'm hungry, so this will have to do...
*/

return 12; // 12 is my lucky number
126
ответ дан 23 November 2019 в 00:15
поделиться
// no comments for you
// it was hard to write
// so it should be hard to read
186
ответ дан 23 November 2019 в 00:15
поделиться
Другие вопросы по тегам:

Похожие вопросы: