1. Pascal / Говнокод #5260

    +97

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    TPicture = class(TInterfacedPersistent, IStreamPersist)
    ....
        property Bitmap: TBitmap read GetBitmap write SetBitmap;
        property Icon: TIcon read GetIcon write SetIcon;
        property Metafile: TMetafile read GetMetafile write SetMetafile;
    ....
    
    procedure TPicture.ForceType(GraphicType: TGraphicClass);
    begin
      if not (Graphic is GraphicType) then
      begin
        FGraphic.Free; // 0_0 йобаный стыд!!
        FGraphic := nil;
        FGraphic := GraphicType.Create;
        FGraphic.OnChange := Changed;
        FGraphic.OnProgress := Progress;
        Changed(Self);
      end;
    end;
    
    function TPicture.GetBitmap: TBitmap;
    begin
      ForceType(TBitmap);
      Result := TBitmap(Graphic);
    end;
    
    function TPicture.GetIcon: TIcon;
    begin
      ForceType(TIcon);
      Result := TIcon(Graphic);
    end;
    
    function TPicture.GetMetafile: TMetafile;
    begin
      ForceType(TMetafile);
      Result := TMetafile(Graphic);
    end;

    Взято из "ДНК", т.е. VCL от Delphi7. unit graphics.pas

    Методы get-аксессоры свойств Bitmap, Icon и Metafile вызывают ForceType(). Шутка в том, что если картинка у вас другого типа - то она будет ВНЕЗАПНО выпилена насовсем, стоит только прочитать(sic!) не то свойство объекта класса TPicture.

    Наступил сам на эти грабли и потратил драгоценный, час пока понял в чем дело.

    StriderMan, 13 Января 2011

    Комментарии (21)
  2. PHP / Говнокод #5259

    +43

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    function ntfs_filesize($filename) 
    {
        return exec("
                for %v in (\"".$filename."\") do @echo %~zv
        ");
    }
    // LINUX SERVERS:
    // str perl_filesize( str $filename );
    /*
    DESCRIPTION: returns the filesize of a large file in string format to... 
    ... prevent 32-bit integer walls  using perl through linux command line.
    */
    function perl_filesize($filename) 
    {
        return exec("
                perl -e 'printf \"%d\n\",(stat(shift))[7];' ".$filename."
        ");
    }

    вот вам!
    http://ru.php.net/filesize отсюда.

    вообще ебанутость filesize в пхп теперь не позволит мне без костылей хранить на сайте файлы больше 2х гиг. хнык хнык
    (пока правдо не надо но я попутно свою файлопомойку хочу личную)

    brainstorm, 13 Января 2011

    Комментарии (9)
  3. PHP / Говнокод #5258

    +165

    1. 1
    2. 2
    3. 3
    if(strpos($email,'@')===FALSE)die('error');
    if(strpos($email,'.')===FALSE)die('error');
    if(strlen($email)<7)die('error');

    Четкая проверка почты. Регулярки зря придумывали :)

    assous, 13 Января 2011

    Комментарии (11)
  4. Python / Говнокод #5257

    −81

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    import psycopg2
    from loki.libs.net.ipaddr import IPAddress
    import sys
    sys.path.append('../libs/')
    
    try:
        loki_db = psycopg2.connect (port="15432", host="noc2.t72.ru", database="loki_db", user="utkin", password="2UtaWEvaspuv")
        loki_cur = loki_db.cursor()
    except:
        print "Нет коннекта к локи_дб"
    
    try:
        cherry_db = psycopg2.connect (port="5432", host="noc2.72.ru", database="cherry", user="utkin", password="2UtaWEvaspuv")
        cherry_cur = cherry_db.cursor()
    except:
        print "Нет коннекта к черри_дб"
    
    loki_cur.execute("""
    select id, nas_id, service, ip_addr_id from inet_inetsessionactive;
    """);
    
    rows = loki_cur.fetchall()
    
    for (id, nas_id, service, ip_addr_id) in rows:
        loki_cur.execute("""select ip from inet_nasserver where id = %s;""",(nas_id,))
        try:
            nas_ip = loki_cur.fetchone()[0]
        except:
            print "Нет записи о NAS-сервере"
        loki_cur.execute("""select addr from inet_ouripall where id = %s;""",(ip_addr_id,))
    
        ip = str(IPAddress(int(loki_cur.fetchone()[0]))._ip)
    
        cherry_cur.execute("""select client_id, water_mark from inet_dynamic_ip_services where id = %s;""", (service,))
        try:
            (client_id, water_mark) = cherry_cur.fetchone()
        except:
            print "Нет записи в таблице inet_dynamic_ip_services: id, nas_id, service = (%s, %s, %s)"%(id, nas_id, service)
            
        cherry_cur.execute("""select balance from base_clients where client_id = %s;""",(client_id,));
        try:
            balance = cherry_cur.fetchone()[0]
            if balance <= water_mark:
                kill(ip, nas_ip)
        except:
            print "Нет записи в base_clients: client_id = %s"%client_id

    tanenn, 13 Января 2011

    Комментарии (15)
  5. JavaScript / Говнокод #5256

    +162

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    function check_all(){
    	<?
    		if(!empty($this->params["show"]))  foreach($this->params["show"] as $key_ar => $ar){			
    			echo "document.getElementById('id[".$ar["id"]."]').checked=true; \n";
    		}
    	?>
    }

    Вот так в проектах одной из ведущих компаний по разработке сайтов в моем городе пишут функции для выбора всех checkbox.
    p.s. сам код в HTML файле. $this->params["show"] это массив данных полученный после запроса к mysql (фактически выборка данных из справочника)
    p.p.s на сайте даже jquery подключен.

    supercoder, 13 Января 2011

    Комментарии (5)
  6. C# / Говнокод #5255

    +119

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    public enum PageType
    {
        Default,
        Billing,
        UserCabinet
    }
    
    public PageType GetPageType(int code)
    {
         if(code == 1){return PageType.Default;}
         if(code == 2){return PageType.Billing;}
         if(code == 3){return PageType.UserCabinet;}
         return PageType.Default;
    }
    
    private int PageType
    {
        get
        {
                int page;
                Int32.TryParse(Request["page"], out page);
                return page;
        }
    }

    Думаю что объяснять тут ничего не нужно...

    Arnezami, 13 Января 2011

    Комментарии (1)
  7. C# / Говнокод #5254

    +112

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    static Concept()
            {
                s_deserialize = new Dictionary<string, deserializationHandler>
                                    {{"1.0", (deserialize_1_0)}};
            }
    
            private static void serialize(Concept concept, BinaryWriter writer)
      {
                writer.Write ( concept.Name );
                writer.Write ( concept.Score );
    
                writer.Write ( concept.Documents.Count );
                foreach (var doc in concept.Documents)
                    writer.Write(doc.ToString());
    
                writer.Write ( concept.Nested.Count );
                foreach (var nested in concept.Nested)
                    serialize ( nested, writer );
    }
    
           public static List<Concept> Deserialize(Stream stream)
            {
                using (var reader = new BinaryReader(stream, Encoding.UTF8))
                {
                    var version = reader.ReadString();
                    if (!s_deserialize.ContainsKey(version))
                        throw new NotSupportedException(String.Format("Unsupported version of format. Version: {0}", version));
    
                    var concepts = new List<Concept>(50);
                    s_deserialize[version](null, concepts, reader);
                    return concepts;
                }
            }
    
    private delegate void deserializationHandler(Concept parent, IList<Concept> concepts, BinaryReader reader);
    
    private static readonly Dictionary<string, deserializationHandler> s_deserialize;
    
      private static int s_lastId = 0;
           private static int getNextConceptId()
            {
                if (s_lastId == Int32.MaxValue)
                    s_lastId = 0;
                return System.Threading.Interlocked.Increment(ref s_lastId);
            }
    
    private static void deserialize_1_0(Concept parent, IList<Concept> concepts, BinaryReader reader)
    		{
                for (var i = reader.ReadInt32(); i > 0; i--)
    			{
                    var c = new Concept(reader.ReadString(), reader.ReadDouble(), parent);
    				concepts.Add(c);
    
                    for (var d = reader.ReadInt32(); d > 0; d--)
                        c.Documents.Add(Convert.ToInt32(reader.ReadString()));
    
    				deserialize_1_0(c, c.Nested, reader);
    			}
            }
    }

    Человек в очередной раз изобрел свой велосипед, на этот раз как сериализовать _свои_ классы - с поддержкой версий! По тому что некоторые переменные в классе были помечены [NonSerialized] было похоже что он что то слышал про уже имеющиеся но решил как обычно что самописный - всегда лучше. Но аттрибуты оставил - на всякий пожарный :)

    eval_2009, 13 Января 2011

    Комментарии (0)
  8. Python / Говнокод #5253

    −97

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    import string
    k=input()
    a=range(1000)
    if k==1:
            a[0]=input()
    else:
            t = string.replace(str(raw_input()), ' ', ', ')
            a=eval('('+t+')')

    4
    2 3 4 5
    ----
    Не знаю я питон :(
    По другому не смог быстро написать..

    Tanger, 13 Января 2011

    Комментарии (2)
  9. PHP / Говнокод #5252

    +161

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    function toTrash($id)
        {
            $data = array(
                'order_id'          => $id,
                'order_archived'    => 0,
                'order_trashed'     => 1,
    			'order_candelled' 	=> 0
            );
    
            return $this->update_order($data);
        }
    
        function toArchive($id)
        {
            $data = array(
                'order_id'          => $id,
                'order_archived'    => 1,
                'order_trashed'     => 0,
    			'order_candelled' 	=> 0
            );
    
            return $this->update_order($data);
        }
    
        function restore($id)
        {
            $data = array(
                'order_id'          => $id,
                'order_archived'    => 0,
                'order_trashed'     => 0
    			'order_candelled' 	=> 0
            );
    
            return $this->update_order($data);
        }
    	    
    	function cancelled($id)
    	    {
    	        $data = array(
    	            'order_id'          => $id,
    	            'order_archived'    => 0,
    	            'order_trashed'     => 0,
    				'order_candelled' 	=> 1
    	        );
    
    	        return $this->update_order($data);
    	    }

    DyX_LesA, 12 Января 2011

    Комментарии (9)
  10. PHP / Говнокод #5251

    +170

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    function loger2($comment)
    {
    	$f = fopen(dirname(__FILE__).'/log2.html', 'a+');
    	fwrite($f, $comment);
    	fclose($f);
    }
    function loger($comment)
    {
    	$f = fopen(dirname(__FILE__).'/log.html', 'a+');
    	fwrite($f, $comment);
    	fclose($f);
    }

    loger100500?

    govnozmey, 12 Января 2011

    Комментарии (11)