Flask와 Canjs를 이용한 다국어 어플리케이션 토대

canjs와 python flask를 이용한 다국어 어플리케이션 제작을 위한 토대입니다.
Flask 부분은 Matt Wright님의 에서 영감을 얻었습니다.



Flask-Canjs-i18n-Boilerplate 소스



특징

  • Flask/Canjs 연동.
  • 다국어 지원.
  • 사용자 CRUD 구현.
  • 사용자 following/followers 기능 구현.
  • 소셜 네트워크 연결 구현.
  • 페이스북
  • 기타 (TODO)
  • RESTful API 구현.
  • 반응형 웹 디자인.
  • 구글 크롤러 친화적 url('#!').
  • 간편한 개발 문서 제작.(Sphinx)
  • 쉬운 테스팅. (nosetests)
  • 다양한 브라우저 호환 (IE7, IE8, IE9, IE10, Firefox, Chrome, Opera..)
  • 더 많은 기능을 윈하신다면, 함께 만들어 가요! :D


써보기

http://flask-canjs-i18n-boilerplate.ap01.aws.af.cm/



어떻게 동작하나요?

flask-canjs-i18n-boilerplate



환경


클라이언트 사이드

  • Canjs, 클라이언트 사이드 자바스크립트 프레임워크.
  • RequireJS, 자바스크립트 파일•모듈 로더.
  • Initializr, HTML5 템플릿.
  • Bootstrap, 프론트엔드 프레임워크.
  • Bootstrap-ie7, 부트스트랩 3에서 IE7을 지원을 도움.
  • mustache, 템플릿 엔진.
  • i18next, 자바스크립트 다국어 도구.
  • Font Awesome, 크기 변환등 개별화 가능한 백터 아이콘 모음을 제공.
  • typeahead.js, 텍스트 자동 완성 라이브러리.
  • spin.js, 작업중 활동 표시기.
  • Placeholders.js, 자바스크립트를 통해 HTML5의 placeholder 속성을 사용 할 수 있게 함.
  • Jade(pyjade), 파이썬용 Jade 템플릿 엔진 확장.
  • jQuery, 작고 빠르고 유용한 자바스크립트 라이브러리.
  • jQuery BBQ, HTML5 hashchange 이벤트 사용을 도와줌.

서버 사이드

  • Flask, 가벼운 파이썬 프레임워크.
  • Flask-Babel, 플라스크용 다국어 확장.
  • Flask-Gravatar, 플라스크용 그라바타 확장.
  • Flask-Security, 플라스크용 로그인 보안 확장.
  • Flask-Social, Flask-Security에서 Oauth를 지원하는 확장.
  • Flask-Assets, 자바스크립트와 스타일시트를 관리하는 플라스크용 확장.
  • Flask-SQLAlchemy, SQLAlchemy사용을 위한 플라스크용 확장.
  • Flask-WTF, WTForms 통합 확장.
  • Flask-Cache, 캐쉬 사용을 도와주는 플라스크용 확장.
  • Alembic, SQLAlchemy 데이터베이스 마이그레이션 관리 도구.
  • Celery, 분산 메시지 전달 기반의 비동기 작업 queue/job 큐.

디버깅과 테스팅

  • flask-debugtoolbar, django-debug-toolbar를 플라스크 용으로 포팅한 디버깅 툴바.
  • nose, 멋진 파이썬용 테스팅 도구.
  • BusterJS, 자바스크립트 테스팅 도구.

문서 생성

  • Sphinx, 지적이고 아름다운 문서를 만들어주는 도구.
  • JSDoc, 자바스크립트 문서화 도구.


설치


도구 설치

  • virtualenv, 분리된 파이썬 환경을 만들어줍니다.
  • virtualenvwrapper, virtualenv를 보다 편리하게 사용하도록 돕습니다.

프로젝트 복제

$ git clone https://github.com/dorajistyle/flask-canjs-i18n-boilerplate.git
$ cd flask-canjs-i18n-boilerplate.git

프로젝트를 위한 virtualenv 생성

$ mkvirtualenv flask-canjs-i18n-boilerplate

필요 라이브러리 설치

$ pip install -r requirements.txt

데이터베이스 마이그레이션

$ alembic revision --autogenerate -m "Alembic initilized boilerplate tables."
$ alembic upgrade head

관리자 추가

'admin@github.com'와 'password'로 로그인 하시면 됩니다.
$ python manage.py init_user

설정

설정 값을 올바르게 설정해야 합니다.(데이터베이스, 메일, 소셜 네트워크 정보...)

  • application/settings.py엔 서버 사이드 설정이 들어 있습니다.
  • application/frontend/static/js/settings.js엔 클라이언트 사이드 설정이 들어 있습니다.
  • ./alembic.ini엔 alembic설정이 들어있습니다.

번역

  • 서버 사이드 번역(Babel)은 applications/frontend/translations 폴더에 있습니다.
  • 클라이언트 사이드 번역(i18next)은 applications/frontend/static/locales 폴더에 있습니다.

바벨 번역 컴파일

$ python tr_compile.py



사용


어플리케이션 실행

$ python wsgi.py

어플리케이션 프로파일 실행

$ python profile.py

문서 생성

$ python generate_documents.py


정적 폴더 최적화

Nodejs 와 RequireJS가 설치되어 있어야 합니다.
더 자세한 문서를 원하신다면 다음을 클릭하세요. RequireJS Optimizer.
$ optimize_static.sh

테스트

$ nosetests

아래의 테스트 스크립트를 이용하셔도 됩니다.

$ python run_nosetests.py



사용권

Flask-canjs-i18n-boilerplate는 MIT license를 따릅니다.



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

파이썬 flask 개발 문서 만드는데 5분. Sphinx.

문서 작성도 개발의 일환입니다.
개발자는 깔끔한 문서를 만들고 싶지만,
문서 작성에 많은 시간을 들이고 싶지는 않지요.
Sphinx가 바로 그 딜레마를 해결해 주는 도구입니다.


Sphinx로 파이썬 Flask 개발 문서 만들기 순서

  1. Sphinx와 sphinxcontrib-httpdomain를 설치합니다.
    $ pip install sphinx
    $ pip sphinxcontrib-httpdomainproject 폴더에 doc 폴더 생성합니다.
  2. doc 폴더로 갑니다.
  3. sphinx-quickstart를 실행하여 기본 설정을 잡습니다.
    $ sphinx-quickstart
  4. conf.py에 다음을 추가합니다.
    sys.path.append(os.path.abspath('..'))
    # 확장
    extensions = ['sphinx.ext.autodoc',
    'sphinx.ext.intersphinx',
    'sphinxcontrib.autohttp.flask']
    # 테마 (default|basic|sphinxdoc|scrolls|agogo|traditional|nature|haiku|pyramid)
    html_theme = "nature"

    기본으로 제공하는 테마 외에도 내려받거나 직접 만든 테마도 사용 가능합니다.
  5. rst파일을 생성합니다.
    API 예시
    Users
    --------------------------
    .. autoflask:: application.api:create_app()
    :undoc-static:
    # api에 포함시키고 싶지 않은 blueprints.
    :undoc-blueprints:
  6. 문서를 생성합니다.
    $ make html

참고 자료

http://sphinx-doc.org/tutorial.html
http://sphinx-doc.org/theming.html
http://pythonhosted.org/sphinxcontrib-httpdomain/



by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

개발이 끝났다면? NGINX서버와 supervisor를 써서 배포해 봅시다.

NGINX

