12/30/2010

set image path in django template

add the below to urls.py


site_media = os.path.join( os.path.dirname(__file__), 'site_media' )


in urlpatterns, add this


(r'^site_media/(?P.*)$', 'django.views.static.serve', { 'document_root': site_media } ),


All images or something should be in site_media folder.

In a template file, insert a tag like



12/22/2010

enabling 한글 address in http django..

When 한글 address are given to django, ascii error occurs .

Solution :


$ cat /usr/local/lib/python2.6/site-packages/sitecustomize.py
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
ref1: http://bbs.python.or.kr/viewtopic.php?p=64687&highlight=&sid=cee81191b135b182f8f28a25b37d42f7
ref2: http://blog.codeguruz.com/tag/python

Then,
$ vi /usr/lib/pymodules/python2.6/django/http/__init__.py
goto line 309 (or something..)
def _convert_to_ascii(self, *values):
"""Converts all values to ascii strings."""
for value in values:
if isinstance(value, unicode):
try:
#value = value.encode('us-ascii') ## remove this line
value = value.encode('utf-8') ## add this
except UnicodeError, e:
e.reason += ', HTTP response headers must be in US-ASCII format'
raise
else:
value = str(value)
if '\n' in value or '\r' in value:
raise BadHeaderError("Header values can't contain newlines (got %r)" % (value))
yield value

12/09/2010

데드리프트 그립과 악력

출처 : http://speedandpower.co.kr/07/list.asp?mode=view&toron_gubun=y&board_id=3003&board_idx=2389&blog_id=


ergy님의 답변:

데드리프트는 가벼운 중량으로 운동하는 쌩초보단계에서 부터 오버핸드그립으로만 연습해야 하고,

중량이 엄청 무거워져서 더이상 오버그립이 힘들어지는 단계에서도

웜업세트는 오버그립으로하고 고중량의 본세트도 할 수 있는 최대한 오버그립으로 버티다가

도저히 안되는 마지막세트 마지막 1~2회만을 훅그립이나 스트랩 사용 또는 믹스그립으로 해주어야

중량증가에 상응하는 악력을 동시에 기를 수 있습니다.


데드리프트에 필요한 악력을 키우는 운동으로는 고중량 케틀벨을 들고 하는 Farmer's Walk를

1주일에 1회 하면 좋습니다. 더 이상을 하면 악력운동도 오버트레이닝으로 오히려 약해집니다.


그리고 데드리프트할 때, 한번 들어올렸다가 완전히 내려놓고서,

1회 호흡(불가피한 경우에는 2~3호흡도 가능)을 하는 동안 등판도 쉬고 손아귀도 쉬어준 다음

시작자세를 다시 제대로 갖추고나서 들어올렸다가 완전히 내려놓고 1회 호흡 하는 동안 쉬어주기를 반복하는 게 정식입니다.

이 런식으로 하게되면, 악력이 딸려서 들지 못하는 경우는 별로 생기지 않습니다.

운동후 허리통증에 시달리거나 척추디스크손상, 지나친 복압상승으로 인한 두통 등의 부작용도 겪지 않게 됩니다.


무게 욕심에 완전히 내려놓지 않고 바닥에 살짝 되튀겨서 다시 들어올리기를 반복하는 경우가 아주 많은데

이런식으로 하는 것은 데드리프트가 아닌 극히 위험한 묘기대행진이라는 것을 명심하고 절대 따라하면 안됩니다.

데드리프트는 죽은 듯이 완전히 바닥에 놓여있는(dead) 중량을 들어올리는(lift) 운동입니다. 튀겨올리는 게 절대 아닙니다.


반면에 스쿼트나 벤치프레스처럼, 위에서 내렸다가 다시 올라가는 운동은 되튀김(stretch reflex)가 허용됩니다.

하지만 보다 빡세고 강한 자극을 위해 바닥에서 1~2초 완전히 멈추었다가 올라가는 훈련을 하기도 합니다.

-----------------------------------------------



저도 막 질문하려던 참이었는데..
얼터네이트그립과 일반그립 차이가 많이 납니다.
얼터네이트그립 위험할수있다는 얘기가 있어서 훅그립 해보려하는데
제 생각엔 훅그립에서 엄지에 꽤 무리가 올것같은데, 손가락스트레칭이라도 해야하는건 아닌지, 안전한건지, 여쭤보고싶습니다.

그리고 훅그립이라도 어느정도 고중량되면 한계가 올것같은데 ,
보통 고중량들때어느정도 까지 스트랩없이 맨손으로 하시는지도 궁금하네요.
-------------------------------------------------------------------------------------------------------------------

훅 그립은 1회용이라고 보면 됩니다. 1회용 종이컵처럼 서너번 이상 쓰기 힘듭니다. 원래 역도에서 쓰이는 그립방법이니까요.

역 도훈련에서도 고반복 부분훈련으로 엄지에 무리를 줄 수 있을 경우에는 스트랩을 사용합니다.

훅그립으로 하는 게 좋은 이유는 끝까지 맨손으로 해냈다는 자부심과 더불어

