2018년 11월 28일 수요일

[C#] 속성코스

Crash Course on C#
nonezerok@gmail.com

----------------------------------------
0.기본
----------------------------------------
객체: 변수, 함수
Form 객체
- 변수, 함수
- 속성, 이벤트 (이 점이 윈도우 프로그래밍을 기가 막히게 쉽게 만드는 요인)

----------------------------------------
1.프로그램종료
----------------------------------------
Application.Exit();

----------------------------------------
2.마우스클릭 + 메세지박스
----------------------------------------
MessageBox.Show(" ");

----------------------------------------
3.마우스무브 이벤트 + 글자 출력
----------------------------------------
private void Form1_MouseMove(object sender, MouseEventArgs e)
        {         
Graphics g = CreateGraphics();
String drawString = "Sample Text";
Font drawFont = new Font("Arial", 16);
SolidBrush drawBrush = new SolidBrush(Color.Black);
PointF drawPoint = new PointF(150.0F, 150.0F);
g.DrawString(drawString, drawFont, drawBrush, drawPoint);
g.Dispose();

/*
           Graphics g = CreateGraphics();

            Font drawFont = new Font("FixedSys", 16);
            SolidBrush drawBrush = new SolidBrush(Color.Black);

            float x = 0.0F;
            float y = 0.0F;
            float width = 200.0F;
            float height = 50.0F;
            RectangleF drawRect = new RectangleF(x, y, width, height);

            // 글자가 쓰여지는 부분을 회색으로 채운다.
            Color backGray = Color.FromArgb(240, 240, 240);
            SolidBrush backBrush = new SolidBrush(backGray);
            g.FillRectangle(backBrush, 0, 0, 200, 50);

            String str = string.Format("{0:d5} {1:d5}", e.X, e.Y);
            g.DrawString(str, drawFont, drawBrush, drawRect);
       
            g.Dispose();
*/                         
         
        }

----------------------------------------
4. 자식윈도우생성, 생성이벤트, 종료
----------------------------------------
    private void Form1_Load(object sender, EventArgs e)
        {
            frm2 = new Form2(); // Form2(this) 식으로 구현
            frm2.Owner = this; // Form1의 자식윈도우로 설정
            frm2.Show();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            MessageBox.Show("I'm going to die");
            //frm2.Close(); // 윈도우파괴
            //frm2.Dispose(); // 메모리해제
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            MessageBox.Show("I am dead"); 
        }

----------------------------------------
5. 자식윈도우 스타일: TopLevel=false, Control.Add(frm2)
----------------------------------------
        private void Form1_Load(object sender, EventArgs e)
        {
            frm2 = new Form2();
            frm2.Owner = this;
            frm2.TopLevel = false;
            Controls.Add(frm2);
            frm2.Show();
        }

FormBorderStyle
IsMdiContainer

private Form1 frmMain=null; // 자식윈도우
frmMain = this.Owner as Form1; // 자식윈도우; frm2.Owner = this;
//frmMain = (Form2)this.Owner;
frmMain.TextBox1.Text = "Message From Child Window";
Form2(Form parent)
{
frmMain = parent as Form1;
}

----------------------------------------
6. 컨트롤윈도우
----------------------------------------
button, textbox, label, progressbar, timer, picture box, menu
메뉴-
frmMain.Dispose();
Application.Exit();

----------------------------------------
7.대화상자윈도우
----------------------------------------
Form2 frm2 = new Form2();
if (frm2.ShowDialog(this) == DialogResult.OK)
{
textBox1.Text = frm2.textBox1.Text; // 도구상자 속성에서 public으로 설정
               //MessageBox.Show("오케이");
}
frm2.Dispose(); // 메모리 해제

private void button1_Click(object sender, EventArgs e)
{
DialogResult = System.Windows.Forms.DialogResult.OK;
this.Close(); // 윈도우 파괴
}

----------------------------------------
8. (2016/11/20)OpenCVSharp
- NuGet
----------------------------------------
using OpenCvSharp;
using OpenCvSharp.Extensions;

// https://www.nuget.org/packages/
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Mat src = new Mat("lena.bmp", ImreadModes.Color);
    src = src.Blur(new OpecCvSharp.Size(7,7));


            /*
            using (new Window("dst image", src))
            {
                Cv2.WaitKey();
            }
            */
            // 필터링 적용

            //
            // 아래와 같이 했을때는 올바른 버퍼를 가리키고 있지 않았음.
            //byte[] pImg = src.ToBytes();
            //

            IntPtr pImg = src.Data;

            // for unsafe
            //1. 프로젝트의 속성 페이지를 엽니다.
            //2. 빌드 속성 페이지를 클릭합니다.
            //3. 안전하지 않은 코드 허용 확인란을 선택합니다.
            unsafe
            {
                //byte* buff = (byte*)pImg.ToPointer();
                byte* buff = (byte *)src.DataPointer;

                for (int i = 0, idx = 0; i < src.Cols * src.Rows; i++, idx += 3)
                {
                    int gray=0;
                    gray = (buff[idx + 0] + buff[idx + 1] + buff[idx + 2]);
                    gray = gray / 3;

                    buff[idx + 0] = (byte)gray;
                    buff[idx + 1] = (byte)gray;
                    buff[idx + 2] = (byte)gray;
                }
            }

            //
            // 한번은 비트맵으로 바꾸어야 한다
            //
            Bitmap bmp;
            bmp = src.ToBitmap();

            // 이렇게 하는 것 보다는...
            // pictureBox1.Image = bmp;
            //
            // 아래와 같이 하는 것이 낫지 않을까.
            // (고속처리)
            IntPtr hWnd = pictureBox1.Handle;
            Graphics newGraphics = Graphics.FromHwnd(hWnd);
            // newGraphics.DrawRectangle(new Pen(Color.Red, 3), 0, 0, 200, 100);i
            newGraphics.DrawImage(bmp, 0, 0);
            newGraphics.Dispose();
        }
