2016년 7월 17일 일요일

Docker / iTerm Troubleshooting

맥북에서 Docker를 사용할 일이 있어 설치 후 Docker Quick Start Terminal의 Default를 iTerm으로 잡아주니 비정상적으로 동작한다.

찾아보니 iTerm 관련 오류가 있었고, 아래 링크에서 iterm.scpt를 복사하여,
"/Applications/Docker/"Docker Quickstart Terminal.app"/Contents/Resources/Scripts/iterm.scpt" 에 덮어씌워주고 해결됨.

https://github.com/virajkanwade/toolbox/blob/b45ae79a4b7eb16e397b759c53cac8d5c0da134c/osx/mpkg/quickstart.app/Contents/Resources/Scripts/iterm.scpt

* 위 경로는 Default location에 Docker를 설치한 경우에만 해당함. 아닌 경우 iterm.scpt를 찾아서 패치하면 된다.

2016년 5월 15일 일요일

19대 국회의원 정치자금 사용 내역 EDA (2탄)

[목차]
3. '분류항목'별 지출액 금액 분포를 보자. 
중복 제거한 '분류항목'의 개수는 총 59개이다. 그냥 분포가 아니라 정말 지출한 금액이니 아웃라이어 제거 같은 건 하지 말고 그냥 한번 구간을 좁혀가면서 보자. 

3-1. 전체 분류항목별 지출 금액 분포 
 - 부동산, 송사비용, 차량구입비 등이 중간값으로 1등

3-2. 1000만원 이하만 다시 보면?
 - 정치여론조사 컨설팅 / 의정보고 발송비... 평판 관리(?!)와 홍보에 건별로 비싸게 지불하고 있다.

3-3. 100만원 이하만 다시 보면?
 - 택시를 타고 어떻게 다니면 도대체 30만원이 나오는 거지?
 - 신문구독비가 70만원에 육박하는 건 무슨 신문을 몇 부나 보는 건가?
 - 주유비 분포도 참으로 다양하다. 

4. 그럼 누가누가 많이 썼나?
 4-1. 개인별 지출액 Top 20


 4-2. 당별 개인별 Top
  4-2-1. 새누리당



  4-2-2. 새정치

  4-2-3. 진보정의

  4-2-4. 통합진보


  4-2-5. 무소속

2016년 5월 9일 월요일

19대 국회의원 정치자금 사용 내역 EDA (1탄)

[목차]
19대 국회의원 정치자금 사용 내역 EDA (1탄) 
19대 국회의원 정치자금 사용 내역 EDA (2탄)
=========================================
짬짬이 해보는 19대 국회의원 정치자금 사용 내역 EDA.

오마이뉴스가 중앙선관위를 통해 받은 19대 국회의원 322명의 정치자금 수입/지출 보고서의 지출 내용 368,148건에 대한 심심풀이 분석이며,
해당 자료는 아래 링크에서 다운로드 할 수 있다.
https://github.com/OhmyNews/12-14_kapf

짬짬이 진행해 보는대로 후속 업데이트할 예정.

0. 로딩한 데이터 Summary부터.
 1) 총 368,148건.
 2) 지출액은 -8천만원 ~ 1.7억 (마이너스는 뭐지 ;)
 3) 사용처 중 가장 많이 등장하는 아이는 케이티. 아마도 통신비.


1. 당별 지출액 계를 살펴보자

2. "분류항목"별 비교를 해보자.
2-1. 어떤 분류에 내 세금을 많이 썼을까? (Top 20) 
 1) 인건비가 엄청 높음. 사람 쓰는데 돈 많이 쓰는군.
 2) 용처가 매우 수상쩍은 '정치-활동비용'이 두번째.
 3) 역시 부동산 비용.

2-2. 당별 Top 10 지출 분류 항목은? 
당별로 지출 분류 Top 20을 뽑아보자.
 1) 새누리: 인건비, 정치활동비, 사무실 ...

 2) 새정연: 새누리와 동일

 3) 통진당: 특별당비(?), 정치활동비, 사무실. 특별당비의 정체는 나중에 밝혀보자.

 4) 무소속: 인건비.

 5) 진보정의당 : 정치활동비, 특별당비

모두 '정치 활동비'라는 녀석의 정체를 밝힐 필요가 있어보인다.
'후원-특별당비' 항목도 뭔가 궁금하다.
2탄은 다음 번에 시간날때 이어서...


2016년 4월 27일 수요일