최후에 한 두번 밖에는 쓸 수 없는 한계가 바로 악력을 발달을 촉진시켜주는 요인이되기 때문입니다.

맨손이지만 얼터네이트그립은 좌우 불균형문제가 있습니다.

스트랩에 관한 것은 메인화면 자작갤러리에 자작스트랩 올려놓은 데에 댓글로 달아놓았으니 참고하세요.

어떤 그립방법이든 악력에 한계가 오면 풀리기 마련입니다.



자신이, 최선의 방법으로 운동했을 경우, 얼마의 무게까지 들 수 있을지는 자신의 유전자만이 알고 있습니다.

얼마까지 맨손으로 데드리프트할 수 있을지도 마찬가지로 유전자만이 압니다.

평 균적인 일반인의 경우, 자신의 몸무게의 2배 어름까지는 가능하지 않을까 추정할 뿐입니다.


------------------------------------------


훅그립이 1회용이라는 말씀은 데드리프트 할때 1회 들어올리고 완전히 내린다음 다시 시작 하라는 말씀인가요?

그리고 데드리프트할때 완전히 내려놓으면 자세가 흐트러질것 같은데
손풀고 일어나서 처음부터 자세를 다시 잡아야하는건 아닌가요?
-------------------------------------------------------------------------------------------------------------------

훅 그립은 엄지손가락에 부담이 되므로 장시간 버티는 용도나 고반복에는 쓰기 어렵습니다.

역도처럼 엄청난 고중량을 엄청난 속도의 파워로 1회 들어올리는 경우 손이 풀리는 것을 막아주는 용도입니다.


데드리프트 할 때 완전히 내려놓고 1~2회 호흡하는 잠시동안, 그립도 풀고 쉬었다가 다시 잡고,

등판의 긴장도 잠시 풀었다가 다시 강력하게 수축시키고서 다음 들기를 반복하므로

매 반복마다 시작자세를 정확하게 다시 가다듬을 수 있게 되는 것입니다.


바 닥에 살짝 되튀겨 올리는 치팅을 하게 되면 점점 자세가 흐트러져 등판이 앞으로 둥글게 휜 상태로

세트를 마감한다는 것을 동영상을 보면 쉽게 알 수 있습니다. 허리와 척추디스크의 관점에서 볼 때 자해행위나 다름없습니다.

경고를 무시하고 그런식으로 계속하게되면,

조만간, 적어도 몇달 후, 늦어도 몇년 후에는 반드시 척추디스크 파열이란 불운이 닥치게 됩니다.



스티프레그드 데드리프트도 역시 Deadlift이므로

매 반복마다 완전히 내려놓고서 호흡하는 동안 등판과 그립을 잠시 쉬고서 다시 자세가다듬고 들어올리길 반복합니다.

그리고 컨벤셔널 데드리프트든 스티프레그드 데드리프트이든, 숨을 최대한 들어마시고 멈춘 다음

들어올렸다가 내려놓아야 한다는 것, 즉 움직이는 동작 중에는 숨을 멈춘 상태를 유지해야 한다는 것을 잊지마세요.


그 런데, 루마니안 데드리프트는 이름과는 달리, 우선 들고 선채로 시작해서 중량이 내려왔다가 올라가는 운동입니다.

세트 중에는 바벨을 계속 들고 있어야 하므로 그립을 쉴 수 없습니다.

루마니안 데드리프트는 Deadlift의 일종이 아니고 '(Stiff-legged) Deadlift와 비슷한 동작으로 하는 루마니아식 운동'이라는 의미입니다.



좌 우 불균형이라는 문제는 근육발달이나 자세의 불균형을 의미한다기 보다

바벨을 다시 내려놓았을 때 바가 원래의 위치에 고스란히 돌아와 놓이지 않고 자꾸만 삐뚜름하게 놓여져서

반복 들기동작의 시작자세가 흐트러지게 되는 것을 의미합니다.

광 배근으로 당김이, 과하면 정강이를 긁히고, 모자라면 바가 다리 윗면에서 이탈하거나 내려놓을 때 원래보다 훨씬 앞쪽에 놓이게 되고

좌 우가 불균형이면 바가 번번히 삐뚜름하게 놓이게 되어 그 조절이 쉽지 않습니다.


얼터네이트그립은, 왼손(왼손잡이는 오른손)을 뒤집어 잡는다는 것,

뒤집어잡는 쪽의 광배근 사용감각이 달라져서 한번 거기에 익숙해지면 좌우균형상 계속 얼터네이트그립으로만 하게되어

악력발달에 소홀하게 된다는 것,

왼손 오른손 바꾸어가며 하게되면 광배근사용감각이 자꾸 헷갈려 익숙해지기 힘들 것이라는 것,

이외에는, 개인적으로 얼터네이트 그립을 사용한 적이 없어서 더이상 알고 있는 노하우가 없습니다.



다시한번 강조하지만, 얼터네이트그립이든 훅그립이든 스트랩사용이든

불가피한 경우 마지막 세트에 한두차례 사용하는 데 그쳐야 합니다.


-----------------------------------------



감사합니다 ergy님!!
많은 것을 배우고 가네요^^