----------------------------------------
Last Updated: 2016/10/05

2018년 10월 17일 수요일

[MFC] 일반윈도우생성

[사용자 윈도우 생성]

class CMyWnd: public CWnd
{
     DECLARE_MESSAGE_MAP()
     afx_msg void OnMouseMove(UINT nFlag, CPoint pt);
}
BEGIN_MESSAGE_MAP(CMyWnd, CWnd)
    ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()

void CMyWnd::OnMouseMove(UINT nFlag, CPoint pt)
{
    CWnd::OnMouseMove(nFlag, pt);
}

[윈도우 클래스 등록]

CString strClass;
strClass = AfxRegisterWndClass(
CS_VREDRAW | CS_HREDRAW,
::LoadCursor(NULL, IDC_ARROW),
(HBRUSH) ::GetStockObject(BLACK_BRUSH),
::LoadIcon(NULL, IDI_APPLICATION));


[윈도우생성 - 자식윈도우 스타일]

CMyWnd* pWnd = new CMyWnd();

pWnd->Create(
0, /* strClass */
L"My Window - Child",
WS_CHILD | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_VISIBLE,
CRect(300, 0, 600, 400),
 this,
 888, // 아이디
 0);

* 자동으로 WS_CHILD 적용되어 버림

[윈도우생성 - 팝업윈도우 스타일]

pWnd->CreateEx(
0, //  WS_EX_CLIENTEDGE, WS_EX_TOPMOST,
strClass, // 사용자 등록 클래스가 반드시 존재해야 한다.
L"My Window - Popup",
 WS_VISIBLE | WS_CAPTION | WS_SYSMENU | WS_BORDER | WS_THICKFRAME,
 CRect(100,100,600,400),
this, // NULL로 해도 된다. 대신 명시적으로 파괴해주어야 한다.
0 // 1이상의 값으로 하면 프로그램 죽는다.!!!
);

2018년 10월 12일 금요일

[MFC] 메세지처리실습

0. WindowProc(UINT msg, WPARAM wParam, LPARAM lParam)
    - Win32처럼 메세지 처리

[1번 유형]
1. WM_MOUSEMOVE
    - OnMouseMove( )
    - ON_WM_MOUSEMOVE
    - 클래스위저드

[2번 유형]
2. WM_COMMAND
   - 메뉴 추가 (리소스 편집기)
   - Min, Max
   - CChildView에서 실습, Max는 추후 실습
   - ON_COMMAND

[2번 유형]
3. 버튼생성 및 WM_COMMAND
   - OnCreate( )
   - WM_COMMAND
   - ON_COMMAND

[3번 유형]
4. 에딧박스 생성
   - EN_CHANGE
   - ON_EN_CHANGE

[5번 유형]
5. 사용자메세지 처리
   - #define WM_MYMESSAGE WM_USER+1
   - ON_MESSAGE(WM_MYMESSAGE, OnMyMessage)
   - LRESULT OnMyMessage(WPARAM, LPARAM)

* 4번 유형은 다음 예제에서 다룸.

--------------------
CChildView.H
--------------------

// ChildView.h: CChildView 클래스의 인터페이스
//


#pragma once

#define WM_MYMESSAGE WM_USER+1

// CChildView 창

class CChildView : public CWnd
{
// 생성입니다.
public:
CChildView();

// 특성입니다.
public:
CButton * m_pBtn;
CEdit* m_pEdt;

// 작업입니다.
public:

// 재정의입니다.
protected:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);

// 구현입니다.
public:
virtual ~CChildView();

// 생성된 메시지 맵 함수
protected:
afx_msg void OnPaint();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnTestMin();
afx_msg void OnClick();
afx_msg void OnChange();
afx_msg LRESULT OnMyMessage(WPARAM, LPARAM);
};

--------------------
CChildView.CPP
--------------------

// ChildView.cpp: CChildView 클래스의 구현
//

#include "stdafx.h"
#include "My.h"
#include "ChildView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CChildView

CChildView::CChildView()
{
m_pBtn = 0;
m_pEdt = 0;
}

