3/27/2014

OpenCV Study, Mat Resize, simple example source code


Here, srcA, dstB is Mat class.

resize(srcA, srcB, Size(srcA.size().width/2, srcA.size().height/2) );

3/18/2014

Python Study, put_nowait(), get_nowait(), example source code

#put_nowait, get_nowait method


import queue
q = queue.Queue(2) #buffer size is 2
q.put("apple")
q.put("banana")
#q.put("orange")  # wait infinity until there is available space


#q.put_nowait("orange") #error occurs
# Line 187, in put_nowait return self.put(item, block=False)
# line 133, in put raise Full


q.get_nowait()
q.get_nowait()
#q.get_nowait() #error occurs
#line 195, in get_nowait return self.get(block=False)
#line 164, in get raise Empty


q.put("AA", True, 5);
q.put("AA", True, 5);
#q.put("AA", True, 5);  # wait 5 second until there is available space, if no space after 5 second, error occur



Python Study, queue, stack, priority queue, example source code

import queue

def GetItemList(q):
    ret = []
    n = q.qsize()
    while n>0:
        ret.append(q.get())
        n -= 1
    return ret

l = 'apple,banana,orange'


#queue test
q = queue.Queue()
for x in l.split(','):
    print(x)
    q.put(x)

print( GetItemList(q) )


#stack case
#LIFO last in first out
q = queue.LifoQueue()
for x in l.split(','):
    q.put(x)
print( GetItemList(q) )


#priorityQueue
q = queue.PriorityQueue()
q.put((5,"apple"))
q.put((10,"banana"))
q.put((1,"orange"))
print( GetItemList(q) )

"""
out put is...
['apple', 'banana', 'orange']
['orange', 'banana', 'apple']
[(1, 'orange'), (5, 'apple'), (10, 'banana')]
"""

Pyton study, Queue example source code

import queue

q = queue.Queue()
q.put("apple")
q.put("banana")
q.put(10)
print( q.qsize() )
print( q.get() )
print( q.get() )
print( q.qsize() )

"""
output is...

3
apple
banana
1

"""

Python Study, multiprocessing example source code

__author__ = 'mare'


from multiprocessing import Process, Lock, Value
import time


def run(name, l, c):
    print( name, 'process is created.')
    fixed = 0
    while 1:

        l.acquire()

        if c.value>0:
            c.value -= 1
            l.release()
            fixed += 1
            time.sleep(0.1)
        else:
            l.release()
            print(name, 'fixed', fixed, 'defects')
            break



if __name__=='__main__':
    lock = Lock()
    count = Value('i', 10)



dev_list = []
for name in ['Mare1', 'Mare2', 'Mare3']:
    dev = Process( target=run, args=(name, lock, count))
    dev_list.append(dev)
    dev.start()

for dev in dev_list:
    dev.join()
    print('All processes are finished.')





#out put is..
"""
Mare1 process is created.
Mare2 process is created.
Mare3 process is created.
Mare2 fixed 3 defects
Mare3 fixed 3 defects
Mare1 fixed 4 defects
All processes are finished.
All processes are finished.
All processes are finished.
"""

Python Study, Threading example source code

#Thread.start() //thread start
#Thread.run()   //thread main function run
#Thread.join([timeout]) //wait until thread end


from threading import Thread, Lock
import time

count = 10
lock = Lock()



class developer(Thread):

    def __init__(self, name):   #initialize
        Thread.__init__(self)
        self.name = name
        self.fixed = 0

    def run(self):              #thread main function


        global count
        while 1:
            #lock.acquire()      #lock  -> Untie comment, error occurs, I don't know why error occurs...
            if count > 0:
                count -= 1
                #lock.rlease()   #unlock -> Untie comment, error occurs, I don't know why error occurs...
                self.fixed += 1
                time.sleep(0.1)
            else:
                #lock.release()  #unlock -> Untie comment, error occurs, I don't know why error occurs...
                break




dev_list = []
for name in ['Mare1', 'Mare2', 'Mare3']:
    dev = developer(name)       #create thread
    dev_list.append(dev)
    dev.start()                 #thread start


for dev in dev_list:
    dev.join()                  #wait
    print(dev.name, 'fixed', dev.fixed)


#Mare1 fixed 3
#Mare2 fixed 4
#Mare3 fixed 3

3/17/2014

OpenCV Study, cvResize function

float percent = 50.0;
IplImage *source = cvLoadImage("bigImage.jpg");
IplImage *destination = cvCreateImage( cvSize((int)((source->width*percent)/100) , (int)((source->height*percent)/100) ),source->depth, source->nChannels );

//use cvResize to resize source to a destination image
cvResize(source, destination);

// save image with a name supplied with a second argument
cvSaveImage( "resizeImage.jpg", destination );



3/16/2014

Python study, sys modules




import sys

print(sys.prefix)
#/Library/Frameworks/Python.framework/Versions/3.3

print(sys.base_exec_prefix)
#/Library/Frameworks/Python.framework/Versions/3.3

#sys.exit([arg]) #process exit

t="test refcount"
print(sys.getrefcount(t))
#4
t1 = t
print(sys.getrefcount(t))
#5


#print(sys.getwindowsversion())
#sys.moudles

print(sys.path)
#['/Users/mare/PycharmProjects/sys_functions', '/Users/mare/PycharmProjects/sys_functions', '/Library/Frameworks/Python.framework/Versions/3.3/lib/python33.zip', '/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3', '/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages']

print( sys.copyright )
"""
Copyright (c) 2001-2013 Python Software Foundation.
All Rights Reserved.

Copyright (c) 2000 BeOpen.com.
All Rights Reserved.

Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.

Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
"""

print("====")
print( sys.version )
#3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35)
#[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]


print(sys.getdefaultencoding())
#utf-8

print( sys.stdout.write("hhh") )
print( sys.stderr.write("eee") )