악력 때문에 데드 중량 치는데 한계가 있었는데,
말 씀 해주신 방법을 한번 사용해봐야겠네요.

그런데 무조건 일회 하고 쉬고 일회하고 해야하는 건가요?
아니면 삼사회 하고 악력 딸릴 때 한번 내려놓고 또 다시 삼사회 하고 해도 되는건가요??
-------------------------------------------------------------------------------------------------------------------

1 회 하고 그립을 쉬어야 한다는 게 아니라,

숨을 참고 1회 들어올렸다가 내려놓고는, 숨을 쉬는 동안 그립과 척추기립근의 긴장도 잠시 풀어줄 수 있다는 의미입니다.


완전히 내려놓지 않고 여러차례 들고 내리기를 반복하는 것은 극히 위험한 치팅입니다.

중량을 위에서 내렸다가 바로 올리면 내리는 동안 근육에 축적되는 탄력으로 쉽게 올릴 수 있는데(stretch reflex),

스쿼트나 벤치처럼 위에서 내렸다 올리는 운동에서만 허용되고,

바 닥에서 뽑아 올리는 데드리프트에서는 허용되지 않습니다.

운동은 어떻게든 들어올리는 게 목적이 아니라, 올바른 운동을 통해 강해지는 것이 목적입니다.


반복하는 동안 숨을 쉴 수 없어 마음이 급해져 동작은 더욱 엉망이 되기 쉽고

지 나치게 오랫동안 숨을 참고 엄청난 복압을 유지해야 하므로, 운동후 두통을 겪을 수 있습니다.

허리부상이나 척추손상은 이미 예약한 상태이고...


숨을 쉬면서 여러차례 들고내리기를 반복한다면, 가벼운 무게에서는 몰라도 무거운 중량에서는

지금 당장 허리를 다치는 게 소원이라는 뜻입니다. "꿈은 (조만간에) 이루어진다"는 말도 있지요

그 정도로 위험한 치팅입니다.

12/03/2010

set mysql charset to utf8 in ubuntu 10.04

1. MySQL setting

Edit my.cnf with this command :
$ sudo vi /etc/mysql/my.cnf

in [client] section, add this :

default-character-set = utf8

and, in [mysqld] section, add these :

default-character-set=utf8
default-collation=utf8_general_ci
init_connect=set collation_connection=utf8_general_ci
init_connect=set names utf8
character-set-server=utf8
collation-server=utf8_general_ci
character-set-client-handshake = TRUE

The restart mysqld

$ sudo /etc/init.d/mysql restart



Confirm :

mysql> show variables like 'char%'
-> ;
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

* IMPORTANT : Create database with "defalut charset=utf8" option.
user@myserver:/home/user$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 56
Server version: 5.1.41-3ubuntu12.7 (Ubuntu)

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database DBNAME default charset=utf8;

Query OK, 1 row affected (0.00 sec)

mysql> Bye

2. Django settting

in settings.py add this :

LANGUAGE_CODE = 'ko-KR'
./managy.py syncdb should be run.


Then, 한글 입력 is ok in Django application.

11/27/2010

Setting mp3 quality when using rhythmbox to sync iphone or ipod

When I sync music library with iphone in ubuntu, rhythmbox convert almost any type of music file into mp3 file automatically.

However, the default quality set is vbr, and I want the best quality, i.e., 320kbps, not vbr.

Rhythmbox - Edit - Preference - Music - Edit Preferred format
Select MP3.

Change the setting like this :

audio/x-raw-int,rate=44100,channels=2 ! lame name=enc mode=0 vbr=0 bitrate=320 ! id3v2mux



.

11/15/2010

django + apache server 1

1. Set apache to read my django project

cat /etc/apache2/httpd.conf

(location "/")
SetHandler python-program
PythonHandler django.core.handlers.modpython
PythonPath "['[path.to.django.project]', '[path.to.other.location.which.has.python.code]'] + sys.path"
SetEnv DJANGO_SETTINGS_MODULE [projectName].settings
PythonDebug On
(/location)

where, "(" and ")" should be replaced with "<" and ">"

In web browser, http://localhost/ gives the "It worked" page of django.
If "import error" occur, check the [path.to.directory] point out the right directory which contains the module.

2. utf-8 setting

$ cat /etc/apache2/envvars

...
export LANG=ko_KR.UTF-8
export LC_ALL=ko_KR.UTF-8
...

$ /etc/init.d/apache2 restart


3. Running a development server with apache mod_python

If a django python code was changed, apache server must be restarted.
To avoid this, just set

MaxRequestsPerChild 1

in /etc/apache2/apache2.conf

This force apache to reload everything for each request.


When debugging, use the code below to display a debugging information.

assert False, 'debug text'


4. Make database (mysql)


5. Make project, app

django-admin startproject (aaa)
cd aaa
./manage.py startapp (bbb)


in settings.py

add the code below

import os
ROOT_PATH = os.path.dirname(__file__)

add to TEMPLATE_DIRS

ROOT_PATH + '/templates',


and in INSTALLED_APPS, add

'aaa.bbb',


