## 1/23/2014

### (python study) about function (example source code)

```__author__ = 'mare'

def Times(a, b):
return a*b

print(Times)
#

print( Times(10, 10) )
#100

myTimes = Times;
r = myTimes(10, 10);
print( r )
#100

#return

def setValue(newValue):
x = newValue

retval = setValue(10)
print( retval )
#None

def swap(x, y):
return y, x
swap(1,2)
#(2,1)

a, b = swap(1,2)
#a = 2, b = 1

x = swap(1,2)
print( type(x) )
#

#more complex function
def intersect(prelist, postlist):
retlist = []
for x in prelist:
if x in postlist and x not in retlist:
retlist.append(x)
return retlist

list1 = "SPAM"
list2 = "AM"

list3 = intersect(list1, list2)

print(list3)
#['A', 'M']

#parameters
a=10
b=20

def sum1(x,y):
return x+y

print( sum1(a,b) )
#30

x = 10
def sum2(x,y):
x = 1
return x+y

print( sum2(x, b), x )
#21 10

def change(x):
x[0] = 'H'

wordlist = ['J', 'A', 'M' ]
change(wordlist)
print(wordlist)
#['H', 'A', 'M']

def change(x):
x = x[:]
x[0] = 'H'
return None

wordlist[0] = 'J'

change(wordlist)
print(wordlist)
#['J', 'A', 'M']

#scoping rule
x=1
def func2(a):
x=2
return a+x
print( func2(10) )
#12

def func3(a):
global x
x = 20
return x+a

print( func3(10 ), x)
#30 20

dir( __builtins__ )
#you can see inner function names

#arguments
def Times(a=10, b=20):
return a+b

print( Times() )
#30

print( Times(5) )
#25

#keyword arguments
def connectURI( server, port):
str = "http://" + server +  ":" + port
return str

print( connectURI("test.com", "800" ))
print( connectURI(port="8080", server="test.com"))
#http://test.com:800
#http://test.com:8080

#variable argument
def test(*args):
print( type(args) )

test(1,2)
#

def union2(*ar):
res = []
for item in ar:
for x in item:
if not x in res:
res.append(x)
return res

print( union2( "HAM", "EGG", "SPAM" ) )
print( union2("GIR", "Generation", "gee") )
#['H', 'A', 'M', 'E', 'G', 'S', 'P']
#['G', 'I', 'R', 'e', 'n', 'r', 'a', 't', 'i', 'o', 'g']

def userURIBuilder(server, port, **user):
str = "Http://" + server + ":" + port + "/?"
for key in user.keys():
str += key + "=" + user[key] + "&"
return str

s = userURIBuilder("Test.com", "8080", id='userid', passwd='1234')
print(s)
#Http://Test.com:8080/?id=userid&passwd=1234&

#lambda function

g = lambda x, y : x*y
g(2,3)
#6

(lambda x: x*x)(3)
#9

#recursive function call
def factorial(x):
if x == 1:
return 1
return x*factorial(x-1)

factorial(10)
#3628800

#pass
#while True:
# pass #control + c if you stop

class temp:
pass

#help
def factorial(x):
"return factorial of n, ...."
if x == 1:
return 1
return x*factorial(x-1)

#help( factorial)
#return factorial of n, ....

#iterator
"""
for element in [1, 2, 3]:
for element in (1, 2, 3):
for key in {'one':1, 'two':2}:
for char in "123":
for line in open("myfile.txt") read line by line in the file
"""

#generator
def reverse(data):
for index in range(len(data) -1, -1, -1):
yield data[index]

for char in reverse('golf'):
print( char)
#f
#l
#o
#g

#enumerate
for i, season in enumerate(['spring', 'summer', 'fall', 'winter']):
print(i, season)
#0 spring
#1 summer
#2 fall
#3 winter

#iter
s='abc'
it = iter(s)
print(next(it))
#a
print(next(it))
#b
print(next(it))
#c
#print(next(it)) -> error

```

## 1/22/2014

### (Python study) deep copy and shallow copy (example source code)