#sys.argv
#sys.exc_info()







3/15/2014

OpenCV Study, Write text on the image, cvPutText, putText


...code start

...code end

output example)




OpenCV Study, Mat Size Width, Height

int width = frame.size().width;
int height = frame.size().height;

OpenCV Study, IplImage * display to PictureBox on Dialog (MFC), example source code

void DisplayIplImageToPictureBox(IplImage* pImgIpl, CDC* pDC, CRect rect)
{
 BITMAPINFO bitmapInfo;
 bitmapInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
 bitmapInfo.bmiHeader.biPlanes=1;
 bitmapInfo.bmiHeader.biCompression=BI_RGB;
 bitmapInfo.bmiHeader.biXPelsPerMeter=100;
 bitmapInfo.bmiHeader.biYPelsPerMeter=100;
 bitmapInfo.bmiHeader.biClrUsed=0;
 bitmapInfo.bmiHeader.biClrImportant=0;
 bitmapInfo.bmiHeader.biSizeImage=0;
 bitmapInfo.bmiHeader.biWidth=pImgIpl->width;
 bitmapInfo.bmiHeader.biHeight=-pImgIpl->height;

 IplImage* tempImage=NULL;

 if(pImgIpl->nChannels == 3)
 {
  tempImage = (IplImage*)cvClone(pImgIpl);
  bitmapInfo.bmiHeader.biBitCount=tempImage->depth * tempImage->nChannels;

 }
 else if(pImgIpl->nChannels == 1)
 {
  tempImage =  cvCreateImage(cvGetSize(pImgIpl), IPL_DEPTH_8U, 3);
  cvCvtColor(pImgIpl, tempImage, CV_GRAY2BGR);
  bitmapInfo.bmiHeader.biBitCount=tempImage->depth * tempImage->nChannels;
 }
 if( tempImage != NULL)
 {
  pDC->SetStretchBltMode(COLORONCOLOR);
  ::StretchDIBits(pDC->GetSafeHdc(), rect.left, rect.top, rect.right, rect.bottom, 
   0, 0, tempImage->width, tempImage->height, tempImage->imageData, &bitmapInfo, 
   DIB_RGB_COLORS, SRCCOPY);

  cvReleaseImage(&tempImage);
 }
}


void DrawFunction()
{
     //code is omitted..
     //~~~~
     //~~~~~

     CDC* vDC;
     vDC = m_PicBox.GetDC(); //m_PicBox is PictureBox CStatic variable.
     CRect rect;
     m_PicBox.GetClientRect(&rect);
     DisplayIplImageToPictureBox(img, vDC, rect); //img is IplImage* variable.
     ReleaseDC(vDC);
     //~~~
     //~~~

}



..
Example picture of display(drawing) IplImage * on a dialog


OpenCV Study, Mat to IplImage* convert, simple method


Data Copy
IplImage * img = cvCloneImage( &(IplImage)frame ); //where frame is Mat!!
//~~~
//~~
cvReleaseImge(&img);



Point Copy
IplImage * img = &((IplImage)frame) //where frame is Mat!!

3/13/2014

C,C++, To get a list of files in a directory using CFileFind function, example source code


        CFileFind finder;
 CString strFileName;
 //CStringList list;
 strFiles.Format("C:\\Demo\\*.avi", pszPathname);
 BOOL bWorking = finder.FindFile(strFiles);
 while(bWorking)
 {
  bWorking = finder.FindNextFile();
  //list.AddTail(finder.GetFileName());
  ::AfxMessageBox(finder.GetFileName());
 }


C, C++, To select folder only and get path using SHBrowseForFolder function, example source code

//Get only folder name
 ITEMIDLIST *pidlBrowse;
 WCHAR pszPathname[MAX_PATH];
 
 BROWSEINFO BrInfo;
 BrInfo.hwndOwner = GetSafeHwnd();
 BrInfo.pidlRoot = NULL;
 
 CString str =_T("c:\\"); //initial path
 LPCTSTR lpszDefaultFolder = str;
 memset(&BrInfo, 0, sizeof(BrInfo));
 BrInfo.pszDisplayName=(LPSTR)pszPathname;
 BrInfo.lpszTitle=_T("Select directory");
 BrInfo.ulFlags=BIF_RETURNONLYFSDIRS; //select folder only
 //BrInfo.ulFlags=BIF_BROWSEINCLUDEFILES; //select folder and file
 BrInfo.lParam=(LPARAM)lpszDefaultFolder;
 //BrInfo.lpfn=BrowseCallback;
 
 pidlBrowse = ::SHBrowseForFolder(&BrInfo);

 
 if (pidlBrowse != NULL)
 {
  //Get Path
  SHGetPathFromIDList(pidlBrowse, (LPSTR)pszPathname);
  AfxMessageBox((LPCSTR)pszPathname);
 }


...



C, C++, To select a file and get path and file name using CFileDialog function, example source code

TCHAR szFilter[] = _T("All Files(*.*)|*.*||");
CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY, szFilter);

CString strPathName, m_filename;
if(IDOK == dlg.DoModal()) {
 m_filename=dlg.GetFileName();   //file name
 strPathName = dlg.GetPathName(); //full path info
}

..



C,C++, Get current directory( path ), GetCurrentDirectory function

Get path
#Case 1
char reDir[500];
::GetCurrentDirectory(500,reDir);
::AfxMessageBox(reDir);

#Case 2
TCHAR buff[MAX_PATH];
memset(buff, 0, MAX_PATH);
::GetCurrentDirectory(MAX_PATH, buff);
CString strFolder = buff;





Get path & module name 
TCHAR buff[MAX_PATH]; 
 memset(buff, 0, MAX_PATH); 
 ::GetModuleFileName(NULL,buff,sizeof(buff)); 
 CString strFolder = buff; 
 strFolder = strFolder.Left(strFolder.ReverseFind(_T('\\'))+1);