/etc/nginx/nginx.conf
http {
keepalive_timeout 65;
gzip on;
add_header Cache-Control private;
gzip_static on;
gzip_http_version 1.1;
gzip_proxied expired no-cache no-store private auth;
gzip_disable "MSIE [1-6]\.";
gzip_vary on;
gzip_types application/x-javascript text/css *;

map $http_x_requested_with $nocache {
default 0;
XMLHttpRequest 1;
}

include /etc/nginx/sites-enabled/*;
}

/etc/nginx/sites-available/myapp.conf

server {
listen 80;
server_name _;

root /path/myapp;

access_log /path/myapp/logs/access.log;
error_log /path/myapp/logs/error.log;

proxy_cache_bypass $nocache;
proxy_no_cache $nocache;

location /static {
expires modified +24h;
alias /path/myapp/application/frontend/static-build;
}

location /api/_uploads {
expires modified +24h;
alias /path/myapp/images;
}

location / {
proxy_pass http://127.0.0.1:8000;
proxy_redirect off;

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 30;
proxy_read_timeout 30;
}
}

* static 폴더를 설정할 때 주의 점
root를 사용할 땐 static 폴더의 상위 폴더를 지정하고,
alias를 사용할 땐 static폴더를 지정한다.

Upload file size setting
client_max_body_size

권한이 필요합니다. 오류 해결.
error log.
2013/07/10 18:31:54 [crit] 23626#0: *127 stat() "PATH" failed (13: Permission denied) request: "GET PATH HTTP/1.1", host: "localhost", referrer: "http://localhost/"
chmod 751 PATH
all path in PATH should have access permission.
PATH에 모든 경로에 접근 권한이 필요하다.
예) /home/example/applications/myapp 경로에 접근해야 할 땐.
/ , /home, /home/example, /home/example/application, /home/example/applications/myapp 에 접근 권한이 필요하다.

location 설정
인덱스 파일이 없을때 오류 처리와 디렉토리 목록을 보여준다.
autoindex on;

설정 파일 심볼릭 링크 걸기
ln -s /etc/nginx/sites-available/myapp.conf /etc/nginx/sites-enabled/

Arch Linux 기준 nginx 서버 실행과 정지.
sudo systemctl start nginx
sudo systemctl stop nginx


supervisor

/etc/supervisor.d/myapp.ini
[program:myapp]
command = gunicorn --debug --log-level debug -w 4 -b 127.0.0.1:8000 wsgi:application
; command = twistd web --port 5000 --wsgi wsgi.application
directory = /path/myapp
user = root
autostart=true
autorestart=true
; stdout_logfile=NONE
; stderr_logfile=NONE
; Handy for debugging:
stdout_logfile=/var/log/supervisor/webapp.stdout
stderr_logfile=/var/log/supervisor/webapp.stderr

supervisor 실행법
데몬 실행(테스트를 위해 프론트에서 실행함)
sudo supervisord -n
변경사항을 다시 읽고 업데이트 함.
sudo supervisorctl reread
sudo supervisorctl update
supervisor 실행
sudo supervisorctl start myapp
supervisor 재실행
supervisorctl restart webapp


※ 만약 고정 아이피에서 서비스를 한다면 gunicorn을 실행할 때 localhost가 아닌 고정 아이피 주소(예: gunicorn -b 123.456.789.000:8000)로 실행해야 외부에서 접근이 가능하다.
물론 nginx설정도 그에 맞게 변경해야 한다.

참고 자료



by


Tags : , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

데이터베이스 마이그레이션 관리를 간편하게! alembic.

alembic은 파이썬 SQLAlchemy DB Toolkit과 연동하여 마이그레이션 관리를 돕는 편리한 도구입니다.

프로젝트 폴더로 가서 alembic을 초기화 한다.
alembic init alembic

alembic.ini파일에서 데이터 베이스를 설정해 준다.
sqlalchemy.url = mysql://scott:tiger@localhost/test

마이그레이션을 자동으로 생성하기 위해 다음을 alembic/env.py에 추가한다.
import os, sys
sys.path.append(os.getcwd())
from application import db
target_metadata = db.Model.metadata

* 자동 생성에서는 테이블명이나 컬럼명을 변경한 것은 감지하지 못한다.

다음 커멘드를 이용해 자동으로 마이그레이션을 생성한다.
alembic revision --autogenerate -m "Added account table"

DB를 새 마이그레이션으로 업그레이드 하려면?
alembic upgrade head

원하는 마이그레이션으로 업그레이드 하거나 다운그레이드 하려면?
$ alembic upgrade +2
$ alembic downgrade -1

alembic 튜토리얼



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Canjs와 Flask를 이용한 웹개발 예제

클라이언트 사이드 자바스크립트 프레임워크인 Canjs와
파이썬 마이크로 프레임워크인 Flask를 이용한 웹 어플리케이션 예제입니다.
이 Canjs + Flask 예제가 프레임워크 이해에 도움이 되길 바랍니다.


Canjs + Flask 예제 소스


예제에 사용된 라이브러리

  • Canjs, 클라이언트 사이드 자바스크립트 프레임워크.
  • RequireJS, 자바스크립트 파일•모듈 로더.
  • Initializr, HTML5 템플릿.
  • Bootstrap, 프론트엔드 프레임워크.
  • JSDoc, 자바스크립트 문서화 도구.
  • BusterJS, 자바스크립트 테스팅 도구.
  • mustache, 템플릿 엔진.
  • i18next, 자바스크립트 다국어 도구.
  • Flask, 가벼운 파이썬 프레임워크.
  • Flask-SQLAlchemy, SQLAlchemy의 플라스크 플러그인.
  • Jade(pyjade), 파이썬용 Jade 템플릿 엔진 플러그인.
  • Flask-Babel, 플라스크용 다국어 플러그인.

예제의 이해를 돕는 글



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

잘 짜여진 자바스크립트 MVC 프레임워크. Canjs

Backbone, AngularJS, Spine….
그동안 나왔던 자바스크립트 프레임워크를 조금씩 건드려는 보았지만,
항상 아쉬움이 남았습니다.
이번에 Canjs를 써보니, 정말 잘 만들어진 프레임워크라는 생각이 들어요.
자바스크립트MVC 프레임워크를 써 볼까 생각 중이시라면, Canjs 한번 고려해 보세요.

can.Control

컨트롤러에서 이벤트 처리

"li .destroy {Event.destroy}": function( el, event) {
var todo = el.closet('li').data('todo);
todo.destroy();
event.stopPropagation();}
});
Events = {destroy : "click"};

css Selector, html.getElementBy, $(selector)가 Control의 셀렉터로 사용된다.

When the element your Control is bound to is removed from the DOM,
the Control destroys itself, cleaning up any bound event handlers.

can.Control 이 아는 이벤트.
* change
* click
* contextmenu
* dblclick
* focusin
* focusout
* keydown
* keyup
* keypress
* mousedown
* mouseenter
* mouseleave
* mousemove
* mouseout
* mouseover
* mouseup
* reset
* resize
* scroll
* select
* submit

링크 처리 방법(How can I make a link in Canjs?)

레이어(layer)
<a id="id" href="javascript://">href</a>

페이지(page)
<a id="id" href="#!id">href</a>

무스타치에서 콜백 받기(Mustache Element Callback)

{{data 'model'}}

경로 설정(RequireJS Paths)

requireJS can require is /can
requireJS에서 canJS를 쓸 땐 can.js를 패스로 잡고 사용해야 한다.
registerHelper이용을 위해서는 can/view/mustache가 필요하다.

404루트 잡기(How to define a catch all route to handle 404 in can js?)

http://stackoverflow.com/questions/13824665/how-to-define-a-catch-all-route-to-handle-404-in-can-js

can.route.bind('change', function(ev, newVal) {
if (newVal === 'route') {
var valid = false;
$.each(can.route.routes, function(k,v) {
if (new RegExp(v.test).test(window.location.hash)){
valid = true;
return; //exit loop
}
})
if (!valid) {
//handle the false route here
}
}
});

다국어 지원(Localization)

Localization is a good example of a custom helper you might implement in your application. The below example takes a given key and returns the localized value using jQuery Globalize.

1. Mustache.registerHelper('l10n', function(str, options){
2. return Globalize != undefined
3. ? Globalize.localize(str)
4. : str;
5. });

can.route에서 i18next 데이터를 받아오지 못할 때

can.when을 이용하여 초기화가 된 후 can라우팅 처리를 해 준다.


var lang =utils.getParam('lang');
var i18noption = {debug: true};
lang != undefined
? i18n
option.lng = lang
: i18n_option.lng = "en";
can.when(i18n.init(i18n_option)).then(function (){});

모델 관계(model associations)

https://forum.javascriptmvc.com/topic/questions-about-model-associations

<div class="header">
<h1>Association</h1>
</div>
<!-- YOUR CODE HERE -->
<div id="contacts"></div>

can.fixture("/contacts.json", function(){
return [{
'id': 1,
'name' : 'Justin Meyer',
'birthday': '1982-10-20',
tasks : [{
id: 1,
title: "write up model layer",
due: "2010-10-5"
}]},{
'id': 2,
'name' : 'Brian Moschel',
'birthday': '1983-11-10',
tasks : [{
id: 2,
title: "write up funcunit",
due: "2009-5-1"
},{
id: 3,
title: "test funcunit",
due: "2010-3-15"}]
},{
'id': 3,
'name' : 'Bobby Joe',
'birthday': '1980-2-10'
}];
})

can.Model.convert.date = function(raw){
if(typeof raw == 'string'){
var matches = raw.match(/(\d+)-(\d+)-(\d+)/);
return new Date( +matches[1],
(+matches[2])-1,
+matches[3] );
}else if(raw instanceof Date){
return raw;
}
};

// A task model that has a date
can.Model("Task",{
attributes : {
due : 'date',
}
},{
weeksPastDue : function(){
return Math.round( (new Date() - this.due) /
(1000*60*60*24*7 ) );
}
});

// A contact model that has many tasks
can.Model("Contact",{
attributes : {
birthday : 'date',
tasks: "Task.models"
},
findAll : "/contacts.json"
},{
ageThisYear : function(){
return new Date().getFullYear() -
this.birthday.getFullYear()
},
getBirthday : function(){
return ""+this.birthday.getFullYear()+
"-"+(this.birthday.getMonth()+1)+
"-"+this.birthday.getDate();
}
});

// Get all contacts and put them on the page
Contact.findAll({},function(contacts){
var contactsEl = can.$('#contacts');

can.each(contacts, function(contact){
var li = can.$('<li>')
.html(contact.name + " "+ contact.ageThisYear())
.appendTo(contactsEl);

var ul = can.$("<ul>");
var tasks = contact.attr('tasks')

if(tasks){
tasks.each(function(){
this.attr('contact', contact);
ul.append('<li>'+this.title+" "
+this.weeksPastDue()+' contact: '+ this.attr('contact.name') +'</li>')
});
}

ul.appendTo(li)
});
});

 

Canjs 웹사이트



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Javascript 모듈 관리엔 RequireJS

자바스크립트 모듈이 많아 관리가 어렵다면, RequireJS를 사용 해 보세요.

설정(Configuration)


require.config({
"baseUrl": "/static/js/vendor",
"paths": {
"app": "../app",
"bootstrap": [
'//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min',
"bootstrap"
],
"jquery": [
"//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min",
"jquery-1.9.1.min"
],
"can": "can",
shim: {
"bootstrap": {
deps: ["jquery"],
exports: "$.fn.popover"
},
enforceDefine: true
}
}
});

모듈 정의(define function)


define(["jquery"],function($){
return {
getParam: function(paramname){
var value = new RegExp('[\?&]' + param
name + '=([^&#]*)').exec(window.location.href);
return value[1];
},
test: function(text){
console.log("test : "+text);
}
};
});

두 모듈을 한 파일에 넣는 방법(requirejs, two classes in one file)

http://stackoverflow.com/questions/9806940/requirejs-two-classes-in-one-file

define('test', ['jquery'], function() {
var exports = {};
exports.test1 = {
method1 : function () {
console.log("test1 - method 1");
},
method2 : function () {
console.log("test1 - method 2");
}
};
exports.test2 = {
method1 : function () {
console.log("test2 - method 1");
},
method2 : function () {
console.log("test2 - method 2");
}
};

return exports;
});

그리고 아래처럼 사용하면 된다.
require(['test'], function (test) {
var test1 = test.test1;
});

두 모듈을 한 파일에 넣는 다른 방법
http://blog.credera.com/topic/technology-solutions/java/modular-javascript-with-requirejs


define(['json!data/customers'], function(customers){
var getRow = function(id) {
return customers[id];
};

var getAll = function() {
return customers;
};

var update = function(data) {
// do something cool with the data
};
return {
get: getRow,
list: getAll,
update: update
};
});


오류 해결

  • Jquery CDN경로가 올바르지 못할 경우 Bootstrap로딩에 오류가 난다.
  • 같은 모듈(예: bootstrap)이 중복 로드될 경우 충돌이 일어난다.

RequireJS 홈페이지



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

유용한 javascript 예제와 팁

URL 파라메터 받아오기(get PARAM)

http://www.codetreat.com/get-url-parameters-values-with-javascript

$.params = function(paramname){
var value = new RegExp('[\?&]' + param
name + '=([^&#]*)').exec(window.location.href);
return value[1];
}

Jquery 셀렉터 성능(JQUERY SELECTOR Performance)

http://jsperf.com/selectors-perf/6
cssSelector는 id 나 element와 함께 쓰지 않고 단독으로 사용한다.


var obj = document.getElementById("childDiv");
xxx = obj.getElementsByClassName("txtClass");

 

이벤트 처리

preventDefault() : 이벤트의 기본 행동을 막는다.
If this method is called, the default action of the event will not be triggered.
stopPropagation() : 상위 핸들러로 이벤트를 넘기지 않도록 막는다.
Prevents the event from bubbling up the DOM tree,
preventing any parent handlers from being notified of the event.

prepend() - 앞쪽에 내용을 붙인다.(to attach content as a prefix.)
append() - 뒷쪽에 내용을 붙인다. (to attach content as a suffix.)

배열 요소에서 데이터를 받고 싶을 땐 $()로 한번 더 감싼다.
$($(array_selector)[0]).data(something);


두번 submit되는 문제(prevent submit twice)
onclick이벤트 보다는 onsubmit 이벤트를 사용한다.
http://stackoverflow.com/questions/2830542/prevent-double-submission-of-forms-in-jquery

this.element.find('.save').attr('disabled','disabled');

// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function() {
$(this).bind('submit',function(e){
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
// Keep chainability
return this;
};


JSON

Object to String
JSON.stringify(obj);
Parse JSON response
JSON.parse(obj);

JSON.parse()사용시 오류 : Uncaught SyntaxError: Unexpected token o
http://stackoverflow.com/questions/8081701/i-keep-getting-uncaught-syntaxerror-unexpected-token-o
데이터형이 올바르지 않아서 나는 오류이다.
Looks like jQuery takes a guess about the datatype.
It does the JSON parsing even though you're not calling getJSON()--
then when you try to call JSON.parse() on an object, you're getting the error.


loglevel

https://github.com/pimterry/loglevel
원하는 레벨의 로그를 콘솔 메시지로 보낸다.
켜고 끄는 것이 편리하다.
log.enableAll() and log.disableAll() methods.
* log.trace(msg)
* log.debug(msg)
* log.info(msg)
* log.warn(msg)
* log.error(msg)


JavaScript 디버깅

chrome dev tool -> Settings -> General -> Disable cache
Timeline을 이용하면 어떤 코드가 어플리케이션에 부하를 주는지 찾아준다.
메모리 누수가 발생한다면 찾아 개선한다.
Profiles도구에서 Heap Snapshot을 두 개 만들어 comparison view로 비교하면 성능 저하 원인을 찾기 편하다.



by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

자바스크립트용 개발 문서 작성기. JSDOC

주석 달기


/** define namespace
* @namespace category
*/

/** use namespace with hash
* @name category#name
* @constructor
*/

/** use member of for constructor
*@memberof category#name
*/


설정(configuration)

remove all comments.
// You must remove the comments before adding these options to your .json file

{
"tags":{
"allowUnknownTags":true
},
"source":{
"include":[],
"exclude":[],
"includePattern":".+\.js(doc)?$",
"excludePattern":"(^|\/|\\)_"
},
"plugins":[],
"templates":{
"cleverLinks":false,
"monospaceLinks":false
},
"opts":{
"template":"default", // same as -t default
"encoding":"utf8", // same as -e utf8
"destination":"./out/", // same as -d ./out/
"recurse":true, // same as -r
"tutorials":"path/to/tutorials",// same as -u path/to/tutorials, default "" (no tutorials)
"query":"value", // same as -q value, default "" (no query)
"private":true, // same as -p
"lenient":true, // same as -l
// these can also be included, though you probably wouldn't bother
// putting these in conf.json rather than the command line as they cause
// JSDoc not to produce documentation.
"version":true, // same as --version or -v
"explain":true, // same as -X
"test":true, // same as -T
"help":true, // same as --help or -h
"verbose":true, // same as --verbose, only relevant to tests.
"match":"value", // same as --match value, only relevant to tests.
"nocolor":true // same as --nocolor, only relevant to tests
}
}


실행
jsdoc -c conf.json

JSDOC github



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

파이썬 Flask 플러그인 안내와 팁.

데이터베이스
Flask-SQLAlchemy : OR매핑을 지원하는 플라스크용 파이썬 SQL toolkit
SQLAlchemy에서 상속(Inheritance) : http://docs.sqlalchemy.org/en/rel_0_7/orm/inheritance.html

SQLAlchemy 컬럼에 데이터가 생성될때나 업데이트 될때 현재 시각을 자동으로 넣는 방법.
updated_at = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now())