CChildView::~CChildView()
{
if (m_pBtn) {
m_pBtn->DestroyWindow();
delete m_pBtn;
}


if (m_pEdt) {
m_pEdt->DestroyWindow();
delete m_pEdt;
}
}


BEGIN_MESSAGE_MAP(CChildView, CWnd)
ON_WM_PAINT()
ON_WM_MOUSEMOVE()
ON_WM_CREATE()
ON_COMMAND(999, OnClick)
ON_COMMAND(ID_TEST_MIN, &CChildView::OnTestMin)
ON_EN_CHANGE(888, OnChange)
ON_MESSAGE(WM_MYMESSAGE, OnMyMessage)
END_MESSAGE_MAP()



// CChildView 메시지 처리기

BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs)
{
if (!CWnd::PreCreateWindow(cs))
return FALSE;

cs.dwExStyle |= WS_EX_CLIENTEDGE;
cs.style &= ~WS_BORDER;
// cs.style |= (WS_CAPTION|WS_THICKFRAME);
cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS,
::LoadCursor(nullptr, IDC_ARROW), reinterpret_cast(COLOR_WINDOW+1)
/*(HBRUSH)::GetStockObject(GRAY_BRUSH)*/,
nullptr);

return TRUE;
}

void CChildView::OnPaint()
{
CPaintDC dc(this); // 그리기를 위한 디바이스 컨텍스트입니다.

// TODO: 여기에 메시지 처리기 코드를 추가합니다.

// 그리기 메시지에 대해서는 CWnd::OnPaint()를 호출하지 마십시오.
}



void CChildView::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다.
CDC* pDC = 0;
pDC = GetDC();
CString strPos;
strPos.Format(L"%04d %04d", point.x, point.y);
pDC->TextOut(0, 0, strPos);
ReleaseDC(pDC);
CWnd::OnMouseMove(nFlags, point);
}


int CChildView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;

// TODO:  여기에 특수화된 작성 코드를 추가합니다.
m_pBtn = new CButton();
m_pBtn->Create(L"click", WS_CHILD | WS_VISIBLE, 
CRect(0, 200, 200, 400), this, 999);

m_pEdt = new CEdit();
m_pEdt->Create(WS_CHILD | WS_VISIBLE | WS_BORDER,
CRect(200, 200, 400, 400), this, 888);

return 0;
}


void CChildView::OnTestMin()
{
// TODO: 여기에 명령 처리기 코드를 추가합니다.
this->MoveWindow(500, 100, 500, 500, 1);
}

void CChildView::OnClick()
{
//MessageBox(L"button click");
SendMessage(WM_MYMESSAGE, 0, 0);
}

void CChildView::OnChange()
{
CDC* pDC = 0;
pDC = GetDC();

CString strMsg;
m_pEdt->GetWindowText(strMsg);

pDC->TextOut(0, 32, strMsg);

ReleaseDC(pDC);
}

LRESULT CChildView::OnMyMessage(WPARAM wParam, LPARAM lParam)
{
MessageBox(L"WM_MYMESSAGE");
return 0;
}

2018년 10월 1일 월요일

[MFC] 프로젝트시작하기-실습계획

프로젝트 시작 설정 및 실습계획

-MFC 프로젝트 설정
-MFC 핵심 실습 목차
   -MFC 에서 자유롭게 메세지 처리하기
   -MFC 에서 자유롭게 윈도우 생성하기
- MFC 기법 실습 목차
   -그래픽/대화장사/도큐먼트-뷰/동적라이브러리 등

https://www.slideshare.net/jaepilko10/mfc-117702027

2018년 9월 16일 일요일

[python] 파일입출력

# 파일 입출력

file = open("test.txt", "w")
file.write('hello')
file.write("\n")
file.write('world')
file.write("\n")
file.close()

file=open("test.txt", "r")
lines = file.read()
file.close()
print(lines)

#
msg = ["HELLO\n", "WORLD\n", "안녕\n"]
file = open("test.txt", "w", encoding='utf-8')
file.writelines(msg)
file.close()

file = open("test.txt", "r", encoding='utf-8')
line = file.readline()
while line != '':
    print(line, end='')
    line = file.readline()
file.close()

print()
file = open("test.txt", "r", encoding='utf-8')
lines = file.readlines()
file.close()
line = ''
for line in lines:
    print(line, end='')
   

# list 저장
#
import csv
f=open('a.csv', 'w',newline='')
writer=csv.writer(f, delimiter=',')
writer.writerow([1,2,3])
writer.writerow([4,5,6])
f.close()

#
# list 읽기; 읽어들인 결과는 문자
#
import csv
f=open('a.csv', 'r', encoding='utf-8')
reader=csv.reader(f)
for line in reader:
    print(line)
f.close()

#
# 읽어들일 타입지정:
#
print()
import numpy as np
data = np.loadtxt('a.csv', delimiter=',', dtype=np.int32) #np.float32
print(data)

-----
참고
-----
a=[1,2,3,4,5,6]
for i in range(len(a)-1):
    print(a[i],",",end="")