C, C++, The meaning of LPSTR, LPCSTR, LPTSTR, LPCTSTR, LPWSTR

LP is Long Pointer.
C is constant.
STR is String.

LPSTR = long pointer string = char*
LPCSTR = long pointer constant string = const char*



W means Wide char and unicode.

LPWSTR = long porinter wide string = w_char*
LPCWSTR = long porinter constant wide string = const w_char*


T is ..

LPCTSTR = long pointer constant t_string = const tchar*



3/11/2014

Python Study, Pycharm color setting

Pycharm color setting menu is here..

Preference ->  Editor -> Colors & Fonts.
Pycharm support 5 colors mode. (default, darcula, monokai, twilight, warmneon)
But we can set more various color setting detailed.

Refer to screen captures of color skin.









Python Study, Pycharm first setting

At first, you have to register python compiler,
Setting menu is here ...

Preference -> Project interpreter
or
File -> Default settings... -> project interpreter

And then, Add(+) python interpreter path and click apply or ok button




C,C++, string split example source code (stringstream, getline functions)


#include < iostream >
#include < string >
#include < sstream >

using namespace std;

vector< string> str_split(const string &s, char delim) 
{
    vector< string> elems;
    stringstream ss(s);
    string item;
    
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
 
    return elems;
}



int main()
{

 vector< string> str = str_split( "123,456", ',');
 for(int i=0; i< str.size(); ++i)
 {
  printf("%s\n", str[i].c_str() );
 }

}


3/10/2014

Python study, OS modules

__author__ = 'mare'

import os

print( os.getcwd() )
#/Users/mare/PycharmProjects/OS_module

print( os.access('.', os.F_OK ) )
print( os.access('.', os.W_OK | os.X_OK | os.R_OK ) ) #write, exec, read
#True
#True

os.rmdir('test1')
print( os.listdir('.') )
#['.idea', 'osModule.py']
os.mkdir('test1')
print( os.listdir('.' ) )
#['.idea', 'osModule.py', 'test1']

os.removedirs('test2/sub1/sub2/leaf')
os.makedirs('test2/sub1/sub2/leaf')
print( os.listdir('test2/sub1/sub2') )
#['leaf']

print(os.listdir('.'))
os.rename('newfile.txt', 'oldfile.txt')
print(os.listdir('.'))
#['.idea', 'newfile.txt', 'osModule.py', 'test1', 'test2']
#['.idea', 'oldfile.txt', 'osModule.py', 'test1', 'test2']
os.rename('oldfile.txt','newfile.txt')


os.renames('newfile.txt', 'ttt/moved.txt')
print( os.listdir('ttt') )
#['.DS_Store', 'moved.txt']
os.renames('ttt/moved.txt', 'newfile.txt')

print( os.stat('newfile.txt') )
#posix.stat_result(st_mode=33188, st_ino=5325009, st_dev=16777219, st_nlink=1, st_uid=501, st_gid=20, st_size=0, st_atime=1394464185, st_mtime=1394463961, st_ctime=1394463961)


#I made directory like that
# - test_walk
#  +- a
#  +- b
#      +- newfile.txt

for path, dirs, files in os.walk('test_walk'):
 print( path, dirs, files)
#test_walk ['a', 'b'] ['.DS_Store']
#test_walk/a [] []
#test_walk/b [] ['newfile.txt']

for path, dirs, files in os.walk('test_walk', topdown=False):
 print( path, dirs, files)
#test_walk/a [] []
#test_walk/b [] ['newfile.txt']
#test_walk ['a', 'b'] ['.DS_Store']


print( os.pipe() ) #create pipe to communicate between proccess


#file object creation
#r, w = os.pipe()
#rd = os.fdopen(r)

#rp = os.popen('dir' 'r')
#print( p.read() )


print(os.name)
#posix

print( os.environ )
#environ({'__CF_USER_TEXT_ENCODING': '0x1F5:3:51', 'SSH_AUTH_SOCK': '/tmp/launch-XLOLCi/Listeners', 'PYCHARM_HOSTED': '1', 'VERSIONER_PYTHON_PREFER_32_BIT': 'no', 'PYTHONIOENCODING': 'UTF-8', 'PYTHONUNBUFFERED': '1', 'PATH': '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', 'LOGNAME': 'mare', 'USER': 'mare', 'HOME': '/Users/mare', 'TMPDIR': '/var/folders/b7/gxpfjkqs0bs33cyyn76q7drw0000gn/T/', 'VERSIONER_PYTHON_VERSION': '2.7', '__CHECKFIX1436934': '1', 'Apple_PubSub_Socket_Render': '/tmp/launch-bHTzXo/Render', 'SHELL': '/bin/bash', '__PYVENV_LAUNCHER__': '/Library/Frameworks/Python.framework/Versions/3.3/bin/python3', 'PYTHONPATH': '/Users/mare/PycharmProjects/OS_module'})
print( os.environ.keys() )
#KeysView(environ({'__CF_USER_TEXT_ENCODING': '0x1F5:3:51', 'SSH_AUTH_SOCK': '/tmp/launch-XLOLCi/Listeners', 'PYTHONPATH': '/Users/mare/PycharmProjects/OS_module', 'LOGNAME': 'mare', 'PATH': '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', 'PYCHARM_HOSTED': '1', '__CHECKFIX1436934': '1', 'PYTHONUNBUFFERED': '1', 'SHELL': '/bin/bash', 'Apple_PubSub_Socket_Render': '/tmp/launch-bHTzXo/Render', 'PYTHONIOENCODING': 'UTF-8', 'TMPDIR': '/var/folders/b7/gxpfjkqs0bs33cyyn76q7drw0000gn/T/', 'VERSIONER_PYTHON_PREFER_32_BIT': 'no', 'USER': 'mare', 'VERSIONER_PYTHON_VERSION': '2.7', '__PYVENV_LAUNCHER__': '/Library/Frameworks/Python.framework/Versions/3.3/bin/python3', 'HOME': '/Users/mare'}))

