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~!!