Posts

Showing posts from August, 2014

Simple Restful Api (get) without db Connection ( Node Js + Express)

This sample will show you that how simple nodejs http restful API is working

first test is returning array json data

second and Third is just restun json data


======== sample source ===========


var express = require('express');
var app = express();
app.get('/school', function(req,res){
    res.send([{bus:'bus1'}, {bus:'bus2'}]);
});


app.get('/school/:number', function(req, res){
    res.send({id:'two path', number:req.params.number});
});

app.get('/school/:number/:destination', function(req, res){
    res.send({id:'three path', destination:req.params.destination});
})

app.listen(3000);
console.log('Listen on port 3000......');


and result list


1.  http://192.168.123.165:3000/school

[
{
"bus": "bus1"
},
{
"bus": "bus2"
}
]
2. http://192.168.123.165:3000/school/second
{
"id": "two path",
"number": "second"
}
3. http://192.168.123.165…

webstorm and node js setup

in webstorm you can use nodejs easily


1. file -> setting -> javascript -> library ->
  and Node.js check

2. file -> setting -> Node.js and NPM  and install packages


event emiter in nodejs

var custom = new process.EventEmitter();

custom.on('hello', function(){ console.log('event generated')});

custom.emit('hello');



======================
"event generated" log will be written in console

file write sync and async in nodejs

var fs = require('fs');
var data= 'heloo world';

fs.writeFile('filename.txt', data, 'utf-8', function(error){
console.log('write file async');
});

fs.writeFile('filenameSync.txt', data, 'utf-8');
console.log('write file sync');

read file in folder and write in browser in nodejs

this is a sample http server and read file and print in brwoser
when you call
http://localhost:8888/

var http = require("http");
var fs = require('fs');
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
var text= fs.readFileSync('textfile.txt', 'utf-8');

response.write(text);  response.end();
}).listen(8888);

Search Content Architecture

Image
In this generation lots of book publicshed day by day
and If I go to library to find some book which containing some contents (I want)
there is no way to find  may you have to use you whole life to find books which you are looking for
so library must provide tools or program for looking books .
this is architecture that searching title, content, date and so on
there is good opensource Lucene.

Simple http server architecture

Image
This is what i usually setting in my Simple http server
some people say that this is very old~
because recently people tend to use new technology like node.js or nosql

What I learned serverside is used like this architecture and no problem generated~

This architecture pages will be written and paged from my experience.

I'm not sure It is best way or not
but i'm sure that this will help improving my skill and knowloged about IT

Have a good job~

exports in nodejs

Require and Exports ~!
require will get file
exports will help file to be used in require file

example

main.js var mymodule = require('./mymodule.js');
console.log('asdfasdf ' + mymodule.hello());
mymodule.js exports.hello = function(){ return 'hello 2'; }

이름 자동완성 리스트

내 안드로이드폰 주소록 검색을 보게 되면 ㄱ만 쳐도 ㄱ을 포함하고 있는 사용자 이름을 다 검색하게 되어있다. 그것도 빠른 시간내에..
문뜩 이것을 따라 만들고 싶은 욕망이 치 솟아서 저번에 배운 한글 초성 + 중성 + 종성으로 나눠 따라 해보기로 했다.
1. 테이블을     name     name_index 필드를 만들었다.
  name 에는 홍길동이 들어가고   name_index  에는 ㅎㅗㅇㄱㅣㄹㄷㅗㅇ  이런식으로 초성중성조성으로 구분되어서 각각이 하나의 문자로 들어간다.
그러면 TextEdit box에서 정을 쳤을때  " ㅈㅓㅇ " 을 like 검색을 하면 정에 관한 데이터들이 쭈루룩 올라온다.
약 500건의 데이터로 테스트를 했는데 실제 DB 에서 가져오는 시간은 0.01초 걸렸다.  즉 10ms
많지 않는 내용의 값을 검색할때는 초성중성종성 을 넣은 란은 Like검색해서 가져오면 충분히 효율성이 있을 것이라고 생각한다.
물론 Server side의 입장을 다르게 될것이다 좀더 나은 효율성과 Perfomance 를 위해 
Lucene같은 라이브러리를 이용해도 되고 아니면 데이터베이스를 이용해도 되겠다.

네이버 자동완성 기능 분석 - client side 편

