2/24/2014

(python study) string functions

__author__ = 'mare'

#STRING functions

#capitalize()
print( "PYTHON".capitalize() )
#Python

print( "Python is powerful".capitalize() )
#Python is powerful


#count(keyword, [start, [end]])
print( "python is powerful".count('p') )
print( "python is powerful".count('p', 5) ) #[5:]
print( "python is powerful".count('p', 0, -1) ) #[0:-1]
#2
#1
#2


#encode([encoding, [errors]])
print( "κ°€λ‚˜λ‹€".encode('cp949') )
print( "κ°€λ‚˜λ‹€".encode('utf-8') )
#b'\xb0\xa1\xb3\xaa\xb4\xd9'
#b'\xea\xb0\x80\xeb\x82\x98\xeb\x8b\xa4'

#endswith(postfix, [start, [end]])
print( "python is powerful".endswith('ful'))
print( "python is powerful".endswith('ful', 5))
print( "python is powerful".endswith('ful', 5, -1))
#True
#True
#False

print( "python is powerful".endswith(('m', 'l')) )
#True


#expandtabs([tabsize])
print( "python\tis\tpowerful".expandtabs() )
print( "python\tis\tpowerful".expandtabs(1) )
#python  is      powerful
#python is powerful

#find(keyword, [start, [end]])
print( "python is powerful".find('p') )
print( "python is powerful".find('p', 5, -1) )
print( "python is powerful".find('pa') )
#0
#10
#-1


#index(keyword, [start, [end]])
print( "python is powerful".index('p') )
print( "python is powerful".index('p', 5, -1) )
#0
#10

#print( "python is powerful".index('pa') )
#Traceback (most recent call last):
#File "/Users/mare/PycharmProjects/str_handling/str_handle.py", line 58, in 
#print( "python is powerful".index('pa') )
#ValueError: substring not found


#isalnum()
print( "python".isalnum() )
print( "python3000".isalnum() )
print( "python3.2".isalnum() )
#True
#True
#False


#isalpha()
print( "python".isalpha() )
print( "python3000".isalpha() )
#True
#False



#islower()
print( "python".islower() )
print( "Python".islower() )
print( "python3.2".islower() )
#True
#False
#True


#isspace() space, tab, change line... is ture
print( " ".isspace() )
print( "\t\n".isspace() )
print( "\thi\n".isspace() )
#True
#True
#False


#istitle()
print( "python is powerful".istitle() )
print( "PYTHON IS POWERFUL".istitle() )
print( "Python Is Powerful".istitle() )
#False
#False
#True

#isupper()
print("python".isupper())
print("PYTHON".isupper())
print("PYTHON3.2".isupper())
#False
#True
#True


#isdecimal(), isdigit()
print( "2580".isdecimal() )
#True

#isnumeric()
print( '\u00bc'.isdecimal() )
print( '\u00bc'.isnumeric() )
#False
#True

print("id_1".isidentifier())
print("1_id".isidentifier())
#True
#False


#isprintable()
print("test".isprintable() )
print( '\u0014'.isprintable() )
#True
#False


#join(sequence)
print(".".join("HOT"))
print("\t".join(["python","is","powerful"]))
#H.O.T
#python is powerful

#lstrip([chars])
print( "\t python".lstrip())
print( ">>> python is powerful".lstrip("> "))
#python
#python is powerful


#maketrans(x, [y, [z]])
transmap = str.maketrans( {"p":"P"} )
print( "python is powerful".translate(transmap) )
#Python is Powerful

transmap = str.maketrans( "poieu", "P0129" )
print( "python is powerful".translate(transmap) )
#Pyth0n 1s P0w2rf9l

transmap = str.maketrans( "p", "P", "!" )
print( "python is powerful!!!".translate(transmap) )
#Python is Powerful


#partition(separator)
print( "python is powerful".partition("is") )
#('python ', 'is', ' powerful')

#replace(old, new, [count])
print( "python is powerful".replace("p", "P"))
print( "python is powerful".replace("p", "P", 1))
#Python is Powerful
#Python is powerful


#rfind(keyword, [start, [end]])
print( "python is powerful".rfind('p'))
print( "python is powerful".rfind('p', 0, 9))
print( "python is powerful".rfind('pa'))
#10
#0
#-1

#rindex(keyword, [start, [end]])
print( "python is powerful".rindex('p'))
#10

#rpartition(separator)
print( "python is powerful".rsplit())
print( "python is powerful".rsplit(' ',1))
#['python', 'is', 'powerful']
#['python is', 'powerful']


