1. Column, Row, and Minigrid Elimination (CRME)

이번 챕터에서는 Column, Row, and Minigrid Elimination (CRME)을 이용하여 퍼즐을 해결한다. 아마도 난이도가 높은 퍼즐은 단순한 CRME 만 가지고는 해결이 안될터지만, 향후에 해결할 것 같다.

일단 기본 생각은 아래와 같다.



Scan each cell in the grid from left to right, top to bottom

	For each cell:

		Set possible values for each cell to 123456789

		Scan its column and eliminate the values already present in the column
		Scan its row and eliminate the values already present in the row
		Scan its minigrid and eliminate the values already present in the minigrid

		If there is only one possible value for the cell,
			the number for the cell is confirmed

Until no more cells can be confirmed






2. 예외

  • 해결 불가능한 퍼즐
  • 플레이어가 입력한 값으로 인해 퍼즐이 해결 불가능해 질 경우

위 두가지 상황에서는 경고를 한다.



3. CRME 구현


아래의 member variable을 Form1 class에 추가한다.



		//	for CRME technique
		private String [,] possible = new String[9, 9];
		private Boolean HintMode;


possible[,]은 각 셀의 가능한 값들을 저장한다. String 클래스의 Replace() 같은 메쏘드를 이용하는 것이 편리하여 String 타입으로 선언. HintMode는 유저가 힌트를 요구했는지를 보관하는 변수. 만약에 HintModetrue 이면, CRME 알고리즘은 현재 셀의 값을 찾아 확정하고, 다른 셀의 값을 찾지 않고 콘트롤을 유저에게 넘긴다.



4. SetCell() 수정


아래 코드와 같이 (추가 부분)을 추가한다. 세을 지울경우 possible value 값을 초기화 하는 루틴이다.



		//
		//	set a cell to a given value
		//
		public void SetCell( int col, int row, int value, int erasable )
		{
			//	locate particular Label control
			Control [] lbl = this.Controls.Find( col.ToString() + row.ToString(), true );
			Label cellLabel = lbl[0] as Label;

			//	save the value in the array
			actual[col, row] = value;

			//	if erasing a cell, you need to reset the possible values
			//		for all cells
			//	(추가 부분)
			if ( value == 0 )
				for ( int r = 1; r < 10; r++ )
					for ( int c = 1; c < 10; c++ )
						if ( actual[c, r] == 0 )
							possible[c, r] = String.Empty;


			//	set the appearance for the Label control
			if ( value == 0 )		//	erasing the cell
			{
				cellLabel.Text = String.Empty;
				cellLabel.Tag = erasable;
				cellLabel.BackColor = DEFAULT_BACKCOLOR;
			}
			else
			{
				if ( erasable == 0 )
				{
					//	means default puzzle values
					cellLabel.BackColor = FIXED_BACKCOLOR;
					cellLabel.ForeColor = FIXED_FORECOLOR;
				}
				else
				{
					//	means user-set value
					cellLabel.BackColor = USER_BACKCOLOR;
					cellLabel.ForeColor = USER_FORECOLOR;
				}

				cellLabel.Text = value.ToString();
				cellLabel.Tag = erasable;
			}
		}



5. ToolTip Control 추가


유저가 퍼즐을 해결하는데 도움을 주기위해 아래 그림과 같이 possible value를 표시해주는 ToolTip Control을 추가한다. 마우스 커서가 해당 셀에 위치할 때 possible value들을 표시한다.



ToolTip Control을 추가하기 위해, ToolBox의 Common Controls -> ToolTip 을 찾아 더블클릭한다.



그리고 아래의 코드를 추가한다.



		//
		//	set the Tooltip for a Label Control
		//

		public void SetToolTip( int col, int row, String possibleValues )
		{
			//	locate the particular Label Control
			Control [] lbl = this.Controls.Find( col.ToString() + row.ToString(), true );
						
			toolTip1.SetToolTip( lbl[0] as Label, possibleValues );

		}


그리고 StartNewGame() 함수에 toolTip1.RemoveAll(); 을 아래와 같이 추가한다.



		//
		//	start a new game
		//
		public void StartNewGame()
		{
			saveFileName = String.Empty;
			txtActivities.Text = String.Empty;
			seconds = 0;

			ClearBoard();

			GameStarted = true;
			timer1.Enabled = true;
			toolStripStatusLabel1.Text = "New game started";

			toolTip1.RemoveAll();
		}



6. 셀의 입력 가능한 값 계산

CalculatePossibleValues() 함수를 아래와 같이 작성하고 추가한다. CalculatePossibleValues()는 해당 셀의 입력 가능한 값을 String으로 리턴하며, 만약 Empty면 Exception을 발생한다.



		//
		//	Calculate the possible values for a cell
		//

		public string CalculatePossibleValues( int col, int row )
		{
			String str;

			if ( possible[col, row] == String.Empty )
				str = "123456789";
			else
				str = possible[col, row];

			//	step 1. check by column

			for ( int r = 1; r < 10; r++ )
				if ( actual[col, r] != 0 )
					//	that means there is an actual value on it
					str = str.Replace( actual[col, r].ToString(), String.Empty );

			//	step 2. check by row

			for ( int c = 1; c < 10; c++ )
				if ( actual[c, row] != 0 )
					//	that means there is an actual value on it
					str = str.Replace( actual[c, row].ToString(), String.Empty );

			//	step 3. check by minigrid

			int startC = col - ( ( col - 1 ) % 3 );
			int startR = row - ( ( row - 1 ) % 3 );

			for ( int rr=startR; rr < startR + 3; rr++ )
				for ( int cc=startC; cc < startC + 3; cc++ )
					if ( actual[cc, rr] != 0 )
						//	that means there is a actual value on it
						str = str.Replace( actual[cc, rr].ToString(), String.Empty );

			//	if possible value is an empty string then error,
			//	because of invalid move

			if ( str == String.Empty )
				throw new Exception( "Invalid Move" );

			return str;
		}



7. Grid 탐색