print( os.getpid() )
#10140

os.system('calc')
#os.startfile('LICENSE.txt')





3/09/2014

Python Study, SQLite3

SQLite3 is already included in your python, so you do not need install.

__author__ = 'mare'


import sqlite3

con = sqlite3.connect("test.db")
con2 = sqlite3.connect(":memory:") #create db in memory space, it is faster but all clear after program turn off

#sql excute
cur = con.cursor()
cur.execute("DROP TABLE phoneBook;")
cur.execute("CREATE TABLE PhoneBook(Name text, PhoneNum text);")
cur.execute("INSERT INTO PhoneBook VALUES('Derick', '010-1234-5678');")
cur.execute("INSERT INTO PhoneBook VALUES('Merry', '010-5678-0000');")


name = "SangJung"
phoneNumber = '010-5670-2343'
cur.execute("INSERT INTO PhoneBook VALUES(?, ?);",(name, phoneNumber))



cur.execute("INSERT INTO PhoneBook VALUES(:inputName, :inputNum);",
 {"inputNum":phoneNumber, "inputName":name})



#datalist = (('Tom', '010-543-5432'), ('DSP', '010-123-1234'))
#cur.execute("INSERT INTO PhoneBook VALUES(?, ?);", datalist)


#view reccord
cur.execute("SELECT * FROM PhoneBook;")
for row in cur:
 print(row)
#('Derick', '010-1234-5678')
#('SangJung', '010-5670-2343')
#('SangJung', '010-5670-2343')

cur.execute("SELECT * FROM PhoneBook;")
print( cur.fetchone() )
print( cur.fetchmany(2))
#('Derick', '010-1234-5678')
#[('SangJung', '010-5670-2343'), ('SangJung', '010-5670-2343')]


cur.execute("SELECT * FROM PhoneBook;")
print( cur.fetchone() )
print( cur.fetchall() )
#('Derick', '010-1234-5678')
#[('SangJung', '010-5670-2343'), ('SangJung', '010-5670-2343')]


con.commit()  #you have to run commit function to udpate db contents.
con.isolation_level = None #auto commit mode


#record ordering
cur.execute("SELECT * FROM PhoneBook ORDER By Name")
print( [r for r in cur])
cur.execute("SELECT * FROM PhoneBook ORDER By Name DESC")
print( [r for r in cur])
#[('Derick', '010-1234-5678'), ('Merry', '010-5678-0000'), ('SangJung', '010-5670-2343'), ('SangJung', '010-5670-2343')]
#[('SangJung', '010-5670-2343'), ('SangJung', '010-5670-2343'), ('Merry', '010-5678-0000'), ('Derick', '010-1234-5678')]

cur.execute("INSERT INTO PhoneBook VALUES('apple', '010-369-3639');")
cur.execute("SELECT * FROM PhoneBook ORDER By Name")
print( [r[0] for r in cur] )
#['Derick', 'Merry', 'SangJung', 'SangJung', 'apple']



#user define condition function
def OrderFunc(str1, str2):
 s1 = str1.upper()
 s2 = str2.upper()
 return (s1 > s2 ) - (s1 < s2 )

con.create_collation('myordering', OrderFunc)
cur.execute("SELECT Name FROM PhoneBook ORDER By Name COLLATE myordering")
print( [r[0] for r in cur])
#['apple', 'Derick', 'Merry', 'SangJung', 'SangJung']




#new table creation
cur.execute("DROP TABLE PhoneBook2")
cur.execute("CREATE TABLE PhoneBook2(Name text, Age ineger);")
list = (('Tom', 24), ('Derick',30), ('Peter',53), ('Jane',29))
cur.executemany("INSERT INTO PhoneBook2 VALUES (?,?);", list)
#cur.execute("INSERT INTO PhoneBook2 VALUES(?,?);", list[0])
#cur.execute("INSERT INTO PhoneBook2 VALUES(?,?);", list[1])
#cur.execute("INSERT INTO PhoneBook2 VALUES(?,?);", list[2])

cur.execute("SELECT length(Name), upper(Name), lower(Name) FROM PhoneBook")
print(" == length(), upper(), lower() ==")
print( [r for r in cur] )
#== length(), upper(), lower() ==
#[(6, 'DERICK', 'derick'), (5, 'MERRY', 'merry'), (8, 'SANGJUNG', 'sangjung'), (8, 'SANGJUNG', 'sangjung'), (5, 'APPLE', 'apple')]


#User-defined aggregate functions
class Average:
 def __init__(self):
  self.sum = 0
  self.cnt = 0

 def step(self, value):
  self.sum += value
  self.cnt += 1

 def finalize(self):
  return self.sum / self.cnt

con.create_aggregate("avg", 1, Average)
cur.execute("SELECT avg(Age) FROM PhoneBook2")
print( cur.fetchone() )
#34.0


#Type of variables in SQLite3
#Python -> SQLite3
#None -> NULL
#int -> INTEGER
#float -> REAL
#str, bytes -> TEXT
#buffer -> BLOB

#db dump
for l in con.iterdump():
 print(l)
"""
BEGIN TRANSACTION;
CREATE TABLE PhoneBook(Name text, PhoneNum text);
INSERT INTO "PhoneBook" VALUES('Derick','010-1234-5678');
INSERT INTO "PhoneBook" VALUES('Merry','010-5678-0000');
INSERT INTO "PhoneBook" VALUES('SangJung','010-5670-2343');
INSERT INTO "PhoneBook" VALUES('SangJung','010-5670-2343');
INSERT INTO "PhoneBook" VALUES('apple','010-369-3639');
CREATE TABLE PhoneBook2(Name text, Age ineger);
INSERT INTO "PhoneBook2" VALUES('Tom',24);
INSERT INTO "PhoneBook2" VALUES('Derick',30);
INSERT INTO "PhoneBook2" VALUES('Peter',53);
INSERT INTO "PhoneBook2" VALUES('Jane',29);
COMMIT;
"""


 