print(a[len(a)-1])

python a.py > a.txt
python a.py >> a.txt

#
#
#
a=[]
for i in range(3):
    b = input()
    a.append(b)
print(a)
#다음과 같이 키보드에서 입력
1
2
3
>>>['1', '2', '3']

----- a.txt -----
1
2
3
----------------
python a.py < a.txt
>>>['1', '2', '3']

[python] 넘파이예제

print("# 1 #")
data = (11, 9, 6, 14)
n = len(data)
for i in range(n):
    print(data[i])

#
print()
print("# 2 #")
s = sum(data)
print("sum={0}".format(s))

#
print("\n# 3 #")
print("data = ( ", end="")
for i in range(n):
    print(data[i], end=" ")
print(")")

#
print("\n# 4 #")
for i in range(n):
    if (i==0):
         print("data=( %d"%(data[0]), end="")
    else:
        print(", %d"%(data[i]), end="")
print(" )")

#
print("\n# 5 #")
for freq in data:
  s += freq
print("sum={0}".format(s))
print()

#
print("\n# 6 #")
print("sum=%d"%(s))
print("sum=%5d"%(s))
print("sum=%-5d*"%(s))
print("sum=%05d"%(s))
print("sum=%05d %5.2f"%(s, s))
print("sum=%05d %6.2f"%(s, s))

#
print("\n# 7 #")
def show(list):
    n = len(list)
    for v in list:
        print(v, end=" ")
    print()
 
relativeFreq=[]
for freq in data:
    relativeFreq.append(freq / s)
 
show(relativeFreq)

# initialize list
print("\n# 8 #")
lst = [0 for _ in range(10)]
lst = [0]*10
show(lst)

#
a = np.array([])
a = np.resize(a, 10)
a.size '10
a.shape '(10,)

#
a = np.arange(0, 3)
'a=[0,1,2]

# relative frequency
print("\n# 9 #")
relativeFreq = [0]*len(data)
for idx, freq in enumerate(data):
    relativeFreq[idx] = freq / s
show(relativeFreq)

# label
print("\n# 10 #")
label = ['A', 'B', 'C', 'D']
for idx in range(len(data)):
   print("%1c\t%2d\t%1.3f" %(label[idx], data[idx], relativeFreq[idx]))

# numpy
print("\n# 11 #")
import numpy as np
ndata = np.array([11, 9, 6, 14])
s = ndata.sum()
relativeFreq = [ freq / s for freq in ndata]
for idx in range(ndata.size):
   print("%1c\t%2d\t%1.3f\t%2.2f%%" %(label[idx], ndata[idx], relativeFreq[idx], relativeFreq[idx]*100.0))


# * graph
print("\n# 12 #")
HEIGHT = 10
star = np.array([f * HEIGHT for f in relativeFreq])
show(star)
star = star.round()
star = star.astype(np.int32)
show(star)

space = [HEIGHT-s for s in star]
show(space)

for i in range(HEIGHT):
    c = [i < s for s in space]
    print(c)
    c = [' ' if c[idx]==True else '*' for idx in range(len(star))]
    print(c)


#
print("\n# 13 #") 
for i in range(HEIGHT):
    c = [i < s for s in space]
    c = [' ' if c[idx]==True else '*' for idx in range(len(star))]
    print(c)

 
#
print("\n# 14 #") 
for i in range(HEIGHT):
    c = [i < s for s in space]
    c = [' ' if c[idx]==True else '*' for idx in range(len(star))]
    for j in range(len(star)):
        print("%c "%c[j], end="")
    print()
 
 
# remove empty line
print("\n# 15 #") 
for i in range(HEIGHT):
    c = [i < s for s in space]
    c = [' ' if c[idx]==True else '*' for idx in range(len(star))]
    d = all([c[idx]==' ' for idx in range(len(star))])
    if (d==False):
        for j in range(len(star)):
            print("%c "%c[j], end="")
        print()
 
     
 # another example
print("\n# 16 #")
label = ['seoul', 'pusan', 'daegu', 'incheon', 'kwangju', 'daejeon', 'ulsan']
ndata = np.array([5087, 1639, 1180, 1350, 664, 726, 544])
sum = ndata.sum()
rf = [f/sum for f in ndata]
for idx in range(ndata.size):
  print("%10s\t%2d\t%1.3f\t%2.2f%%" %(label[idx], ndata[idx], rf[idx], rf[idx]*100))
print()
H = 20
star = np.array([f * H for f in rf])
star = star.round()
star = star.astype(np.int32)
star = [H-s for s in star]
for i in range(H):
  c = [' ' if i < s else '*' for s in star]
  d = all([c[idx]==' ' for idx in range(ndata.size)])
  if (d == False):
      for j in range(ndata.size):
          print("%c" %c[j], end='')
      print()
   
   
 # pyplot
print("\n# 17 #")
import matplotlib.pyplot as plt
plt.plot(rf)
plt.bar(range(ndata.size), rf)
plt.xticks(range(ndata.size), label)
plt.show()

