// function for multiplying two big number in big endian
// big endian means, the number in a first index is the most significant byte.
static void multiply(const unsigned char *a, int la, const unsigned char *b, int lb, unsigned char *mul, int *lmul)
{
unsigned char *c = NULL;
unsigned char *temp = NULL;
int i,j,k=0,x=0,y;
long int r=0;
long sum = 0;

c = (unsigned char*)malloc(la+lb);
temp = (unsigned char*)malloc(la*lb*2);
la--;
lb--;

for(i=lb;i>=0;i--){
r=0;
for(j=la;j>=0;j--){
temp[k++] = (b[i]*a[j] + r)%256;
r = (b[i]*a[j]+r)/256;
}
temp[k++] = r;
x++;
for(y = 0;y<x;y++){
temp[k++] = 0;
}
}

k=0;
r=0;
for(i=0;i<la+lb+2;i++){
sum =0;
y=0;
for(j=1;j<=lb+1;j++){
if(i <= la+j){
sum = sum + temp[y+i];
}
y += j + la + 1;
}
c[k++] = (sum+r) %256;
r = (sum+r)/256;
}
c[k] = r;
j=0;
while(c[k-1]==0)
k--;
for(i=k-1;i>=0;i--){
mul[j++]=c[i];
}
*lmul = j;

free(c);
free(temp);
}
Posted by 배트
,
// to do: build the code and execute the binary twice at the same time!

int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE hMutex;
    DWORD dwWaitResult;

    for( int i=0 ; i<3 ; i++ )
    {
        // if the mutex with the same name exists, it opens the mutex with MUTEX_ALL_ACCESS right.
        hMutex = CreateMutex(NULL, FALSE, _T("XXXXXXX_uid:0a0b6203-cd11-4b50-877b-3965da7275cc"));

        // waiting for other thread release the mutex
        // then this thread will get the mutex
        _tprintf( _T("Waiting for the mutex... ") );
        dwWaitResult = WaitForSingleObject(hMutex, INFINITE);
        switch(dwWaitResult)
        {
        case WAIT_OBJECT_0:
            // This thread got a mutex!
            _tprintf(_T ("thread got mutex ! \n") );
            break;
        case WAIT_TIMEOUT:
            // A time out occurs...
            _tprintf(_T ("timer expired ! \n") );
            break;
        case WAIT_ABANDONED:
            // Another thread may not release the mutex before it terminated.
            // The mutex has been abandoned.... how poor....
            _tprintf(_T ("abandoned ! \n") );
            break;
        }

        _tprintf( _T("Thread Running (%d) ! \n"), i+1 );
        for( int j=0 ; j<10 ; j++)
        {
            _puttch(_T('.'));
            Sleep(100);
        }
        _puttch(_T('\n'));

        // should release the mutex
        _tprintf( _T("One loop ended, the mutex will be released! \n\n") );
        ReleaseMutex(hMutex);
    }

    _tprintf( _T("Test has terminated.\nPress any key to continue... \n") );
    _gettch();

    return 0;
}
Posted by 배트
,
내가 이딴건 왜 만들었을까...

class SafeData {
public:
    SafeData();
    virtual ~SafeData();
    void SetByCopy( Data inData );
    void SetByCopy( uint8 *d, int l );
    void SetByRef( Data inData );
    void SetByRef( uint8 *d, int l );
    uint8 *GetData();
    int GetLength();
    void Clear();
    
protected:
    uint8 *pBuffer;
    int length;
};

SafeData::SafeData()
{
    pBuffer = NULL;
    length = 0;
};

SafeData::~SafeData()
{
    Clear();
};

void SafeData::SetByCopy( Data inData )
{
    Clear();
    pBuffer = new uint8[inData.len];
    if( pBuffer==NULL )
        return;
    length = inData.len;
    memcpy( pBuffer, inData.d, length );
}

void SafeData::SetByCopy( uint8 *d, int l )
{
    Clear();
    pBuffer = new uint8[l];
    if( pBuffer==NULL )
        return;
    length = l;
    memcpy( pBuffer, d, length );
}

void SafeData::SetByRef( Data inData )
{
    Clear();
    pBuffer = inData.d;
    length = inData.len;
}

void SafeData::SetByRef( uint8 *d, int l )
{
    Clear();
    pBuffer = d;
    length = l;
}

uint8 *SafeData::GetData() {return pBuffer;}

int SafeData::GetLength() {return length;}

void SafeData::Clear()
{
    if( pBuffer )
    {
        delete [] pBuffer;
        pBuffer = NULL;
    }
    length = 0;
}