CheckColumnsAndRows() 함수는 그리드를 검사하여 각 셀을 검사한다. CalculatePossibleValues()를 호출하고 이를 ToolTip Control과 연계시킨다. 만약에 입력 가능한 값이 한개로 결정되면, 셀의 값으로 저장한다. 만약에 유저가 힌트를 요구했을 경우, 첫번째로 값이 결정된 



		//
		//	Calculates the possible values for all the cells
		//
		public Boolean CheckColumsAndRows()
		{
			Boolean changes = false;

			//	check all cells
			for(int row = 1; row < 10;row++)
			{
				for(int col = 1;col < 10;col++)
				{
					if(actual[col,row] == 0)
					{
						try
						{
							possible[col, row] = CalculatePossibleValues(col,row);
						}

						catch(Exception ex)
						{
							DisplayActivity("Invalid placement, please undo move", false);

							throw new Exception("Invalid Move");
						}

						//	display the possible values in the ToolTip
						SetToolTip( col, row, possible[col, row] );

						if ( possible[col, row].Length == 1 )
						{
							//	that means a number is confirmed
							SetCell( col, row, int.Parse( possible[col, row] ), 1 );

							//	number is confirmed
							actual[col, row] = int.Parse( possible[col, row] );
							DisplayActivity( "Col/Row and Minigrid Elimination", false );
							DisplayActivity( "=========================", false );
							DisplayActivity( "Inserted value " + actual[col, row] + " in"
												+ "(" + col + ", " + row + ")", false );

							//	get the UI of the application to refresh
							//		with the newly confirmed number
							Application.DoEvents();

							//	saves the move into the stack
							Moves.Push( col.ToString() + row.ToString() + possible[col, row] );

							// if user only ask for a hint, stop at this point
							changes = true;

							if ( HintMode )
								return true;

						}
					}
				}
			}

			return changes;
		}


8. Hint / Solve Puzzle 기능 구현

Hint 버튼과 Solve Puzzle 버튼의 이벤트 핸들러를 생성하고 아래와 같이 수정한다.



		//
		//	Hint button
		//
		private void btnHint_Click( object sender, EventArgs e )
		{

			//	show hints one cell at a time
			HintMode = true;

			try
			{
				SolvePuzzle();
			}
			catch
			{
				MessageBox.Show(
					"Please undo your move",
					"Invalid Move",
					MessageBoxButtons.OK,
					MessageBoxIcon.Error );
			}
		}



		//
		//	Solve Puzzle button
		//
		private void btnSolvePuzzle_Click( object sender, EventArgs e )
		{

			//	solve the puzzle
			HintMode = false;

			try
			{
				SolvePuzzle();
			}
			catch
			{
				MessageBox.Show(
					"Pleas undo your move",
					"Invalid Move",
					MessageBoxButtons.OK,
					MessageBoxIcon.Error );
			}
		}


그리고 SolvePuzzle()은 다음과 같이 작성한다.



		//
		//	Steps to solve the puzzle
		//
		public bool SolvePuzzle()
		{

			bool changes;
			bool ExitLoop = false;

			try
			{
				do
				{
					//	perform Col/Row and Minigrid Elimination
					changes = CheckColumsAndRows();

					if ( ( HintMode && changes ) || IsPuzzleSolved() )
					{
						ExitLoop = true;
						break;
					}
				} while ( !changes );
			}
			catch
			{
				throw new Exception( "Invalid Move" );
			}

			if ( IsPuzzleSolved() )
			{
				timer1.Enabled = false;
				Console.Beep();
				toolStripStatusLabel1.Text = "**** Puzzle Solved ****";
				MessageBox.Show( "Puzzle Solved" );
				return true;
			}
			else
				return false;


		}



테스트한다.

여기까지 과정중에 알게된 문제점은, Game start를 하기전에 Hint 나 Solve Puzzle 버튼을 누르면, exception 이 발생하는 점, 그리고 Hint나 Solve Puzzle 버튼을 눌러 셀 값을 찾는데 있어서, 하나의 셀값도 확정값을 찾지 못할경우 무한루프에 빠지는 점 두가지이다.

SolvePuzzle()에 다음과 같이 내 임의로 수정했다.



		//
		//	Steps to solve the puzzle
		//
		public bool SolvePuzzle()
		{
			bool changes;
			bool ExitLoop = false;

			int loopCounter = 0;


			//	if game is not started, return
			if ( !GameStarted )
				return false;

			try
			{
				do
				{
					//	perform Col/Row and Minigrid Elimination
					changes = CheckColumsAndRows();

					if ( ( HintMode && changes ) || IsPuzzleSolved() )
					{
						ExitLoop = true;
						break;
					}

					if ( loopCounter++ == 3 )
						return false;


				} while ( !changes );
			}
			catch
			{
				throw new Exception( "Invalid Move" );
			}

			if ( IsPuzzleSolved() )
			{
				timer1.Enabled = false;
				Console.Beep();
				toolStripStatusLabel1.Text = "**** Puzzle Solved ****";
				MessageBox.Show( "Puzzle Solved" );
				return true;
			}
			else
				return false;

		}



이렇게 수정해도 툴팁 업데이트 로직이 이해가 가질 않는다. hint 나 solve puzzle 버튼이벤트에 의해 값이 찾아지는 셀까지 툴팁 업데이트가 이뤄진다. 이것은 나중에 내가 해결한다.

Posted by 쿨한넘


1. Undo 와 Redo


움직임의 undo는 Moves stack에서 pop, 그리고 이를 RedoMoves stack에 push, 반대로 redo는 RedoMoves stack에서 pop, 이것을 Moves stack에 push 한다. 디자인 뷰에서 Edit -> Undo를 선택하고 더블클릭하여 이벤트 핸들러 코드를 생성하고 다음과 같이 수정한다.



		//
		//	undo a move
		//
		private void undoToolStripMenuItem_Click( object sender, EventArgs e )
		{
			//	if no previous moves, then exit
			if ( Moves.Count == 0 )
				return;

			//	remove from the Moves stack and push into the RedoMoves stack
			String str = Moves.Pop();
			RedoMoves.Push( str );

			//	save the value in the array
			SetCell( int.Parse( str.Substring( 0, 1 ) ), int.Parse( str.Substring( 1, 1 ) ), 0, 1 );
			DisplayActivity( "Value " + str[2] + " removed at (" + str[0] + ", " + str[1] + ")", false );
		}