change the LANGUAGE_CODE option like

LANGUAGE_CODE = 'ko-KR'


and setting DB infomation.

DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'dbname' # Or path to database file if using sqlite3.
DATABASE_USER = 'userid' # Not used with sqlite3.
DATABASE_PASSWORD = 'password' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.


6. sync db

manage.py syncdb

Here, set user name and password.


7.

11/11/2010

Converting a date value read from a calc cell into readable format using python

When a date value, such as "2010-10-12" or etc., is in a cell,

oCell.getValue() and oCellRange.DataArray methods give just a number, not date format,
while oCell.getString() gives a date format string

The code below shows how to convert a date value into date format.


#!/usr/bin/python
import datetime, uno

# .... some lines to get oCell

# cell value shown in calc -> 2010-10-12
dateValue = oCell.getValue()
# get date value from a cell with getValue() method,
# note that I did NOT used the getString() method.

print dateValue # this gives 40463.0 <- This means the elapsed date from 1899-12-30

DateValue = datetime.timedelta(dateValue) + datetime.date(1899, 12, 30) # converting
# DateValue -> datetime.date(2010, 10, 12)

print DateValue # this gives 2010-10-12.



* The starting date 1899-12-30 can be changed in option > openoffice Calc > calculate > date

11/06/2010

Control Calc chart using python

ref: http://wiki.services.openoffice.org/wiki/Documentation/BASIC_Guide/Structure_of_Charts

ref: http://www.oooforum.org/forum/viewtopic.phtml?p=56037


Legend show/hide

oChart = oSheet.Charts.getByIndex(0).EmbeddedObject
oChart.HasLegend = False


Set main title

oChart.HasMainTitle = True
oChart.Title.String = "main-title-string"


Set XAxis title

oDiagram = oChart.Diagram
oDiagram.HasXAxisTitle = True
oDiagram.XAxisTitle.String = "x-title"


Set XAxis label text rotation

oDiagram.XAxis.TextRotation = 90 * 100 # for 90 degree rotation

Set cell border

oBorderLine = createUnoStruct("com.sun.star.table.BorderLine2")
oBorderLine.InnerLineWidth = 2
oBorderLine.Color = 255 # blue

oCell.LeftBorder = oBorderLine
oCell.RightBorder = oBorderLine

Set cellRange border (apply to every cells)

oCellRange = oSheet.getCellRangeByPosition(1, 2, 3, 4)
oCellRange.BottomBorder = oBorderLine

Set cellRange TableBorder (apply to only edge lines not inner lines)

oCellRange.TableBorder -> com.sun.star.table.TableBorder

oTableBorder = createUnoStruct("com.sun.star.table.TableBorder")

# there are 2 types: BorderLine and BorderLine2. Confusing, be careful to choose.
oBorderLine = createUnoStruct("com.sun.star.table.BorderLine")
#oBorderLine2 = createUnoStruct("com.sun.star.table.BorderLine2")

# make oTableBorder object
oTableBorder.BottomLine = oBorderLine
oTableBorder.TopLine = oBorderLine
oTableBorder.LeftLine = oBorderLine
oTableBorder.RightLine = oBorderLine

# ... something like this ...
oTableBorder.IsTopLineValid = True
oTableBorder.IsBottomLineValid = True
oTableBorder.IsLeftLineValid = True
oTableBorder.IsRightLineValid = True

# set
oCellRange.TableBorder = oTableBorder
### Sometimes the code above does not work.
### Be sure that "oTableBorder.IsTopLineValid = True" line is correct.



.....

11/03/2010

ubuntu nautilus dirs config

$ cat ~/.config/user-dirs.dirs
# This file is written by xdg-user-dirs-update
# If you want to change or add directories, just edit the line you're
# interested in. All local changes will be retained on the next run
# Format is XDG_xxx_DIR="$HOME/yyy", where yyy is a shell-escaped
# homedir-relative path, or XDG_xxx_DIR="/yyy", where /yyy is an
# absolute path. No other format is supported.
#
XDG_DESKTOP_DIR="$HOME/바탕화면"
XDG_DOWNLOAD_DIR="$HOME/다운로드"
XDG_TEMPLATES_DIR="$HOME/서식"
XDG_PUBLICSHARE_DIR="$HOME/공개"
XDG_DOCUMENTS_DIR="$HOME/문서"
XDG_MUSIC_DIR="$HOME/음악"
XDG_PICTURES_DIR="$HOME/"
XDG_VIDEOS_DIR="$HOME/"

10/20/2010

python encoding error solution

/usr/lib/python2.6/site.py

find 'ascii' and change to 'utf-8'

7/15/2010

openoffice calc macro : Copy a chart to GDI meta format by python macro


def myAddChart(oDataRangeAddress, oSheet, oChartPositionCell):
tmpChartName = "tmpChartName"
#--------- make a chart
oCharts = oSheet.Charts

X = oChartPositionCell.Position.X
Y = oChartPositionCell.Position.Y

oCharts.addNewByName(tmpChartName, makeRectangle( X, Y, 8000, 3500 ), Array( oDataRangeAddress ), True, True)
oChart = oCharts.getByName(tmpChartName)