# data set -> relative freq., cumulative relative freq. table, histogram
# read data from file, data.csv
# pyplot: http://bcho.tistory.com/m/1201 pyplot 사용법
# numpy: http://taewan.kim/post/numpy_cheat_sheet/

2018년 8월 14일 화요일

[C] 데이터타입 숫자 범위

[출처] http://mwultong.blogspot.com/2006/09/c-char-int-float-data-type-ranges.html

[정수형] 

▶ char, unsigned char          1 byte (8비트)
------------------------------------------------------
char 의 최소값: -128
char 의 최대값: 127

unsigned char 의 최소값: 0
unsigned char 의 최대값: 255 (0xff)



▶ short, unsigned short        2 bytes (16비트)
------------------------------------------------------
short 의 최소값: -32768
short 의 최대값: 32767

unsigned short 의 최소값: 0
unsigned short 의 최대값: 65535 (0xffff)


▶ wchar_t 또는 __wchar_t       2 bytes (16비트)
------------------------------------------------------
wchar_t 의 최소값: 0
wchar_t 의 최대값: 65535

※ wchar_t 는 유니코드 글자 1개를 저장합니다. "unsigned short"과 동일.



▶ int, unsigned int            4 bytes (32비트)
------------------------------------------------------
int 의 최소값: -2147483648
int 의 최대값: 2147483647

unsigned int의 최소값: 0
unsigned int의 최대값: 4294967295 (0xffffffff)



▶ long, unsigned long          4 bytes (32비트)
------------------------------------------------------
long 의 최소값: -2147483648L
long 의 최대값: 2147483647L

unsigned long 의 최소값: 0UL
unsigned long 의 최대값: 4294967295UL (0xffffffffUL)

※ 32비트OS에서의 long 은 int 와 동일



▶__int64 또는 long long        8 bytes (64비트)
------------------------------------------------------
__int64 의 최소값: -9223372036854775808i64
__int64 의 최대값: 9223372036854775807i64

unsigned __int64 의 최소값: 0ui64
unsigned __int64 의 최대값: 18446744073709551615ui64 (0xffffffffffffffffui64)


[실수형] 

▶ float                        4 bytes (32비트)
------------------------------------------------------
가장 작은 양수: 1.175494351e-38F
가장 큰 양수  : 3.402823466e+38F



▶ double                       8 bytes (64비트)
------------------------------------------------------
가장 작은 양수: 2.2250738585072014e-308
가장 큰 양수  : 1.7976931348623158e+308



▶ long double                  8 bytes (64비트)
------------------------------------------------------
double 과 같음.

[MFC] 파일입출력

[출처] http://phiru.tistory.com/138

// 읽기(바이너리로 읽기) 
// 쓰기(바이너리로 쓰기)

CFile rawData;              // 읽을 파일
CFile processData,            // 쓸 파일
CFileException proEx, rawEx;        // 예외

if(!rawData.Open(strFullPath, CFile::modeRead | CFile::typeBinary, &rawEx))  // 오류 체크
{
AfxMessageBox("rawData exception!");
rawData.Close();
return;
}

if(!processData.Open(strProData, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary, &proEx))
{
AfxMessageBox("ProcessData exception!");
processData.Close();
return;
}

UINT nRet = 0;                                // 읽은 크기
char buffer[KD_BUFFER_SIZE];        // 읽을 버퍼 싸이즈

while(1)
{
ZeroMemory(buffer, sizeof(buffer));
nRet = rawData.Read(buffer, sizeof(buffer)); // 읽기
if(nRet == sizeof(buffer))                                               // 읽을 데이터가 남아있다(확률적으로 맞지)
{
processData.Write(buffer, sizeof(buffer));        // 사실 이거 만들때는 조건이 있어서 일케 분류했다.
}
else // 파일이 끝부분일 경우(안맞을 확률 1/버퍼 싸이즈)
{
processData.Write(buffer, sizeof(buffer));
break;
}
}

// 다 읽고 썼으니깐 핸들 닫자
processData.Close();
rawData.Close();

// 파일 잘 되었는지 친절히 폴더도 열어주자
ShellExecute(NULL, "open", dataDir, NULL, NULL, SW_SHOWNORMAL);

------------------------------------------------------------------------------------------
std::fstream rawData;                    // 읽고 쓸 파일.(여기에서는 덮어쓰기한다. 요고 디지게 찾았다)
std::fstream headerData;                // 읽을 파일(이걸 읽어서 rawData에 덮는 식으로 예제를 짰다)

rawData.open(cFileFullPath, std::ios::binary | std::ios::out | std::ios::in);        // Open할때 바이너리, 읽고 쓰기로.
if(!rawData.is_open())    // 잘 열렸는지 인. 아니면 오류 났다고 해주자
{
// 현재 fstream은 unicode가 안되어서?? 잘 모르겠지만 경로에 한글 있음 안된다.
MessageBox("File Open Error.(Don't use Korean title)", "Error", 0);
printf("error\n");
rawData.close();
return;
}