```#this is Shallow copy
a=[1, 2, 3]
b=a
a[0] = 38
print(a, b)
print(id(a), id(b))
#[38, 2, 3] [38, 2, 3]
#4320547040 4320547040

#this is deep copy
b = a[:]
print(id(a), id(b))
#4320427976 4320427472

a[0] = 50;
print(a, b)
#[50, 2, 3] [38, 2, 3]

import copy

a=[1,2,3]
b = copy.deepcopy(a)
a[0] = 38
print(a, b)
[38, 2, 3] [1, 2, 3]

```

### (Python study) boolean (example)

```>>> isRight = False
>>> type(isRight)
< type 'bool'>
>>> 1<2
True
>>> 1 != 2
True
>>> 1 == 2
False
>>> True and False
False
>>> True & True
True
>>> False | False
False
>>> not True
False
>>>
>>> bool(0)
False
>>> bool(-1)
True
>>> bool('test')
True
>>> bool(None)
False
>>>

```

### (python study) about dictionary variable (example source code)

```__author__ = 'mare'

d = dict(a=1, b=3, c=5)
#{'a': 1, 'c': 5, 'b': 3}
type(d)
#< type 'dict'>

color = {"apple":"red", "banana":"yellow"}
#{'apple': 'red', 'banana': 'yellow'}

print( color["apple"] )
#red

#color[0] is not support, error

#color += {"cherry":"red"} -> error
color["cherry"] = "red"
#{'cherry': 'red', 'apple': 'red', 'banana': 'yellow'}
color["apple"] = "green"
#{'cherry': 'red', 'apple': 'green', 'banana': 'yellow'}

#items(), keys(), values()

for c in color.items():
print(c)
#('apple', 'green')
#('cherry', 'red')
#('banana', 'yellow')

print('--')

for k, v in color.items():
print(k, v)
#apple green
#cherry red
#banana yellow

print('--')

for k in color.keys():
print(k)
#apple
#cherry
#banana

print('--')

for v in color.values():
print(v)
#green
#red
#yellow

del color['cherry']
print(color)

color.clear()
#{'apple': 'green', 'banana': 'yellow'}

print(color)
#{}

#more complex
s = {'age':40.5, 'job':[1, 2, 3], 'name':{'kim':2, 'Cho':1}}
print(s)
#{'name': {'Cho': 1, 'kim': 2}, 'age': 40.5, 'job': [1, 2, 3]}

```

### (Python Study) list, set, tuple type casting

```#can change freely
a = set((1,2,3))
b = list(a)
c = tuple(b)
d = set(c)

>>> a
set([1, 2, 3])
>>> b
[1, 2, 3]
>>> d
set([1, 2, 3])
>>> c
(1, 2, 3)
>>>

```

### (python study) about tuple variable (example source code)

```#tuple is similar with list but notation is () and read only
#but access speed is faster than list

t = (1, 2, 3)
print( type(t) )
#< class 'tuple'>

a, b = 1, 2
(a, b) = (1, 2)
print(a, b)
#1 2

```

### (Python study) about set variable (example source code)

```a = {1, 2, 3}
print(a)

b = {3, 4, 5}

print( a.union(b) )
#{1, 2, 3, 4, 5}

print( a.intersection(b) )
#{3}

print( a-b )
print( a|b )
print( a&b )
#{1, 2}
#{1, 2, 3, 4, 5}
#{3}

```

### (Python Study) about list variable (example source code)

```##list
color = ['red', 'green', 'gold']
print(color)
#['red', 'green', 'gold']

color.append('blue')
print(color)
#['red', 'green', 'gold', 'blue']

color.insert(1, 'black')
print(color)
#['red', 'black', 'green', 'gold', 'blue']

color.extend(['white', 'gray'])
print(color)
#['red', 'black', 'green', 'gold', 'blue', 'white', 'gray']

color += ['red']
print(color)
#['red', 'black', 'green', 'gold', 'blue', 'white', 'gray', 'red']

print( color.index('red') )
print( color.index('red', 1 ) ) #1 is search start position
#0
#7

print( color.count('red') )
#2

color.pop()
color.pop()
color.pop(1)

print( color )
#['red', 'green', 'gold', 'blue', 'white']

color.remove('gold')
print( color )
#['red', 'green', 'blue', 'white']

color += 'red'
print( color )
#['red', 'green', 'blue', 'white', 'r', 'e', 'd']
color += ['red']
print( color )
#['red', 'green', 'blue', 'white', 'r', 'e', 'd', 'red']

color.remove('red')
print( color )
#['green', 'blue', 'white', 'r', 'e', 'd', 'red']

color.sort()
color.reverse()
print(color)
#['white', 'red', 'r', 'green', 'e', 'd', 'blue']

print( color[-1] )
#blue

def mysort(x):
return x[-1]

color.sort(key=mysort)
print(color)
#['red', 'd', 'white', 'e', 'blue', 'green', 'r']

```

