Sunday, August 17, 2014

네이버 자동완성 기능 분석 - 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" : ["기", "기"],
"answer" : [],
"nature" : [],
"items" : [
[["길찾기"],["기상청"],["기리보이"],["김소현"],["김연아"],["김민교"],["김설진"],["김새론"],["김수현"],["김원중"],["김범수"],["김수로"],["김영희"],["김남길"],["기아자동차"],["김우빈"],["김민희"],["김태희"],["기분좋은날"],["김광석"]],
[]
]
})

설명 : 초성 중성까지 기 으로 시작하는 모든 단어중에 자동완성할 수 있는 단어들을 정렬해서 내려준다. Max검색어는 20개인가보다

3. 길
window.__jindo_callback._$3361_0({
"query" : ["길", "길"],
"answer" : [],
"nature" : [],
"items" : [
[["길찾기"],["기리보이"],["길구봉구"],["길"],["길거리야"],["기린"],["기리보이 안경"],["길찿기"],["기리보이 밖에비온다"],["길찾기 어플"],["기리보이 특별해"],["길병원"],["기리보이 안경벗은거"],["길림대"],["길상사"],["기리보이 탈락"],["길트"],["기름때 지우는법"],["길티크라운"],["길버트증후군"]],
[]
]
})

설명 : 여기서 특이한 사항은 한글이 초성 + 중성으로 이루어진 것과
        초성 + 중성 + 종성으로 이루어진 사항이 있는데 길이라는 검색을 했는데
        기린이라는 2단어의 검색결과도 나오는걸 확인 할 수 있다.
        즉 네이버의 자동완성 시스템은 종성의 자음을 다음글자의 초성으로 판단해서 1글자와 2자일 경우의 혼합의 데이터를 내려준다. 


Daum에서는
길이라는 단어를 검색하면 길의 마지막 종성의 ㄹ로 다음글자의 초성을 예측하는 검색을 하지 않는다.

Naver 와  Daum에서는 서로 다른 성격의 자동완성 검색을 하다고 판단 할 수 있다.


다시 네이버로 돌아와서

궁금증1 ?
ㄱ을 쳤다가 지우고 다시 ㄱ을 치면 통신이 재반복의 통신이 이루어지나?
크롬사이트로 네트워크를 보면서 확인해보았다.

네트워크가 이루어지는걸 확인해본 결과 한번 검색한 결과의 값은 재 요청을 하지 않으며
잠시 브라우져의 메모리에 캐쉬하는걸 확인할 수 있었다.

그러면 cookie에다가 저장하는지 확인해보았다.
cookie를 열어보니 검색결과에 대한 결과의 내용을 저장해놓지 않았다.
Localstorage, SessionStorage모두 결과의 대한 내용을 저장해놓았지 않았다.

즉 검색결과를 javascript단의 변수에 휘발성의 임시 메모리로 가지고 있는다는걸 알게되었다. (브라우져를 리프레쉬 하게 될 경우 데이터가 날아감)



Monday, August 11, 2014

SRM 528 DIV 2 250 problem

My Answer is 

public class BishopMove {
public static void 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));
}
public static int 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;
}
}

}

Friday, August 8, 2014

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);
}
}

Wednesday, August 6, 2014

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 IdleStateEvent whose state is IdleState.ALL_IDLE will be triggered when neither read nor write was performed for the specified period of time. Specify 0 to disable.


pipeline.addLast("idleStateHandler", new IdleStateHandler(60, 30, 0));        pipeline.addLast("myHandler", new MyHandler());



class MyHandler extends ChannelDuplexHandler {
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                System.out.println("reader ");
                System.out.println("reader ");
                System.out.println("reader ");
                System.out.println("reader ");
            ctx.close();
            } else if (e.state() == IdleState.WRITER_IDLE) {
                 try{
             ctx.channel().writeAndFlush("ping:"+ctx.channel().hashCode() );
                 }catch(Exception es){
                 es.printStackTrace();
                 }
             System.out.println("writer ");
                 System.out.println("writer ");
            }
        }
    }
}

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>

Wednesday, July 30, 2014

I Just wanted get the Redis Manage Tools on windows like sqldeveloper

I found good manage tool for redis on windows 

this show us datas and be able to use console like redis-cli

anyway 

I think I just prepare to enjoy redis


http://redisdesktop.com/





Tuesday, July 29, 2014

Redis java client Jedis

It is very easy to use

I just follow sample code

and output is excellent ~!!

Jedis jedis = new Jedis("localhost");
jedis.set("foo", "bar");
String value = jedis.get("foo");

System.out.println(value);


and if you access to multithread enviroment follow this article

Basic usage example

using Jedis in a multithreaded environment

You shouldn't use the same instance from different threads because you'll have strange errors. And sometimes creating lots of Jedis instances is not good enough because it means lots of sockets and connections, which leads to strange errors as well. A single Jedis instance is not threadsafe! To avoid these problems, you should use JedisPool, which is a threadsafe pool of network connections. You can use the pool to reliably create several Jedis instances, given you return the Jedis instance to the pool when done. This way you can overcome those strange errors and achieve great performance.
To use it, init a pool:
JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
You can store the pool somewhere statically, it is thread-safe.
JedisPoolConfig includes a number of helpful Redis-specific connection pooling defaults. For example, Jedis with JedisPoolConfig will close a connection after 300 seconds if it has not been returned.
You use it by:


Jedis jedis = pool.getResource();
try {
  /// ... do stuff here ... for example
  jedis.set("foo", "bar");
  String foobar = jedis.get("foo");
  jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike"); 
  Set<String> sose = jedis.zrange("sose", 0, -1);
} finally {
  /// ... it's time to release alive/broken Jedis instance...
  if (null != jedis) {
    jedis.close();
  }
}
/// ... when closing your application:
pool.destroy();


https://github.com/xetorthio/jedis/wiki/Getting-started