1. Куча / Говнокод #12569

    +141

    1. 1
    http://sqlserverplanet.com/troubleshooting/cannot-insert-explicit-value-for-identity-column-in-table-table-when-identity_insert-is-set-to-off

    Последний комментарий

    denis90, 11 Февраля 2013

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

    +88

    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
    //До рефакторинга
    static function initConnectOnce(){
        $who = get_called_class();
        if(!$GLOBALS[$who][class_cllct]){
            $db = new DataBase();
            $GLOBALS[$who][class_cllct] = $db->selectCollection(get_called_class());
        }
        return $GLOBALS[$who][class_cllct];
    }
    //После
    public static function initCollectOnce(){
        $who = get_called_class();  
        $cllct = &self::$cacheCollect[$who];
        if(!$cllct){
            $db = new DataBase();
            $cllct = $db->selectCollection($who);
        }
        return $cllct;
    }

    Недавно начал рефакторить свой же код. Нашел такой вот незаметный гавнокод...
    Для тех кто в танке =)
    1. selectCollection(get_called_class()) - зачем вызывать по второму разу, если результат уже есть в переменной $who.
    2. $GLOBALS[$who][class_cllct] - немного глюкнуло наверное, когда писал... Логичнее так $GLOBALS[class_cllct][$who].
    3. initConnectOnce - тут даже наверное не Connect должно быть, а Collect.
    4. Вместо $GLOBALS[$who][class_cllct] лучше(имхо) заюзать статичное свойство для класса.
    5. static function initConnectOnce - забыл public описать....

    haker, 11 Февраля 2013

    Комментарии (16)
  3. Java / Говнокод #12567

    +61

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    public void insert()
    {
        super.insert();
        if (this.ItemId == "")
            this = this;
    }

    нарочно не придумаешь

    bodeaux, 11 Февраля 2013

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

    +135

    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
    namespace CuttingBox
    {
    
        class Program
        {
            static public Tuple<int[], String> getProperty()
            {
                int[] itemDimensionProperty = new int[3];
                String itemColorProperty;
                String[] parseResult = new String[4];
                parseResult = (Console.ReadLine().Split(' '));
                for (int counter = 0; counter < 3; counter++)
                {
                    itemDimensionProperty[counter] = Convert.ToInt32(parseResult[counter]);
                }
                itemColorProperty = parseResult[3];
                Tuple<int[], String> itemProperty = new Tuple<int[], string>(itemDimensionProperty, itemColorProperty);
                return itemProperty;
            }
    
            static void Main(string[] args)
            {
                List<Tuple<int[], String>> itemProperty = new List<Tuple<int[], String>>();
                itemProperty.Add(getProperty());
                int numberOfBoxes = Convert.ToInt32(Console.ReadLine());
                for (int counter=1; counter<=numberOfBoxes; counter++){
                    itemProperty.Add(getProperty());
                }
            }
        }
    }

    Парсим строки правильно...

    javanesovsemgovno, 11 Февраля 2013

    Комментарии (3)
  5. Куча / Говнокод #12565

    +141

    1. 1
    http://habrahabr.ru/post/168723/

    Я даже копипастить всё не буду.

    kasthack, 10 Февраля 2013

    Комментарии (12)
  6. Pascal / Говнокод #12564

    +86

    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
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    Function TMainForm.PrimGenerateMaze(Width, Height: Integer): Maze;
    
    Type Point = record
      x, y: Integer;
    end;
    
    Var
      TehMaze: Maze;
      Todo: array of Point;
      todonum: integer;
      x,y,n,d: integer;
    
    Const
      dx: array [0..3] of Integer = (0, 0, -1, 1);
      dy: array [0..3] of Integer = (-1, 1, 0, 0);
    
    BEGIN
      SetLength(TehMaze, Width, Height);
      SetLength(Todo, (Width * Height) - 1);
    
      For x:=0 to Width-1 do
        For y:=0 to Height-1 do
          If (x = 0) or (x = Width-1) or (y = 0) or (y = Height-1) then
            TehMaze[x][y]:=32
          Else TehMaze[x][y]:=63;
    
      Randomize;
      x := Random(Width-2)+1;
      y := Random(Height-2)+1;
      todonum := 0;
    
      TehMaze[x][y]:= TehMaze[x][y] and not 48; // Пометить клетку как принадлежащую лабиринту
    
       // Пока не обработаны все клетки
       Repeat
        Begin
           // Занести в список todo все ближайшие необработанные клетки
           For d:=0 to 3 do
               if (TehMaze[x + dx[d]][y + dy[d]] and 16) <> 0 then
               Begin
                 todo[todonum].x := x + dx[d];
                 todo[todonum].y := y + dy[d];
                 Inc(todonum);
                 TehMaze[x + dx[d]][y + dy[d]] := TehMaze[x + dx[d]][y + dy[d]] and not 16;
               End;
    
           // Выбрать из списка todo произвольную клетку
           n:= Random(todoNum);
           x:= ToDo[n].x;
           y:= ToDo[n].y;
    
           // Удалить из списка обработанную клетку
           Dec(todonum);
           ToDo[n]:= todo[todonum];
    
           // Выбрать направление, которое ведет к лабиринту
           Repeat
               d:=Random(4);
           Until ((TehMaze[x + dx[d]][y + dy[d]] and 32) = 0);
    
           // Присоединить выбранную клетку к лабиринту
           TehMaze[x][y] := TehMaze[x][y] and not ((1 shl d) or 32);
           TehMaze[x + dx[d]][y + dy[d]] := TehMaze[x + dx[d]][y + dy[d]] and not (1 shl (d xor 1));
        End;
       Until (todonum = 0);
    
       TehMaze[1][1] := TehMaze[1][1] and -2;                 // начало лабиринта - в левом верхнем углу
       TehMaze[Width-2][Height-2] := TehMaze[Width-2][Height-2] and not 2; // конец лабиринта - в правом нижнем углу
    
       Result := TehMaze;
    END;

    Генерация лабиринтов по алгоритму Прима.

    Govnocoder#0xFF, 10 Февраля 2013

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

    +12

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    class Thread
    {
    public:
    	Thread(const Thread&);
    	Thread() : handle(NULL), running(false), finished(false)
    	{
    		handle = (HANDLE)(_beginthreadex(NULL, 0, &(Thread::threadRun), this, CREATE_SUSPENDED, NULL));
    	}
    	~Thread()
    	{
    		if(isRunning()) {
    			TerminateThread(handle, 0);
    		} 
    
    		CloseHandle(handle);
    	}
    	void start(void* arg)
    	{
    		if(isRunning() || isFinished()) {
    			throw Exception("Thread is running or finished!");
    		} else {
    			this->arg = arg;
    			ResumeThread(handle);
    		}
    		
    	}
    	void pause()
    	{
    		if(isRunning()) {
    			SuspendThread(handle);
    		} else {
    			throw Exception("Thread is not running or finished!");
    		}
    	}
    	void resume()
    	{
    		if(!(isRunning())) {
    			throw Exception("Thread is finished!");
    		} else {
    			ResumeThread(handle);
    		}
    	}
    	void stop()
    	{
    		if(isRunning()) {
    			TerminateThread(handle, 0);
    			running = false;
    			finished = true;
    			throw Exception("Thread stopped!");
    		} else {
    			throw Exception("Thread is not running or finished!");
    		}
    	}
    	void setPriority(ThreadPriority priority)
    	{
    		if(isFinished()) {
    			throw Exception("Thread is finished!");
    		} else {
    			switch(priority) {
    			case ThreadPriorityLow:
    				SetThreadPriority(handle, THREAD_PRIORITY_LOWEST);
    				break;
    			case ThreadPriorityNormal:
    				SetThreadPriority(handle, THREAD_PRIORITY_NORMAL);
    				break;
    			case ThreadPriorityHigh:
    				SetThreadPriority(handle, THREAD_PRIORITY_HIGHEST);
    				break;
    			default:
    				throw Exception("Invalid priority!");
    				break;
    			}
    		}
    	}
    	bool isRunning()
    	{
    		return (running);
    	}
    	bool isFinished()
    	{
    		return (finished);
    	}
    protected:
    	virtual void run(void *arg) = 0;
    private:
    	static unsigned int __stdcall threadRun(void *arg)
    	{
    		Thread *thread = static_cast<Thread*>(arg);
    		thread->running = true;
    		thread->run(thread->arg);
    		thread->running = false;
    		thread->finished = true;
    		_endthreadex(0);
    		return (0);
    	}
    	void *arg;
    	HANDLE handle;
    	bool running;
    	bool finished;
    };

    Из предыдущей оперы.

    dreesto, 10 Февраля 2013

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

    +7

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    template<typename T>
    class Enumerable
    {
    public:
    	Enumerable() : enumerableInProcess(false) { };
    	virtual void begin() = 0;
    	virtual void end() = 0;
    	virtual bool enumeration(T* item) = 0;
    protected:
    	bool enumerableInProcess;
    };
    template<typename T>
    class List : Enumerable<T*>
    {
    public:
    	class ListItem
    	{
    	public:
    		friend class List;
    		T item;
    		ListItem(T item) : item(item), next(nullptr), previous(nullptr)
    		{
    		}
    	private:
    		class ListItem* next;
    		class ListItem* previous;
    	};
    
    	/* ... */
    	
    	void begin()
    	{
    		if(enumerableInProcess) {
    			throw Exception("Error Enumerable!");
    		}
    
    		enumerableInProcess = true;
    		enumerationItem = first;
    	}
    	bool enumeration(T** item)
    	{
    		if(enumerableInProcess) {
    			if(enumerationItem != nullptr) {
    				(*item) = &(enumerationItem->item);
    				enumerationItem = enumerationItem->next;
    				return (true);
    			} else {
    				(*item) = nullptr;
    				return (false);
    			}
    		} else {
    			throw Exception("Error Enumerable!");
    		}
    	}
    	bool enumeration(ListItem **listItem)
    	{
    		if(enumerableInProcess) {
    			if(enumerationItem != nullptr) {
    				(*listItem) = enumerationItem;
    				enumerationItem = enumerationItem->next;
    				return (true);
    			} else {
    				(*listItem) = nullptr;
    				return (false);
    			}
    		} else {
    			throw Exception("Error Enumerable!");
    		}
    	}
    	void end()
    	{
    		if(!enumerableInProcess) {
    			throw Exception("Error Enumerable!");
    		}
    		enumerableInProcess = false;
    	}
    private:
    	const int size;
    	int count;
    	ListItem *first;
    	ListItem *last;
    	ListItem *enumerationItem;
    };
    void list_t_1()
    {
    	List<int> list(8);
    	List<int>::ListItem *item;
    	list.add(1);
    	list.add(2);
    	list.add(4);
    	list.add(8);
    	list.add(16);
    
    	list.begin();
    	while(list.enumeration(&item))
    	{
    		printf("%i\n", (item->item));
    	}
    	list.end();
    }

    dreesto, 09 Февраля 2013

    Комментарии (13)
  9. Java / Говнокод #12561

    +75

    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
    public class ExtractSubstrings {
    	public static void main(String[] args) {
    		String text = “To be or not to be”;
    		int count = 0;
    		char separator = ‘ ‘;
    
    		int index = 0;
    		do {
    			++count;
    			++index;
    			index = text.indexOf(separator, index);
    		} while (index != -1);
    
    		String[] subStr = new String[count];
    		index = 0;
    		int endIndex = 0;
    	
    		for(int i = 0; i < count; ++i) {
    			endIndex = text.indexOf(separator,index);
    			
    			if(endIndex == -1) {
    				subStr[i] = text.substring(index);
    			} else {
    				subStr[i] = text.substring(index, endIndex);
    			}
    			
    			index = endIndex + 1;
    		}
    
    		for(String s : subStr) {
    			System.out.println(s);
    		}
    	}
    }

    Очень чёткий, простой и с первого взгляда сразу понятный способ сделатЬ сплит строки.

    taburetka, 09 Февраля 2013

    Комментарии (34)
  10. C# / Говнокод #12560

    +140

    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
    string num = number.ToString();
    num = num.Replace(',', '.');
    string num2 = number2.ToString();
    num2 = num2.Replace(',', '.');
    int displace = 0;
    
    int i = 0;
    for (i = 0; i <= num.Length - 1; i++)
    {
        if (num.Substring(i, 1) != ".")
        {
            int curNum = Convert.ToInt16(num.Substring(i, 1));
            Microsoft.Xna.Framework.Rectangle source = new Microsoft.Xna.Framework.Rectangle(curNum * 46, 0, 46, 64);
            sb.Draw(numbers, new Microsoft.Xna.Framework.Rectangle((int)position.X + (i * 24), (int)position.Y - 5, (int)(46.0f * scale), (int)(64.0f * scale)), source, color);
        }
        else
        {
            Microsoft.Xna.Framework.Rectangle source = new Microsoft.Xna.Framework.Rectangle(10 * 46, 0, 46, 64);
            sb.Draw(numbers, new Microsoft.Xna.Framework.Rectangle((int)position.X + (i * 24), (int)position.Y - 5, (int)(46.0f * scale), (int)(64.0f * scale)), source, color);
        }
        displace += (int)(46.0f * scale);
    }
    Microsoft.Xna.Framework.Rectangle src = new Microsoft.Xna.Framework.Rectangle(11 * 46, 0, 46, 64);
    sb.Draw(numbers, new Microsoft.Xna.Framework.Rectangle((int)position.X + displace, (int)position.Y - 5, (int)(46.0f * scale), (int)(64.0f * scale)), src, color);
    displace += (int)(46.0f * scale);
    for (i = 0; i <= num2.Length - 1; i++)
    {
        if (num2.Substring(i, 1) != ".")
        {
            int curNum = Convert.ToInt16(num2.Substring(i, 1));
            Microsoft.Xna.Framework.Rectangle source = new Microsoft.Xna.Framework.Rectangle(curNum * 46, 0, 46, 64);
            sb.Draw(numbers, new Microsoft.Xna.Framework.Rectangle((int)position.X + (i * 24) + displace, (int)position.Y - 5, (int)(46.0f * scale), (int)(64.0f * scale)), source, color);
        }
        else
        {
            Microsoft.Xna.Framework.Rectangle source = new Microsoft.Xna.Framework.Rectangle(10 * 46, 0, 46, 64);
            sb.Draw(numbers, new Microsoft.Xna.Framework.Rectangle((int)position.X + (i * 24) + displace, (int)position.Y - 5, (int)(46.0f * scale), (int)(64.0f * scale)), source, color);
        }
    }

    Nuff said.
    Как я тогда давным давно поленился импортировать неймспейс XNA - чёрт его знает.

    RaZeR, 09 Февраля 2013

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