마찬가지로 Redo 메뉴의 이벤트 핸들러 코드를 생성하고 아래와 같이 수정한다.



		//
		//	redo the move
		//
		private void redoToolStripMenuItem_Click( object sender, EventArgs e )
		{
			//	if RedoMove stack is empty, the exit
			if ( RedoMoves.Count == 0 )
				return;

			//	remove from the RedoMoves stack and push into the Moves stack
			String str = RedoMoves.Pop();
			Moves.Push( str );

			//	save the value in the array
			SetCell( int.Parse( str.Substring( 0, 1 ) ), int.Parse( str.Substring( 1, 1 ) ), int.Parse( str.Substring( 2, 1 ) ), 1 );
			DisplayActivity( "Value " + str[2] + " reinserted at (" + str[0] + ", " + str[1] + ")", false );
		}



2. 게임의 저장


퍼즐은 숫자로 이루어진 String으로 텍스트화일에 저장된다. SaveGameToDisk()를 다음과 같이 수정한다.



		//
		//	Save the game to disk
		//
		public void SaveGameToDisk( Boolean saveAs )
		{
			//	if saveFileName is empty, means game has not been saved before
			if ( ( saveFileName == String.Empty ) || saveAs )
			{
				SaveFileDialog saveFileDialog1 = new SaveFileDialog();

				saveFileDialog1.Filter = "SDO files (*.sdo)|*.sdo|All files (*.*)|*.*";
				saveFileDialog1.FilterIndex = 1;
				saveFileDialog1.RestoreDirectory = false;

				if ( saveFileDialog1.ShowDialog() == DialogResult.OK )
				{
					//	store the filename first
					saveFileName = saveFileDialog1.FileName;
				}
				else
				{
					return;
				}
			}

			//	formulate the string representing the values to store
			StringBuilder str = new StringBuilder();

			for ( int row = 1; row < 10; row++ )
				for ( int col = 1; col < 10; col++ )
					str.Append( actual[col, row].ToString() );

			//	save the values to file
			Computer myComputer = new Computer();

			try
			{
				Boolean fileExists;

				fileExists = myComputer.FileSystem.FileExists( saveFileName );

				if ( fileExists )
					myComputer.FileSystem.DeleteFile( saveFileName );

				myComputer.FileSystem.WriteAllText( saveFileName, str.ToString(), true );

				toolStripStatusLabel1.Text = "Puzzle saved in " + saveFileName;
			}
			catch ( Exception )
			{
				MessageBox.Show( "Error saving game. Please try again." );
				throw;
			}
		}



코드를 추가하면 Computer 클래스를 알지 못한다고 에러를 띄운다.

솔루션 익스플로러에서 Reference를 마우스 오른쪽 클릭하고 Add Reference 선택하여 .NET 탭에서 Microsoft.VisualBasic를 선택한다.



그리고 코드 맨 위에 아래 코드를 추가한다.



using Microsoft.VisualBasic.Devices;



File->Save As... 메뉴의 이벤트 핸들러를 생성하고 아래와 같이 수정한다.



		//
		//	Save As... menu item
		//
		private void saveAsToolStripMenuItem_Click( object sender, EventArgs e )
		{
			if ( !GameStarted )
			{
				DisplayActivity( "Game not started yet.", true );
				return;
			}

			SaveGameToDisk( true );
		}


File->Save 메뉴의 이벤트 핸들러를 생성하고 아래와 같이 수정한다.



		//
		//	Save menu item
		//
		private void saveToolStripMenuItem_Click( object sender, EventArgs e )
		{
			if ( !GameStarted )
			{
				DisplayActivity( "Game not started yet.", true );
				return;
			}

			SaveGameToDisk( false );
		}



3. 저장된 게임 열기


File->Open 메뉴의 이벤트 핸들러는 다음과 같다.



		//
		//	Open a saved game
		//
		private void openToolStripMenuItem_Click( object sender, EventArgs e )
		{
			if ( GameStarted )
			{
				var response = MessageBox.Show( "Do you want to save current game?",
												"Save current game",
												MessageBoxButtons.YesNoCancel,
												MessageBoxIcon.Question );

				if ( response == DialogResult.Yes )
					SaveGameToDisk( false );
				else if ( response == DialogResult.Cancel )
					return;

			}

			//	load the game from disk

			String fileContents;
			OpenFileDialog openFileDialog1 = new OpenFileDialog();
			Computer myComputer = new Computer();

			openFileDialog1.Filter = "SDO files (*.sdo)|*.sdo|All files (*.*)|*.*";
			openFileDialog1.FilterIndex = 1;
			openFileDialog1.RestoreDirectory = false;

			if ( openFileDialog1.ShowDialog() == DialogResult.OK )
			{
				fileContents = myComputer.FileSystem.ReadAllText( openFileDialog1.FileName );
				toolStripStatusLabel1.Text = openFileDialog1.FileName;
				saveFileName = openFileDialog1.FileName;
			}
			else
			{
				return;
			}

			StartNewGame();

			//	initialize the board

			int counter = 0;
			int value;

			for ( int row = 1; row < 10; row++ )
			{
				for ( int col = 1; col < 10; col++ )
				{
					try
					{
						value = int.Parse( fileContents[counter].ToString() );

						if ( value != 0 )
							SetCell( col, row, value, 0 );
					}
					catch ( Exception )
					{
						MessageBox.Show( "File does not contain a valid Sudoku puzzle" );

						throw;
					}

					counter++;
				}
			}

		}


4. 게임 종료


File -> Exit 메뉴의 이벤트 핸들러는 다음과 같다.



		//
		//	Exit the application
		//
		private void exitToolStripMenuItem_Click( object sender, EventArgs e )
		{

			if ( GameStarted )
			{
				DialogResult reponse = MessageBox.Show( "Do you want to save current game?",
														"Save current game",
														MessageBoxButtons.YesNoCancel );

				if ( reponse == DialogResult.Yes )
					SaveGameToDisk( false );
				else if ( reponse == DialogResult.Cancel )
					return;

			}

			this.Close();
			Application.Exit();
		}