Posted by 배트
,
으...폰트 이름과 헤더 수정 못했음.
두 폰트 모두 편집과 배포가 자유로운 폰트지만,
헤더의 저작권를 적절히 수정하지 못해서 문제가 생길 수는 있음.
Posted by 배트
,
언젠가 유용하게 쓰겠지...
The temporary file handling class for Win32.

class TempFileUtility {
public:
    TempFileUtility()
    {
        ResetData();
    }

    virtual ~TempFileUtility()
    {
        CloseTempFile();
    }

    int OpenTempFile( BOOL bCloseAfterCreated )
    {
        if( m_bInitialized==TRUE )
            return ERROR_ALREADY_INITIALIZED;

        const int cMaxTempDir = MAX_PATH-14;        
        TCHAR szTempDir[cMaxTempDir];
        
        int nResult = 0;
        
        nResult = GetTempPath( cMaxTempDir, szTempDir );
        if( nResult==0 || nResult>cMaxTempDir )
        {
            nResult = SHGetSpecialFolderPath( NULL, szTempDir, CSIDL_MYDOCUMENTS, TRUE );
            
            if( nResult==FALSE )
                return ERROR_CANNOT_MAKE;
        }
        
        nResult = GetTempFileName( szTempDir, _T(""), 0, m_szTempFile );
        if( nResult==FALSE )
        {
            ResetData();
            return ERROR_CANNOT_MAKE;
        }

        if( bCloseAfterCreated==TRUE )
        {    
            m_hFile = CreateFile( m_szTempFile, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY, NULL );
            if( m_hFile==INVALID_HANDLE_VALUE )
            {
                DeleteFile( m_szTempFile );
                ResetData();
                return ERROR_OPEN_FAILED;
            }
        }

        m_bInitialized = TRUE;
        return ERROR_SUCCESS;
    }

    int WriteTempFile(
        LPCVOID lpBuffer,
        DWORD nNumberOfBytesToWrite
        )
    {
        if( m_bInitialized==FALSE )
            return ERROR_NOT_READY;

        if( m_hFile==INVALID_HANDLE_VALUE )        
            return ERROR_NOT_READY;

        BOOL bSuccess;
        DWORD dwWritten = 0;

        bSuccess = WriteFile( m_hFile, lpBuffer, nNumberOfBytesToWrite, &dwWritten, NULL );

        if( bSuccess==FALSE )
            return GetLastError();

        return ERROR_SUCCESS;
    }


    int CloseTempFile()
    {
        if( m_bInitialized==FALSE )
            return ERROR_NOT_READY;

        if( m_hFile!=INVALID_HANDLE_VALUE )
            CloseHandle( m_hFile );

        DeleteFile( m_szTempFile );
        ResetData();
        return ERROR_SUCCESS;
    }

    LPCTSTR GetTempFilePath() {return m_szTempFile;}
    HANDLE GetTempFileHandle() {return m_hFile;}

protected:
    BOOL m_bInitialized;
    TCHAR m_szTempFile[MAX_PATH];
    HANDLE m_hFile;

    void ResetData()
    {
        m_bInitialized = FALSE;
        memset( m_szTempFile, 0, MAX_PATH );
        m_hFile = INVALID_HANDLE_VALUE;
    }
};

Posted by 배트
,

2011년 계획

斷想 - Note 2010. 12. 24. 17:35
Beta
Posted by 배트
,

2010년 생활 점검

斷想 - Note 2010. 12. 23. 10:10
2010년이 저물어가고 있고, 새 다이어리도 산 기념으로 올 한해를 뒤돌아본다.
이 점검은 내년 계획에 큰 영향을 미칠 것이다.
구체적인 이벤트 기록이 없는 건 아쉽지만, 그런 것 까지 챙길 정성은 없다.ㅋㅋㅋ

가치
설정한 중요가치
깸, 정직, 버림, 품위, 기도, 상생, 대화/타협, 바른 개인주의, 함께, 가족애, 사랑, 목표지향, 보람, 시간/공간 분리, 여유, 이완, 기록, 지속가능

지켜진 가치
정직, 상생, 가족애, 목표지향, 시간/공간 분리, 여유

자기계발
설정한 중요목표
영어 TOEIC 900, OPIc IL
일본어 JPT B
운동 체중 65kg, 건강한 심장
그림 4p 원고 6개, 그림 블로그 운영, 웹툰일기
금전 자유 입출금 500만원 만들기
절주/금연
독서 매달 2권, 독서일기
즐겁게 일하기

목표 달성 상황
TOEIC 850, 미달
OPIc X, 안함
JPT 405, 미달
체중 증가; 61kg, 미달
체력 개선했으나 약함, 미달
원고/그림블로그/웹툰일기, 안함
저축 500만원, 미달
절주/금연, 절주성공 금연실패
독서 매달 2권, 성공
즐겁게 일하기, 즐겁다기 보다 너무 여유롭게 일했음