로그인·보안
Flask-Social : 소셜 네트워크와의 연결을 간편하게 해 줌.
Flask Security(Auth) : 로그인과 권한관리.

관리자 페이지
Flask-Admin : 관리자 페이지를 손쉽게 만들도록 도와줌.

다국어 지원
Flask-Babel : 파이썬용 다국어 지원 Babel의 Flask 플러그인

캐쉬
flask-cache : 캐쉬 설정을 도와줌.

에셋 관리
flask-assets : 각종 static 에셋 관리를 편하게 도와줌.
사용하고자 하는 기능에 따라 추가 모듈이 필요하다. (css 압축, scss사용)
pip install cssmin
pip install pyscss
Flask-Assets extension에서 pyScss컴파일러 사용 설정법

from flask import Flask, render_template
from flask.ext.assets import Environment, Bundle

app = Flask(__name__)

assets = Environment(app)
assets.url = app.static_url_path
scss = Bundle('foo.scss', 'bar.scss', filters='pyscss', output='all.css')
assets.register('scss_all', scss)
And in the template include this:

{% assets "scss_all" %}
{% endassets %}

SCSS file은 debug모드에서도 컴파일 된다.

캐쉬
Flask-Cache : 플라스크에서 캐쉬 사용 하기 쉽게 도와줌.
# Flask-Cache Cache Type
CACHE_TYPE = 'simple' # 개발 시
CACHE_TYPE = 'redis' # 배포 시. redis 서버 구동 필요.
from flask.ext.cache import Cache

app = Flask(__name__)
cache = Cache()
cache.init_app(app, config={'CACHE_TYPE': CACHE_TYPE})

파일 업로드
Flask-Uploads : 파일 업로드 관련 처리를 도와줌.
from flask.ext.uploads import UploadSet
images = UploadSet()
images.__init__('upload', IMAGES)
filename = images.save(files, folder='/images', name='test.')
image_path = images.path(filename)
url = images.url(thumbnail)

텍스트 검색
Flask-WhooshAlchemy : 텍스트 기반 검색을 쉽게 도와줌

오류 추적
flask-exceptional : 오류 추적 서비스인 exceptional를 flask에서 이용 가능하게 도와줌.

전자상거래(e-commerce) [flask용 extension 아님]
stripe : 결제 모듈을 간편하게 시스템에 붙이도록 도와주는 서비스.
satchmoproject : 오픈소스 전자 상점 프레임워크 (satchmo Wiki)
satchless : 프레임워크에 종속적이지 않은 e-commerce용 클래스와 패턴 모음
flamaster : flask용 e-commerce eventing 시스템

Flask에서 JSON 다루기(JSON Handling in Flask)
http://flask.pocoo.org/docs/api/#module-flask.json

import requests
r = requests.get(QUERY_URL)
return r.json
//normal return
return jsonify(username=g.user.username,
email=g.user.email,id=g.user.id)

jsonify a SQLAlchemy result set in Flask
http://stackoverflow.com/questions/7102754/jsonify-a-sqlalchemy-result-set-in-flask
jsonify의 문제는 object가 자동으로 json화 되지 않는다는 것이다.
serialize를 위해 다음을 모델에 추가 해 준다.


def dump_datetime(value):
"""Deserialize datetime object into string form for JSON processing."""
if value is None:
return None
return [value.strftime("%Y-%m-%d"), value.strftime("%H:%M:%S")]

class Foo(db.Model):
//... SQLAlchemy defs here..
def __init__(self, ...):
//self.foo = ...
pass
@property
def serialize(self):
"""Return object data in easily serializeable format"""
return {
'id' : self.id,
'modified_at': dump_datetime(self.modified_at),
# This is an example how to deal with Many2Many relations
'many2many' : self.serialize_many2many
}
@property
def serialize_many2many(self):
"""
Return object's relations in easily serializeable format.
NB! Calls many2many's serialize property.
"""
return [ item.serialize for item in self.many2many]

뷰에서는 아래처럼 사용한다.

return jsonify(json_list=[i.serialize for i in qryresult.all()])

gunicorn서버 사용 설정.

from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)

if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run()

Blueprint
routing관리에 이용한다.
application/feedback 폴더에 모듈을 넣을 경우.

from flask import Blueprint
mod = Blueprint('root', __name__, url_prefix='') // prefix를 공란으로 두면 root를 의미한다.
mod = Blueprint('feedback', __name__, url_prefix='/feedbacks') // prefix를 채우면 route('/')가 해당 prefix와 같다.
@mod.route('/')

새로운 디렉토리를 만들고 __init__.py파일을 추가해야 import시 인식한다.

모듈을 사용하려면 어플리케이션에서 등록해 준다.

from application.feedback.views import mod as feedbacksModule
app.register_blueprint(feedbacksModule)

파일 여러개 올리기(Uploading multiple files with Flask)
http://stackoverflow.com/questions/11817182/uploading-multiple-files-with-flask


@app.route("/upload", methods=["POST"])
def upload():
uploadedfiles = flask.request.files.getlist("file[]")
print uploadedfiles
return ""

동적으로 생성된 이미지 파일의 url 받기(How to get url for dynamically generated image file?)
http://stackoverflow.com/questions/12034949/flask-how-to-get-url-for-dynamically-generated-image-file

@app.route("/imgs/")
def images(path):
generateimg(path)
fullpath = "./imgs/" + path
resp = flask.makeresponse(open(fullpath).read())
resp.content_type = "image/jpeg"
return resp

mydomain.com/static/test.jpg

from flask import Flask, redirect, url_for

app = Flask(__name__)
@app.route('/')
def index():
generate_img("test.jpg"); #save inside static folder
return '<img src=' + url_for('static',filename='test.jpg') + '>'

Jade
두개의 속성을 지정할 땐 콤마(,)를 잊지 않는다.

script(data-main='js/app', src='js/vendor/require.js')



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

블로그 글 찾아보기를 편리하게! 월풍서가(月風書架)

블로그를 시작한 지 꽤 오랜 시간이 흘렀습니다.
가끔 예전에 쓴 글을 보고 싶은데, 글 제목이 생각 안 날 때가 있더라고요.
그래서 페이지를 하나 만들었습니다.
월풍서가(月風書架)
분류별로 글을 정리해 월풍도원 블로그 글을 찾아보기 쉽게 하기 위함입니다.
우선 책 감상평만 정리하였지만,
나머지 부분도 체계적으로 정리해 나갈 생각입니다.