headerData.open(cHeaderPath, std::ios::binary | std::ios::in);     // 바이너리로 하고 읽기로.
if(!headerData.is_open())
{
MessageBox("File Open Error.(Don't use Korean title)", "Error", 0);
printf("error\n");
headerData.close();
return;
}

char buffer[KD_BUFFER_SIZE];
memset(buffer, 0, sizeof(buffer));
headerData.read(buffer, sizeof(buffer));        // 읽기
int size = strlen(buffer);                            // 읽은 사이즈 한번 보고
rawData.write(buffer, sizeof(buffer));            // 쓴다. 덮어서!
rawData.flush();                                    // 적용!!
rawData.close();                            // 닫어
headerData.close();                        // 요곳도 닫어

2018년 7월 23일 월요일

[python] 인터넷강의

경영학과 출신 교수님이 본인이 공부하고 계신 사이트를 소개해 주셨다.
들어보니 강의 스킬이 좋은 것 같다.
파이선 공부는 아래 사이트에서 하면 좋을 듯.

2018년 6월 16일 토요일

[공개강좌] 선형대수

살면서 정말 멋진 강의를 만나는 것은 행운이다.
나는 대학원때 그런 강의를 2번 석사를 마치고 사회에서 개발자로 일하고 있을 때 1번, 이렇게 3번 있었다.
다음 강의 또한 정말 멋지다.

MIT 공개강의 - 선형대수

by Professor Gilbert Strang.

[딥러닝] 캡슐네트워크

힌톤교수가 제안하여 더욱 주목을 받았던 신경망이었지만,
미루고 미루다 이제야 살펴보았다.
의미있다.
앞으로 많은 진전이 있을 것 같다.
Dynamic Routing과 Equivariance에 대한 Aurelien Geron의 설명력은 정말 대단하다.

2018년 5월 23일 수요일

[python] 문법10

--------------------------------------------------------------------------------
#
# 이벤트처리
#
--------------------------------------------------------------------------------
# 화면에 마우스클릭 위치까지 선그리기

import turtle

t = turtle.Turtle()

def drawit(x, y):
#t.penup()
t.goto(x, y)
t.write("click")

s = turtle.Screen()
s.onscreenclick(drawit) #onscreenclick( ) 여기 괄호 안에 들어가는 함수는 변수 2개를 갖도록 되어 있다.

turtle.done()

# 윈도우프로그래밍 = 이벤트처리 프로그래밍
# "스크린 윈도우"에서 "클릭" 이벤트에 대해 클릭위치에 click 출력하는 "처리"를 한 예제
# 터틀에서 하는 방법일 뿐.
# 보다 범용적인 방법 필요: Tk, Qt

--------------------------------------------------------------------------------
# 사건기반(event-driven) 프로그래밍 (~ 윈도우프로그래밍)
# 대표적인 사건: 마우스클릭, 키보드입력 ...
# 사건이 발생되는 토대: 윈도우

[윈도우에서 사건기반 프로그래밍]
- with Turtle in Python
- Win32 API in C
- MFC in C++
- C#, VB
- Java
- Qt in C++

[코딩요소]
- 윈도우생성
- 이벤트처리
- 메세지처리 반복(루프)

[기타]
- 부모윈도우 - 자식윈도우 관계 설정
--------------------------------------------------------------------------------
from tkinter import *

window = Tk()
button = Button(window, text="클릭")
button.pack() # 일단 그냥 하는 걸로

window.mainloop()

----------------------------------------
이벤트 처리 1:
- command; 버튼 클릭할 때 발생; 메뉴 아이템 클릭
----------------------------------------
from tkinter import *

def process():
print("안녕하세요?")

window = Tk()

button = Button(window, text="눌러봐", command=process)
#  버튼에서, command (클릭) 이벤트가 발생하면 process 함수를 호출해라

button.pack()

window.mainloop()

----------------------------------------
윈도우 크기 및 배치
----------------------------------------
from tkinter import *

def process():
print("안녕하세요?")

window = Tk()
window.title('my first window')
window.geometry("500x500")
window.resizable(0, 0)

button = Button(window, text="클릭", command=process)
btn.place(x=0, y=0, width=100, height=100)

# btn.destroy()

window.mainloop()

# 기타 배치관리자: pack; grid;
# 웹브라우저(부모 윈도우)같이 윈도우의 크기가 (확대/축소)변경되는 경우 pcak, grid가 유용할 수 있음
----------------------------------------
에딧 윈도우
----------------------------------------
from tkinter import *

def onHello():
    msg = edt.get()
    edt2.insert(10, msg)

window = Tk()
window.title('my first window')
window.geometry("500x500")
window.resizable(0, 0)

btn = Button(window, text='hello', command=onHello)
btn.place(x=0, y=0, width=100, height=100)

edt = Entry(window, bg='white', fg='black')
edt.place(x=100, y=0, width=200, height=100)

edt2 = Entry(window, bg='white', fg='red')
edt2.place(x=100, y=100, width=200, height=100)

