2017년 7월 17일 월요일

[python][django] RuntimeWarning: DateTimeField received a naive datetime 에러

DateTimeField에 날짜를 테스트하려 할 때 문제가 발생했다.
from datetime import datetime
AA.objects.create(my_date=datetime.now())
장고는 날짜에 Timezone을 추가해서 사용한다. timezone을 함께 넣어주던가
사용하지 않는다고 명시하던가 해야한다.
from django.utils import timezone
AA.objects.create(my_date=timezone.now())

[python][django] Model 테이블의 이름을 변경하려면 어떻게 해야 할까?

makemigrations 손보기

ORM에 대해서 많이 들어보고 그냥 쓰면 좋다는 생각에..
그리고 장고를 사용하면 자연스럽게 쓸 수밖에 없기에 그 편리함에 놀라워했다

makemigrations와 migrate만 알면 전부 다 될 줄 알았다. 하지만 이제 알겠다.
편리하기 위해선 많이 배워야 함을... 어쩌면 한 번도 사용한 적이 없어서일지도 모르겠다.
여하튼
단순히 Model명을 변경하고 makemigrations를 하면 에러가 난다.
장고는 내 맘과 같지 않아서, 이 모델이 rename된건지 확신하지 못하는 것같다.
그러면 내가 확신을 가지도록 명시해줘야 한다.
일단 원래대로 돌려놓고
python manage.py makemigrations --empty <앱이름>
이렇게 하면 makemigrations의 빈 통이 보인다. 다른건 보지말고 얘만 보자.
...
operations = [
]
이 안에다가 무슨일을 한 건지 적어준다.
operations = [
  migrations.RenameModel(
    old_name='Pattern',
    new_name='MessagePattern',
    ),
]
이후 Model명을 바꾸고 사용하고 있는 다른 파일들 모델명을 전부 바꾼다.

출처: 이것저것 바꾸다가 makemigrations 스키마가 이런걸 사용하는 것을 확인. python 도큐먼트를 뒤늦게 확인

[python] 파이썬 디렉터리 삭제하기

os.removedirs, shutil.rmtree

단순히 디렉터리를 삭제할 때는 os.removedirs를 사용하는 것으로 가능하다.
import os

os.removedirs(some_path)
하지만 디렉터리 안에 파일이 있다면 삭제되지 않는다. 그럴땐
import shutil
shutil.rmtree(some_path)
이렇게 삭제하자

2017년 7월 7일 금요일

[python] eval 악마와의 계약

eval()을 사용해보자

후위표현식 AB+를 A+B로 변환해서 산술연산하는 함수를 만들자.
def postfix_eval(expr):
    operand_stack = []
    token_list = postfix_expr.split()

    for token in token_list:
        if token in '0123456789':
            operand_stack.append(int(token))
        else:
            operand2 = operand_stack.pop()
            operand1 = operand_stack.pop()
            result = do_math(token, operand1, operand2)
            operand_stack.append(result)
    return operand_stack.pop()

def do_math(op, op1, op2):
    if op == "*":
        return op1 * op2
    elif op == "/":
        return op1 / op2
    elif op == '+':
        return op1 + op2
    else:
        return op1 - op2
실행
print(postfix_eval('7 8 + 3 2 + /'))
여기서 주목할 것은 do_math
여기 do_math의 내용을 이렇게 바꾼다면
def post_math(op, op1, op2):
    return eval(op1 + op + op2)
테스트를 해보자.
post_math('+', '1', '2')
3
문자열을 그대로 맘대로 합쳐서 그 문자열 자체를 평가
이런 것에 대한 엄청난 효과를 볼 수 있는 것은 리스프 형태일 것 같다.
다음엔 python 리스트 형태 언어인 hy로도 조금씩 적어봐야겠다.

2017년 7월 4일 화요일

Extra Long Factorials python3

사실 푼 것도 아님. 그런데 너무 빨라서... 널 쓸 수 밖에 없었단다...
#!/bin/python3
import sys
from math import factorial

n = int(input().strip())

print(factorial(n))

2017년 7월 1일 토요일