#rsplit([separator, [maxsplit]])
print( "python is powerful".rsplit() )
print( "python is powerful".rsplit(' ',1) )
#['python', 'is', 'powerful']
#['python is', 'powerful']


#rstrip([chars])
print( "python \t".rstrip() )
#python


#split([separator, [maxsplit]])
print("python is powerful".split() )
print("python is powerful".split(' ', 1))
#['python', 'is', 'powerful']
#['python', 'is powerful']


#splitlines([keep])
print( "python\r\nis\npowerful".splitlines() )
#['python', 'is', 'powerful']


#startswith(prefix, [start, [end]])
print( "python is powerful".startswith('py'))
print( "python is powerful".startswith('py', 5))
print( "python is powerful".startswith('py', 0, 5))
print( "python is powerful".startswith(('p', 'm')))
#False
#True
#True


#strip([chars])
print( "\t python \t".strip() )
print( ">>> python <<<".strip("<> ") )
#python
#python

#swapcase()
print("Python3.2".swapcase() )
#pYTHON3.2

#title()
print( "python is powerful".title() )
#Python Is Powerful

#upper()
print(" Python3.2".upper() )
#PYTHON3.2


2/11/2014

(python study) C Module for using in python using distutils (and Unable to find vcvarsall.bat problem)

The method to make C module for using in python using Visual Studio IDE is introduced on the http://feelmare.blogspot.kr/2014/02/python-study-c-module-for-using-in.html

In this page, I will introduce to make c module using distutils.
The method to use distutils is more simple than VS version.

Firstly, we have to make setup.py file like this.


...
# -*- coding:  cp949 -*-
# python
# install method : setup.py install
# setup.py -help

#from distutils.core import setup, Extension
from distutils.core import setup, Extension
spam_mod = Extension('spam', sources = ['spammodule.c'])
setup (name = "spam",
      version = "1.0",
      description = "A sample extension module",
      ext_modules = [spam_mod],
)
---


type "python setup.py install" on the command line.

Note, python.exe, setup.py, spammodule.c is placed in same folder.

After running, Our .pyd (lib) is made in the python\Lib\site-packages

Now, we can import spam 


!!!
If you meet "unable to find vcvarsall.bat" error, dont be worry, 't is not serious error.
I also meet this error and solve.

The problem is occurred python find vs 9.0 version even though my computer installed vs 11. 
so correct this miss-match.

firstly, try this method 


if you cannot solve error
try this method
open python/Lib/distutils/msvc9compiler.py
and modify code like figure.


I solved this error by second method.

good luck~!!

(python study) C Module for using in python , in Visual Studio

Firstly, I describe to make C module in Visual Studio.

open visual studio
make project -> win32 console application
check DLL, Empty project on setting page




make new .c file and set property 
select Include directories and Library directories on the VC++ Directories page.
In my case, My installed python is located 
Include -> C:\Python33_32\include
Library -> C:\Python33_32\libs  (Caution, not LIB folder)


Notice, my compile option is release, because I have only release version lib(python32.lib),
Python32_d.lib file is not support default. 
If you compile by debug version, you rebuild python source code to debug version by CMake.

programing this source code and compile~!

...
#include "Python.h"

#pragma comment(lib, "python33.lib")          

static PyObject *
 spam_strlen(PyObject *self, PyObject *args)
{
 const char * str = NULL;
 int len = 0; 

 if(!PyArg_ParseTuple(args, "s", &str))
  return NULL;

 //main source code
 len = strlen(str);

 return Py_BuildValue("i", len);
} 

static PyMethodDef SpamMethods[] = { 
 {"strlen", spam_strlen, METH_VARARGS, "count a string length."},
 {NULL, NULL, 0, NULL} //represent end of array
};

static struct PyModuleDef spammodule = {
 PyModuleDef_HEAD_INIT,
 "spam", //name of module
 "It is test module.", //description
 -1,
 SpamMethods
};

PyMODINIT_FUNC PyInit_spam(void)
{
 return PyModule_Create( &spammodule);
}
---

rename ~.dll to spam.pyd
If module name is not matched, cannot use module, error occurred when run in python.


copy spam.pyd into python\LIB folder



In the python, programing following source and run~!

...
import spam
print( spam.strlen( "Hello world") )
---


2/07/2014

(python Study) input/output and file handle (example source code)

__author__ = 'mare'


print(1)
print('hi, guyz')
a = 'hello\n'
print(a)
#1
#hi, guyz
#hello



x=0.2
print(x)
str(x)
print( str(x) )
a = repr('hello\n')
print(a)
#0.2
#0.2
#hello\n



print(x, 'test')
print(a + 'this is test')
#0.2 test
#'hello\n'this is test