python study, Get list item using __getitem__ function

list = (('Tom', 24), ('Derick',30), ('Peter',53), ('Jane',29))
print( list[0] )
print( list[0].__getitem__(0))
print( list[1].__getitem__(1))
#('Tom', 24)
#Tom
#30


3/07/2014

Python Study, os.path functions

__author__ = 'mare'


from os.path import *


print( abspath('tmp') )
#/Users/mare/PycharmProjects/OS_system/tmp

print( basename('C:/Python32/tmp') )
print( basename('C:/Python32/tmp/test.txt') )
#tmp
#test.txt

print( commonprefix(['c:/python32/lib', 'c:/python32/Tools', 'c:/python32']))
#c:/python32
print( commonprefix(['c:/python26/lib', 'c:/python25/Tools']))
#c:/python2

print( dirname('C:/Python32/tmp'))
print( dirname('C:/Python32/tmp/test.txt'))
#C:/Python32
#C:/Python32/tmp

print( exists('/Users/mare/PycharmProjects/OS_system/'))
print( exists('/Users/mare/'))
print( exists('/Users/mare/AAAA/'))
#True
#True
#False

print( expanduser('~/test'))
#/Users/mare/test
print( expanduser('~someone/test'))
#~someone/test

print( expandvars('$HOME/temp'))
#/Users/mare/temp
print( expandvars('$SYSTEMROOT/var'))
#$SYSTEMROOT/var -> mac is not supported


print(getatime('/Users/mare'))
#1394212008.0 -> latest time to access the path

print(getmtime('/Users/mare'))
#1389968107.0 -> latest time to modify the path

print(getctime('/Users/mare'))
#1389968107.0 -> latest time to create the folder

print( isabs('/Users/mare') ) #absolute path is true another is false
#True
print( isabs('../mare') )
#False

print( isfile('/Users/mare/PycharmProjects/OS_system/main.fy'))
print( isfile('/Users/mare/PycharmProjects/OS_system/main.py'))
#False
#True

print( isdir('/Users/mare/PycharmProjects/OS_system/main.py') )
print( isdir('/Users/mare/PycharmProjects/OS_system/'))
#False
#True


print( join('/python32', 'Script', 'test.py'))
#/python32/Script/test.py

print( split('/python32/Script/test.py'))
#('/python32/Script', 'test.py')

print( splitext('/python32/Script/test.py') )
#('/python32/Script/test', '.py')


import glob

print( glob.glob('*'))
#['main.py']









3/06/2014

(C, C++) int to char *, char * to int, _itoa_s and atoi functions

char *s="100";
int a = atoi(s);
printf("%d\n", a);

char s2[30];
a=211;
_itoa_s(a, s2, 10); //in here, 10 is Decimal, 2 is Binary.
printf("%s\n", s2);

(C, C++) converting char * to float , strtod and atof functions

#include < stdlib.h>
#include < stdio.h>

void main()
{
  char *floatText = "34.12";
  double Afloat = strtod(floatText ,NULL);
  float Bfloat = atof(floatText );
  printf("%f, %f",Afloat ,Bfloat );

}



/* Output */
34.120000, 34.120000

(C, C++) char * compare, strcmp function


#include < stdio.h>
#include < string.h>

int main ()
{
  char szKey[] = "apple";
  if( strcmp (szKey,"apple") == 0)
       printf("same\n");
  else
       printf("different\n");

  
  return 0;
}


(c, c++) 'char * to string' and 'string to char *'

//string to char*

string str = "hello";
char cstr[10];
strcpy(cstr,str.c_str());
 
// char * to string

char cstr[] = "hello";
string str = cstr; //string(cstr)

3/05/2014

(C, C++) TinyXML , xml read & write

Firstly, download TinyXML source code on here -> http://sourceforge.net/projects/tinyxml/

After unzip, you can see many files and folders like that.

But, we only need 6 files.  
Copy these files to appropriate folder.

Make your project and add 6 files in your project.


This is example of xml file. Save file name to "ex4.xml"

---
< ? xml version="1.0" ?>
< LibraryIndex>
    < !-- Settings for MyApp -->
    < Messages>
        < Welcome>Welcome to MyApp< /Welcome>
        < Farewell>Thank you for using MyApp< /Farewell>
    < /Messages>
    < Windows>
        < Window name="MainFrame" x="5" y="15" w="400" h="250" />
    < /Windows>
    < Connection ip="192.168.0.1" timeout="123.456000" />
< /LibraryIndex>

----

Make code like this and run.
In my case, 6 TinyXML files are located "./tinyXML/"

---
#include < stdio.h>
#include "./tinyXML/tinyxml.h"


void main()
{
 TiXmlDocument doc;
 bool loadOkay = doc.LoadFile("ex4.xml");

 if (loadOkay)
 {
  printf("open success\n");
 }
 else
 {
  printf("Failed to load file \n");
 } 
}
---

If you see the "open success" massage, xml file is opened nomally.


-----------------------------
XML read & parsing example source code.
---
#include < stdio.h>
#include "./tinyXML/tinyxml.h"


void main()
{
 TiXmlDocument doc;
 bool loadOkay = doc.LoadFile("ex4.xml");

 if (loadOkay)
 {
  printf("open success\n");
 }
 else
 {
  printf("Failed to load file \n");
 } 


 //root node access
 TiXmlElement* pRoot = doc.FirstChildElement("LibraryIndex"); 
 if (!pRoot) return;

 //access "welcom" element to get value
 TiXmlElement* pElem = pRoot->FirstChildElement("Messages")->FirstChildElement("Welcome");
 if (!pElem) return;

 //get element value (Welcome).
 char* pszNode = (char*)pElem->Value();
 if (pszNode)
  printf("Node: %s\n", pszNode);

 //get element text(Welcome to MyApp)
 char* pszText = (char*)pElem->GetText();
 if (pszText)
  printf("Text: %s\n", pszText);


}