#==========================================================
#--------- Copy the Chart to GDI meta image into the position on where the chart is
#==========================================================
oDoc = getReady()
oController = oDoc.getCurrentController()

oDrawPage = oSheet.getDrawPage()
nNumShapes = oDrawPage.getCount()

### select the chart.
### No way for direct selecting a chart. So, get shapes and find the chart from shapes.
for loopi in range(nNumShapes) :
oShape = oDrawPage.getByIndex( loopi )
if "CLSID" in dir(oShape) : # only charts have the CLSID attribute
if oShape.CLSID == "12DCAE26-281F-416F-a234-c3086127382e" : # this is the CLSID of charts
oController.select( oShape )
break

# PropertyValue format=3 means the PasteSpecial format to be the GDI meta file format
PropertyValue = uno.createUnoStruct("com.sun.star.beans.PropertyValue")
PropertyValue.Name = "Format"
PropertyValue.Value = 3

serviceMgr = uno.getComponentContext().ServiceManager
dp = serviceMgr.createInstance('com.sun.star.frame.DispatchHelper')
#--- copy the selected object (chart)
dp.executeDispatch( oController.getFrame(), ".uno:Copy", "", 0, ())
#--- remove the selected object
oCharts.removeByName(tmpChartName)
#--- now select the cell where the GDI meta image will be on
oController.select(oChartPositionCell)
#--- paste
dp.executeDispatch( oController.getFrame(), ".uno:PasteSpecial", "", 0, (PropertyValue,)) # <- The last (PropertyValue,) option is important.




..

7/06/2010

python code snippets for openoffice calc

getReady() -> return oDoc (calc document)
gotoOffset -> similar to Range.Offset(x, y) in excel VBA
gotoLeftEnd -> Range.End(xlToLeft) in VBA for excel


import uno

def gotoOffset(oCell, coffset, roffset):
currentColumn = oCell.getCellAddress().Column
currentRow = oCell.getCellAddress().Row

newColumn = currentColumn + coffset
newRow = currentRow + roffset

if newColumn < 0 : newColumn = 0
if newRow < 0 : newRow = 0

tmpCell = oCell.getSpreadsheet().getCellByPosition(newColumn, newRow)
return tmpCell


def gotoRightEnd(oCell):
tmpCell = oCell
while True :
tmpCell = gotoOffset(tmpCell, 1, 0)
if tmpCell.getString() == '' :
tmpCell = gotoOffset(tmpCell, -1, 0)
break
return tmpCell

def gotoLeftEnd(oCell):
tmpCell = oCell
while True :
tmpCell = gotoOffset(tmpCell, -1, 0)
if tmpCell.getRangeAddress().StartColumn == 0 :
break
if tmpCell.getString() == '' :
tmpCell = gotoOffset(tmpCell, 1, 0)
break
return tmpCell

def gotoTop(oCell):
tmpCell = oCell
while True :
tmpCell = gotoOffset(tmpCell, 0, -1)
if tmpCell.getRangeAddress().StartRow == 0 :
break
if tmpCell.getString() == '' :
tmpCell = gotoOffset(tmpCell, 0, 1)
break
return tmpCell

def gotoBottom(oCell):
tmpCell = oCell
while True :
tmpCell = gotoOffset(tmpCell, 0, 1)
if tmpCell.getString() == '' :
tmpCell = gotoOffset(tmpCell, 0, -1)
break
return tmpCell



def getReady():
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
ctx = resolver.resolve( "uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext" )
smgr = ctx.ServiceManager
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
oDoc = desktop.getCurrentComponent()

return oDoc

7/02/2010

Searching a text in openoffice calc sheet using python code


sd = oSheet.createSearchDescriptor()
sd.setSearchString("SearchString")

fc = oSheet.findFirst(sd)

while True :
if fc == None : break
fc.CellBackColor = 12341234
fc = oSheet.findNext(fc, sd)

Set optimal width for all columns of a sheet in openoffice calc with python script code

oSheet.Columns.OptimalWidth = True

.

set image size in openoffice calc with python code

1. resizing selected images


def ResizingSelectedImages(height = 10000, width = 8000):
oDoc = getReady()
cSelection = oDoc.getCurrentSelection()
for loopi in range(cSelection.Count) :
tmpImage = cSelection.getByIndex(loopi)
tmpSize = tmpImage.Size
tmpSize.Width = width
tmpSize.Height = height

tmpImage.setSize(tmpSize)



2. Resizing the first images (getByIndex(0)) in the selected sheet.



oSheet = oDoc.getSheets().getByIndex(0)
oDraw = oSheet.getDrawPage()
oImage = oDraw.getByIndex(0)

newSize = oImage.Size
newSize.Height = 20000
newSize.Width = 20000

oImage.setSize(newSize)

select (activate) a sheet in openoffice calc by python code


import uno
localContext = uno.getComponentContext()
resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
# note the port number is 8100, where the default value is 2002
ctx = resolver.resolve( "uno:socket,host=localhost,port=8100;urp;StarOffice.ComponentContext" )
smgr = ctx.ServiceManager
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)
oDoc = desktop.getCurrentComponent()