import sys
print("welcome","to","python", sep="~", end="!")
#welcome~to~python!
#print("welcome","to","python", sep="~", end="!", file=sys.stderr)
#/Library/Frameworks/Python.framework/Versions/3.3/bin/python3 /Users/mare/PycharmProjects/input_output/example.py
#1
#welcome~to~python!


###########
#alienment
print('\n')
for x in range(1, 6):
 print(x, '*', x, '=', x*x)
#1 * 1 = 1
#2 * 2 = 4
#3 * 3 = 9
#4 * 4 = 16
#5 * 5 = 25

#using rjust for alienment
for x in range(1, 6):
 print(x, '*', x, '=', str(x*x).rjust(4))

#1 * 1 =    1
#2 * 2 =    4
#3 * 3 =    9
#4 * 4 =   16
#5 * 5 =   25

#zfill example
for x in range(1, 6):
 print(x, '*', x, '=', str(x*x).zfill(3))
#1 * 1 = 001
#2 * 2 = 004
#3 * 3 = 009
#4 * 4 = 016
#5 * 5 = 025

####
#formatting

print( "{0} is {1}".format("apple", "red"))
print("{0} is {1} or {2}".format("apple", "red", "green"))
#apple is red
#apple is red or green

print("{item} is {color}".format(item="apple", color="red"))
#apple is red

dic = {"item":"apple", "color":"red"}
print("{0[item]} is {0[color]}".format(dic))
#apple is red


#using local variables
item = "apple"
color = "red"

print("{0[item]} is {0[color]}".format(locals()))
#apple is red

print("{0:$=5}".format(10))
#$$$10
print("{0:$<5}".format(10))
print("{0:$>5}".format(10))
#10$$$
#$$$10
print("{0:q<5}".format(10))
print("{0:q>5}".format(10))
#10qqq
#qqq10
print("{0:#<5}".format(10))
print("{0:#>5}".format(10))
#10###
####10

print("{0:#^6}".format(10))
##10##

print("{0:x}".format(10))
print("{0:b}".format(10))
print("{0:o}".format(10))
print("{0:c}".format(65))
#a
#1010
#12
#A

print("{0:#x}, {0:#o}, {0:#b}".format(10))
#0xa, 0o12, 0b1010

print("{0:e}".format(4/3))
#1.333333e+00
print("{0:f}".format(4/3))
print("{0:%}".format(4/3))
#1.333333
#133.333333%

print("{0:.3f}".format(4/3))
#1.333

#input
#a = input('insert any key:')
#print(a)
#insert any key:sadfsaf
#sadfsaf


#file input/output
f= open('test.txt')
print(f.read())
f.close()
print( f.closed )


#binary mode and file copy

f = open('Horse2.mp3', 'wb')
f.write(open('Horse.mp3','rb').read())
f.close()




f = open('test.txt')
print( f.read() )
print( f.read() )
print( f.tell() ) #return position
print( f.seek(0) ) #move to position
print( f.read() ) #read again
f.seek(0)
print( f.readline() )
print( f.readline() )
print( f.readline() )
f.seek(0)

print( f.readlines() )

f.close()
"""
I am boy
Who are you
Hello~ world

I am boy

Who are you

Hello~ world

['I am boy\n', 'Who are you\n', 'Hello~ world\n']
"""


with open('test.txt') as f:
 print(f.readlines())
 print(f.closed) #not close

print(f.closed) #closed because if use with keyword, when escape with block file is colsed automatically

#['I am boy\n', 'Who are you\n', 'Hello~ world\n']
#False
#True

####
#pickle, save variables or class
colors = ['red', 'green', 'black']

import pickle
f = open('colors', 'wb')
pickle.dump( colors, f)
f.close()

del colors

f = open('colors', 'rb') #note! must read by binary
colors = pickle.load(f)
f.close()

print( colors )

#['red', 'green', 'black']


2/05/2014

(Mac Tip) How to make new txt file in Finder

On the window, we made new file easily by right button click.
But on the mac, there is no function. So, very incompatible...

By the way, we can do make new file easily on Mac by using this app

The usage is as follows..
After install,
run App.

Select Gestures and Keyboard menu, 
And click +Add New Shortcut
And click keyboard shortcut and make shortcut key combination

After, click trigger predefined action, and select system actions->create new file in current folder.


Setting is done.
New, make new file in folder by the shortcut key.


Good luck~!!






(python study) about exception (example source code)

exception running structure  is like that
see the example source code carefully referencing this structure.


...
__author__ = 'mare'


#exception test

def divide(a, b):
 return a/b

try:
 c = divide(5,0)

except:
 print("Exception is occured!!")

#-> Exception is occured!!