---
The result is like that.

--------------------------
modify example.
***
#include < stdio.h>
#include "./tinyXML/tinyxml.h"


void main()
{
 TiXmlDocument doc;
 bool loadOkay = doc.LoadFile("ex4.xml");

 if (loadOkay)
 {
  printf("open success\n");
 }
 else
 {
  printf("Failed to load file \n");
 } 

 // access root node
 TiXmlElement* pRoot = doc.FirstChildElement("LibraryIndex");   
 if (!pRoot) return;  

 // access welcome element to modify value  
 TiXmlElement* pElem = pRoot->FirstChildElement("Messages")->FirstChildElement("Welcome");  
 if (!pElem) return;

 // element clear and new value adding 
 pElem->Clear();
 pElem->LinkEndChild( new TiXmlText("Edit My App"));

 doc.SaveFile("m_ex4.xml");
}
***
The result is like the figure.


-------------
Example source code to make New xml file.
In the source code, new and delete pair is do not need because created variable by new keyword will be delete automatically after block.
***
#include < stdio.h>
#include "./tinyXML/tinyxml.h"


void main()
{
 
 // Declaration XML format
 TiXmlDocument doc;
 TiXmlDeclaration* pDecl = new TiXmlDeclaration("1.0", "euc-kr", "");  
 doc.LinkEndChild(pDecl);

 //Add Root node
 TiXmlElement* pRoot = new TiXmlElement("LibraryIndex2");
 doc.LinkEndChild(pRoot);

 // Add Comment sentence
 TiXmlComment * pComment = new TiXmlComment();
 pComment->SetValue("Settings for MyApp");
 pRoot->LinkEndChild(pComment);

 // Add child node and data
 TiXmlElement* pElem = new TiXmlElement("Messages");
 pRoot->LinkEndChild(pElem);

 TiXmlElement* pSubElem = new TiXmlElement("Welcome");
 pSubElem->LinkEndChild( new TiXmlText("Welcome to MyApp"));
 pElem->LinkEndChild(pSubElem);

 pSubElem = new TiXmlElement("Farewell");
 pSubElem->LinkEndChild( new TiXmlText("Thank you for using MyApp"));
 pElem->LinkEndChild(pSubElem);

 // Add child node and set attribute 
 pElem = new TiXmlElement("Windows");
 pRoot->LinkEndChild(pElem);

 pSubElem = new TiXmlElement("Window");
 pElem->LinkEndChild(pSubElem);
 pSubElem->SetAttribute("name", "MainFrame");
 pSubElem->SetAttribute("x", 5);
 pSubElem->SetAttribute("y", 15);
 pSubElem->SetAttribute("w", 400);
 pSubElem->SetAttribute("h", 250);

 pElem = new TiXmlElement("Connection");
 pRoot->LinkEndChild(pElem);
 pElem->SetAttribute("ip", "192.168.0.1");
 pElem->SetDoubleAttribute("timeout", 123.456);

 //Save xml file format
 doc.SaveFile("new_ex4.xml");

}
***
The result is like the figure.

-------
Finally, This source code is searching all node and text by using recursive routine.

#include < stdio.h>
#include "./tinyXML/tinyxml.h"

void searchXMLData(TiXmlElement* pElem)
{
 TiXmlHandle hRoot(0);
 TiXmlElement* pSubElem = pElem;
 TiXmlAttribute* pAttrib = NULL;

 
 //Set current node to root node and determine childe node is exist or not
 hRoot = TiXmlHandle(pSubElem);
 pSubElem = hRoot.FirstChildElement().Element();
 if (!pSubElem) return;

 char* pszNode = NULL;
 char* pszAttrib = NULL;
 char* pszText = NULL;

 while (pSubElem)
 {
  //node
  pszNode = (char*)pSubElem->Value();
  if (pszNode)
   printf("Node: %s\n", pszNode);

  //Attribute
  pAttrib = pSubElem->FirstAttribute();
  while (pAttrib)
  {
   char* pszAttrib = (char*)pAttrib->Name();
   char* pszText = (char*)pAttrib->Value();

   printf("------------Attribute: %s, Data: %s\n", pszAttrib, pszText);

   pAttrib = pAttrib->Next();
  }
  
  //Data
  pszText = (char*)pSubElem->GetText();
  if (pszText)
   printf("Text: %s\n", pszText);

  // Recursive call for searching child node based current node
  searchXMLData(pSubElem);
  pSubElem = pSubElem->NextSiblingElement();
 }
}

int main()
{
 TiXmlDocument doc;
 doc.LoadFile("ex4.xml");
 TiXmlHandle hDoc(&doc);

 //access root node
 TiXmlElement* pRoot = hDoc.FirstChildElement().Element();
 if (!pRoot) return 0;

 
 //search childe node step by step from starting root node
 searchXMLData(pRoot);
 
 return 0;
}

The result is like the figure.


Thank you.
Good luck!.

3/04/2014

(OpenCV Study) xml write & read, example source code.

This is very simple example source code for write and read xml file.
OpenCV version will be no matter.
I hope helpful to you.
Thank you.



//Write example
FileStorage xmlW("A.xml", FileStorage::WRITE);
Mat A(3,3, CV_32F);
setIdentity(A);
xmlW << "A" << A;
xmlW.release();

//read example
FileStorage xmlR;
xmlR.open("A.xml", FileStorage::READ);
Mat B;
xmlR["A"] >> B;
cout << B << endl;
xmlR.release();

3/03/2014

python study, math modules, example source code

__author__ = 'mare'