# sheet to be activated
oSheet = oDoc.getSheets().getByIndex(2)

# activate the sheet
oController = oDoc.getCurrentController()
oController.setActiveSheet(oSheet)

# set first visible row
oController.setFirstVisibleRow(3)

7/01/2010

openoffice start option enable python macro

openoffice calc should be run with the command


$ ooffice -calc --accept="socket,host=localhost,port=8100;urp;StarOffice.ServiceManager"


or edit /usr/bin/ooffice (in ubuntu)


$ cat /usr/bin/ooffice
#!/bin/sh
/usr/lib/openoffice/program/soffice "$@" --accept="socket,host=localhost,port=8100;urp;StarOffice.ServiceManager"
$

6/29/2010

Extract icon from EXE file in ubuntu

$ wrestool -x -t14 TARGET.EXE -o result.icon
$ convert result.icon result.png


why -t14 ?

wrestool -l TARGET.EXE
-> shows a list of resources included in TARGET.EXE file, where type=14 (type=group_icon) is the icon image we want to extract.

-x option means extract
-o where to place extracted files

6/24/2010

olym opt

-start=s,mMets

6/23/2010

Let google desktop find MS doc, xls, or ppt files

sudo apt-get install wv
sudo apt-get install catdoc


http://desktop.google.com/support/linux/bin/answer.py?hl=en&answer=76816

5/21/2010

The path of openoffice impress templates

/usr/lib/openoffice/basis3.1/share/template/en-US/presnt

...

5/19/2010

scanning port state whether opened, closed or filtered by using nmap

[root@localhost ~]# nmap -sT -p 1-65535 localhost

Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2008-02-19 01:47 KST
Interesting ports on xxx.xxx.xxx.xxx:
Not shown: 65531 closed ports
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
111/tcp open rpcbind
645/tcp open unknown
ref: http://kldp.org/node/91134





Nmap finished: 1 IP address (1 host up) scanned in 2.391 seconds

5/15/2010

5/14/2010

changing menu font color in firefox

$ cat ~/.mozilla/firefox/[blahblah~].default/chrome/userChrome.css

menubar, menubutton, menulist, menu, menuitem {
font-family: sans !important;
font-size: 10pt !important;
color: black ! important;
}

$

It is useful when a firefox theme such as OSX theme makes menu font size too small or font color not distinguishable.


Modify the OSX theme -> remove shadow in toolbar and tab

/* ----- DEFAULT PRIMARY TOOLBAR BUTTONS ----- */

.toolbarbutton-text-shadow,
.tab-text-shadow {
color: #f0f0f0;
padding-top: 0px;
opacity: 0;
}

.tab-text-shadow {
padding-top: 0;
font-size: 10pt;
font-weight: normal;
font-family: "sans";
}


/.mozilla/firefox/jwi2ie5q.default/extensions/{00352F14-3F76-4e4d-ACFF-9972D7E4B3B9}/chrome/MacOSX.jar

edit -> browser/browser.css file

Always show nautilus location bar in text format

gconf-editor

/apps/nautilus/preferences/always_use_location_entry

-> check

.

5/13/2010

Virtualbox on Ubuntu 10.04

repo :

deb http://download.virtualbox.org/virtualbox/debian lucid non-free


key :

wget -q http://download.virtualbox.org/virtualbox/debian/sun_vbox.asc -O- | sudo apt-key add -


install :

sudo apt-get update
sudo apt-get install virtualbox-3.1

5/07/2010

새로 시작하는 회사에 대한 생각.

새로 시작하는 회사에 대한 생각.

직원들은 지난 직장의 경험을 갖고 있다.
이전 회사가 단지 망하지 않을 정도 혹은 약간 나은 정도였다면, 새로운 회사에서도 예전 하던 방식대로 일을 진행할 가능성이 많다.

아무리 각자가 마음가짐을 새롭게 하고 정신무장을 한다 해도 그렇다. 이전 회사에서 일하던 방식의 단점을 잘 알고 있더라도 그렇다.

기업에서 변화는 그리 쉽게 이루어지지 않는다. 변화에 대한 두려움이 있기 때문에.

예전에도 이렇게 했는데 실패하지는 않았잖아 하는 생각이 변화를 막는다. 최소한의 안전장치라고 착각한다.

심지어 기술 혁신을 이루고자 하는 벤처에서도 그렇다. 기술 혁신은 자신 있어도, 기업 문화나 일하는 방식등에 대해서는 자신이 없는 것이다.


이끌어 가는 사람들 (경영자, 이사 등) 이 마음먹지 않는 한, 기존 방식을 답습하게 되고, 똑 같이 그럭저럭 굴러가는 수준에 머무를 가능성이 크다.

4/10/2010

Super squat routine...



Ref: http://www.trulyhuge.com/news/tips62d.htm


FITNESS TIP FOR 8/10/2002
___________________________________________

Increase Your Squat

How to add 120 pounds to your squat lift within the next 6 weeks
by Oliver Wolter