오래전 글을 다시 읽는 재미가 쏠쏠합니다.
‘그 땐 저런 생각을 하고 살았구나.’
‘저건 불과 반 년 전인데도 낯설구나.’
이렇게 저를 돌아보며 블로그를 계속 써온 것에 뿌듯함을 느꼈어요.
월풍서가(月風書架)'
저에겐 지난날을 곱씹는 반추의 공간으로,
블로그를 찾으시는 분들께는 편리한 정보 검색 공간이 되게 하겠습니다.

저의 블로그를 찾아주셔서 고맙습니다.



by


Tags : , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

생소한 맥. OS X에 익숙해지기.

최근에 맥(Mac)을 써볼 기회가 있었습니다.
익숙하지 않은 환경이라 생소했어요.
그렇지만 조금 만지다 보니 금방 익숙해집니다.
다음에 또 맥을 쓰게 되면 참고하려고 사용환경을 정리해봤어요.

유용한 앱

일반
Plain Text : 리치 텍스트를 일반 텍스트로 변환할 때 씁니다.
Textwrangler(http://www.barebones.com/products/textwrangler/) : 가벼운 코드 편집과 텍스트 편집에 씁니다.
Degrees : 메뉴바에 표시되는 날씨 앱입니다.
Chrome : 웹 브라우져 입니다.
Evernote(https://evernote.com) : 메모할 때 좋습니다.
CheatSheet(http://www.cheatsheetapp.com/CheatSheet/) : 맥 단축키를 익히기 좋습니다.
Vox MP3 player(https://www.macupdate.com/app/mac/24852/vox) : MP3플레이어로 메뉴바에 플레이 버튼이 생겨 좋습니다.
Alfred(http://www.alfredapp.com/) : 빠른실행, 검색등 다양한 기능을 담은 유틸리티입니다.
Dropbox(https://www.dropbox.com/) : 파일 저장을 위한 클라우드 서비스입니다.
uTorrent(http://www.utorrent.com/intl/ko/downloads/mac) : 토렌트 클라이언트 입니다.

개발
JSRef : CSS / HTML5 / Javascript 사전입니다.
Pycharm : 파이썬 개발도구입니다.
Iterm(http://www.iterm2.com/#/section/home) : 맥용 터미널 입니다.
Xcode : 맥용 개발 도구 모음입니다.
MariaDB(https://mariadb.org/en/) : 오픈소스 데이터베이스입니다.
Mysql Workbench(http://www.mysql.com/products/workbench/) : Mysql에서 제공하는 데이터베이스 설계 도구입니다.
homebrew(http://mxcl.github.io/homebrew/) : 패키지 설치를 쉽게 도와줍니다.
홈브루 설치법 : ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"
홈브루 패키지 정보 업데이트 : Brew update formula
홈브루 업데이트 : brew update
홈브루에서 파이썬 설치(https://github.com/mxcl/homebrew/wiki/Homebrew-and-Python) : brew install python
홈브루에서 마리아db 설치 : brew install mariadb

단축키

fn + ↑ : Page Up
fn + ↓ : Page Down
fn + ← : Home
fn + → : End
fn + delete : windows del키
Option(alt) + enter : 한자
Command + Option + ESC : 강제 종료
Command+Shift+3 : 캡쳐 파일 저장
Command+Ctrl+3 : 클립보드로 저장
Command+Shift+4 : 영역 지정 캡쳐
Command+Ctrl+4 : 어플리케이션 윈도우 캡쳐

Finder
Command+Shift+N : 새 폴더
Command+Shift+G : 폴더로 이동

사전
Command+Ctrl+D : 사전에서 찾기.(커서를 원하는 텍스트에 두고 누른다. 크롬등의 웹 브라우져에서도 지원한다.)
* 추가할 사전이 있을 때 : /Library/Dictionaries 에 압축 해제

사용자 정의 단축키 설정
automator -> service -> utility -> run shell script
명령어 입력후 키보드 서비스 단축키 설정

기타 팁

맥 부팅 소리 끄기
sudo nvram SystemAudioVolume=%80
맥 부팅 소리 켜기
sudo nvram -d SystemAudioVolume

맥에서 패스 잡기
모든 유저에게 적용할 땐 /etc/paths에,
단일 사용자에 정용할 땐 ~User/.bash_profile에 아래를 추가해 준다.
PATH=$PATH:/my/new/path/
(http://blog.just2us.com/2011/05/setting-path-variable-in-mac-permanently/)

맥 초기화
맥 전원을 끈다.
맥 전원을 켠 후 Command+R키를 누른다.
OS X를 재설치 한다.

맥에서 파이참 디렉토리 위치
/Users/dorajistyle/Library/Preferences/PyCharm20



by


Tags : , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

구글 블로거와 궁합이 맞는 광고. 구글 애드센스.


2011년 말에 제 블로그에서 광고를 지웠었어요.
블로그를 찾아주시는 분들의 가독성을 해치고 싶지 않았기 때문입니다.
대신 기부코너를 만들었었죠.
이번에 다시 광고를 단 건, 요즘 생활이 어려워서입니다.^^;
비록 구글 애드센스 수익이 얼마 되진 않지만, 한 달에 밥 한 끼도 아쉬운 요즘이라 그렇습니다.

구글 애드센스와 블로거의 만남-'시리아 팔미라'

구글 블로거에 애드센스 다는 방법

구글 블로거는 애드센스와 연동이 잘되어 있습니다.

  1. 구글 블로거 내 블로그 메뉴로 갑니다.
  2. 수익 > 내 블로그에 광고 보이기 체크박스에 '예'라고 선택만 하면 광고가 바로 나옵니다.
  3. 물론 애드센스 계정은 가지고 있어야 합니다.
  4. 광고 스타일은 레이아웃에서 변경합니다.

블로그 광고 수익이 아쉽지 않을 정도의 형편이 되면,
구글 애드센스 광고를 내리도록 하겠습니다.:D

꾸준히 월풍도원을 찾아주셔서 고맙습니다.
행복하세요!



by


Tags : , , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

리눅스 환경에 발을 담그다. Arch 리눅스.

오래도록 MS 윈도우를 사용했습니다.
개발자로서 조금은 리눅스를 만질 일이 있었지만,
그야말로 수박 겉핥기였지요.
리눅스를 좀 잘 다뤄보고 싶었습니다.
하지만 공부를 해 볼까 버츄얼 머신에 리눅스를 깔아도, 사용 안 하게 되더라고요.
6년 전엔 큰마음 먹고 노트북에 윈도우 대신 Gentoo를 설치해 보았습니다.
데이터 백업도 안 하고 설치를 하다가 파티션을 잘못 건드려서 모든 자료가 다 날갔었지요.
게다가 일주일 동안 씨름을 했는데도, 그래픽인지 사운든지 드라이버를 하나 못 잡아서 결국 포기했던 기억이 납니다.

이번에 리눅스를 주 OS로 사용하기로 마음먹었을 때 Gentoo의 악몽이 되살아났어요.
설치와 유지 보수가 간편한 리눅스를 사용하기로 마음먹었죠.
설정이 복잡하거나 너무 마이너한 배포판은 설치하지 않기로 했습니다.

디스트로 와치(http://distrowatch.com/dwres.php?resource=popularity)를 참고하여 제게 맞는 배포판을 탐색했어요.

Mint가 가장 인기가 좋았지만 별로 내키지 않았고, Arch 가 눈에 들어왔습니다.
새로운 버전이 나왔을 때 통째로 갈아엎을 필요가 없이,
Pacman을 이용해 업데이트가 유연하게 된다는 점이 특히 마음에 들었지요.
그런데 설정에 너무 많은 시간을 쏟기는 싫었습니다.
그러다 발견한 게 만자로(Manjaro)에요.
사용자 편의에 초점을 맞춘 Arch 기반의 리눅스 배포판입니다.
Cinnamon 데스크을 넣은 Cinnarch도 괜찮아 보였지만, 만자로에 더 끌렸어요.
만자로(Manjaro)를 설치하고 두 달가량 사용을 하고 있는데 아주 만족스럽습니다.
물론 윈도우를 쓰다가 넘어왔으니 불편한 점이 많아요.
윈도우에서 주로 쓰던 소프트웨어와 대응되는 애플리케이션도 찾아야 했고,
각종 설정을 하는데도 많은 시간이 들었지요.
적응 기간 윈도우를 사용할 때보다 불편했지만, 지금은 딱히 그렇지도 않습니다.
앞으로도 리눅스를 쭉 쓰려고 해요.
나중에 좀 익숙해지면 개발에도 참여해 보고 싶습니다.

U43F with 리눅스 시스템 -'Arch linux(Manjaro)'

만자로(manjaro)리눅스를 쓰며 메모한 것들을 정리해 보았습니다.

USB 부팅 디스크 만들기

pendrivelinux.com

manjaro 설치

http://wiki.manjaro.org/index.php/Burn_an_ISO_File
http://wiki.manjaro.org/index.php/Installation_to_SSD_(quick_guide)
GRUB에서 e누른후 linux 라인에 cryptdevice를 추가해준다.
http://wiki.debian.org/SSDoptimization
https://wiki.archlinux.org/index.php/Solid_State_Drives
https://wiki.archlinux.org/index.php/Using_DM-Crypt#GRUB2
http://wiki.manjaro.org/index.php/Installation_Guide_for_Experienced_Users_0.8.2
LVM(Logical Volume Manager) 설정
https://wiki.archlinux.org/index.php/LVM

설정

커널 업데이트
http://wiki.manjaro.org/index.php/Manjaro_Kernels
커널 목록 보기
mhwd-kernel -li
커널 업데이트 하며 오래된 커널 지우기
sudo mhwd-kernel -i linux310 rmc

미러 자동 추가
pacman -S reflector
https://wiki.archlinux.org/index.php/Reflector
reflector --verbose -l 5 --sort rate --save /etc/pacman.d/mirrorlist

grub
yaourt -S grub-customizer

로케일
http://manjaro.org/2012/08/22/change-to-your-personal-locales/

커널 버젼 보기
cat /proc/version
pacman -S base-devel 로 devel 도구 설치
pacman -Syu base-devel linux-headers
pacman -Syu base-devel linux37-headers

서비스 설정
https://wiki.archlinux.org/index.php/Systemd#Basic_systemctl_usage

그래픽 카드
https://wiki.archlinux.org/index.php/Bumblebee
https://github.com/Bumblebee-Project/Bumblebee/wiki/Troubleshooting
/etc/bumblebee/xorg.conf.nvidia
한영키 먹게 하려면
Section "ServerLayout"
Identifier "Layout0"
Option "AutoAddDevices" "true"
EndSection

듀얼 모니터
https://wiki.archlinux.org/index.php/Xorg#Multiple_monitors.2FDual_screen
https://wiki.archlinux.org/index.php/DualScreen
xrandr --output LVDS1 --mode 1366x768 --output HDMI1 --mode 1920x1080 --right-of LVDS1

사운드
pacman -S lib32-alsa-lib
pacman -S lib32-libxml2

유선 인터넷
ifconfig로 인터넷 연결 확인
http://www.linuxfoundation.org/collaborate/workgroups/networking/alx에서 alx 드라이버 받음.(compat)

./scripts/driver-select alx
make
sudo make install
modprobe alx

혹은
sudo yaourt -S dkms-alx

무선 인터넷 관리자 Wicd로 변경
https://wiki.archlinux.org/index.php/Wicd

Before installing WICD I run these commands.
sudo systemctl stop netcfg
sudo systemctl stop dhcpcd
sudo systemctl stop NetworkManager
sudo systemctl stop netctl
sudo systemctl disable dhcpcd.service

After install
systemctl start wicd
systemctl enable wicd.service
gpasswd -a USERNAME users

sudo systemctl disable NetworkManager

rm /var/lib/NetworkManager/NetworkManager.state

블루투스 헤드셋 설치
https://wiki.archlinux.org/index.php/Bluetooth#Headset_and_Alsa_Devices
https://wiki.archlinux.org/index.php/Bluetooth_Headset
sudo hciconfig hci0 voice 0x0060
sudo pacman -S PulseAudio

블루투스 키보드
blueman에서 설정.
키보드에서 블루투스 신호를 보내고 잡아야 한다.

키맵이 이상하게 나오면 블루투스 키보드 연결을 해제하고,
노트북 키보드로 키맵 설정을 고정시킨다.
xmodmap -pke > ~/.Xmodmap
xmodmap ~/.Xmodmap


시작할 때 적용하려면?
~/.xprofile
~/.xinitrc
if [ -s ~/.Xmodmap ]; then
xmodmap ~/.Xmodmap
fi


https://wiki.archlinux.org/index.php/Xmodmap

exfat 마운트
pacman -S fuse-exfat exfat-utils

메모리카드 리더
1. Follow this link to know the exact model of your card reader. mine was RealTek smth smth.
and the output before the solution was like this:
03:00.0 Unassigned class [ff00]: Realtek Semiconductor Co., Ltd. RTS5229 PCI Express Card Reader (rev 01)
2. Download the suitable driver from this site:
http://www.realtek.com/Downloads/downloadsView.aspx?Langid=1&PNid=15&PFid=25&Level=4&Conn=3&DownTypeID=3&GetDown=false
3. Extract the zipped archive, then again extract the tar archive, then cd into the final directory, open the reademe file and follow the instructions.
4. After reboot, it simply worked :)
5. Note that I didn't notice a change in the output after the solution.
!not work sudo yaourt -S rts5229
원문(http://askubuntu.com/questions/20100/how-can-i-find-out-what-kind-of-card-reader-i-have)

xfce 설정
xfce4-settings-manager
윈도우 메니져에서 윈도우 관련 키 설정 가능하다.

저장된 세션 지우기
~/.cache/sessions/xfce4 를 삭제한다.

Chromium에서 Keyring을 자꾸 물어볼 때
https://wiki.archlinux.org/index.php/GNOME_Keyring

업데이트시 문제 해결

Unable to lock database가 날 때
sudo rm /var/lib/pacman/db.lck
http://wiki.manjaro.org/index.php/Pacman_troubleshooting

kalu나 package-query가 더 낮은 버전이 필요하다고 업데이트가 안 될때.
pacman -Syu
Do you want to cancel the current operation
:: and upgrade these packages now?
에 No라고 대답한다.

시스템 업그레이드시 package-query와 pacman이 충돌할 때
sudo pacman -R yaourt
sudo pacman -R package-query
then sudo pacman -Syyu
mv /etc/pacman.conf /etc/pacman.conf.backup # just in case
mv /etc/pacman.conf.pacnew /etc/pacman.conf

실행 파일 만들기 (batch)
#!/bin/sh
command
...
chmod +x

시작시 자동실행
gedit /etc/rc.local로 파일을 열어서 스크립트를 추가해 준다.

소프트웨어 설치

팩맨(Pacman)

설치
pacman -S 패키지 ( packer -S 패키지)

삭제
pacman -R 패키지

커맨드가 익숙치 않은 사용자를 위한 gui툴 소개
gtkpacman (AUR)

팩맨 미러
/etc/pacman.d/mirrorlis 파일을 수정

설치 가능한 패키지 목록 보기
$ pacman -Ss ^ibus-*

최적화 (안쓰는 패키지 삭제)
sudo pacman -Rns $(pacman -Qqtd)
Clean cache
pacman -Sc
pacman -Qdt

Yaourt (Yet AnOther User Repository Tool)

pacman -S yaourt

AUR과 동기화
yaourt -Syy

AUR 패키지 검색
yaourt package-name

설치
yaourt -S package-name
대부분의 Pacman 명령어와 Yaourt 명령어가 비슷합니다.

한글 키 입력 (ibus-hangul,fcitx 설치해봐도 잘 안되어 uim 설치.)
https://wiki.archlinux.org/index.php/Input_Japanese_using_uim
https://wiki.archlinux.org/index.php/Extra_Keyboard_Keys
https://wiki.archlinux.org/index.php/Extra_Keyboard_Keys_in_Xorg

pacman -S uim
Default input method 에 벼루만 빼고 다 버린다.
Byeoru key bindings 1
[Byeoru] on과 [Byeoru] off에 Hangul(한/영) 키 추가.
한자키에 한자키 추가.

uim 실행
uim-xim& //입력창을 보지 않는경우
uim-toolbar-gtk & //입력창을 따로 표시하는 경우
https://code.google.com/p/uim/wiki/UimSystemConfiguration
http://x86osx.com/bbs/view.php?id=knowhow&no=525&ksn=0&kss=0&ksc=0&kst=1&ksm=0&kw=:X11:

/etc/rc.conf
LOCALE="ko_KR.UTF-8"

~/.xprofile
IM="uim"
export GTK_IM_MODULE=$IM
export XMODIFIERS="@im=$IM
export QT_IM_MODULE=$IM
export XIM=$IM

http://wiki.kldp.org/wiki.php/%C7%D1%BF%B5%C5%B0 를 참조하였으나 아무런 도움이 되지 않았습니다.

아치 리눅스 글꼴
https://aur.archlinux.org/packages.php?ID=17314
https://aur.archlinux.org/packages.php?ID=49832

한글 폰트
yaourt ttf-nanumgothic_coding

http://manjaro.org/2012/08/22/change-to-your-personal-locales/

유용한 소프트웨어

글쓰기
Focus Writer
yaourt -S focuswriter

PKGBUILD
qt4 -> gambas3-gb-qt4
qmake-qt4 -> qmake
https://aur.archlinux.org/packages/focuswriter/
http://gottcode.org/focuswriter/
https://github.com/gottcode/focuswriter

linux Autohotkey
제대로 작동 안함 http://www.ironahk.net/
yaourt -S autokey

와인(Wine - Run Windows apps)
http://appdb.winehq.org/
http://www.howtogeek.com/107462/easily-install-windows-games-software-on-linux-with-playonlinux/
http://www.playonlinux.com/en/download.html
https://wiki.archlinux.org/index.php/Wine

pacman -S wine
pacman -S wine_gecko
pacman -s winetricks
http://wiki.winehq.org/Mono

/usr/share/wine/mono
설정
wine control
재부팅
wineboot -r
한글폰트
winecfg
sudo cp * ~/.wine/drive_c/windows/Fonts/
한글 설정
~/etc/wine.inf
~/.wine/system.reg
"MS Shell Dlg"="Gulim"
"MS Shell Dlg 2"="Gulim"

실행 전
export LANG=ko_KR.UTF-8
또는
export LC_ALL=ko_KR.UTF-8

regedit
[HKEY_CURRENT_USER\Software\Wine\X11 Driver]
"UseXIM"="N"

http://nemonein.egloos.com/4682100
http://kldp.org/node/93502
http://kldp.net/projects/saenaru/wiki/%EC%84%A4%EC%B9%98%EB%AF%B8%EB%A6%AC%EB%B3%B4%EA%B8%B0
http://mingiber.blogspot.kr/2008/12/crossover.html
http://www.dlldump.com/download-dll-files_new.php/dllfiles/K/kbdkor.dll/5.1.2600.0/download.html
kbdkor.dll을 system32에 win.
HKEY_CURRENT_USER\Keyboard Layout\Preload
Locale = 00000412
프로그램 제거
wine uninstaller

리눅스에서 와우(World Of Warcraft) 하기
런쳐에서 32비트 클라이언트로 실행.
p2p 전송 끔.
https://wiki.archlinux.org/index.php/World_of_Warcraft#Using_OpenGL

black textures
S3TC texture compression support. It can be enabled through driconf or by installing libtxc_dxtn.
wine reg add "HKCU\Software\Wine\Direct3D" /v AlwaysOffscreen /d enabled
VideoMemorySize 1024

primusrun opengl모드에선 안되지만 d3d9에선 실행 됨.
__GL_THREADED_OPTIMIZATIONS=1 WINEDEBUG=-all wine wow-64
https://help.ubuntu.com/community/WorldofWarcraft

optirun bash
#!/bin/sh
__GL_THREADED_OPTIMIZATIONS=1 optirun wine /home/dorajistyle/data/games/World\ of\ Warcraft/World\ of\ Warcraft\ Launcher.exe -opengl

리눅스에서 인터넷 뱅킹
Virtual box
http://www.microsoft.com/en-us/download/details.aspx?id=11575
혹은
curl과 unrar 설치후에
curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS="9" bash
/home/userid/.ievms/vhd'에 저장됨.
http://deviantcj.tistory.com/336

Setting -> Storage -> IDE -> vhd 파일 추가.
Setting -> Storage -> SCSI 삭제.

처음 암호는 Password1
인증 cmd -> slmgr –rearm

리눅스 - x3f
yaourt -S xnviewmp - 속도도 만족, ui도 만족.

Permanent rotation
Also, you can rotate permanently the images based on the EXIF information. This will ensure that the images are oriented properly when viewing in any graphic programs. To do this, you select all your images and select "Tools > JPG Lossless tranformations" (or dropdownlist of symbol 'JPG lossless transformations' in toolbar). In the dialog check the button with "EXIF" on it and then press "Go". XnView will permanently rotate the images based on the EXIF orientation flag.

http://www.xnview.com/en/index.html
http://www.digikam.org/ - 돌아는 가지만 속도가 엄청 느리다.
http://www.proxel.se/x3f.html 속도 빠르고 기본 x3f 추출 기능에 충실하다.
http://www.faststone.org/FSViewerDownload.htm - wine으로 돌리는게 가능하지만 속도가 느리다.

http://www.irfanview.com/ - 지원한다고 써있지만 오류가 난다.

http://www.irfanview.com/plugins.htm

리눅스 - 포토스케이프
wine에서 gdiplus를 native library에 추가 정상 작동.
http://www.oaultimate.com/computers/install-photoscape-3-6-on-ubuntu-11-10.html
일괄변환에서 파일 읽기가 제대로 안될땐 winecfg applications에서 호환성을 윈도우 2003이나 xp로 바꾸니 된다.

Lingoes 대체. Stardict.
http://www.stardict.org/
http://artha.sourceforge.net/neki/index.php/Installation
pacman -S stardict

jpeg 최적화
yaourt -S jpegoptim
jpegoptim --dest=output_folder input_jpegs

mp3 플레이어
sudo pacman -S deadbeef

메신저
pidgin
gtalk
google-talkplugin
pidgin-gtalksharedstatus

토렌트
pacman -S transmission-qt

스크린 캡쳐
yaourt -S shutter

듀얼 모니터 설정
xrandr --output VGA1 --auto --output LVDS1 --auto --right-of VGA1
pacman -S arandr

화면 잠금
yaourt -S slimlock
image : /usr/share/slim/themes/default

날씨
pacman -S xfce4-weather-plugin

지구본,지도
pacman -S kdeedu-marble

시스템 정보.
pacman -S conky
https://wiki.archlinux.org/index.php/Conky
https://aur.archlinux.org/packages/i-nex-bzr
https://wiki.archlinux.org/index.php/Lm_sensors

Temp file clean
yaourt -S bleachbit-svn

용량 큰 파일 검색- Disk usage analyzer with an ncurses interface
sudo pacman -S ncdu

중복파일 검색 / 삭제
sudo pacman -S fdupes
하위 폴더 포함해서 중복파일 검색
fdupes -r /dir

중복 파일 중 첫번째 파일은 제외.
fdupes -f /dir

결과에서 중복 파일 제거
fdupes -d /dir

하위 폴더 포함해서 중복파일을 검사해서 첫번째 파일 빼고 모두 지운다.
fdupes -rdN /dir


빠르고 편리한 파일 검색 ack
http://beyondgrep.com/documentation/
sudo pacman -S ack
검색을 원하는 디렉토리에서 다음과 같이 사용한다.
ack "검색할 문장"


파일 비교(Meld) - Diff 툴
sudo pacman -S meld


동영상 인코딩(handbrake)
sudo pacman -S handbrake


자막 편집(aegisub)
sudo pacman -S aegisub


자막 다운로드(subdownloader)
sudo pacman -S subdownloader


smi srt 변환
승네군님의 smi 2 srt script on archlinux v3.1(http://handmade.egloos.com/5756133)
사용하려면 subs가 필요하다.
yaourt -S perl-subtitles



개발
ssh
pacman -S openssh
ssh-keygen -t rsa
cat ~/.ssh/id_rsa.pub

ruby
pacman -S ruby
mongodb
pacman -S mongodb
bundle
bundle install --deployment
vendor/bundle
젬 환경 보기
gem env
번들 패스 설정
export PATH=$PATH:~/.gem/ruby/1.9.1/bin

libv8 (3.11.8.13 x86_64-linux, 3.3.10.4 x86_64-linux)
therubyracer (0.10.2)
Gemfile
if HOST_OS =~ /linux/i
gem 'therubyracer', '~> 0.10.2'
end

redis 암호 설정
/etc/redis.conf 에서 주석(#)을 제거한다.
# requirepass foobared

mongodb start
mongod --dbpath ~/work/dev/db


Ruby Gem 바이너리 경로 .bashrc에 추가.
export PATH="${PATH}:/home/dorajistyle/.gem/ruby/2.0.0/bin"


문제 해결

libpng cannot open shared object file: No such file or directory
ldd /usr/bin/gtk-update-icon-cache | grep png
LC_ALL=C sudo pacman -Syu


부팅 속도 개선
http://forum.manjaro.org/index.php?topic=6610.0
부팅 속도를 느리게 하는 원인 분석
systemd-analyze plot > plot.svg
systemd-analyze blame

readahead 활성화로 성능 개선
sudo systemctl enable systemd-readahead-collect systemd-readahead-replay

There was an error loading the theme
http://forum.manjaro.org/index.php?topic=8943.0
pacman -S mdm-themes-extra
Customize Desktop Environment for xRDP Session
http://sigkillit.com/tag/xfce/
sudo echo “startxfce4″ > ~/.Xclients
sudo chmod +x ~/.Xclients
sudo systemctl restart xrdp.service


HowTo: LVM encrypted install on SSD disk with cli installer
http://forum.manjaro.org/index.php?topic=1145.15
boot your system now, but when the grub screen comes up
do not press "enter", do not wait 5 seconds, but press "e". just read the text at the bottom of the screenshot: " ’e’ to edit the commands", that's what we need to do now.
search for the line beginning with "linux". this line will end with "ro". now insert "cryptdevice=/dev/sda3:cryptVG" before that "ro".
by pressing F10 grub will now load the kernel with our "modified" command.



by


Tags : , , , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

기름기 쫙 빠진 웹 프레임워크. Python Flask.

15년 전 웹(Web)에 처음 관심을 후로 여러 언어를 접해봤습니다.

우선
HTML, CSS를 사용했고,
더 나아가 Javascript를 사용하게 되었습니다.
백 엔드는 20대 이후에 접하게 되었네요.
그러다 대학에 들어가게 되면서 PHP를 잠시 만졌고,
Java에 빠진 뒤론 JSP가 최고인 줄 알았습니다.
객체지향 개발.
MVC!
그러나 자바에 맛 들인지 얼마 되지 않아,
편한 개발을 돕는다는 명목으로 각종 프레임워크가 난무했고,
새로운 프레임워크를 익히는데 염증을 느꼈습니다.
프레임워크는 개발의 편의를 돕기 위한 것인데 개발이 재미없어지다니, 슬픈 일이었죠.
웹 개발이 싫어졌었어요.

그러다가 Ruby on Rails를 만났습니다.
아~ 이건 정말 신세계에요.
개발하는 재미가 쏠쏠합니다.
루비를 레일즈에 얹으니, 정말 이보다 좋은 개발 도구가 있을까요?
그렇게 RoR에 좋은 감정을 유지해 왔습니다.
하지만 Rails는 군더더기가 좀 있어요.
다음엔 Rails 보다 좀 더 가벼운 Sinatra도 한번 써봐야겠다는 마음먹고 있었죠.

그러다가 우연한 기회에 파이썬 플라스크를 만났습니다.


python-'Python Flask 개발 from http://imgs.xkcd.com'
Python!!!

파이썬.
루비나 펄 같은 스크립트 언어를 접해봐서 그런지 진입 장벽은 그리 높지 않았습니다.
문법이 조금 다르긴 하지만 필요한 함수는 안내에서 찾아 개발하면 됩니다.

마이크로 프레임워크인 플라스크(Flask)를 처음 깔았을 때 좀 당황했습니다.
달랑 7줄 짜리 헬로우 월드 코드를 보고 고민에 빠졌죠.
‘어떻게 사용해야 하지?’
‘정말 이게 다야?’
Rails는 프레임워크를 설치했을 때 설정 파일을 비롯하여 수많은 파일이 생성됩니다.
그런데 Flask는 참 단순하더군요.
아마 덩치와 편의성은 Django가 Rails와 비슷하겠지요.

짧은 튜토리얼만 봐도 바로 개발할 수 있니다.
DB는 Flask-SQLAlchemy를 사용하여 만들었는데, 이 역시 익히기가 간편하여 좋더군요.

그런데 막상 개발하다 보니 눈이 어지럽습니다.
html 코드 때문이었는데요.
즐겨쓰던 haml 템플릿 엔진을 쓰려고 했으나, 지원이 시원치 않아서 Jade로 갈아탔습니다.
설정이 아주 간편해요.

자. 이제 본격적으로 개발해 볼까요?
그런데 뭔가 허전합니다.
템플릿에서 파이썬 함수를 쓰고 싶어요.
레일즈의 helper처럼 말이죠.
그건 flask의 context_processor를 이용하면 됩니다.
자세한 내용은 flask 안내서 있어요.

대체로 개발이 수월했지만,
문법이 달라서 골치가 잠깐 아픈 부분이 한곳 있습니다.
형 변환이 자동으로 안되어서 수동으로 해야 하는데,
jade템플릿에서 숫자를 문자로 바꾸는 함수가 안 통하는 거에요.
찾아보니 바꾸는 방법이 4가지씩이나 된다고 합니다.
이 중 3번과 4번은 Jade템플릿에서도 잘 동작해요.

  1. str(숫자)
  2. repr(숫자)
  3. '숫자'
  4. '%d' % 숫자

간단한 웹 어플리케이션을 만들며, 파이썬 플라스크 개발을 맛보았습니다.

고객제안과 투표 기능을 구현했어요.

코드는 아래 주소에서 보실 수 있습니다.

Python + Flask + Flask-SQLAlchemy + Jade Proposal Center Example



Python Flask 개발에 도움이 되는 링크

파이썬 함수 도움말 (http://docs.python.org/2/library/functions.html)

플라스크(http://flask.pocoo.org/)

Flask-SQLAlchemy(http://pythonhosted.org/Flask-SQLAlchemy/index.html)

플라스크 다국어 지원 (http://pythonhosted.org/Flask-Babel)

파이썬 Jade(https://github.com/syrusakbary/pyjade)

파이썬 Scss(https://github.com/Kronuz/pyScss)



by


Tags : , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

익숙하지만 낯선 운영체제. 윈도우즈 8


저는 오래도록 마이크로소프트사의 제품을 사용해 왔습니다.
MS도스부터 윈도우즈 3.1, 95, 98, 2000, 2003, XP, Vista, 7.
그리고 윈도우즈 8까지.
MS빠라고 해도 할 말이 없군요.
올해는 익숙한 마이크로소프트 진영을 벗어나려고 합니다.
하지만 어무이도 컴퓨터는 쓰셔야 하므로 집 컴퓨터를 윈도우즈 8로 업그레이드했어요.


시작화면-'윈도우즈8'
우선 윈도우즈 8을 설치하고 부팅할 때 뜨는 로딩화면이 단순해 마음에 듭니다.
부팅 속도도 윈도우즈 7보다 빨라졌어요.
시작화면이 조금 낯섭니다.
스마트폰과 비슷하거든요.
앱을 추가해서 마음에 맞는 시작화면을 꾸밀 수 있습니다.
돋보이는 기능은 마이크로 소프트 계정과 동기화 기능인데요.
계정을 동기화해 두면, 어떤 장치에서도 같은 환경으로 윈도우즈를 쓸 수 있습니다.
편리한 기능이지요.

데스크톱은 윈도우즈 7에 비해 크게 바뀐 것은 없습니다.
그런데 어무이께서 전화를 하셨어요.
"컴퓨터 끄려면 어떻게 해야 하니?"
이전 버전의 윈도우즈에선 시작 메뉴를 마우스로 클릭하고 시스템 종료 하면 되었잖아요?
윈도우즈 8엔 시작 메뉴가 없습니다.
그럼 컴퓨터를 어떻게 끄느냐고요?

1. 키보드의 시작 버튼을 누릅니다.
2. 우측 하단의 - 로 커서를 가져다 댑니다.
3. 설정을 누릅니다.
4. 전원을 누릅니다.
5. 시스템 종료를 누릅니다.

컴퓨터 끄기가 참 번거롭지요?

웹서핑을 해보니 윈도우즈 8 종료버튼 만들기 팁이 올라왔습니다.
윈도우8의 필수 팁! 윈도우8 종료버튼 만들기


팁의 도움을 받아 종료버튼을 만들었습니다.
시작 메뉴에 넣어두니 한결 편리하네요.^^

마이크로소프트 윈도우즈가 앞으로도 누구나 쓰기 쉬운 OS로 발전해 나가길 바랍니다.



by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

이젠 담배와 작별을 고하세요. Smoke Free Project


아일랜드에서 지내는 동안, 친구를 도와 금연 서비스를 만들었습니다.

금연을 시작하기 전부터 준비사항을 알려주고,

담배를 끊고 하루하루가 지날 때마다 어려움을 어떻게 극복하면 좋은지 안내가 잘 되어있습니다.

같이 금연을 하는 사람들과 정보를 나누기도 좋지요.

아직 한국어 버젼은 없지만,

다국어 서비스를 생각하고 만들었기에, 번역만 되면 언제든지 한국어로도 서비스가 가능합니다.

혹시 금연에도 관심이 있다면 한 번 들러보시고,

한국어로 번역하고 싶은 마음이 드시면, 서비스를 꾸려가는 세바스찬에게 이메일을 보내세요.:D

Smoke Free Project(SmokeFreeProject.org)




by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

자주 쓰는 엑셀 함수 정리.


엑셀, 문자열 다루기 - 문자열 함수 (텍스트 함수)

  • CHAR - 코드 번호에 해당하는 문자를 반환합니다.
  • CODE - 텍스트 문자열의 첫 문자를 나타내는 코드 값(숫자)을 반환합니다.
  • CONCATENATE - 여러 텍스트 항목을 한 텍스트 항목으로 조인합니다.
  • EXACT - 두 텍스트 값이 동일한지 검사합니다.
  • FIND - 텍스트 값에서 다른 텍스트 값을 찾습니다(대/소문자 구분).
  • LEFT - 텍스트 값에서 맨 왼쪽의 문자를 반환합니다.
  • LEN - 텍스트 문자열의 문자 수를 반환합니다.
  • LOWER - 텍스트를 소문자로 변환합니다.
  • MID - 텍스트 문자열의 지정한 위치로부터 지정한 개수의 문자를 표시합니다.
  • PROPER - 텍스트 값에 있는 각 단어의 첫 글자를 대문자로 바꿉니다.
  • REPLACE - 텍스트 내의 문자를 바꿉니다.
  • REPT - 텍스트를 지정한 횟수만큼 반복합니다.
  • RIGHT - 텍스트 값에서 맨 오른쪽의 문자를 반환합니다.
  • SEARCH - 텍스트 값에서 다른 텍스트 값을 찾습니다(대/소문자 구분 안 함)
  • SUBSTITUTE - 텍스트 문자열에서 기존 텍스트를 새 텍스트로 바꿉니다.
  • T - 인수를 텍스트로 변환합니다.
  • TEXT - 숫자 표시 형식을 지정하고 텍스트로 변환합니다.
  • TRIM - 텍스트에서 공백을 제거합니다.
  • UPPER - 텍스트를 대문자로 변환합니다.
  • VALUE - 텍스트 인수를 숫자로 변환합니다.
  • CONCATENATE (문자열1,문자열2,...)
  • REPLACE(문자열, 시작위치, 바꿀 문자수, 바꿀 문자열)
  • SUBSTITUTE(문자열, 찾을 문자열, 바꿀 문자열)
엑셀, 문자열 다루기 - 문자열 함수 (텍스트 함수) [강동의별님의 블로그]

엑셀, 문자열 다루기 - 문자열 함수 (텍스트 함수)

  • 상대참조(A1 형식) : 셀의 변위에 따라 상대적으로 참조셀의 위치도 변하는 형식.
  • 절대참조($A$1 형식) : 셀의 변위에 상관없이 참조셀이 고정적으로 정해진 형식.
엑셀 절대참조,상대참조 - 기본 중의 기본 [강동의별님의 블로그]

컬럼 합치기

=A1&" "&B1

텍스트 추출하여 날짜/시간 형식으로 변환

=DATE(LEFT(A1,4),MID(A1,5,2),MID(A1,7,2))+TIME(MID(A1,10,2),RIGHT(A1,2),0)

조건절에 만족하면 갯수 세기

=IF(COUNTIF(Sheet1!$A$2:$A$6,Sheet2!A2)=1,1,0)

원하는 범위에서 값 찾아 바꾸기

VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)
=vlookup(B1,sheet1!$C$1:$E$13, 3,false),0)


원하는 범위에서 여러 컬럼 값 찾아 바꾸기

=index(Sheet1!$D$1:$D$44,match(A1&B1,Sheet1!$A$1:$A$44&Sheet1!$B$1:$B$44,0))
Sheet1!$A$1:$A$44&Sheet1!$B$1:$B$44 범위에서 A1&B1값을 찾으면 Sheet1!$D$1:$D$44값을 컬럼에 채운다.


함수를 적용시키려면 CTRL+ENTER
배열 수식{}을 적용시키려면 CTRL+SHIFT+ENTER

엑셀 함수 참조 사이트

Contextures - Excel Tips and Excel Tutorials



by


Tags : , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Web application development References


ISO-639-1


Official languages of the United Nations

  • Arabic
  • Chinese (Mandarin)
  • English
  • French
  • Russian
  • Spanish

CLDR

Unicode Common Locale Data Repository

터미널 한글 설정

windows cmd - chcp 65001
linux shell - export LC_ALL=ko_KR.UTF-8


구글 맵스 지도 검색

https://maps.google.com/?q=이름@위도,경도

구글 정의 검색

define:something

Protocol SPDY

http://www.chromium.org/spdy

MongoDB

사용자추가 스키마생성 DB삭제

mongod 를 기동할 때는 --auth 옵션을 추가해야 함
mongoDB는 system영역 내에서 admin이라는 DB관리를 위한 스키마를 가짐
>use admin // admin DB 사용
>db.addUser('name','pswd') // 사용자 추가
>use newDB => 해당 디비가 없으면, 새로운 디비를 생성함
   mysql의 스키마 생성과 같음
>db.collectionName.drop() => 해당 collection을 삭제함
   mysql의 DROP TABLE과 같음

Mongodb eclipse

log path configuration

"C:\data\mongodb-xxxxxxxxx\bin\mongod" --service  --logpath  c:\data\test.log

import

mongoimport --host localhost --db myapp_development --collection my_collection --type csv --file C:\dev\data\test.csv --headerline --upsert

regex

mongodb regex = '^[work|accus*|planet]'
MongoDB can only use indexes on Regular Expression searches that are front (^) anchored.
RegEx searches that front-anchor and then use a wildcard query like .* will use the index for as much of the un-wildcarded area as it can before scanning --- i.e., ^foo.* will run a partial scan.


Mysql

mysql backup and restore


mysqldump -uUSER -pPASSWORD -hHOST DB > ./filename.sql
mysql -uUSER -pPASSWORD -hHOST DB < ./filename.sql

MySQL index

What should be indexed?
–All attributes where you JOIN
–All attributes where you filter (WHERE)
–All attributes where you ORDER or GROUP BY
–All attributes where you want to do an Index Scaninstead of a Table scan.
–NOT on attributes with an evenly distributed lowcardinality.
•How should be indexed?
–Indexes can only be used from left to right.
–Keep them short.
–Compound indexes: INDEX(a, b).
–Prefixed indexes: INDEX(a, b(10)).
–Do not function-cover indexed attributes

http://www.scribd.com/doc/80792061/MySQL-Performance-Tuning

MySQL Date and Time Functions


Mysql 동일 테이블에서 여러 필드 값의 합 쿼리

//쿼리1 보다 쿼리2가 두 배 이상 빠르다. 단, 하나의 칼럼 갯수를 구할 땐 where절과 count(*)를 쓰는 것이 더 빠르다.
//쿼리1
select sum(cnt) from (
    select count(*) as cnt from `my_table` WHERE `field_x` =1
    union all
    select count(*) as cnt from `my_table` WHERE `field_y` =1
    union all
    select count(*) as cnt from `my_table` WHERE `field_z` =1
) as cnt_all
//쿼리2
SELECT
(SUM(IF(`field_x` = 1,1,0)) +   
    SUM(IF(`field_y` = 1,1,0)) +
    SUM(IF(`field_z` = 1,1,0))) as cnt_all
FROM `my_table`
WHERE 1


firefox - keyword.url

http://www.google.co.kr/search?num=50&hl=ko&lr=&newwindow=1&tbo=1&as_qdr=all&aq=f&aqi=&aql=&oq=&gs_rfai=&ie=UTF-8&oe=UTF-8&sourceid=navclient&gfns=1&q=

리눅스 crontab

crontab -l

CSS FONT BASE-64

/* Fonts as files */
@font-face {
    font-family: 'MyFontFamily';
    src: url('myfont-webfont.eot?') format('eot'),
         url('myfont-webfont.woff') format('woff'),
         url('myfont-webfont.ttf')  format('truetype'),
         url('myfont-webfont.svg#svgFontName') format('svg');
    }
/* Fonts as data uris */
@font-face {
    font-family: 'MyFontFamily';
    src: url('myfont-webfont.eot?') format('embedded-opentype');
    }
   
@font-face {
    font-family: 'MyFontFamily';
         url(data:font/truetype;charset=utf-8;base64,BASE64_ENCODED_DATA_HERE)  format('truetype'),
         url(data:font/woff;charset=utf-8;base64,BASE64_ENCODED_DATA_HERE)  format('woff'),
         url('myfont-webfont.svg#svgFontName') format('svg');
    }


CSS Sticky windows

    .outer {
        width:200px;
        height:600px;
        background-color:red;
        margin:0 auto;
    }
    .inner {
        width:50px;
        border:1px solid white;
        position:fixed;
    }
 


Insert the word (image) into the alt text of an image that hasn’t loaded In Firefox

img:after   { content:" (image)"; }
img::after  { content:" (image)"; } /* New CSS3 standard notation */


FYI

References and Articles

빠른 웹 개발

도구


출처

  • 직접 작성
  • google 검색



by


Tags : , , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Ruby Gems Cheat Sheet


GEM 설정

gem environment
set GEM_PATH = D:\dev\ruby192\lib\ruby\gems\1.9.1\gems
gem update --system
gem uninstall gemname
bundle update
(vendor 폴더에 bundle 설치하기)
bundle install --path vendor/bundle


devise

Controller filters and helpers

Devise will create some helpers to use inside your controllers and views. To set up a controller with user authentication, just add this before_filter:
before_filter :authenticate_user!
To verify if a user is signed in, use the following helper:
user_signed_in?
For the current signed-in user, this helper is available:
current_user
You can access the session for this scope:
user_session
Callbacks
    after_set_user
    after_authentication
    before_failure
    before_logout
    Warden::Manager.after_authentication do |user,auth,opts|
        user.last_login = Time.now
    end
   

generator

devise g view with haml
rails g devise_views -t=haml

OmniAuth

Add :password => Devise.friendly_token[0,20] when creating a new user from facebook omniauth.

Passwords Encrypt manually


Assuming you have a mysql database with a "users" table and a "password" column And an ActiveRecord model class called "user" that is hooked up to devise
Create an ActiveRecord model class in your app app/models/old_user.rb
OldUser < ActiveRecord::Base
  set_table :users
  establish_connection :database => "old_database", :user => "old user", :adapter => "mysql"
end
then create a rake task: app/lib/tasks/migrate_users.rake
task :migrate_users => :environment do
  OldUser.find_each do |old_user|
    u = User.new(:email => old_user.email, :password => old_user.password, :password_confirmation => old_user.password);
    #if your using confirmation
    u.skip_confirmation!
    u.save!
  end
end
Modify as necessary (make sure you're saving any app-specific user attributes)
Then$ rake migrate_users
   
Good news and bad news.
Good news:
The following works to create your user's password manually.
 pepper = nil
 cost = 10
 encrypted_password = ::BCrypt::Password.create("#{password}#{pepper}", :cost => cost).to_s
You can find your pepper and cost in your devise initializer. This method was confirmed using Devise's "valid_password?" method.
Bad news:
The entire reason I was trying to avoid "User.new(password: password).encrypted_password" was because of speed. It's terribly slow. With all my other pieces of my import task, I've intentionally avoided this.
But as it turns out, the major cost here is not instantiating a User object -- but BCrypt itself. There is very little noticeable speed boost when using BCrypt directly because it's intentionally designed to be slow.
My final answer: suck it up, run the rake script, go find a beverage.

mailer locale configuration

-ActionMailer::Base.default_url_options[:locale] = I18n.locale


Simple_form

<%= simple_form_for(@user, :builder => CustomBuilder) do |f| %>
  <%= f.input :name %>
<% end %>


Client side validations

Client side validations Registering own form builder
https://github.com/bcardarella/client_side_validations/wiki/Registering-your-own-custom-form-builder


Client MVC

Spine

Important is only that the public directory of the application is specified
as domainroot in Confixx. If the domain is called Passenger will start automatically.."
rails g spine:model Card text is_private order user_id card_type
rails g spine:controller Cards
rails g spine:scaffold card text is_private order user_id card_type
rails g spine:model Organization title description url image admins members followers
rails g spine:controller Organizations
rails g spine:scaffold organization title description url image admins members followers
var card = App.Card.create({ 
  is_private: true,
  order: 0,
  card_type: 'Reason',
  text: 'Spine & Rails, sitting in a tree!'
});
straightforward way to do that without extending Spine Model's
to allow for instances to be added in memory without syncing
Ajax.disable -> saveStuff()
Model.refresh()
extends
Contact.extend(Spine.Model.Ajax);
Contact.extend({
url: '/users/'
});
'/': ->
    if AuthenticatedUser
         @controller = new OtherController
         @replace @controller.render()
    else
         @controller = new LoginController
         @replace @controller.render()
http://spinejs.com/docs/controller_patterns         
         


Compass

compass init rails D:/dev/workspace/baksisi
compass init rails -r html5-boilerplate -u html5-boilerplate --syntax sass --force
css와 javascript를 asset 폴더로 옮겨준다. rails.js는 제외 (jquery_ujs와 동일하다)


Geo_location

https://github.com/chrisyour/geo_location
http://www.maxmind.com/app/geolitecountry


Mongoid id 변경하기

http://blog.joshdzielak.com/blog/2011/12/24/tame-the-mongoid-id-field-in-your-rails-and-backbone-js-app/
http://lostechies.com/derickbailey/2011/06/17/making-mongoid-play-nice-with-backbone-js/


Mongoid Follow unfollow

class User
  include Mongoid::Document
  field :name, type: String
  has_and_belongs_to_many :following, class_name: 'User', inverse_of: :followers, autosave: true
  has_and_belongs_to_many :followers, class_name: 'User', inverse_of: :following
  def follow!(user)
    if self.id != user.id && !self.following.include?(user)
      self.following << user
    end
  end
  def unfollow!(user)
    !self.following.include?(user)
    self.following.delete(user)
  end    
end
relation_ids instead? that is self.member_count = self.member_ids.size
self.challenged.where(_id: event.id).destroy_all
def unchallenge!(announce)
  self.announcements.destroy_all( conditions: { _id: announce.id })
  self.save!
end
Finally I successfully deleted the relation using self.challenged_ids.delete(event.id)
validates_inclusion_of :foo, in: [['foo'], ['bar']]


Mongoid polymorphic behaviour

When a child embedded document can belong to more than one type of parent document, you can tell Mongoid to support this by adding the as option to the definition on the parents, and the polymorphic option on the child.
class Doctor
  include Mongoid::Document
  embeds_one :name, as: :namable
end
class Nurse
  include Mongoid::Document
  embeds_one :name, as: :namable
end
class Name
  include Mongoid::Document
  embedded_in :namable, polymorphic: true
end


TEST

Cucumber

rails g cucumber:install ?capybara ?rspec
  ruby script/rails generate cucumber:feature user email:string password:string confirm_password:string name:string nickname:string gender:integer location_name:string location:integer email_is_priavate:boolean name_is_private:boolean danted:boolean description:string
  ruby script/rails generate scaffold post title:string body:text published:boolean
  rake db:migrate
  rake cucumber


Cucumber Errors Handling

If SystemStackError: stack level too deep 
Then add gem "rspec", ">= 2.6.0.rc2", :group => [:development, :test] to Gemfile


Cucumber & Capybara Ajax

sleep second
page.driver.browser.execute_script %Q{ $('.ui-menu-item a:contains("#{link_text}")').trigger("mouseenter").click(); }
Clicking any element with Cucumber and Capybara
class Capybara::XPath
  class << self
    def element(locator)
      append("//*[normalize-space(text())=#{s(locator)}]")
    end
  end
end
When 'I click "$locator"' do |locator|
  msg = "No element found with the content of '#{locator}'"
  locate(:xpath, Capybara::XPath.element(locator), msg).click
end
The step looks for any element with the given text. Here it is in use:
Scenario: Creating an item
  Given I am signed in as "brandon@example.com"
   When I click "Add to your list"
    And I fill in "Description" with "blog about clicking any element"
    And I press enter
   Then I should see "The item was added to your list"
    And I should see "blog about clicking any element"
   


Cucumber Capybara

selenium chrome driver
https://github.com/jnicklas/capybara
http://code.google.com/p/chromium/downloads/list
http://code.google.com/p/selenium/wiki/ChromeDriver#Overriding_the_Chrome_binary_location
Capybara.register_driver :selenium_with_firebug do |app|
  Capybara::Driver::Selenium
  profile = Selenium::WebDriver::Firefox::Profile.new
  profile.add_extension(File.expand_path("features/support/firebug-1.6.0-fx.xpi"))
  Capybara::Driver::Selenium.new(app, { :browser => :firefox, :profile => profile })
end
Before("@selenium_with_firebug") do
  Capybara.current_driver = :selenium_with_firebug
end


I18n

I18n-js initialize

layout/application.html.haml
- html_tag :class => 'no-js', :lang => "#{I18n.locale}"
applcation.js
I18n.default_locale = "en"
I18n.locale = $($("html")[0]).prop("lang")
I18n.fallbacks = true


Media - Flickraw

    flickr.upload_photo(params[:photo].tempfile.path)


Gem Trouble shooting

Q. `require': no such file to load -- thin (LoadError)
A. => Add gem 'thin' to Gemfile


Rails Performance

  • Curb for Http (libcurl)
  • Yajl, the fastest JSON library.
  • excon #=> faster http
  • Nokogiri, the fastest XML library.
  • Snappy, super fast compression tool by google.
  • fast_xs
  • Memcache. (libmemcached)
  • use Ree Garbage Collector

Fastest Server

  • Unicorn
  • Thin

Profiling Tools

  • NewRelic - Monitoring Tool (Commercial)
  • Ganglia - Monitoring Tool (OpenSource)
  • Cloudflare - Performance & Security
  • rack-perftools

Rack-bug

1. Install rack-bug (branch rails3) as plugin
cd vendor/plugins
git clone -b rails3 https://github.com/brynary/rack-bug.git
If you want to you it as gem then add following line into Gemfile
gem 'rack-bug', :git => 'https://github.com/brynary/rack-bug.git', :branch => 'rails3'
2. Replace the code from file actionview_extension.rb
which is avilable in vendor/plugins/rack-bug/lib/rack/bug/panels/templates_panel/ as specified in bug of rack_bug repository
if defined?(ActionView) && defined?(ActionView::Template)
ActionView::Template.class_eval do
def render_with_rack_bug(*args, &block)
Rack::Bug::TemplatesPanel.record(virtual_path) do
render_without_rack_bug(*args, &block)
end
end
alias_method_chain :render, :rack_bug
end
end
If you are using gem override the specified file in some way
3. Add following lines into your config.ru
require 'rack/bug'
use Rack::Bug, :secret_key => "someverylongandveryhardtoguesspreferablyrandomstring"
run myapp
4. Start your server and access the URL http://your_app/__rack_bug__/bookmarklet.html
and enter the password.
http://blog.railsupgrade.com/2011/04/configure-rack-bug-for-rails-3.html


출처



by


Tags : , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!