의외의 성과
기타 코드
프리젠테이션 능력
업무 능력 확대에 대한 비전


종합평가
가치
금년에 지킨 가치에 포함되지 않은 가치들은 지키기 어렵거나 다른 가치와 중복된 것이 많다. 핵심 가치는 지켜졌다고 보고 있다. 다만 '기도'는 기도할 대상을 찾지 못해 어려움을 겪는다. '기록'과 '지속가능'은 중요한 가치이며 목표로 설정하기보다는 지속되어야 할 프로세스화 해야 한다. 학습과 발전 대한 가치를 중요시 여기면서도 작년도에 설정하지 못한게 아쉽다.
2011년에 설정할 중요 가치도 2010년과 크게 다를 것은 없지만, 다소 다듬을 것이다.

목표
목표에 대해서는 거의 대부분이 미진하다. '일본어'는 구체적인 비전이 없는 막연한 목표였으니 차치하더라도, '영어'의 성취도는 조금 아쉽다. 올해 설정한 목표는 2011년 초에 달성할 것이다. '운동'은 평일에 하면 다음날 업무에 지장이 있으므로 큰 성취가 어려웠다. 체력을 기를 수 있는 짜투리 기회(퇴근시 런닝, 자전거 출퇴근)가 있었는데,활용하지 못한 점도 아쉽다. 인생에서 가장 큰 취미인 '그림'은 올해 성취와 활동 모두 매우 미진하다. 몇가지 이론 공부, 감각 연마, 작품 활동 모두 매우 저조하다. 기대 이하 정도가 아니라, 매우 저조하다.
다만 그림에 쏟을 노력을 '기타'에 쏟아서 얻은 성취는 기대 이상이다. 자유롭지는 않지만 어느정도 코드를 잡을 수 있게 되었으니, 지금 수준을 지키며 즐기는 것이 중요하다. 하지만 이 능력을 유지할 수 있는 수단이 있을지 불투명하다.
내년에는 생활양식을 좀 더 단순하게 개선한다. 그리고 중요 목표를 현실적으로 설정할 것이다. 단적으로 일본어는 중요목표에서 제외하고, 그림은 좀 더 구체적인 달성 방안을 제시한다. 목표 대신 프로세스로 설정할 것은 별도 항목으로 이전한다. 그리고 영어에 좀 더 집중하고, 업무 능력 향상과 사진 공부를 중요 목표에 추가한다. 내년도 험난할 것 같다.

인성
인성적으로는 최근 2~3년의 추세를 이어 점점 '목표지향'적이 되어가고, 생활과 노력의 '효율'을 중요시 여기게 되었다. 목표가 높고 자기계발욕이 강한 바쁜 도시인의 모습의 전형을 그대로 반영하고 있다. 다만 자신의 시간을 중요시 여기기 때문에 다른 사람들과 어울리기는 점점 어려워진다. 예전에 시간을 들여서 사람에게 정성과 노력을 기울였다면 최근에는 요령과 입담으로 사람에게 환심을 사려고 노력한다. 어쩔 수 없는 변화지만, 소중한 사람에게만은 깊은 정성을 보여야 한다는 것은 잊지 말자.
다른 큰 성과는 가족과의 관계가 개선된 것이다. 나를 향한 간섭이 적어지고, 나의 의견을 존중해준다. 나는 웃으면서 가족들과 대화를 하고, 많은 이야기를 나눈다. 이런 관계 개선이 가족들과 적당한 거리를 두고, 사람을 대하는 요령이 좋아진 것이 원인이라서 조금 씁쓸하긴 하다.
인성의 변화에는 생활양식의 변화가 큰 영향을 미쳤다. 밝아지고, 여유로워졌다. 하지만 마음 속의 부조리를 의탁할 기도의 대상이 없다는 것은 안타까운 일이다.