[python][트리] 백준 알고리즘 1991번

테스트를 위해 인풋을 파일로 만들었음.
할일
  1. 파일을 읽어온다.
  2. 파일을 정재하여 리스트에 넣는다.
  3. 간단한 트리구조로 변환할 함수를 만든다
  4. 트리의 루트를 글로벌로 하나 생성한다.
  5. 트리구조의 리스트로 변환한다
  6. 전위, 후위, 중위 탐색을 함수를 만든다.
  7. 출력한다.
1. 파일을 읽어온다. 2. 파일을 정재하여 리스트에 넣는다.
def readFile(filename):
  with open(filename) as file:
    return [ x.strip('\n').replace(' ','') for x in file.readlines()]
list_ = readFile('1991.txt')

3. 간단한 트리구조로 변환할 함수를 만든다. 4. 트리의 루트를 글로벌로 하나 생성한다.
def my_tree(r):
    return [r, [], []]
root = None

5. 트리구조의 리스트로 변환한다.
def add(data, left, right):
    global root
    if root is None:
        if data != '.':
            root = my_tree(data)
        if left != '.':
            root[1] = my_tree(left)
        if right != '.':
            root[2] = my_tree(right)
        return root
    else:
        return search(root, data, left, right)

def search(root, data, left, right):
    if root is None or root == []:
        return root
    elif root[0] == data:
        if left != '.':
            root[1] = my_tree(left)
        if right != '.':
            root[2] = my_tree(right)
        return root
    else:
        search(root[1], data, left, right)
        search(root[2], data, left, right)


for l_ in list_[1:]:
    add(l_[0],l_[1],l_[2])

6. 전위 후위 중위 탐색 함수를 만든다.
def preorder(root):
    if root:
        print(root[0], end='')
        if root[1]:
            preorder(root[1])
        if root[2]:
            preorder(root[2])

def inorder(root):
    if root:
        if root[1]:
            inorder(root[1])
        print(root[0], end='')
        if root[2]:
            inorder(root[2])

def postorder(root):
    if root:
        if root[1]:
            postorder(root[1])
        if root[2]:
            postorder(root[2])
        print(root[0], end='')

7. 출력한다.
preorder(root)
print()
inorder(root)
print()
postorder(root)
print()

2017년 6월 27일 화요일

[hackerrank][java8][clojure] Simple Array Sum

/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scan = new Scanner(System.in);
int[] i_arr = new int[scan.nextInt()];
for(int i = 0 ; i < i_arr.length; i++) 
  i_arr[i] = scan.nextInt();