Posted by 쿨한넘
Linux/Tip2012. 10. 1. 07:09

<fontconfig>

<!-- Set preferred Korean fonts -->
    <match target="pattern">
        <test qual="any" name="family">
            <string>serif</string>
        </test>
        <edit name="family" mode="prepend" binding="strong">
            <string>UnShinmun</string>
            <string>은신문</string>
        </edit>
    </match>
    <match target="pattern">
        <test qual="any" name="family">
            <string>sans-serif</string>
        </test>
        <edit name="family" mode="prepend" binding="strong">
            <string>magun</string>
            <string>맑은고딕</string>
        </edit>
    </match>
    <match target="pattern">
        <test qual="any" name="family">
            <string>monospace</string>
        </test>
        <edit name="family" mode="prepend" binding="strong">
            <string>DejaVuSansMono</string>
        </edit>
    </match>


<!-- Bind EunGuseul Mono with Bitstream Vera Sans Mono -->
<match target="pattern">

    <test name="family">
        <string>DejaVuSansMono</string>
    </test>
    <edit mode="append" binding="strong" name="family">
        <string>naverdic</string>
        <string>네이버사전</string>
    </edit>
</match>

<!--
  은글꼴과 alee 글꼴에 대하여 안티앨리어스와 오토힌팅을 켭니다.
  원래는 이곳에 필요가 없었으나, 한글 글꼴의 영문 이름이 인식되지
  않게 되면서 아래와 같이 해 줘야 합니다.
-->
<!-- Turn on antialias and hinting with hintmedium for ttf-Unfonts -->
<match target="font">
    <test name="family" compare="contains">
        <string>은</string>
        <string>방울</string>
        <string>반달</string>
        <string>Un</string>
    <string>naver</string>
    <string>mal</string>
    </test>
    <edit name="antialias" mode="assign">
        <bool>true</bool>
    </edit>
    <edit name="hinting" mode="assign">
        <bool>true</bool>
    </edit>
    <edit name="hintsytle" mode="assign">
        <const>hintfull</const>
    </edit>
</match>


</fontconfig>

'Linux > Tip' 카테고리의 다른 글

Linux + Apache2 + Mysql + PHP/Perl/Python 환경을 설치  (0) 2012.10.01
linux 글꼴 설정 내용  (0) 2012.10.01
linux 글꼴 설치  (0) 2012.10.01
ubuntu : ko_KR.UTF-8을 ko_KR.EUC-KR로 바꾸는 방법  (0) 2012.10.01
Ubuntu MySQL utf-8 설정  (0) 2012.10.01
Posted by 쿨한넘
Linux/Tip2012. 10. 1. 07:08

일반적으로 LAMP 라고 부르고 있는 Linux + Apache2 + Mysql + PHP/Perl/Python 환경을 설치 해보자


설치 순서는

Apache2 -> Mysql -> PHP 

1. Apache 설치

시냅틱패키지관리자에서 apache2 , libapache2-mod-auth-mysql 을 설치한다.

* libapache2-mod-auth-mysql : mysql 인증을 위한 모듈

 



터미널에서 다음과 같이 설치할수 있다.

sudo apt-get install apache2sudo apt-get install libapache2-mod-auth-mysql

2. Mysql 설치

시냅틱패키지관리자에서 mysql-server, mysql-client  을 설치한다

 




터미널에서는 다음과 같이 설치 가능 :

sudo apt-get install mysql-server mysql-client

3. PHP5 설치

시냅틱패키지관리자에서 php5-common, php5, libapach-mod-php5 을 설치한다.

 



터미널 설치 :

sudo apt-get install  php5-common, php5, libapach-mod-php5


Mysql과 php 연동을 위한 모듈 설치 시냅틱패키지 관리자에서 php5-mysql 설치

 



4. AMP 설치 확인

아파치 재시작

sudo /etc/init.d/apache2 restart

 






MySQL 확인

 




** mysql 에 문제가 있으면 재시동한다. sudo /etc/init.d/mysql restart


아파치 설치를 확인해 보기 위해서 http://localhost/ 입력해 보자

 




다음은 php 설치 확인을 위해서 ..

/var/www/phpinfo.php 에 다음과 같이 코드를 입력하고

$ sudo vi phpinfo.php

<?php

phpinfo();

?>

그리고 웹브라우저에서 http://localhost/phpinfo.php 를 입력

 






위와 같이 나오면 php 설치는 완료된것이다.

mysql 와 연동이 잘되었는지 확인해 보기위해서 mysql관련 내용도 찾아서 확인한다.

 


'Linux > Tip' 카테고리의 다른 글

69-language-selector-ko-kr.conf  (0) 2012.10.01
linux 글꼴 설정 내용  (0) 2012.10.01
linux 글꼴 설치  (0) 2012.10.01
ubuntu : ko_KR.UTF-8을 ko_KR.EUC-KR로 바꾸는 방법  (0) 2012.10.01
Ubuntu MySQL utf-8 설정  (0) 2012.10.01
Posted by 쿨한넘
Linux/Tip2012. 10. 1. 07:00

<fontconfig>

<!-- Set preferred Korean fonts -->
    <match target="pattern">
        <test qual="any" name="family">
            <string>serif</string>
        </test>
        <edit name="family" mode="prepend" binding="strong">
            <string>UnShinmun</string>
            <string>은신문</string>
        </edit>
    </match>
    <match target="pattern">
        <test qual="any" name="family">
            <string>sans-serif</string>
        </test>
        <edit name="family" mode="prepend" binding="strong">
            <string>magun</string>
            <string>맑은고딕</string>
        </edit>
    </match>
    <match target="pattern">
        <test qual="any" name="family">
            <string>monospace</string>
        </test>
        <edit name="family" mode="prepend" binding="strong">
            <string>DejaVuSansMono</string>
        </edit>
    </match>


<!-- Bind EunGuseul Mono with Bitstream Vera Sans Mono -->
<match target="pattern">

    <test name="family">
        <string>DejaVuSansMono</string>
    </test>
    <edit mode="append" binding="strong" name="family">
        <string>naverdic</string>
        <string>네이버사전</string>
    </edit>