try:
 c = divide(5, 'string')
except ZeroDivisionError:
 print('donot input zero parameter')
except TypeError:
 print('all parameter should be number!')
except:
 print('I don know what error occur')

#->all parameter should be number!


try:
 c = divide(5, 2)
except ZeroDivisionError:
 print('do not input zero parameter')
except TypeError:
 print('all parameter should be only number')
except:
 print('ZeroDivisionError, exception TypeError')
else:
 print('Result: {0}'.format(c) )
finally:
 print('This sentence is always printed')

#Result: 2.5
#This sentence is always printed


try:
 c = divide(5, "af")
except TypeError as e:
 print('error: ', e.args[0] )
except Exception:
 print('I do not know what error occur')
#error:  unsupported operand type(s) for /: 'int' and 'str'




try:
 c = divide(5, 0)
except (ZeroDivisionError, OverflowError, FloatingPointError, FloatingPointError):
 print('this error is relative to arithmetic')
except TypeError:
 print('all parameter should be only number')
except Exception:
 print('I do not know what error occur')
#this error is relative to arithmetic



try:
 c = divide(5, 0)
except ArithmeticError:
 print('this error is relative to arithmetic')
except TypeError:
 print('all parameter should be only number')
except Exception:
 print('I do not know what error occur')
#this error is relative to arithmetic



#raise : uesr error message send
def RaiseErrorFunc():
 raise NameError


try:
 RaiseErrorFunc()
except:
 print("name error is catched")


#--------------user error exception

class NegativeDivisionError(Exception):
 def __init__(self, value):
  self.value = value


def PositiveDivide(a, b):
 if(b < 0):
  raise NegativeDivisionError(b)
 return a/b


try:
 ret = PositiveDivide(10, -3)
 print('10 / 3 = {0}'.format(ret))
except NegativeDivisionError as e:
 print('Error - second argument of positiveDivide is ', e.value)
except ZeroDivisionError as e:
 print('Error - ', e.args[0] )
except:
 print("Unexpected exception!")

#Error - second argument of positiveDivide is  -3


## assert function
def foo(x):
 assert type(x) == int, "input value must be integer"
 return x*10

ret = foo("a")
print( ret )

"""
Traceback (most recent call last):
  File "/Users/mare/PycharmProjects/γ„·γ…Œγ…Šλ°μƒ€γ…γ…œ/pypy.py", line 124, in < module >
    ret = foo("a")
  File "/Users/mare/PycharmProjects/γ„·γ…Œγ…Šλ°μƒ€γ…γ…œ/pypy.py", line 121, in foo
AssertionError: input value must be integer
"""
---

2/03/2014

(Python Study) about Module (example source code)

The reason to use module is like that
Concise code
namespace differently
fast execution of a function

The module in python is similar with #include in C

To make module, make .py file.


...
"""
import math
print( math.pow(2, 10) )
print( math.log(100) )
"""


#make user module
from functools import *
#bring functools module to use reduce function

def intersect(*ar):
 return reduce( __intersectSC, ar )

def __intersectSC( listX, listY):
 setList = []

 for x in listX:
  if x in listY:
   setList.append(x)
 return setList

def difference(*ar):
 setList = []
 intersectSet = intersect(*ar)
 unionSet = union(*ar)

 for x in unionSet:
  if not x in intersectSet:
   setList.append(x)
 return setList

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

#save *.py and copy to python32\lib directory
#and bring this source code using import command
---

and copy this file to lib folder.
In my case lib is located in "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3"
Additionally, my computer is mac.


And import this file. 

...
import simpleset

print( dir(simpleset) )

setA = [1, 3, 7, 10]
setB = [2, 3, 4, 9]

print( simpleset.union(setA, setB) )
print( simpleset.intersect(setA, setB, [1, 2, 3] ))
#[1, 3, 7, 10, 2, 4, 9]
#[3]

---



(Window 2008) disable port 80 on the window 2008 os

I have to close the programs using port 80 to setup APM(Apache, PHP, Mysql)
But I cannot find which program use port 80 on the window 2008 environment.

After a long time later, I figured out the solution.
The method is like that

Control Panel> Administrative Tools> Services to find information about the following 'stop'
Properties in 'Manual' to change.

World Wide Web Publishing Service
SQL Server Integration Services 10.0
SQL Server Reporting Services (MSSQL SERVER)



If not this should not conflict with port 80, the user of MS SQL

1. Start> Programs> Microsoft SQL Server 2008> Configuration Tools> Reporting Services Configuration Manager, run
2. Server Connection
3. In the left menu 'Web service URL', the right to use port 80. -> Change to a different port


good luck~!!