window.mainloop()

[참고자료]
http://effbot.org/tkinterbook/
https://www.tutorialspoint.com/python/tk_button.htm
https://www.python-course.eu/tkinter_layout_management.php

----------------------------------------
이벤트처리2

bind()
: 마우스 움직임 이벤트

printxy(event): event
----------------------------------------
from tkinter import *

def printxy(event):
    print(event.x, event.y)

window = Tk()
window.title("my")
window.geometry("500x500")
window.resizable(0, 0)

window.bind("", printxy)

window.mainloop()

[참고자료]
https://docstore.mik.ua/orelly/other/python/0596001886_pythonian-chp-16-sect-9.html

----------------------------------------
캔바스 - 그림 그리는 함수가 포함되어 있음
create_oval(x1, y1, x2, y2, fill="blue")

----------------------------------------
#
#   오른쪽 버튼 다운 이벤트
#   왼쪽버튼 누른 상태에서 마우스 이동 이벤트
  마우스 이동 이벤트
#

from tkinter import *

mycolor = "blue"

def paint(event):
    x1, y1 = ( event.x-5 ), ( event.y-5 )
    x2, y2 = ( event.x+5 ), ( event.y+5 )
    canvas.create_oval( x1, y1, x2, y2,  fill = mycolor)

def changeColor():
    global mycolor
    mycolor="red"

def toggleColor(event):
    global mycolor
    if (mycolor == "red"):
        mycolor="blue"
    else:
        mycolor="red"

window = Tk()
window.bind("", toggleColor)

canvas = Canvas(window)
canvas.pack()
canvas.bind("", paint)

button = Button(window, text="red", command=changeColor)
button.pack()

window.mainloop()

[참고자료]
http://www.python-course.eu/tkinter_layout_management.php
http://zetcode.com/gui/tkinter/layout/

--------------------------------------------------------------------------------
윈도우 생성 함수와 이벤트 처리 함수를 하나로 묶어 보자
--------------------------------------------------------------------------------
'''https://docs.python.org/3.5/library/tk.html'''

from tkinter import *

class MyButton(Button):
    def __init__(self, window):
        self.button = Button(window, text = "저를 클릭해주세요", command = self.Sum)
        self.button.pack()

    def Sum(self):
        sum = 0
        for i in range(1, 11):
            sum += i
        print("합계 : ", sum)

def main():
    window =Tk()
    a = MyButton(window)
    a.Sum()
    window.mainloop()

main()


#
# 부연설명
#

Tk() -> 뭔가를 만든다 ~ 생성
MyButton() -> 뭔가를 만든다 ~ 생성

이렇게 생성된 것들을 통칭해서 부르는 단어가 있으면 좋겠다 -> "객체; Object"

Tk() -> Tk 객체 생성
MyButton() -> MyButton 객체 생성

객체가 생성되면서 자동으로 호출되는 함수가 바로 __init__() 함수이다.

이와 같이 객체를 생성하려면, 미리 객체를 정의해 두어야 한다.

객체를 정의하는 방법은,

class 로 시작해서 위와 같이 몇 가지 규칙을 따라 작성해야 한다.

__init__() 함수가 반드시 있어야 한다.

class 내부에서 정의하는 함수들 사이에서 공동으로 사용하는 변수는 self.를 앞에 붙인다.

class 내부에서 정의하는 함수를 호출할 때도 self.를 앞에 붙인다.

class 내부에서 정의한 함수를 사용하려면 다음과 같은 형식을 취한다.

a.Sum()

미리 작성해 둔 class가 갖고 있는 함수나 변수를 유지하면서, 새롭게 함수나 변수를 추가해서 class를 정의하려면 위와 같이 객체이름 뒤 괄호안에 class이름을 넣는다.

class MyButton(Button)

그렇지 않은 경우, 다음과 같이 생략하면 된다.

class MyButton()

위 코드를 안보고 타이핑 가능해야 한다.

[참고자료]
http://zetcode.com/gui/tkinter/layout/
--------------------------------------------------------------------------------

2018년 5월 21일 월요일

[python] 파이계산및그래프그리기

import random
import math
import matplotlib.pyplot as plt

xset = []
yset = []

def generateSamples(size):
    xset.clear()
    yset.clear()
 
    for i in range(size):
        x = random.random()
        y = random.random()
        xset.append(x)
        yset.append(y)

def isInsideCircle(x, y):
r = 0.5
distance = (x - 0.5)*(x - 0.5) + (y - 0.5)*(y - 0.5) - r*r
if (distance >= 0.0):
return False
else:
return True

def estimatePi():
    circles = 0
    squares = len(xset)
    x_circle=[]
    y_circle=[]
    for i in range(squares):
        x = xset[i]
        y = yset[i]
        if (isInsideCircle(x, y)==True):
            circles += 1
            x_circle.append(x)
            y_circle.append(y)
        pi = 4 * circles / squares

    plt.scatter(x_circle, y_circle)
    plt.show()

    return pi