</match>

<!--
  은글꼴과 alee 글꼴에 대하여 안티앨리어스와 오토힌팅을 켭니다.
  원래는 이곳에 필요가 없었으나, 한글 글꼴의 영문 이름이 인식되지
  않게 되면서 아래와 같이 해 줘야 합니다.
-->
<!-- Turn on antialias and hinting with hintmedium for ttf-Unfonts -->
<match target="font">
    <test name="family" compare="contains">
        <string>은</string>
        <string>방울</string>
        <string>반달</string>
        <string>Un</string>
    <string>naver</string>
    <string>mal</string>
    </test>
    <edit name="antialias" mode="assign">
        <bool>true</bool>
    </edit>
    <edit name="hinting" mode="assign">
        <bool>true</bool>
    </edit>
    <edit name="hintsytle" mode="assign">
        <const>hintfull</const>
    </edit>
</match>


</fontconfig>

Posted by 쿨한넘
Linux/Tip2012. 10. 1. 06:59

페도라를 쓰던 우분투를 쓰던 항상 골칫거리는 폰트다! 본인은 눈이 너무나 아름답고 예민한 관계로 뿌옇게 보이는 폰트를 보고 있노라면 정신이 오락가락하면서 죄없는 안경만 연신 닦게 된다. MobileSim 새 버전이 윈도우에서 메롱거리는 바람에 VirtualBox로 우분투를 깔고 이것저것 찾아보던 중 정말 효과 만점의 폰트 교체 방법을 찾을 수 있었다.

가장 많이 검색되는 폰트 교체 방법은 맑은 고딕체로 변경하는 것이다. 그러나 맑은 고딕 폰트가 MS에 물려있는데다가 변경한 후의 모습이 윈도우와 다르게 여전히 뿌옇기 때문에 탈락! 그런고로 다음의 방법을 사용하자. 아래의 방법은 http://kldp.org/node/92122 을 참고하여 다시 정리하였다.


1. 글꼴 설치

우리가 받아야 할 폰트는 네이버 사전체와 Lucida이다. 네이버 사전체는 http://cndic.naver.com/font.nhn 에서 받을 수 있다. 웹 페이지를 들어가면 중국어 사전이 뜨는데 그 아래에 보면 사전체 다운로드 링크가 보일 것이다. Lucida 폰트는 apt-get을 통해 설치가 가능하다.

tar xvfz naverdic.tgz
sudo mkdir /usr/share/fonts/truetype/naver
sudo mv naverdic.ttf /usr/share/fonts/truetype/naver
sudo fc-cache -v
sudo apt-get install sun-java6-fonts



2. 글꼴 설정하기

원문에서는 /etc/fonts/local.conf를 수정하라고 했는데, 우분투 9.04는 폰트 컨피규레이션이 세세히 나뉘어져 있어서 저 파일 대신 /etc/fonts/conf.d/69-language-selector-ko-kr.conf 를 수정했더니 잘 동작한다. 다음과 같이 수정하자.

<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">

<fontconfig>

<!-- 'sans' 글꼴을 'sans-serif' 글꼴로 대체합니다. -->
<!-- Accept 'sans' alias, replacing it with 'sans-serif' -->
<match target="pattern">
    <test qual="any" name="family">
        <string>sans</string>
    </test>
    <edit name="family" mode="assign">
        <string>sans-serif</string>
    </edit>
</match>

<!-- Set preferred Korean fonts -->
<match target="pattern">
    <!--
      'serif' 글꼴을 'UnBatang' 글꼴로 대체합니다. 언젠가부터
      글꼴의 영문 이름이 먹질 않습니다. 그래서 '은바탕'을 추가합니다.
    -->
    <test qual="any" name="family">
        <string>serif</string>
    </test>
    <edit name="family" mode="prepend" binding="strong">
        <string>UnBatang</string>
        <string>은바탕</string>
    </edit>
</match>
<match target="pattern">
    <!-- 'sans-serif' 글꼴을 '네이버사전'으로 대체합니다. -->
    <test qual="any" name="family">
        <string>sans-serif</string>
    </test>
    <edit name="family" mode="prepend" binding="strong">
        <string>naverdic</string>
        <string>네이버사전</string>
    </edit>
</match>

<!-- Set prefferd fixed space font -->
<match target="pattern">
    <!--
      'Monospace' 글꼴을 'Lucida Sans Typewriter'나 'Andale Mono'
      글꼴로 대체합니다.
      안티앨리어스 해제 시, 'Lucida Sans Typewriter'가
      'Andale Mono'보다 예뻐 보입니다.
    -->
    <test qual="any" name="family">
        <string>Monospace</string>
    </test>
    <edit name="family" mode="prepend" binding="strong">
        <string>Lucida Sans Typewriter</string>
        <string>Andale Mono</string>
    </edit>
</match>

<!--
  고정폭 영문 글꼴을 네이버사전체와 연결합니다. 이렇게 하면,
  영문은 'Lucida Sans Typewriter' 글꼴로,
  한글은 '네이버사전' 글꼴로 보입니다.
-->
<!-- Bind fixed space font with 네이버사전 -->
<match target="pattern">
    <test name="family">
        <string>Lucida Sans Typewriter</string>
    </test>
    <edit mode="append" binding="strong" name="family">
        <string>naverdic</string>
        <string>네이버사전</string>
    </edit>
</match>

<!--
  은글꼴과 alee 글꼴에 대하여 안티앨리어스와 오토힌팅을 켭니다.
  원래는 이곳에 필요가 없었으나, 한글 글꼴의 영문 이름이 인식되지
  않게 되면서 아래와 같이 해 줘야 합니다.
-->
<!-- Turn on antialias and hinting with hintmedium for ttf-Unfonts -->
<match target="font">
    <test name="family" compare="contains">
        <string>은</string>
        <string>방울</string>
        <string>반달</string>
        <string>Un</string>
    </test>
    <edit name="antialias" mode="assign">
        <bool>true</bool>
    </edit>
    <edit name="hinting" mode="assign">
        <bool>true</bool>
    </edit>
    <edit name="hintsytle" mode="assign">
        <const>hintmedium</const>
    </edit>