Today I want to introduce to you one of the simplest, shortest but most
valuable strength producing workout routines. Probably it's my usual
German spleen but I love short result producing workout routines.

It's like I always design workout routines. Selecting the target - aiming
- shooting and get out of it. I know it's probably not anybody's taste of
workout routine, because it's not much training. But I don't care, because
I call my style results orientated training. It doesn't need to be
entertaining, it doesn't need to look cool - all it is for results.

But the results have to be more than cool - this is what I care about.

This workout routine is not about building up huge muscle mass it's about
getting strong in the basic movements ASAP.

This Super Squat workout routine contains of only 4 basic exercises:

1. Squats
2. Deadlift
3. Pull Ups
4. Chest Dip


That's all!

You have to do one set of each exercise - nothing more - only one short
set. Remember I am talking about putting on strength not putting on muscle
mass.

Do at least 5 repetitions of each exercise and a maximum of 12. But now
comes the little trick. Increase your weight as long as you don't drop
below 5 reps.

Don't care about increasing reps - care about increasing weights - because
you want to gain strength.

If you want to go wild like a few of my clients - increase the weight for
lower body movements (Squat and Deathlift) 20 pounds and for upper body
movements (Pull Ups and Chest Dip) 10 pounds with each workout.

Hmmm...probably you are not that crazy but try at least 10 pounds lower
body and 5 pounds upper body. This should work fine for most people.

Again - if your reps drop below 5 - don't increase the weight - as long as
you stay at 5 reps or above - increase the weight.

Don't overdo it when you start with your first workout. Start with a weight
you could normally use for 10-12 reps.

One question is still open - How many workouts you should do?
ONE SET FOR EACH EXERCISE
ONE WORKOUT EACH WEEK - THAT'S ALL


But I want to give you two example workouts:

WORKOUT NUMBER 1
1. Squats - 220 pounds - 10 reps
90 seconds rest
2. Deadlift - 240 pounds - 11 reps
90 seconds rest
3. Pull Ups - (bodyweight 180 lbs + 5 lbs plate) = 185 pounds - 8 reps
90 seconds rest
4. Chest Dip (bodyweight 180 lbs + 10 lbs plate) = 190 pounds - 10 reps
END OF WORKOUT NUMBER 1

1 WEEK REST

WORKOUT NUMBER 2
1. Squats - 230 pounds - 10 reps
90 seconds rest
2. Deadlift - 250 pounds - 10 reps
90 seconds rest
3. Pull Ups - (bodyweight 180 lbs + 10 lbs plate) = 190 pounds - 7 reps
90 seconds rest
4. Chest Dip (bodyweight 180 lbs + 15 lbs plate) = 195 pounds - 10 reps
END OF WORKOUT NUMBER 2



If you didn't understand it the first time -read it again.
ONE SET OF EACH EXERCISE - ONE WORKOUT EACH WEEK
INCREASE THE WEIGHT WHILE YOU DON'T DROP BELOW 5 REPS.

Sounds to simple to work?

Well I know - a lot of people said this to me about 2 years ago me. So I
made one public test back between 12/02/00 and 01/24/01. This test lasted
about 10 weeks.

Christian the test person was somebody you would call a hard gainer. But
he was extremely motivated, this was the reason I decided he should be the
test person. I wanted to show that you don't have to be a genetic wonder
to achieve great gains as long as you do your best to succeed.

Christian did only 10 workouts in 10 weeks. Here are the results:

Start (12/02/00):
1. Squats - 8 reps with 80 kg (176.37 lbs)
2. Deadlift - 5 reps with 60kg (132.28 lbs)
3. Pull Ups - 5 reps - Bodyweight + 5kg (11.02 lbs)
4. Chest Dips - 5 reps Bodyweight only


End (01/24/01)
1. Squats - 4 reps with 170 kg (374.8 lbs)
2. Deadlift - 4 reps with 110kg (242.5 lbs)
3. Pull Ups - 6 reps Bodyweight + 20kg (44.09 lbs)
4. Chest Dips - 4 reps - Bodyweight + 20kg (44.09 lbs)


This means he increased his strength by:

Squats + 90 kg (198.41 lbs)
Deadlift + 50 kg (110.23 lbs)
Pull Ups + 15 kg (33.07 lbs)
Chest Dips + 20 kg (44.09 lbs)

Not bad for a so called hard gainer within 10 weeks of training?!

After this a lot of people tried the same workout routine. And guess what
- they had similar results.

You can do this too - or have even better results - but you have to be
motivated.

Well this is what I call results based bodybuilding - set your aim -
follow it and achieve it. The training wasn't fancy or exotic - but it
did it's job.

And the results were better than what a lot of people with ordinary workout
routines will ever achieve in a lifetime.

I always use short training routines. They don't have to be this short but
they only have to fulfill what they are for.

In my personal training software X-Size I also
use short routines but in a more advanced way. I created this
software to make something completely different. It's all about timing.

Such short routines could be confusing if you add some advanced
techniques like upgrading exhaustion or advanced splitting. But for this
reason I created my personal training software to keep all guesswork
away from you.