l = list( range(0, 10) )
print( sum(l) )
print( sum(l, 100) )
print( max(l) )
print( min(l) )
print( abs(-11) )
#45
#145
#9
#0
#11

print( "-----" )
print( pow(2, 10) ) #2^10
print( pow(2, 10, 100) )  #(2^10)%10
print( divmod(10, 7) )
print( divmod(5.3, 2.1) )
#1024
#24
#(1, 3)
#(2.0, 1.0999999999999996)

print( round(152.394) )
print( round(152.394, 1) )
print( round(152.394, -1) )
#152
#152.4
#150.0

import math
print( math.ceil(3.14 ) )
print( math.floor(3.14) )
print( math.trunc(3.14) )
#4
#3
#3

print("---")
print( math.copysign(6.5, -0.0) )
print( math.fabs(-6.5) )
print( math.factorial(3.0) )
print( math.modf(-6.5) )
l = [3.14, 1.24, 5.23]
print( math.fsum(l) )
#-6.5
#6.5
#6
#(-0.5, -6.0)
#9.610000000000001


print("---")
print( math.fmod(5.5, 3) )
print( 5.5%3 )
print( math.fmod(-5.5, 3) )
print( -5.5 % 3 )
#2.5
#2.5
#-2.5
#0.5

print( math.pow(2, 10) )
print( math.pow(1.5, 3) )
print( math.sqrt(2) ) #sqrt(2)
print( math.exp(2) ) #e^2
print( math.log(math.e) ) #ln(e)
#1024.0
#3.375
#1.4142135623730951
#7.38905609893065
#1.0

print("---")
r = math.radians(30)
print(math.sin(r))
r = math.radians(180)
v = math.cos(r)
print( v )
print( r == math.acos(v) )
print( math.degrees(r) )
#0.49999999999999994
#-1.0
#True
#180.0


print("---")
#fractions
import fractions
print( fractions.Fraction(4,16) )
print( fractions.Fraction(-6, 21) )
print( fractions.Fraction(3) )
#1/4
#-2/7
#3

f = fractions.Fraction(4,3)
print(f)
#4/3
f2 = fractions.Fraction(f)
print(f2)
#4/3

print("---")
#special functions
print( fractions.Fraction('6/21') )
print( fractions.Fraction('3.14') )
print( fractions.Fraction('     -0.34     '))
s = """
-0.34
"""
print( fractions.Fraction(s) )
#2/7
#157/50
#-17/50
#-17/50

print("---")
from fractions import Fraction
print( Fraction.from_float(0.5) )
print( Fraction.from_decimal(4) )
#1/2
#4

print("---")
from math import pi, cos
from fractions import Fraction
print( Fraction.from_float(pi) )
#884279719003555/281474976710656
print( Fraction.from_float( pi ).limit_denominator(100) )
#311/99

f = Fraction.from_float(3.14)
print( f.__floor__() )
#3

import math
print( math.floor(f) )
print( math.ceil(f) )
print( round(f) )
#3
#3
#4
#3


import fractions
fractions.gcd(120, 180)
fractions.gcd(0.5, 6)
#60, 0.5

print("---")

#decimal
import decimal
print( decimal.Decimal(3) )
print( decimal.Decimal('1.1') )
print( decimal.Decimal(str(1/7)) )
#decimal.Deciaml( (0,(3,1,4),-2) )
print( decimal.Decimal("-Infinity") )
print( decimal.Decimal('-0') )
print( decimal.Decimal('NaN') )
#3
#1.1
#0.14285714285714285
#-Infinity
#-0
#NaN


a, b = decimal.Decimal('3.14'), decimal.Decimal('0.4')
print( a+b )
print( a-b )
print( a*b )
print( a/b )
print( a**b )
#3.54
#2.74
#1.256
#7.85
#1.580417606406722895935118558

a = decimal.Decimal('3.14')
print( a*3 )
print( divmod(a, 2) )
print( round(a, 1) )
print( int(a) )
#9.42
#(Decimal('1'), Decimal('1.14'))
#3.1
#3

print("---")
rawData = '3.14|5.3|1.65|9|-1.28'
l = [decimal.Decimal(x) for x in rawData.split('|') ]
print(l)
#[Decimal('3.14'), Decimal('5.3'), Decimal('1.65'), Decimal('9'), Decimal('-1.28')]
print( max(l) )
print( min(l) )
print( sum(l) )
print( sorted(l) )
#9
#-1.28
#17.81
#[Decimal('-1.28'), Decimal('1.65'), Decimal('3.14'), Decimal('5.3'), Decimal('9')]



from decimal import Decimal
d = Decimal("3.14")
print( d.sqrt() )
#1.772004514666935040199112510
print( d.exp() )
print( d.ln() )
#23.10386685872218278457908458
#1.144222799920161998805694448

d2 = Decimal("-1.414")
print( d.compare(d2) )
print( d.copy_abs() )
print( d.copy_negate() )
print( d.copy_sign(d2) )
#1
#3.14
#-3.14
#-3.14

print( d2.is_signed() )
print( d.is_finite() )
print( d.is_infinite() )
print( d.is_zero() )
#True
#True
#False
#False


#random
import random
print( random.random() )
print( random.random() )
#0.7774163660360384
#0.7987333021579469

print( random.uniform(3, 4) )
#3.013465537004017

for i in range(3):
 print( random.gauss(1, 1.0) )
#0.07892791910471075
#0.49322741367164435
#0.6201914100688197


print( [random.randrange(20) for i in range(10) ])
#[0, 15, 11, 5, 17, 15, 0, 0, 11, 4]

print( random.sample( range(20), 10 ))
#[16, 4, 8, 0, 15, 10, 2, 19, 7, 13]

print( [random.randrange(0,20,3) for i in range(5) ] )
#[18, 18, 18, 12, 12]