</match>

<!--
  위에서 설정한 고정폭 영문 글꼴에 대하여 8~11 포인트에서는
  안티앨리어스와 오토힌트를 끕니다.
-->
<!-- Turn off antialias and autohint for some Mono fonts -->
<match target="font">
    <test name="family" compare="contains">
         <string>Andale Mono</string>
         <string>Lucida Sans Typewriter</string>
    </test>
    <test name="pixelsize" compare="more">
        <int>11</int>
    </test>
    <test name="pixelsize" compare="less">
        <int>16</int>
    </test>
    <edit name="antialias" mode="assign">
        <bool>false</bool>
    </edit>
    <edit name="autohint" mode="assign">
        <bool>false</bool>
    </edit>
    <edit name="hintstyle" mode="assign">
        <const>hintmedium</const>
    </edit>
</match>

</fontconfig>


3. 리부팅따윈 필요없다

설정을 마치면 몇초내에 글꼴이 자동으로 변경된다. 보라 이 깔끔한 폰트를!! 뿌옇게 비실거리던 한글 폰트는 이제 안녕- 터미널에서 출렁거리던 영문 폰트도 이제 안녕-

 

http://semix2.textcube.com/399

Posted by 쿨한넘
Linux/Tip2012. 10. 1. 06:59

우분투를 설치하면 기본적으로 UTF-8 을 사용한다.
때문에 윈도우나 맥을 사용해서 보면 한글이 깨지는 것을 볼수 있다. 우분투에서 euc-kr 을 설치해서 모두 호환할수 있도록하자.

ko_KR.UTF-8을 ko_KR.EUC-KR로 바꾸는 방법

1. language-pack-ko 설치 이후

시냅택패키시 관리자를 이용해서 설치
(8.10 버전에는 기본으로 설치되어 있음)

 

2. sudo locale-gen ko_KR.EUC-KR

citylock$ sudo locale-gen ko_KR.EUC-KRsudo: unable to resolve host 인보강_NW연구팀
Generating locales...
  ko_KR.EUC-KR... done
Generation complete.

 

3. dpkg-reconfigure locales

 

citylock$ sudo dpkg-reconfigure locales
sudo: unable to resolve host 인보강_NW연구팀
Generating locales...
  en_AU.UTF-8... done
  en_BW.UTF-8... done
  en_CA.UTF-8... done
  en_DK.UTF-8... done
  en_GB.UTF-8... done
  en_HK.UTF-8... done
  en_IE.UTF-8... done
  en_IN.UTF-8... done
  en_NZ.UTF-8... done
  en_PH.UTF-8... done
  en_SG.UTF-8... done
  en_US.UTF-8... done
  en_ZA.UTF-8... done
  en_ZW.UTF-8... done
  ko_KR.EUC-KR... up-to-date
  ko_KR.UTF-8... up-to-date
Generation complete.

 

4. /etc/default/locale 수정 (8.10 이후)

 

  1 LANG="ko_KR.UTF-8"
  2 LANG="ko_KR.EUC-KR"
  3 LANGUAGE="ko_KR:ko:en_GB:en"

 

 

/etc/environment 수정 (8.10 이전)

 

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games"
LANGUAGE="ko_KR:ko:en_GB:en"
LANG="ko_KR.UTF-8"
LANG="ko_KR.EUC-KR"

'Linux > Tip' 카테고리의 다른 글

linux 글꼴 설정 내용  (0) 2012.10.01
linux 글꼴 설치  (0) 2012.10.01
Ubuntu MySQL utf-8 설정  (0) 2012.10.01
Using Intel Compilers for Linux with Ubuntu  (0) 2012.10.01
아파치 설치  (0) 2012.10.01
Posted by 쿨한넘
Linux/Tip2012. 10. 1. 06:58

Ubuntu MySQL utf-8 설정

 

Ubuntu는 시슽템의 대부분의 언어셋이 UTF-8임에도 불구하고 APT로 APM를 설치시 Mysql의 기본 인코딩셋은 Latin1입니다. 이를 모든 언어를 지원하는 UTF-8로 변경하려면 my.cnf파일을 다음과 같이 수정합니다. (참고로 기본적으로 Ubuntu Server 설치시 APM을 설치했다면 my.cnf파일의 위치는 /etc/mysql/my.cnf 입니다.)

[client]
default-character-set = utf8

[mysqld]
character-set-client-handshake=FALSE
init_connect="SET collation_connection = utf8_general_ci"
init_connect="SET NAMES utf8"
default-character-set = utf8
character-set-server = utf8
collation-server = utf8_general_ci

[mysqldump]
default-character-set = utf8

[mysql]
default-character-set = utf8


정상적으로 변경되었는지 확인해 보기 위해서는 mysql로 접속하여 다음과 같은 명령어로 확인해 볼 수 있습니다.

\s

'Linux > Tip' 카테고리의 다른 글

linux 글꼴 설치  (0) 2012.10.01
ubuntu : ko_KR.UTF-8을 ko_KR.EUC-KR로 바꾸는 방법  (0) 2012.10.01
Using Intel Compilers for Linux with Ubuntu  (0) 2012.10.01
아파치 설치  (0) 2012.10.01
우분투 - 호스트네임 설정  (0) 2012.10.01
Posted by 쿨한넘
Linux/Tip2012. 10. 1. 06:58

Using Intel Compilers for Linux with Ubuntu

 

 

rev history: 

2009 November 3:  added notes for Ubuntu 9.10

 

Introduction :

 

 

Using Intel(R) Compilers version 11.1 under Ubuntu (9.10, 9.04, 8.04 and 8.10) Desktop and Debian Desktop

 

For older Ubuntu and Debian versions, see THIS ARTICLE.  Make sure to use the latest Intel Compilers version 11.1.  Older compilers will not be compatible with the latest Ubuntu distributions.  For compatibility and supported versions always read the ReleaseNotes document for your compiler.

 

These notes apply to Ubuntu Desktop.  Ubuntu Server was not tested but should be similar.

 

2 November 2009:  Ubuntu 9.10

 