You see the workout routine above is completely easy to understand. But
what happens after a few weeks? You can use this routine only a few weeks
before you hit a plateau. But in X-Size I shoot
for the middle to long term goals. For example I use a similar but more
advanced routine in a feedback controlled manner to shoot for a middle term
goal. What does it mean? I use for example such a routine to initialize your
body for a special muscle mass phase.

Sounds complicated?! It is complicated - but what makes any routine a
real winner is when you can easily follow it. If you have no guesswork. So
this could only be solved with a software that gives you the exact
weights and reps for any workout unit.

Results is all that count!

2/10/2010

Deciding if a Point is Inside a Polygon - Pure Python

Method using matplotlib.nxutils

from matplotlib.nxutils import points_inside_poly
points_inside_poly([[0, 0], [0, 1]], [[1, 0], [1, 1], [0, 1]])


Using python-shapely (http://trac.gispython.org/lab/wiki/Shapely)
(http://gispython.org/shapely/manual.html#polygons)

$ sudo apt-get install python-shapely


in python,

from shapely.geometry import Polygon, Point
polygon2 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0)))
print polygon2.contains(Point(0.1, 0.1)) # print True



another method :

ref : http://www.ariel.com.au/a/python-point-int-poly.html


#!/usr/bin/python
# determine if a point is inside a given polygon or not
# Polygon is a list of (x,y) pairs.
def point_inside_polygon(x,y,poly):

n = len(poly)
inside =False

p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x,p1y = p2x,p2y

return inside


.

1/21/2010

join or split pdf files - pdftk

join

pdftk file1.pdf file2.pdf cat output file12.pdf

split

ex) in.pdf has 10 page total. We want split it in two files.
out1.pdf has page 1 to 5, and out2.pdf has 6 to 10.

pdftk in.pdf cat 1-5 output out1.pdf
pdftk in.pdf cat 6-end output out2.pdf
very simple and elegance !!

detailed manual :

pdftk --help


.




1/17/2010

CPU 점유율 잡아먹는 네이버 실시간 검색어 없애기

firefox 파이어폭스로 네이버 접속했을 때 cpu 점유율 급상승하는 증상.

실시간 검색어 목록이 화려한 (?) 효과로 바뀌고 있는데 이게 원인인 듯.

그리스몽키로 없애버리니 cpu 가 잠잠해 짐.


방법
------------

firefox -> right click on greasemonkey icon -> 새로운 유저 스크립트

이름, 네임 스페이스 적당히 쓸것

동작할 페이지 -> http://*.naver.com/*


스크립트 내용

// ==UserScript==
// @name naver
// @namespace naver
// @include http://*.naver.com/
// ==/UserScript==

var annoying = document.getElementById('au_keyword_rank');
if (annoying)
{annoying.parentNode.removeChild(annoying);
}

실시간 검색어 부분을 소스 확인 해보면 html 태그 ID 가 au_keyword_rank 로 되어 있음.

greasemonkey 에서 이 부분 검색해서 없애는 코드.

.

1/16/2010

[HOWTO] install python-visual_5.13 to jaunty

Preparing related packages

Download linux package in

http://vpython.org/contents/download_linux.html

Uncompress it.
And make temporary folder ( ex. vp_tmp ) and get into the vp_tmp folder

/home/username/somewhere$ ls -d visual-5.13_release
visual-5.13_release
/home/username/somewhere$ mkdir vp_tmp
/home/username/somewhere$ ls
visual-5.13_release
vp_tmp
/home/username/somewhere$ cd vp_tmp
/home/username/somewhere/vp_tmp$


install the following 3 packages using synaptic :

libboost-python-dev
libboost-signals-dev
libboost-thread-dev


install the followings using synaptic :

automake
libgtkglextmm-x11-dev
libgtkmm-2.4-dev
libglademm-2.4-dev

Configure

/home/username/somewhere/vp_tmp$ PYTHON=/usr/bin/python ../visual-5.13_release/configure --prefix=/usr
The configure command should be run in a parallel folder.
The install.txt file recommand that.
(for example, vp_tmp which was made in before step)
So, the configure command should be "../visual-5.13_release/configure" rather than "./configure"



compile

/home/username/somewhere/vp_tmp$ make


install

/home/username/somewhere/vp_tmp$ make install

In jaunty, python site-packages or dist-packages are located in
"/usr/lib/python2.6/dist-packages" or "/usr/lib/python2.6/site-packages"
So, prefix should be "/usr"
Then, python-visual will be installed in prefix/lib/python2.6/site-packages folder.
After "make install", because of ubuntu jaunty's python folder policy, you should

$ sudo cp -R /usr/lib/python2.6/site-packages/* /usr/lib/python2.6/dist-packages/


If "configure" was run without --prefix option, compiled visual-python package is installed in
"/usr/local/lib/python2.6/site-packages"
In this case, user should copy the whole installed packages to "/usr/lib/python2.6/dist-packages"
(i.e.,
/home/username/somewhere/vp_tmp$ sudo cp -R /usr/local/lib/python2.6/site-packages/* /usr/lib/python2.6/dist-packages/
)

.