### (Python Study) about variables (examples source code)

```
print( oct(38) ) #octal
print( hex(38) ) #hex
print( bin(38) ) #binary

#0o46
#0x26
#0b100110

print( type( oct(38) ) )
#

x= 3 - 4j
print( type(x) )
#

print( x.imag )
print( x.real )
print( x.conjugate() )
#-4.0
#3.0
#(3+4j)

x = 5/2
y = 5//2

print(x, y)
#2.5 2

##string##

print(""" aa
dd dd ff
dd dd s""")
# aa
#dd dd ff
#dd dd s

print(''' aa
dd dd ff
dd dd s''')
# aa
#dd dd ff
#dd dd s

print('py' 'thon')
#python
print("py" "thon")
#python
print('py' + 'thon')
#python

print('py'*3)
#pypypy

a="python"
print( a[0], a[5])
#p n

# a[5] = 'a' is error, cannot copy

print( a[0:1] )
print( a[1:4] )
print( a[:2] )
print( a[-2:] )
#p
#yth
#py
#on

print( a[:] )
print( a[::2] )
#python
#pto

##casting
print( str(3.14) )
print( int("49") )
print( float(23) )
#'3.14'
#49
#23.0

```

### (Arduino Study) the method to make library

Original source code is like that

---
```//sos_without_lib.pde
void dot();
void dash();

int pin = 13;

void setup()
{
pinMode(pin, OUTPUT);
}

void loop()
{
dot(); dot(); dot();
dash(); dash(); dash();
dot(); dot(); dot();
delay(3000);
}

void dot()
{
digitalWrite(pin, HIGH);
delay(250);
digitalWrite(pin, LOW);
delay(250);
}

void dash()
{
digitalWrite(pin, HIGH);
delay(1000);
digitalWrite(pin, LOW);
delay(250);
}

```
...

To make library, we have to do 4 steps process,

step 1, write .h , .cpp files,   it is same c++ class, and copy into libraries\morse folder.
step 2, make keywords.txt,  and copy into libraries\morse folder.
step 3, make SOS.pde and copy libraries\morse\Examples\SOS
step 4, programing using the library

.h, .cpp

...
```.h ->
#ifdef Morse_H
#define Morse_H

#include "WProgram.h"

class Morse{
public:
Morse(int pin);
void dot();
void dash();
private:
int _pin;

#endif

.cpp ->
#include "WProgram.h"
#include "morse.h"

Morse::Morse(int pin)
{
pinMode(pin, OUTPUT);
_pin = pin)
}

void Morse::dot()
{
digitalWrite(pin, HIGH);
delay(250);
digitalWrite(pin, LOW);
delay(250);
}

void Morse::dash()
{
digitalWrite(pin, HIGH);
delay(1000);
digitalWrite(pin, LOW);
delay(250);
}
```
---

...
```//SOS.pde
#include < Morse.h>

Morse morse(13);
void setup(){}

void loop(){
morse.dot();morse.dot();morse.dot();
morse.dash();morse.dash();morse.dash();
morse.dot();morse.dot();morse.dot();
delay(3000);
}

```
---

so the directory is like that

\arduino-0022\libraries\Morse\keyword.txt,  Morse.cpp, Morse.h
\arduino-0022\libraries\Morse\Examples\SOS\SOS.pde

## 1/21/2014

### (OpenCV Study) Color Mat convert to gray Mat, cvtColor function example

```cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);

and

cv::cvtColor(greyMat, colorMat, CV_GRAY2BGR);

```

### (python study) for a loop (example source)