def main():
    pi = []
    nums=[]
    for i in range(10000, 10001, 1):
        generateSamples(i)
        p = estimatePi()
        pi.append(p)
        nums.append(i)
        print("%1.20f"%p)
    plt.plot(nums, pi, 'ro')
    plt.axis([0, 10000, 3, 3.3])
    plt.show()

main()

2018년 5월 15일 화요일

[python] 그래프출력

#
# 선그래프 그리기
#
import matplotlib.pyplot as plt
a=[1,2,3,4,5]
plt.plot(a)
plt.show()

y = [2 * x + 1 for x in range(10)]
plt.plot(y)
plt.show()

#
# 막대그리프 그리기
#
import numpy as np
label = ['seoul', 'pusan', 'daegu', 'incheon', 'kwangju', 'daejeon', 'ulsan']
ndata = np.array([5087, 1639, 1180, 1350, 664, 726, 544])
plt.bar(range(ndata.size), ndata)
plt.xticks(range(ndata.size), label)
plt.show()


[참고자료]
https://wikidocs.net/4767
http://bcho.tistory.com/m/1201
http://freeprog.tistory.com/15

2018년 5월 14일 월요일

[python] 문법09

#
# 콘솔파입출력: 리다이렉션 기능
#
a=[1,2,3,4,5,6]
for i in range(len(a)-1):
    print(a[i],",",end="")
print(a[len(a)-1])

python a.py > a.txt
python a.py >> a.txt

#
#
#
a=[]
for i in range(3):
    b = input()
    a.append(b)
print(a)
#다음과 같이 키보드에서 입력
1
2
3
>>>['1', '2', '3']

----- a.txt -----
1
2
3
----------------
python a.py < a.txt
>>>['1', '2', '3']

#
# 파일에 출력
#

#
# 텍스트 파일 - 기본
#
----------------------------------------
file = open("test.txt", "w")
file.write('hello')
file.write("\n")
file.write('world')
file.write("\n")
file.close()

file=open("test.txt", "r")
lines = file.read()
file.close()
print(lines)

#
msg = ["HELLO\n", "WORLD\n", "안녕\n"]
file = open("test.txt", "w", encoding='utf-8')
file.writelines(msg)
file.close()

file = open("test.txt", "r", encoding='utf-8')
line = file.readline()
while line != '':
    print(line, end='')
    line = file.readline()
file.close()

print()
file = open("test.txt", "r", encoding='utf-8')
lines = file.readlines()
file.close()
line = ''
for line in lines:
    print(line, end='')

----------------------------------------
리스트에 있는 값 저장
----------------------------------------
import csv
f=open('a.csv', 'w',newline='')
writer=csv.writer(f, delimiter=',')
writer.writerow([1,2,3])
writer.writerow([4,5,6])
f.close()
----a.csv----
1, 2, 3
4, 5, 6
-------------

import csv
f=open('a.csv', 'r', encoding='utf-8')
reader=csv.reader(f)
for line in reader:
    print(line)
f.close()

>> 실행결과
['1', '2', '3']
['4', '5', '6']
----------------------------------------
data=[1,2,3]
with open('a.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    writer.writerow(data)
----------------------------------------
import numpy as np
data = np.loadtxt('a.csv', delimiter=',', dtype=np.float32)
print(data)

>> 실행결과
[[1. 2. 3.]
 [4. 5. 6.]]
----------------------------------------
f = open('a.csv', 'r')
lines = f.read()
print(lines)
f.close()
>> 실행결과
1,2,3
4,5,6
----------------------------------------
#
# 이진파일
#
import pickle
colors = [1, 2, 3, 4]
pickle.dump(colors, open('colors.txt', 'wb'))
mycolors = pickle.load(open('colors.txt', 'rb'))
print(mycolors)
----------------------------------------

#
# 원그리기 / 파이 추정(근사)하기
#
# 무식한 방법으로 근사하기 ~ 몬테카를로 방법
#
import random
import math
import csv

xset = []
yset = []

def generateSamples(size):
    xset.clear()
    yset.clear()    
    for i in range(size):
        x = random.random()
        y = random.random()
        xset.append(x)
        yset.append(y)

def isInsideCircle(x, y):
r = 0.5
distance = (x - 0.5)*(x - 0.5) + (y - 0.5)*(y - 0.5) - r*r
if (distance >= 0.0):
return False
else:
return True

def estimagePi():
    area_square = 10000
    area_circle = 0
    generateSamples(area_square)
    dataset=[0, 0]
    with open('a.csv', 'w', newline='') as csvfile:
        points = csv.writer(csvfile, delimiter=',')
        for i in range(len(xset)):
            x= xset[i]
            y = yset[i]
            if (isInsideCircle(x, y)==True):
                dataset[0]=x
                dataset[1]=y
                '''points.writerow(dataset)'''
                area_circle = area_circle + 1
    return 4.0 * area_circle / area_square    

pi = estimatePi()
print("pi = %10.9f"%(pi))
----------------------------------------------------------------------------------------