처음 블로그를 시작해서 블로그의 내용은 왠만하면 영어로 작성하자고 다짐을 했다.
그런데 영어로 작성을 하다 보니깐 말도 잘안나오고 어려움이 많이 있었지만
여차 저차 해서 여태까지 블로그를 잘 작성해온것 같다.

오늘은 네이버 자동완성 기능에 대해서 포스팅을 하려고 한다.

만약에 우리가 "길찾기" 라는 단어를 검색하게 될 경우 네이버에서 어떠한 방법으로 API검색이 이루어지는지 확인해보자

길찾기

1. ㄱ
2. 기
3. 길

각각의 검색 결과
1. ㄱ

window.__jindo_callback._$3361_0({
"query" : ["ㄱ", "ㄱ"],
"answer" : [],
"nature" : [],
"items" : [
[["구글"],["괜찮아 사랑이야"],["고속도로교통상황"],["길찾기"],["교황"],["광복절"],["기상청"],["곽동연"],["공효진"],["그것이 알고싶다"],["군도"],["괜찮아 사랑이야 ost"],["기리보이"],["교황 방한일정"],["강동원"],["김소현"],["고고싱"],["김연아"],["교촌치킨"],["걸스데이"]],
[]
]
})

설명 : 초성을 검사해서 보여주고 싶은 순서대로 Item을 정렬해서 서버에서 내려주는 방식인가 보다. 프레임워크는 Naver에서 사용하고 있는 jindo라는것을 사용한다는것을 확인할 수 있다.

2. 기
window.__jindo_callback._$3361_0({
"query" : ["기&quo…

SRM 528 DIV 2 250 problem

My Answer is 
publicclass BishopMove { publicstaticvoid main(String[] args){ System.out.println(howManyMoves(4, 6, 7, 3)); System.out.println(howManyMoves(2, 5, 2, 5)); System.out.println(howManyMoves(1, 3, 5, 5)); System.out.println(howManyMoves(4, 6, 7, 4)); } publicstaticint howManyMoves(int r1, int c1, int r2, int c2){ if((r1 + c1) %2 != (r2 + c2)%2){ return -1; } if(r1 == r2 && c1==c2){ return 0; } if(Math.abs(r1-r2) == Math.abs(c1-c2)){ return 1; }else{ return 2; } }
}

Android Dialog With timeout

This would be good for you


package com.sanghwa.nettychatting.dialog;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Handler;

public class CustomDialog {

static ProgressDialog pDialog =  null;

static int TIME_OUT =  5000;

static Handler handler = new Handler();

public static void showCustomDialog(Activity context){
if(pDialog == null){
pDialog  = new ProgressDialog(context);
pDialog.setCancelable(false);
pDialog.setMessage("loading..");
}

if(pDialog.isShowing()){
return;
}

pDialog.show();
handler.postDelayed(new Runnable() {

@Override
public void run() {
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}, TIME_OUT);


}

public static void close(){
if(pDialog == null){
return;
}
handler.postDelayed(new Runnable() {

@Override
public void run() {
if(pDialog.isShowing()){
pDialog.dismiss();
}
}
}, 0);
}
}

Netty detect when client network changed and closed -> PING, PONG

This guide is for the users who are already used to using netty


Actually I tried to make chatting program with Netty
I was very happy to know netty and it seems to be very good for speed and connections

but I faced with some problem
When Android Client side Stop application exit it Serverside relize that client is disconnected.
but when client change 4g to wifi client connection lost, however Serverside dosen't know about client lost.
noting happend.

so I google and found some good handler .
this is ping periodically .
and server side finally exactly know whether specific client is where alive or not.

=== Explain ==

idleStateHandler

readerIdleTimean IdleStateEvent whose state is IdleState.READER_IDLE will be triggered when no read was performed for the specified period of time. Specify 0 to disable.writerIdleTimean IdleStateEvent whose state is IdleState.WRITER_IDLE will be triggered when no write was performed for the specified period of time. Specify 0 to disable.allIdleTimean Id…

object to jsonObject and string

way to make json object

<script>
var main = new Array();
sub = new Object();    
sub['key1'] = 'value1';
sub['key2'] = 'value2';
sub['key3'] = 'value3';
main[0] = sub;

sub = new Object();    
sub['key1'] = 'value4';
sub['key2'] = 'value5';
sub['key3'] = 'value6';
main[1] = sub;


var jsonObject = {list:main};

alert(JSON.stringify(jsonObject));

</script>