연령대별 장래 인구 추계 (1960 ~ 2060)



통계청 자료로 만든 연령대별 장래 인구 추계. (1960 ~ 2060)
다들 얘기하는 노령화 사회로의 변화를 예고하고 있다.
말그대로 100세시대, '노후'에 대한 대비는 개인의 준비 문제가 아니라 사회의 문제로 심각하게 논의되어야 할 것 같다.

library(ggplot2)
library(dplyr)
library(scales)
library(reshape2)

df <- as.data.frame(read.csv("population2.csv", header=TRUE))
head(df)

df2 <- df %>% mutate(age_range2 = '0~14')
df2[4:13, ]$age_range2 <- '15~64'
df2[14:20, ]$age_range2 <- '65+'

df2m <- melt(cbind(df2[2:12], age_range=df2$age_range2), id.vars=c('age_range'))
levels(df2m$variable) <- gsub("X", "", levels(df2m$variable))

# for annotation
year_total <- 
  df2m %>% 
  group_by(Year) %>%
  summarise(year_total = sum(Percentage))

age_range_total <- df2m %>% 
  group_by(Year, age_range) %>% 
  summarise(avg = sum(Percentage))

df2m_tmp <- left_join(age_range_total, year_total, by="Year")
df2m_tmp <- df2m_tmp %>% mutate(prop = avg/year_total)
df2m_tmp <- df2m_tmp %>% mutate(cumsum = cumsum(prop))

# plotting with annotation
ggplot(df2m,aes(x = Year, y = Percentage, fill = age_range)) + 
  geom_bar(position = "fill",stat = "identity", ylab='percentage', xlab='year') + 
  scale_y_continuous(labels = percent_format()) +
  annotate(geom="text", 
           x=df2m_tmp$Year, 
           y=df2m_tmp$cumsum, 
           label=paste0(as.character(round(df2m_tmp$prop*100, digits=1)),'%'), size=4) 


2016년 4월 5일 화요일

Python request package exception handling

사이트 목록을 돌며 title 내용을 가져오는 간단한 크롤링 코드를 짜서 돌리다가,
목록 중간 특정 웹사이트에서  에러가 발생하여 exception catch 처리한 내용. 기록/메모를 위해 남겨둔다.

[error msg] 
requests.exceptions.ConnectionError: HTTPConnectionPool(host='hostname', port=80): Max retries exceeded with url: hostname ...

response == none 인 경우를 잡아내 주면 보통 문제없이 돌았었는데, 이번처럼 request pkg의 ConnectionError를 handling 안해주면 죽는 경우가 생긴다. 

[Code]
import requests as rq
import bs4

header = {'User-Agent':'Mozilla/5.0'}

def get_html_title(url):        
    request = rq.Request('Get', url, headers = header)
    r = request.prepare()
    s = rq.Session()
    try: 
        response = s.send(r)
    except rq.exceptions.ConnectionError:
        return ''
    if response == None: 
        return ''
    html_content = response.text    
    navigator = bs4.BeautifulSoup(html_content, "html.parser")    
    title = navigator.find('title')
    if title == None:
        return ''
    return title.get_text() 

[Request PKG의 Exception Case]
http://docs.python-requests.org/en/latest/user/quickstart/#errors-and-exceptions

Errors and Exceptions

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise aConnectionError exception.
In the rare event of an invalid HTTP response, Requests will raise an HTTPError exception.
If a request times out, a Timeout exception is raised.
If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.
All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.


2014년 12월 6일 토요일

조직내 밥그릇 싸움과 정보 공유

최근에 주변의 어떤 논쟁을 보며.정말 오랜만에 블로그에 끄적질.



예외적인 얘기들은 빼고 일단 대세상에서 -
조직이건 개인이건 지식은 나눌수록 커진다.

그런데 대기업, 중소기업 가릴 것없이 회사에서 흔히 볼 수 있는 풍경은
 - 별것도 아닌 지식을 자신의 경쟁력과 비밀무기로 삼아 감추고 안 알려주고,
 - 우리 조직과 나의 사업기획, 전략은 극비 중에 극비이며 대내외 보안을 강조한다.

산업사회 등 요새처럼 변화가 빠르지 않던 사회에서는 특정 노하우가 곧 본인의 가치가 되어
그 사람이 없으면 일이 되게 하는 데에 애로사항이 넘치는 경우들이 있어왔겠지만,
진부한 표현으로 know-where가 중요하다고 하는 지식 정보화 사회에서는 더 이상 이런 패러다임이 지속되기는 어렵다고 본다.