생활양식
흑석동에서 누나와 함께 살 때는 내 제어가 미치지 않는 집안 상황에 스트레스를 받았었다.
10월 10일에 이사를 하면서 많은 것이 변했다. 혼자 꾸려야 할 것들이 많았지만 집안 일들을 효율적으로 (손이 덜 가게) 설정해서 큰 무리는 없었다. 공간과 시간적 자유도가 매우 높아졌고, 취향에 맞게 집을 꾸미는 것도 가능해졌다. 운동, 공부, 집안 일 패턴(빨래,설거지,청소), 친구초대, 식사습관도 많이 달라졌고, 나의 이상에 가까워졌다.
하지만 아직 프로세스가 100% 정합하지 않고, 정신적/체력적으로 늘어지는 경우가 많다. 쓸데없는 웹서핑을 줄이고 체력을 더 길러야 한다. 주기적인 운동으로 몸을 자극하고, 문화 생활로 정신을 자극하여 High Quality Home Life를 위한 의욕을 고취시켜야 한다. 반드시 지켜야 할 일정과 원칙을 설정해야 하고, 지키기로 결정한 사항들은 눈에 보기 쉬운 곳에 텍스트를 남겨야 한다.
생활양식을 고정하게 되면 (결정을 위한)정신의 소모를 줄이고, (요령이 생기므로)시간 낭비를 줄이고, 집안 환경을 유지하고, 자기 계발과 정서 안정에 큰 도움이 된다.
Posted by 배트
,
IE ActiveX는 버리고 CEF로 가자!
아..쥰내 아름답네. 한두가지 모자라긴 하지만.
특히 Attribute 세팅이 자동으로 UI에 적용되어야 하는데...그건 당장 구현하기가 귀찮아서 일단은 이렇게 하자.

Posted by 배트
,
CEF는 크로미움의 웹 브라우저 기능을 Win32 Windows 기반의 컨트롤로써 사용할 수 있게 해준다.
기존 IE ActiveX를 애플리케이션에 Embedding하는 방식을 써왔다면, CEF가 좋은 대안이 될 수 있다.

CEF를 사용하면 IE의 불안정과 속도 문제, 불편한 인터페이스를 해결할 수 있다.
CEF는 라이브러리로 제공되기 때문에 IE 또는 인터넷 설정과의 종속성을 해결할 수 있다.
IE가 제공하는 것보다 기능이 적다고 여겨지나,
개발자에게 필요한 기능은 거의 다 있고 사용법이 간단하다.
웹 표준은 말할 것도 없고.

앞으로 웹을 Embedding하는 Windows 애플리케이션은 모두 CEF를 사용할 생각이다.
여기서 소스와 라이브러리를 받을 수 있다. http://code.google.com/p/chromiumembedded/
Posted by 배트
,
중요하진 않지만. 나름 알아내느라 신경썼으니 기록해놔야지.

scrollHeight
complete
clientLeft
offsetParent
firstElementChild
offsetWidth
isContentEditable
hidden
lowsrc
previousElementSibling
localName
parentElement
ownerDocument
nodeValue
lastElementChild
height
x
offsetLeft
tagName
className
prefix
innerHTML
border
width
previousSibling
childElementCount
namespaceURI
scrollLeft
longDesc
lastChild
innerText
clientHeight
align
textContent
nextSibling
scrollWidth
useMap
vspace
offsetHeight
name
clientWidth
nodeName
style
lang
src
scrollTop
offsetTop
childNodes
baseURI
nextElementSibling
title
firstChild
hspace
attributes
dataset
isMap
parentNode
alt
clientTop
naturalWidth
tabIndex
naturalHeight
contentEditable
dir
outerHTML
outerText
id
children
nodeType
draggable
y
insertAdjacentHTML
insertAdjacentText
insertAdjacentElement
getAttribute
setAttribute
removeAttribute
getAttributeNode
getElementsByTagName
getAttributeNS
setAttributeNS
removeAttributeNS
getElementsByTagNameNS
getAttributeNodeNS
hasAttribute
hasAttributeNS
focus
blur
scrollIntoView
scrollIntoViewIfNeeded
scrollByLines
scrollByPages
getElementsByClassName
querySelector
querySelectorAll
webkitMatchesSelector
getClientRects
getBoundingClientRect
setAttributeNode
removeAttributeNode
setAttributeNodeNS
contains
insertBefore
replaceChild
removeChild
appendChild
hasChildNodes
cloneNode
normalize
isSupported
hasAttributes
lookupPrefix
isDefaultNamespace
lookupNamespaceURI
addEventListener
removeEventListener
isSameNode
isEqualNode
compareDocumentPosition
dispatchEvent
ELEMENT_NODE
ATTRIBUTE_NODE
TEXT_NODE
CDATA_SECTION_NODE
ENTITY_REFERENCE_NODE
ENTITY_NODE
PROCESSING_INSTRUCTION_NODE
COMMENT_NODE
DOCUMENT_NODE
DOCUMENT_TYPE_NODE
DOCUMENT_FRAGMENT_NODE
NOTATION_NODE
DOCUMENT_POSITION_DISCONNECTED
DOCUMENT_POSITION_PRECEDING
DOCUMENT_POSITION_FOLLOWING
DOCUMENT_POSITION_CONTAINS
DOCUMENT_POSITION_CONTAINED_BY
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
Posted by 배트
,