- 1
- 2
- 3
- 4
- 5
- 6
- 7
public static class ColorExtension
{
public static bool IsDarkColor(this Color color)
{
return (color.R & 255) + (color.G & 255) + (color.B & 255) < 3*256/2;
}
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+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...? Запуск потоков.
+91
<? die;
if($_GET['tn'])
{
if(($i = $conf['settings'][$s = "{$arg['modpath']}=>img"]) && ($img = explode(",", $i))){ $tn = array_combine($img, $img); }else{
$tn = array($_GET['tn']=>preg_replace('/[^0-9a-z_]/', '', $_GET['tn']));
} $sql = "SELECT `". mpquot($_GET['fn'] ? $_GET['fn'] : "img"). "` FROM {$conf['db']['prefix']}{$arg['modpath']}_{$tn[$_GET['tn']]} WHERE id=".(int)$_GET['id'];
$file_name = mpopendir("include")."/".($fn = mpql(mpqw($sql), 0, ($_GET['fn'] ? $_GET['fn'] : "img")));
if(!array_search(array_pop(explode('.', $file_name)), array(1=>"jpg", "jpeg", "png", "gif"))){
$file_name = mpopendir("img/ext/". array_pop(explode('.', $file_name)). ".png");
}
}else{
$file_name = mpopendir("modules/{$arg['modpath']}/img/". basename($_GET['']));
} header ("Content-type: image/". array_pop(explode('.', $file_name)));
echo mprs($file_name, $_GET['w'], $_GET['h'], $_GET['c']);
?>
это не шуууутки мы встретились в маршруууутке
+76
if ( !log.append(log_line) )
log.append("Can't append to log");
Безумие, оно рядом.
+158
$i = 0;
for ($k = 0; $k<=5; $k++){
if ($i==5)
break;
foreach (getContent($id) as $content_row) {
$i++;
$htmlshowcase = $content_row->getShowcase(1, $k);
if ($htmlshowcase == '')
$i--;
else
$html .= $htmlshowcase;
if ($i==5)
break;
}
}
Лучший способ прохода по циклу.