어차피 본인이 알고 있는 것으로 누군가는 세계 어딘가에서 이미 실행을 하고 있고, 그나마 조금만 시일이 지나면 구닥다리가 되기 때문에.
정보의 개방과 공유로 (이는 WWW의 핵심적 철학이기도 하다), 그리고 적극적 collaboration으로 나를 포함한 전체가 함께 발전하는 것에 익숙하지 않다면 결국 도태될 수 밖에 없을 것이다.

경험과 관심에 따라 서로 서로 아는 분야와 깊이는 다를 수 밖에 없으니 서로의 지식을 적극적으로 공유하여 함께 성장하여,
서로를 볼때마다 긍정적인 자극으로 염통이 쫄깃하여 더 즐겁게 새로운 것을 배우고 만들어 가는 형태가 바람직하지 않나?
(가장 강력한 자극은 위로부터 내려오는 갈굼이 아니라 옆으로부터의 자극이라고도 한다.)
그렇지 않으면 '대기업을 오래 다니면 바보가 된다' 라는 흔한 말처럼 특정 갈라파고스에서 서로 하향평준화를 향해 내리 달리기 십상이다.

조직도 알량하게 보유한 지식에서 경쟁력을 찾을게 아니라 구성원의 배움, 변화의 속도와, 창조적 문화에서 찾아야 한다.
General Intelligence와 Fast-Learning Skill을 갖춘 Self-Motivator들로 A팀을 구성하고, 학습과 공유를 일상화하는 문화의 형성이 최우선적이며 가장 중요한 조직의 과업일 것이다.

2014년 9월 9일 화요일

Getting and Cleaning Data Quiz1

Coursera의 "Getting and Cleaning Data" Quiz 1.
단순한 퀴즈와 짧은 코드지만 기록을 위해 남겨둔다.

Question 1
The American Community Survey distributes downloadable data about United States communities. Download the 2006 microdata survey about housing for the state of Idaho using download.file() from here:
https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv
and load the data into R. The code book, describing the variable names is here:
https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FPUMSDataDict06.pdf 
How many properties are worth $1,000,000 or more?
A1. 
fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
download.file(fileUrl, destfile="./quiz1.csv")
list.files("./")
d <- read.table("./quiz1.csv", sep=",", header=TRUE, na.string=0)
head(d)
d[d$VAL > 23 & !is.na(d$VAL), "VAL"]

Question 3

Download the Excel spreadsheet on Natural Gas Aquisition Program here:

https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FDATA.gov_NGAP.xlsx 

Read rows 18-23 and columns 7-15 into R and assign the result to a variable called:
 dat 
What is the value of:
 sum(dat$Zip*dat$Ext,na.rm=T) 
(original data source: http://catalog.data.gov/dataset/natural-gas-acquisition-program)

A3.
install.packages("xlsx")
library(xlsx)
fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2FDATA.gov_NGAP.xlsx"
download.file(fileUrl, destfile="./quiz2.xlsx")

colIndex <- 7:15
rowIndex <- 18:23
dat <- read.xlsx("./quiz2.xlsx", sheetIndex=1, colIndex=colIndex, rowIndex=rowIndex)
sum(dat$Zip*dat$Ext,na.rm=T) 

Question 4

Read the XML data on Baltimore restaurants from here:

https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Frestaurants.xml 

How many restaurants have zipcode 21231?

A4.
install.packages("XML")
library(XML)
fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Frestaurants.xml"
download.file(fileUrl, destfile="./quiz4.xml")
doc <- xmlTreeParse("./quiz4.xml", useInternal=TRUE)
rootNode <- xmlRoot(doc)
xmlName(rootNode)
zipcode <- xpathSApply(rootNode, "//zipcode", xmlValue)
zipcode[zipcode=="21231"]

Question 5

The American Community Survey distributes downloadable data about United States communities. Download the 2006 microdata survey about housing for the state of Idaho using download.file() from here:

https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv

using the fread() command load the data into an R object
 DT 
Which of the following is the fastest way to calculate the average value of the variable
pwgtp15 
broken down by sex using the data.table package?

A5. 
fileUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv "
download.file(fileUrl, destfile="./quiz5.csv")
DT <- read.table("./quiz5.csv", sep=",", header=TRUE)
head(DT)
sapply(split(DT$pwgtp15,DT$SEX),mean)