- 1
- 2
- 3
- 4
ClassName::~ClassName()
    {
    memset( this, 0, sizeof( *this ) );
    }Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+179
ClassName::~ClassName()
    {
    memset( this, 0, sizeof( *this ) );
    }Написано коллегой из теплой страны. Случайно нашел в коде :)
+115
columnDomain.Visible =
 (grid.MainView.RowCount >
0
&&
 !String.IsNullOrEmpty(
     ((ListItem)
  grid.MainView.
     GetRow(0)).Domain)
&&
  ((ListItem)
 grid.MainView.GetRow(0))
      .Domain !=
 ((ListItem)
 grid.MainView.GetRow(0))
     .DisplayName);Это реальное форматирование кода, очевидно сделанное для удобства чтения на узком и высокои мониторе :) И такого многие и многие экраны
+160
var begin_h = html.indexOf("<h1 class=\"header\">");
var end_h = html.indexOf("</h1>");
var data = "";
if (begin_h != -1 && end_h != -1) {
  data = html.substr(begin_h, end_h + 5); //5 - это длина тега </h1>, чтобы его тоже захватило
}Прелесть, найденная на гугл-ответах. Человек пишет расширение для Firefox.
−121
sub removeSpaces {
  my $str = $_[0];
  while ( $str =~ /[\t ]+/ ) {
    $str = $`.$';
  }
  return $str;
}Найдено при разборе скрипта подготовки данных для тестов.
+138
uses crt;
var c1,c2,c3,k,s:integer;
begin
clrscr;
s:=0;
for c1:=1 to 9 do
for c2:=0 to 9 do
for c3:=0 to 9 do
k:=c1*100+c2*10+c3+k;
if (k mod 5 =0) then writeln('LOADING...');
else if (k mod 7 = 0) then writeln('LOADING...');
else s:=s+k;
writeln('Obshie symaя=',s);
readln;
end.Вот как можно посчитать количество всех трехзначных чисел, которые не делятся на 5 или 7.
+165
<script>
var IllegalChars=new Array("select", "drop", ";", "--", "insert", "delete", "xp_", "update", "/", ":", "char(", "?", "`", "|", "declare", "convert", "cast(", "@@", "varchar", "2D2D", "4040", "00400040", "[", "]");
var IllegalFound=new Array();
var IllegalCharsCount=0;
function ResetCharsCount()
{
 IllegalCharsCount=0;
}
function wordFilter(form,fields)
{
	ResetCharsCount();
	var CheckTextInput;
	var fieldErrArr=new Array();
	var fieldErrIndex=0;
	for(var i=0; i<fields.length; i++)
	{
		CheckTextInput = document.forms[form].elements[fields[i]].value;
		for(var j=0; j<IllegalChars.length; j++)
		{
			for(var k=0; k<(CheckTextInput.length); k++)
			{
				if(IllegalChars[j]==CheckTextInput.substring(k,(k+IllegalChars[j].length)).toLowerCase())
				{
					IllegalFound[IllegalCharsCount]=CheckTextInput.substring(k,(k+IllegalChars[j].length));
					IllegalCharsCount++;
					fieldErrArr[fieldErrIndex]=i;
					fieldErrIndex++;
				}
			}
		}
	}
	var alert_text="";
	for(var k=1; k<=IllegalCharsCount; k++)
	{
		alert_text+="\n" + "(" + k + ")  " + IllegalFound[k-1];
		eval('CheckTextInput=document.' + form + '.' + fields[fieldErrArr[0]] + '.select();');
	}
	if(IllegalCharsCount>0)
	{
		alert("The form cannot be submitted.\nThe following errors were found:\n_______________________________\n" + alert_text + "\n_______________________________\n");
		return false;
	}
	else
	{
		return true;
		document.forms[form].submit();
	}
}
</script>
...
<FORM NAME="FormHome" ACTION="search.asp" METHOD="post" onSubmit="return wordFilter('FormHome',['criteria']);">
            http://www.cadw.wales.gov.uk/
Инъекция не пройдет.
        
+155
insert_image.php:
<?php
require_once('../config.inc.php');
if ((!isset($_SESSION['user_type'])) || ($_SESSION['user_type'] != 0)) {
    header('Location: /');
    die;
}
require('admin_image.inc.php');
settitle.php:
<?php
require_once('../config.inc.php');
if ((!isset($_SESSION['user_type'])) || ($_SESSION['user_type'] != 0)) {
    header('Location: /');
    die;
}
$id = intval($_POST['image']);
$title = $_POST['imgtitle'];
mysql_query("UPDATE images SET title='$title' WHERE id=$id");
require('admin_image.inc.php');
upload_image.php:
<?php
require_once('../config.inc.php');
if ((!isset($_SESSION['user_type'])) || ($_SESSION['user_type'] != 0)) {
    header('Location: /');
    die;
}
if ((isset($_POST['upload'])) && (isset($_FILES['newimage']))) {
    $title = (isset($_POST['title'])) ? $_POST['title'] : '';
    $file = $_FILES['newimage'];
    if ($file['error'] != 0) {
        $msg = 'An error occured during uploading file. (Error code:' . $file['error'] . ')';
    } else {
        $type = $file['type'];
        $tmp_name = $file['tmp_name'];
        //check if we are uploading image or not
        if (!(((preg_match('/\.gif/i', $file['name'])) || (preg_match('/\.jpg/i', $file['name'])) ||
                (preg_match('/\.jpeg/i', $file['name'])) || (preg_match('/\.bmp/i', $file['name'])) ||
                (preg_match('/\.png/i', $file['name'])))
                && ((preg_match('/gif/i', $file['type'])) || (preg_match('/jpg/i', $file['type'])) ||
                (preg_match('/jpeg/i', $file['type'])) || (preg_match('/bmp/i', $file['type'])) ||
                (preg_match('/png/i', $file['type']))))) {
            $msg = 'You are trying to upload a non-image file.';
        } elseif (filesize($tmp_name) <= 0) {
            $msg = 'You are trying to upload file which size is 0 bytes.';
        } else {
            $img_data = fread(fopen($tmp_name, 'r'), filesize($tmp_name));
            if (mysql_query("INSERT INTO images (id, image, type, title)"
                            . " VALUES ('',"
                            . " '" . mysql_escape_string($img_data) . "',"
                            . " '" . mysql_escape_string($type) . "',"
                            . " '" . mysql_escape_string($title) . "')"))
                $msg = 'Image uploaded.';
            else
                $msg = 'An error occured during inserting image in DB.';
        }
    }
}
if (isset($msg))
    $MyPage->assign('msg', $msg);
require('admin_image.inc.php');
            Какая экспрессия, какое необычное именование файлов... lower_case_with_underscores + просто текст
А главное какое необычное представление о модульности: 2 файла по 10 строк, и один на 40, в каждом из которых прописана авторизация и которые инклюдят главный файл
        
+174
(addNewItem) ? (isVideoAudioAttached = true) : (isVideoAudioAttached = false);addNewItem и isVideoAudioAttached типа bool
−181
from django.db import models
# Класс Студент
class Student(models.Model):
    name = models.CharField(max_length=50) # ФИО студента
    group = models.CharField(max_length=10) # Группа студента
    starosta = models.BooleanField(default=False) # Является ли студент старостой группы?
# Класс Пара
class Pair(models.Model):
    name = models.CharField(max_length=30) # Название пары
    auditory = models.CharField(max_length=7) # Аудитория
    lecturer = models.CharField(max_length=50) # ФИО преподавателя
# Класс День
class Day(models.Model):
    pair1 = models.ForeignKey(Pair) # Первая пара
    pair2 = models.ForeignKey(Pair) # Вторая пара
    pair3 = models.ForeignKey(Pair) # Третья пара
    pair4 = models.ForeignKey(Pair) # Четвёртая пара
    pair5 = models.ForeignKey(Pair) # Пятая пара
    pair6 = models.ForeignKey(Pair) # Шестая пара
    pair7 = models.ForeignKey(Pair) # Седьмая пара
# Класс Расписание
class TimeTable(models.Model):
    group = models.CharField(max_length=10) # Группа, к которой относится расписание
    weekcolor = models.BooleanField() # False, 0 - Красная неделя; True, 1 - Синяя неделя
    monday = models.ForeignKey(Day) # Понедельник
    tuesday = models.ForeignKey(Day) # Вторник
    wednesday = models.ForeignKey(Day) # Среда
    thursday = models.ForeignKey(Day) # Четверг
    friday = models.ForeignKey(Day) # Пятница
    saturday = models.ForeignKey(Day) # Суббота
            Очередной шедевр от Magister Yoda
Попытка сделать модель расписания для студентов.
        
−97
if row[0].find('lk_s_du') > -1 or row[0].find('lk_s_su') > -1:
    price = ''
    if row[6] == 'incoming_external':
        if tariff['ie_price_second'] == 0:
            price = row[5] * tariff['ie_price_first'] / 102400
        elif ie_global > tariff['ie_price_switch']:
            price = row[5] * tariff['ie_price_second'] / 102400
        else:
            price = overhead(tariff['ie_price_switch']-ie_global,tariff['ie_price_switch'])*tariff['ie_price_first'] / 102400 + hev((row[5]+ie_global-tariff['ie_price_switch']))*tariff['ie_price_second'] / 102400
        ie_global += row[5]
        unit = 'kb'
        if tariff['price_per_unit'] == 1:
            price = price /1024
            unit = 'mb'
        if tariff['price_per_unit'] == 2:
            price = price /1024/1024
            unit = 'gb'
        if tariff['price_per_unit'] == 3:
            price = price /1024/1024/1024
            unit = 'tb'
    if row[6] == 'internal':
        if tariff['il_price_second'] == 0:
            price = row[5] * tariff['il_price_first'] / 102400
        elif il_global > tariff['il_price_switch']:
            price = row[5] * tariff['il_price_second'] / 102400
        else:
            price = overhead(tariff['il_price_switch']-il_global,tariff['il_price_switch'])*tariff['il_price_first'] / 102400 + hev((row[5]+il_global-tariff['il_price_switch']))*tariff['il_price_second'] / 102400
        il_global += row[5]
        unit = 'kb'
        if tariff['price_per_unit'] == 1:
            price = price /1024
            unit = 'mb'
        if tariff['price_per_unit'] == 2:
            price = price /1024/1024
            unit = 'gb'
        if tariff['price_per_unit'] == 3:
            price = price /1024/1024/1024
            unit = 'tb'
    if row[6] == 'outgoing_any':
        if tariff['oe_price_second'] == 0:
            price = row[5] * tariff['oe_price_first'] / 102400
        elif oe_global > tariff['oe_price_switch']:
            price = row[5] * tariff['oe_price_second'] / 102400
        else:
            price = overhead(tariff['oe_price_switch']-oe_global,tariff['oe_price_switch'])*tariff['oe_price_first'] / 102400 + hev((row[5]+oe_global-tariff['oe_price_switch']))*tariff['oe_price_second'] / 102400
        oe_global += row[5]
        unit = 'kb'
        if tariff['price_per_unit'] == 1:
            price = price /1024
            unit = 'mb'
        if tariff['price_per_unit'] == 2:
            price = price /1024/1024
            unit = 'gb'
        if tariff['price_per_unit'] == 3:
            price = price /1024/1024/1024
            unit = 'tb'
    price = str(price).replace('.',',')Черная магия непосредственно тарификации интернет-трафика.