For users of Ubuntu 9.10, follow the instructions here.  If you have 9.04 or older, skip ahead to the section titled "Ubuntu 9.04 and Older"

 

BEFORE YOU INSTALL Intel(R) Fortran for Linux or Intel(R) C++ for Linux on your fresh Ubuntu Desktop installation, you will first need to install several packages to prepare the system to serve as a development platform.  First, open a Terminal window and become root:

sudo bash
(type your user password)

At this point, you should have a root shell.  Test this with command 'whoami' which should return "root"

Check that gcc is installed. By default. Check this with:

gcc --version

It should return "gcc (Ubuntu 4.4.1-4ubuntu8) 4.4.1 (or some newer version - as long as it returns a version  you have gcc installed)

If, for some reason, you do not have gcc installed, use Synaptic Package Manager (under 'System' -> 'Administration' menus) OR use apt-get to install gcc:


apt-get install gcc


Next, install the 'build-essential' package and package g++. This is not installed by default. Again, use Synaptic Package Manager or apt-get :

apt-get install build-essential

this should also install g++, but in test this with:
g++ --version

if g++ is not found, install it:

apt-get install g++

A few other packages are required:
apt-get install rpm
apt-get install ia32-libs    (this is only required on 64bit Ubuntu/Debian systems)

To use the Intel IDB graphical debugger, you will also need the Java JRE 5 or 6 installed.  We recommend the Sun JRE:

get the latest JRE from:

http://java.com/en/download/manual.jsp

OR you can use the OpenJDK from the distribution:

apt-get install openjdk-6-jre-headless

Next, Ubuntu 9.10 Desktop does not provide libstdc++5, which is required for the Intel Compilers.  You will have to get the package for libstdc++5 from an older Debian or Ubuntu distribution ( 9.04 for example ).  A repository is here:

http://packages.debian.org/stable/base/libstdc++5

On this page, you will see the title "The GNU Standard C++ Library V3".  Scrolling down, find the table for "Download libstdc++5".

9.10:  For 32bit Ubuntu i386 libstdc++5 Installation:
For 32bit  Ubuntu systems you will need to install the 32bit version of libstdc++5, that is, the "i386" package.
Select the download for the libstdc++5 package for "i386".  Pick a mirror site to begin the download.  If you are using Firefox, you will be prompted if you want to "Open with GDebi Package Installer" - select OK to continue.  Otherwise, save the deb package and use your favorite package manager to install.  Install the i386 libstdc++ deb package.  SKIP the Intel 64 Libstdc++5 (AMD64) directions below and find the section on installing the compiler after prerequisites are installed.

9.10: For Intel 64 / AMD64 (64bit Linux installation) Libstdc++5:
follow these instructions IF AND ONLY IF you have a 64bit Ubuntu installation. 

Intel 64 installation:  Select the download for the libstdc++5 package for "amd64".  If you are using Firefox, you will be prompted if you want to "Open with GDebi Package Installer" - select OK to continue.  Otherwise, save the deb package and use your favorite package manager to install.  Install the amd64 libstdc++ deb package.

by default, the 64bit libstdc++.so.5 library will install in /usr/lib which is linked to /usr/lib64. 

Now, you also will need the 32bit libstdc++.so.5 installed in /usr/lib32.  Unfortunately, the "i386" version of the libstdc++5 package wants to install in /usr/lib which is your 64bit library directory and where you just installed the "amd64" libraries - so you DON'T want to download and install the "i386" package into the default location. 
We'll need to download the "i386" package to a temporary directory, use dpkg to extract the contents to the temp directory, then manually copy the library to /usr/lib32 and create the symbolic link:

First, download libstc++5 package for "i386" - save to disk and do NOT launch a package manger to install it.  Save it in your 'Downloads' folder or /tmp (or any other scratch directory).
Using your root terminal window, cd to the directory where you have downloaded the .deb package, it should have a name similar to 'libstdc++5_3.3.6-18_i386.deb'.  The exact version is not important, but make sure it is a "i386" deb package.
Extract to the local directory:

dpkg --extract libstdc++5_3.3.6-18_i386.deb  ./

Notice that a 'usr/' folder was created and the package contents extracted here.  Now we'll copy the library to /usr/lib32

cd usr/lib
cp libstdc++.so.5.0.7 /usr/lib32
cd /usr/lib32
ln -s libstdc++.so.5.0.7 libstdc++.so.5


9.10: Installing the Compiler Now That Prerequisities are Installed (32 and 64bit):

Once you've completed the above, extract your compiler .tgz kit, cd to the compiler installation directory, and run ./install.sh

During the installation, you WILL get a warning message "Detected operating system Debian* (generic) is not supported", followed by
----------------------------------------------------------------- ---------------
Missing optional pre-requisite
-- operating system type is not supported.
-- system glibc or kernel version not supported or not detectable
-- binutils version not supported or not detectable
----------------------------------------------------------------- ---------------
"Would you like to perform an unsupported install of this product [yes/no] (no)?"

enter "yes"

This will complete the installation.  Keep in mind, you will get this warning from the compiler installer until such time as this particular OS and version are supported. Once installed, you can read the ReadMe notes in ...installdir.../Documentation directory which has a list of the supported Linux distributions and versions.




Ubuntu 9.04 and Older:

In order to use Intel(R) Compilers ( Fortran or C++ ) under Ubuntu 9.04, 8.04 or 8.10 you will need the latest 11.0 or 10.1 version of the Intel compiler(s). Older 10.0 and 9.1 versions of the compilers may not work properly under Ubuntu 9.04, 8.04 or 8.10.  Keep in mind that new versions of Ubuntu/Debian may not be OFFICIALLY supported by the Intel Compilers.  Please see your ReleaseNotes document with your compiler version for a list of officially supported distributions and versions.

If you have active support for your compiler, you can download the latest Intel compiler version from
https://registrationcenter.intel.com

BEFORE YOU INSTALL Intel(R) Fortran for Linux or Intel(R) C++ for Linux on your fresh Ubuntu Desktop installation, you will first need to install several packages to prepare the system to serve as a development platform:

Check that gcc is installed. By default. Check this with:

gcc --version