```
print('-- for example')

l = ['Apple', 100, 15.23]
for i in l:
print(i, type(i))

print('-- dictionary')

d = {"Apple":100, "Orange":200, "Banana":300}
for k, v in d.items(): #print dictionary
print(k, v)

print('-- iterator')

l = [10, 20, 30]
iterator = iter(l)
for i in iterator:
print(i)

print('-- 9*9 ')

for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
print("-- {0} step --".format(n))
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9]:
print("{0} * {1} = {2}".format(n, i, n*i))

print('-- break, continue and else example')

l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in l:
if i > 5:
break
print("Item:{0}".format(i))

for i in l:
if i % 2 == 0:
continue
print("Item: {0}".format(i))

for i in l:
if i > 5:
break
print("Item:{0}".format(i))
else:
print("Exit without break")
print("Always this is printed")

print("-- useful function")

list( range(10) )
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list( range(5,10) )
#[5, 6, 7, 8, 9]
list( range(10, 0, -1))
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
list( range(10, 20 , 2))
#[10, 12, 14, 16, 18]

for i in range(10, 20, 2):
print(i)

print("-- to get index and value concurrently")

l = ['Apple', 'orange', 'Banana']
for i in range(len(l)):
print("index:{0}, value:{1}".format(i, l[i]))

print("-- enumerate example")
l = ["Apple", 100, 15.5]
for i in enumerate(l):
print(i)

for i in enumerate(l, 300):
print(i)

#list comprehensions
l = [1, 2, 3, 4, 5]
print( [i ** 2 for i in l] )
#[1, 4, 9, 16, 25]

t = ("apple", "banana", "orange")
print( [len(i) for i in t] )
#[5, 6, 6]

d = {100:"apple", 200:"banana", 300:"orange"}
print( [v.upper() for v in d.values() ] )

print( [i ** 3 for i in range(5)] )
#[0, 1, 8, 27, 64]

print( [i for i in t if len(i) > 5 ] )
#['banana', 'orange']

l1 = [3, 4, 5]
l2 = [1.5, -0.5, 4]
print( [x*y for x in l1 for y in l2 ] )
#[4.5, -1.5, 12, 6.0, -2.0, 16, 7.5, -2.5, 20]

print("-- filter example")
l=[10, 25, 30]
IterL = filter(None, l)
for i in IterL:
print("Item: {0}".format(i))

def GetBiggerThan20(i):
return i > 20

print("---")

IterL = filter(GetBiggerThan20, l)
for i in IterL:
print("Item: {0}".format(i))

print("using lambda")
IterL = filter(lambda i: i>20, l)
for i in IterL:
print("Item: {0}".format(i) )

print("-- zip")

X = [10, 20, 30]
Y = ['A', 'B', 'C']
for i in zip(X, Y):
print("Item: {0}".format(i))

RetList = list(zip(X,Y))
[(10, 'A'), (20, 'B'), (30, 'C')]
#unzip
X2, Y2 = zip(*RetList)

X = [10, 20, 30]
Y = "ABC"
Z = (1.5, 2.5, 3.5)
RetList = list(zip(X, Y, Z))

print("another example for zip")

X = [10, 20, 30]
Y = "ABCD"
RetList = list(zip(X, Y))
#[(10, 'A'), (20, 'B'), (30, 'C')]

print("-- map function example")

L = [1, 2, 3]

return i+10

print("Item: {0}".format(i) )

RetList = list( map((lambda i: i+10), L))
print(RetList)

X = [1, 2, 3]
Y = [2, 3, 4]
RetList = list(map(pow, X, Y))
print(RetList)

print("--join function example")

l = ['Apple', 'Orange', 'Banana']
for i in l:
print(i)

#--> join form
print("\n".join(l))

print("-- processing time compare with noraml print and joint")

import time

l = range(1000)

t = time.mktime(time.localtime())
for i in l:
print(i, )
t1 = time.mktime(time.localtime()) - t

t = time.mktime(time.localtime())
print(",".join(str(i) for i in l))
t2 = time.mktime(time.localtime()) - t

print("for -> Take {0} seconds".format(t1))
print("join -> Take {0} seconds".format(t2))

#result is 0.0 second both.. -.-

```