print("---")
l = list(range(10))
print(l)
print( [random.choice(l) for i in range(3) ])
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#[1, 0, 6]

print( random.sample(l,3))
#[5, 4, 8]


l = list( range(10) )
print( l )
random.shuffle(l)
print( l )
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#[2, 4, 1, 7, 3, 0, 8, 9, 5, 6]


l = list( range(10) )
s = random.sample(l, 10)
print( l, s)
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [9, 5, 6, 8, 7, 1, 3, 4, 0, 2]


Python study, time module, example source code

import time

print( time.time() ) #the timestamp after 1970.1.1
#1393854889.330645
print( time.gmtime() ) #UTC
#time.struct_time(tm_year=2014, tm_mon=3, tm_mday=3, tm_hour=13, tm_min=54, tm_sec=49, tm_wday=0, tm_yday=62, tm_isdst=0)
print( time.localtime() ) #current time based on system
#time.struct_time(tm_year=2014, tm_mon=3, tm_mday=3, tm_hour=22, tm_min=54, tm_sec=49, tm_wday=0, tm_yday=62, tm_isdst=0)
t = time.gmtime(1234567890)
print( t )
#time.struct_time(tm_year=2009, tm_mon=2, tm_mday=13, tm_hour=23, tm_min=31, tm_sec=30, tm_wday=4, tm_yday=44, tm_isdst=0)

print( t.tm_mon )
print( t.tm_hour )
#2
#23

print( time.asctime(t) )
print( time.mktime(t) )
#Fri Feb 13 23:31:30 2009
#1234535490.0


#sleep
t = time.time()
time.sleep(1) #10 second sleep
t2 = time.time()

spendtime = t2 - t
print( "before timestamp: ", t)
print( "after timestamp: ", t2)
print( "wait {0} second".format(spendtime))
#before timestamp:  1393855412.738972
#after timestamp:  1393855413.740086
#wait 1.0011141300201416 second

from time import localtime, strftime
print( strftime( "%B %dth %A %I:%M", localtime() ) )
print( strftime( "%Y-%m-%d %I:%M", localtime() ) )
print( strftime( "%y/%m/%d %H:%M:%S", localtime() ) )
print( strftime("%y/%m/%d %H:%M:%S", localtime() ) )
print( strftime("%x %X", localtime()) )

#March 03th Monday 11:03
#2014-03-03 11:03
#14/03/03 23:03:33
#14/03/03 23:03:33
#03/03/14 23:03:33

import datetime
print( datetime.date(2009, 5, 5) )
#2009-05-05
print( datetime.date.fromtimestamp( time.time() ) )
#2014-03-03
print( datetime.date.today() )
#2014-03-03


d = datetime.date.today()
print( d.year )
print( d.month )
print( d.day )
print( d.max )
print( d.min )
#2014
#3
#3
#9999-12-31
#0001-01-01

d = datetime.date.today()
d2 = d.replace(day=25)
print(d, d2)
#2014-03-03 2014-03-25

d.timetuple()
print( d.toordinal() )
print( d.weekday() )
#735295
#0 -> It means monday.

d = datetime.date.today()
print( d.isoformat() )
print( d.ctime() )
#2014-03-03
#Mon Mar  3 00:00:00 2014

from datetime import time
print( time(7) )
#07:00:00
print( time(8, 14, 20, 3000 ) )
#08:14:20.003000

print( time(hour=3, second=3) )
#03:00:03

print("-----")

from datetime import datetime, date, time
print( datetime.now() )
print( datetime.today() )
print( datetime.utcnow() )
print( datetime.fromtimestamp(1234567890))
print( datetime.utcfromtimestamp(1234567890))
print( datetime.fromordinal(732421))
d = date(2009, 3, 10)
t = time(12, 23, 53)
print( datetime.combine(d, t) )
#014-03-03 23:22:08.580259
#2014-03-03 23:22:08.580277
#2014-03-03 14:22:08.580292
#2009-02-14 08:31:30
#2009-02-13 23:31:30
#2006-04-20 00:00:00
#2009-03-10 12:23:53

print("----")

from datetime import datetime
dt = datetime.now()
print( dt.date() )
print( dt.time() )
print( dt.replace(hour=20, second=30 ) )
print( dt.timetuple() )
#2014-03-03
#23:25:15.304432
#2014-03-03 20:25:30.304432
#time.struct_time(tm_year=2014, tm_mon=3, tm_mday=3, tm_hour=23, tm_min=25, tm_sec=15, tm_wday=0, tm_yday=62, tm_isdst=-1)


print("----")
dt = datetime.now()
print( dt.weekday() )
print( dt.isoweekday() )
#0
#1

print(dt.isoweekday())
print(dt.ctime())
print( str(dt) )
#1
#Mon Mar  3 23:27:26 2014
#2014-03-03 23:27:26.117400

print(" timedelta class ");
from datetime import timedelta
print( timedelta(days=-3 ) )
print( timedelta( hours=7) )
#-3 days, 0:00:00
#7:00:00

print( timedelta(weeks=2, days=3, hours=-3, minutes=30) )
print( timedelta(minutes=3, milliseconds=-20, microseconds=400))
#16 days, 21:30:00
#0:02:59.980400

print("---")

from datetime import timedelta

td_1 = timedelta(hours = 7 )
td_2 = timedelta(days=-3)
print( td_1 + td_2 )
#-3 days, 7:00:00

print( td_1-td_2, td_1+td_2, td_1*4, td_1//3, abs(td_2))
#3 days, 7:00:00 -3 days, 7:00:00 1 day, 4:00:00 2:20:00 3 days, 0:00:00

td_1 = timedelta(hours = 7 )
td_2 = timedelta(days=-3)
print( td_1 > td_2 )
print( td_1 < td_2 )
#True
#False

td_1 = timedelta(hours=24)
td_2 = timedelta(seconds=86400)
print( td_1 == td_2 )
#True