By default, Ubuntu 8.04 Desktop installs gcc 4.2.3-2ubuntu7.  8.10 should have gcc 4.3.2, 9.04 gcc 4.3.3

If, for some reason, you do not have gcc installed, use Synaptic Package Manager (under 'System' -> 'Administration' menus) OR use apt-get to install gcc:


apt-get install gcc


Next, install g++. This is not installed by default. Again, use Synaptic Package Manager or apt-get to install package "g++"

apt-get install build-essential
apt-get install g++


Next, you need to install the 32bit compatibility library libstdc++.so.5. To do this, use apt-get or Synaptic Package Manager to retrieve and install package "libstdc++5"

apt-get install libstdc++5

This package may require installing another package as a prerequisite,
"gcc-3.3-base"

If so, go ahead and install this older gcc package.

For x86-64 architecture, you will also need a number of other packages, including package 'ia32-libs' to install the 32bit versions of libstdc++.so.5 in /usr/lib32 as well as 32bit header files in libc6-dev-i386.   These notes apply to Ubuntu 9.04 but should also apply to 8.10 and 8.04

apt-get install ia32-libs
apt-get install lib32stdc++6
apt-get install libc6-dev-i386
apt-get install gcc-multilib
apt-get install g++-multilib


Finally, there is an optional package to consider: The 11.0 version of the Intel Compiler for Linux has a graphical
debugger, a new graphical interface for the IDB debugger. If you want to use this debugger, please make sure to install the Java JRE version 1.5 or greater. This can be done at anytime after the installation of the compiler. However, you will get a warning message about 'missing prerequisite' for the JRE - simply ignore that message and proceed with the installation.  OR to avoid that message and enable the graphical IDE, get the latest JRE from:

http://java.com/en/download/manual.jsp

Once installation of prerequisites is complete, you are ready to start the Intel compiler(s) installation. During the installation, you may get a message "Detected operating system Debian* (generic) is not supported", followed by
----------------------------------------------------------------- ---------------
Missing optional pre-requisite
-- operating system type is not supported.
-- system glibc or kernel version not supported or not detectable
-- binutils version not supported or not detectable
----------------------------------------------------------------- ---------------
"Would you like to perform an unsupported install of this product [yes/no] (no)?"

enter "yes"

This will complete the installation.  Keep in mind, you will get this warning from the compiler installer until such time as this particular OS and version are supported. Once installed, you can read the ReadMe notes in ...installdir.../Documentation directory which has a list of the supported Linux distributions and versions.

 

 

http://software.intel.com/en-us/articles/using-intel-compilers-for-linux-with-ubuntu/

 

 

Install Intel Compiler(icc) in Ubuntu 8.10

To install icc in Ubuntu:


  1. Download icc from Intel website

  2. tar -zxvf the file.

  3. Run 'install.sh'.

  4. Follow the installer instructions.

  5. When it is done add this line to your ~/.bashrc (or initialization script):
    source /opt/intel/Compiler/11.0/069/bin/iccvars.sh ia32
    Replace ia32 with your platform: (ia32, intel64, ia64)

  6. Log off and log in and that is it. You can test it with icc -v

  7. To use icc with a configure script use ./configure CC=icc


NOTE: If you get a libimf.so error like "file does not exists" while using sudo, you will need to write a bash script adding "source /opt/intel/Compiler/11.0/069/bin/iccvars.sh" and the program you are trying to run.

 

 

http://crazyprogrammerblog.blogspot.com/2008/11/install-intel-compilericc-in-ubuntu-810.html

'Linux > Tip' 카테고리의 다른 글

ubuntu : ko_KR.UTF-8을 ko_KR.EUC-KR로 바꾸는 방법  (0) 2012.10.01
Ubuntu MySQL utf-8 설정  (0) 2012.10.01
아파치 설치  (0) 2012.10.01
우분투 - 호스트네임 설정  (0) 2012.10.01
우분투 : 아파지 서버의 설정 방법  (0) 2012.10.01
Posted by 쿨한넘
Linux/Tip2012. 10. 1. 06:57

아파치 설치

* 공식사이트 : http://httpd.apache.org

1. 최신버전(2.2.11) 내려받기

# wget http://ftp.kaist.ac.kr/pub/Apache/httpd/httpd-2.2.11.tar.gz

2. 설치 컴파일 실행
아파치 설치
설치하기전에 도움말은 $ ./configure --help 상세하게 설치하는 법을 알 수 있다.
내려받은 아파치서버를 압축을 풀어준다.

# tar -xvf httpd-2.2.11.tar.gz
# cd httpd-2.2.11

-- 컴파일 실행
# ./configure --prefix=/usr/local/apache2 --enable-modules=so --enable-so

--prefix : 설치경로
--enable : 활성화

# make
# make install

3. 설정 및 시작

** 설정법은 윈도우 버전과 동일하기 때문에 꼭 알아두도록하자.

# vi /usr/local/apache2/conf/httpd.conf

-- vi 편집기 :set number (줄번호 보기)
줄번호 내용.....

-- 포트번호
 40 Listen 80

-- 서버네임 설정
 97 ServerName "localhost"

-- 웹서비스 루트경로 (sol 경로를 웹서비스로 두었다.)
102 DocumentRoot "/home/sol/www"

-- 웹서비스 루트경로
129 <Directory "/home/sol/www">

-- 인덱스 페이지 설정 index.php 등록
163 <IfModule dir_module>
164     DirectoryIndex index.html index.php
165 </IfModule>

-- 아파치 재시작
# /usr/local/apache2/bin/apachectl restart

4. 아파치 자동시작

-- 서비스 등록
# cp /usr/local/apache2/bin/apachectl /etc/init.d/httpd
# chkconfig -add httpd

-- 서비스 확인
# chkconfig --list|grep httpd
-- httpd                     0:off  1:off  2:on   3:on   4:on   5:on   6:off

-- 재부팅하면 된다.

-- 서비스 확인
# netstat -nlp|grep httpd

그 후 서비스 관리 명령어
# /etc/init.d/httpd [start|stop|restart]

 

 

http://syaku.tistory.com/83

Posted by 쿨한넘