System.out.println(Arrays.stream(i_arr).sum());
clojure코드도 한번 써봤다
(use '[clojure.string :only (split trim)])

(let [
  n (Integer/parseInt (read-line))
  arr_t (split (read-line) #"\s+") 
  arr (map #(Integer/parseInt %) arr_t)]
  (println (reduce + arr))   
)
비교를하면
Arrays.stream(i_arr).sum()
이것과
(reduce + arr)
이것의 차이

2017년 6월 18일 일요일

[JBoss] 설치 및 배포해보기

JBoss를 사용해보자. 일단 다운로드 여기에서 zip 파일을 다운받자.(필자는 6.4버전을 받았다.)
그리고 압축을 푼다.

압축을 푼 모습, 여기서 standalone 폴더로 들어가보자.

일단 바로 배포를 해보자. 만약
  1. 일단 가지고 있는 AAA.war파일의 압축을 푼다.
  2. standalone폴더 안에 deployments폴더로 들어간다.
  3. AAA.war라는 이름으로 폴더를 만든다.
  4. 그 안에 압축푼 내용을 넣는다.
  5. Jboss 루트 폴더로 돌아가서 bin/standalone.bat 파일을 실행한다.
  6. 아래 처럼 AAA.tar.deployed 라는 파일이 생성되면 배포 완료!


만약 폴더 안에 내용을 바꾸고 재배포를 하고 싶다면?
  1. standalone/deployments 안으로 들어간다.
  2. AAA.war.dodeploy라는 파일을 생성한다.
  3. AAA.war.isdeploying 이라는 파일이 생성될 것이다.
  4. 위 두 파일이 사라지고 AAA.war.deployed만 남는다면 성공!!

2017년 6월 12일 월요일

[JavaScript] 스코프 제대로 알기 - 3

스코프 제대로 알기 - 3

부제: 함수를 이용한 스코프

function myAlert(index) {
   $("#js-scope3-number"+index).click(function() {
      alert("js-scope3-number" + index + " 번을 클릭했습니다.");
    });
}
$(document).ready(function(){
  var len = 3,
       i;
  for (i = 0; i < len; i++) {
   myAlert(i);
  }
});
보면 알 수 있겠지만 함수 안에서는 새로운 스코프가 연결된다. 다르게 해보자
$(document).ready(function(){
  var len = 3,
       i;
  for (i = 0; i < len; i++) {
    (function (index) {
      $("#js-scope3-number"+index).click(function() {
       alert("js-scope3-number" + index + " 번을 클릭했습니다.");
     });
    }(i));
  }
});
관련페이지 http://www.whynam.com/2017/06/javascript.html http://www.whynam.com/2017/06/javascript-2.html

[JavaScript] 스코프 제대로 알기 - 2

스코프 제대로 알기 - 2

부제: with내용 대충하고 넘어가기

var yhnam = {
  name="yhnam"
  blog="www.iamfrom.kr"
  git="ssisksl77"

with (yhnam) {
    console.log(name);
    console.log(blog);
    console.log(git);
}
실행안해봐도 대충 뭔지 알았을 것이다. 블록 안에 해당 객체가 가지고 있는 변수들을 추가한다. 이걸로 이용해서 문제를 해결하자.
var len = 3,
     i;
for (i = 0; i < len; i++) {
  with ({idx: i}){
    $("js-scope2-number"+idx).click(function() {
      alert("js-scope2-number" + idx + " 번을 클릭했습니다.");
    }
  }
}
     
하지만 이렇게 쓰지 말길.. ECMAScript에서 with쓰지말라고 아예 없애버린듯 하다. 관련페이지 http://www.whynam.com/search/label/javascript http://www.whynam.com/2017/06/javascript-3.html

[JavaScript] 스코프 제대로 알기 - 1

스코프 제대로 알기 - 1

스코프를 왜 공부해야하는가.

이런 코드를 짰다.
var len = 3,
     i;
for (i = 0; i < len; i++) {
  $("#number" + i).click(function() {
    alert("number" + i + " 번을 클릭했습니다."); 
  });
}
아래 3개의 버튼이 있다. id는 number0, 1, 2 이다. 이제 이들을 클릭해보자. 어째서 이런 것일까? 왜 number3 번을 클릭했습니다. 만 뜨는 것일까
scope에 대한 이해가 필요한 시점이다. 자바스크립트에서 스코프에 영향을 주는 3가지 요소
  1. function
  2. with
  3. catch
우리는 이 중에서 function을 많이 살펴볼 것이다. with는 많이 쓰지 않는 듯하고...이제 못 쓸것 같다. 관련페이지 http://www.whynam.com/2017/06/javascript-2.html http://www.whynam.com/2017/06/javascript-3.html

2017년 5월 24일 수요일

[python] 파이썬으로 twilio써보기

twilio는 SMS/MMS를 보내는 서비스이다. 모듈을 받아서 바로 그냥 쓰기만 하면 된다.(아니 물론 회원가입을 하고 인증키를 받은 후)
서비스는 아주 잘 되는 것으로 보이나 문제점은 한국에서 지원이 안된다. (아주 치명적이다.)
그래도 어떻게 쓰는지는 한 번 적어놔야겠다.
from __future__ import unicode_literals
from twilio.rest import Client

account_sid = "AC...내가 받은 아이디"
auth_token = "273 내가 받은 인증코드"

client = Client(account_sid, auth_token)

message = client.messages.create(
    body="Hello, I'm Younghwan Nam. I love you All. See you.",
    to="+8210000000",
    from_="+13399999999"  # 발급받은 twilio 번호
    )

print message.sid

2017년 5월 17일 수요일

[java][bitwise] 자바 비트연산에 대해서...

분명 학원에서 비트연산이라는 건 배워본 적이 없다. 연산이라하면 더하기, 빼기, 곱하기, 나누기, 그리고 모드(%) 뿐이었다.
비트연산을 쓴 적은 자바스크립트를 사용할 때 써본적은 있지만 서버에서 써본 적은 없다.(물론 알게 모르게 자바에서 네트워크 통신같은 것을 할 때 쓰고 있을 것이다.)
비트 연산은 나름 중요해 보인다.
알아두고 가끔씩 써봐야 나중에 남이 만든 코드를 보았을 때, 읽을 용기가 생긴다.
그렇지 않으면 "아 난 안되는가보다." 하고 다른 소스를 찾게 되는 자신을 바라보면서 언제까지 이러면 안되겠다는 생각을 했었다.
static void bitwiseTest4() {
  int seven = 7; // 0000 0111
  int nineteen = 19; // 0001 0011

  // & : and 연산
  // 0000 0111
  // 0001 0011
  // ---------
  // 0000 0011 ->  2 + 1 -> 3
  System.out.println(seven & nineteen);

  // | : or 연산
  // 0000 0111
  // 0001 0011
  // ---------
  // 0001 0111 -> 16 + ( 4 + 2 + 1 ) -> 23
  System.out.println(seven | nineteen);

  // ^ : xor 연산
  // 0000 0111
  // 0001 0011
  // ---------
  // 0001 0100 -> 16 + 4 -> 20
  System.out.println(seven ^ nineteen);

  // ~ : 보수(반전)
  // 0000 0111 -> 1111 1000 -> 1(부호) 111 0000 -> -128 + 64 + 32 + 16 + 8 ->
  System.out.println(-128 + 64 + 32 + 16 + 8);
  System.out.println(~seven);
}

output: 
3
23
20
-8
-8
이걸로 뭘 할 수 있을까? 그건 나중에 알아보기로 해야겠다. 일단 시프트 연산부터 정리를 해야겠다.
시프트 연산은 비트들을 왼쪽 오른쪽으로 움직이면서 노는 것이다. 처음에는 이게 뭐지 싶지만 익숙해지면 괜찮을 것이다. (아마 그럴 것이다. 나는 초보니까 익숙하지 않다.)
static void bitwiseTest5() {
  //시프트 연산
  int ten = 10; // 0000 1010
  int m_ten = -10; // 1
  System.out.println(Integer.toBinaryString(ten));
  System.out.println(Integer.toBinaryString(m_ten));
  // signed right shift : 오른쪽으로 한칸 이동 이전 맨 왼쪽의 숫자에 따라 새로 생성되는 숫자가 정해진다
  // ten : 0000 1010 -> 0000 0101 -> 5
  // m_ten : 1111 0110 -> 1111 1011 -> -1 - 4 = -5
  System.out.print((ten >> 1) + " " + (m_ten >> 1) + "\n");
  // unsigned right shift : 맨 왼쪽 숫자에 상관없이 0으로 통일한다
  // ten : 0000 1010 -> 0000 0101 -> 5
  // m_ten : 1111 1111 1111 1111 1111 1111 1111 0110 -> 0111 1111 1111 1111 1111 1111 1111 1011
  // -> 2147483647(Integer 최대값) - 4 -> 2147483643
  System.out.print((ten >>> 1) + " " + (m_ten >>> 1) + "\n");
  // left shift : 왼쪽으로 이동하는 것이다 right shift의 반대라고 생각하면 된다.
  // 여기서 주목해야 할 점은 right shift는 2배로 줄어들고 left shift는 2배로 커진다는 것이다.(이진수니까 당연한 것이겠지만)
  // 그래서 10번 움직인다면 2의 10승 1024가 곱해진다.
  System.out.print((ten << 10) + " " + (m_ten << 10) + "\n");
  System.out.println((ten << 1) + " " + (m_ten << 1) + "\n");
}