[javascript] sleep 기능

web 2017. 5. 31. 20:38


자바스크립트에서 타임아웃을 지정하려면 setTimeout 함수를 사용한다. 





setTimeout(function(){

....

}, 10000);

Posted by '김용환'
,


jquery에서 특정 html 컴포넌트를 접근하려면. 다음처럼 접근할 수 있다.


$('#atable > tbody > tr[id]')


그리고 json 객체를 생성하려면 JSON.stringify를 사용한다.



예제는 다음과 같다.



var objects = [];

$('#atable > tbody > tr[id]').each(function( index ) {

  var object = new Object();

  object.index=index;

  object.id=$(this).attr('id');

  objects.push(object);

});

var jsonObject = JSON.stringify(objects);




Posted by '김용환'
,


일래스틱서치는 5가지 저장소 타입을 공개하고 있다. 


기본적으로 일래스틱서치는 운영 체제 환경을 기반으로 최상의 구현을 선택한다.



* 첫 번째 방법은 elasticsearch.yml 파일에서 index.store.type 속성을 추가해 모든 인덱스에 설정하는 것이다. 예를 들어 모든 인덱스에 niofs 저장소 타입을 설정하려면 elasticsearch.yml 파일에 다음 라인을 추가 할 수 있다.


index.store.type: niofs 


두 번째 방법은 다음과 같은 커맨드를 사용해 인덱스를 생성할 때 인덱스의 저장소 타입을 설정하는 것이다.


curl -XPUT "http://localhost:9200/index_name" -d' { 

 "settings": { 

 "index.store.type": "niofs" 

 } 

}'





1. simplefs


simplefs는 랜덤 액세스 파일(Java RandomAccessFile-http://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html)를 사용해 구현된 Directory 클래스 구현을 사용하며 루신의 SimpleFSDirectory (http://lucene.apache.org/core/6_2_0/core/org/apache/lucene/store/SimpleFSDirectory.html)과 매핑된다. 매우 간단한 애플리케이션에서는 simplefs만으로 충분한다. 그러나 simplefs 저장소의 주요 병목은 다중 스레드가 접근할 때이며 이 때 성능이 떨어진다. 


index.store.type을 simplefs로 설정해야 한다.



2. niofs

niofs 저장소 타입은 java.nio 패키지의 FileChannel 클래스 (http://docs.oracle.com/javase/8/docs/api/java/nio/channels/FileChannel.html)를 기반으로하는 Directory 클래스 구현을 사용하며 루신의 NIOFSDirectory (https://lucene.apache.org/core/6_2_0/core/org/apache/lucene/store/NIOFSDirectory.html)과 매핑된다. niofs 저장소 구현은 성능 저하 없이 여러 스레드가 동일한 파일에 동시에 접근할 수 있게 한다. niofs 저장소를 사용하려면 index.store.type을 niofs로 설정해야한다.



3. mmapfs


mmapfs 저장소 타입은 루신의 MMapDirectory (http://lucene.apache.org/core/6_2_0/core/org/apache/lucene/store/MMapDirectory.html) 구현을 사용한다. mmapfs는 읽을 때는 mmap 시스템 호출 (http://en.wikipedia.org/wiki/Mmap)을 사용하고 저장할 때는 랜덤 액세스 파일을 사용한다. mmapfs 저장소는 매핑된 파일의 크기와 동일한 프로세스에서 사용 가능한 가상 메모리 주소 공간의 일부를 사용한다. 잠금 기능이 없으므로 다중 스레드가 접근할 때 확장이 가능하다. 운영 체제의 인덱스 파일을 읽기 위해 mmap을 사용할 때는 이미 캐시된 것처럼 보인다(가상 공간에 매핑되었다). 이 때문에 루신 인덱스에서 파일을 읽을 때 해당 파일을 운영 체제 캐시에 로드할 필요가 없으므로 접근이 더 빠르다. 기본적으로 루신과 일래스틱서치가 I/O 캐시에 직접 접근할 수 있어서 인덱스 파일에 빠르게 접근할 수 있다.


mmap 파일 시스템 저장소는 64비트 환경에서 가장 잘 작동하고 32비트 환경에서는 인덱스가 충분히 작고 가상 주소 공간이 충분하다고 확신할 때만 사용해야 한다. mmapfs 저장소를 사용하려면 index.store.type을 mmapfs로 설정해야 한다.


공부할만한 블로그 


http://blog.thetaphi.de/2012/07/use-lucenes-mmapdirectory-on-64bit.html


http://jprante.github.io/lessons/2012/07/26/Mmap-with-Lucene.html




4. fs

fs 저장소는 기본 파일 시스템 구현이다. fs 저장소가 기본으로 설정되면 일래스틱서치는 운영 체제 환경에 따라 최적의 구현을 선택할 수 있다. 윈도우 32비트에서는 simplefs, 다른 32비트에서는 niofs, 64비트 시스템에서는 mmapfs으로 선택된다.



5. default_fs


일래스틱서치 1.x버전에는 Hybrid(2.x버전에서는 default_fs라고 한다)와 Memory라는 두 가지 다른 저장소 타입이 사용되었다. 일래스틱서치 2.x부터는 Memory 저장소 타입이 제거되었다. 일래스틱서치 5.0 버전부터는 default_fs 저장소 타입이 더 이상 사용되지 않을 것이고 표시하고 있다. 이제 default_fs는 이전 버전과의 호환성을 위해 내부적으로 fs 타입을 지정하도록 되어 있고 조만간에 제거될 것이다.



Posted by '김용환'
,

html에서는 form안에 form을 넣을 수 없다. 

(정확히 말하면 chrom 기준)



html 코드에 div를 사용하는 것이 좋다.


<div class="form-group">

<label for="objectUrl" class="col-xs-2 control-label"><span class="fa fa-fw fa-bars"></span>이미지/동영상 업로드</label>

<div class="col-xs-10">

<input type="text" class="form-control" id="objectUrl" name="objectUrl" value="${actionTagGuide.objectUrl!}" ><br/>

   <label><input type="file" name="file" id="file" accept="image/*,video/*"/></label>

   <button type="button" class="btn btn-danger btn-upload">file upload</button> 

</div>

</div>



스크립트 코드는 다음과 같다.


<script>

$(document).ready(function() {

$('.btn-upload').on('click', function (){

if (confirm('Want to upload a image or a video file?')) {

var data = new FormData();

data.append("file", $('#file').prop('files')[0]);

console.log(data);

$.ajax({

            type: "POST",

            enctype: 'multipart/form-data',

            url: "/actiontag_guide/upload/",

            data: data,

            processData: false,

            contentType: false,

            cache: false,

            timeout: 600000,

            success: function (result) {

                console.log("SUCCESS : ", result.data.url);

                $('#objectUrl').attr("disabled", true) 

                $('#objectUrl').val(result.data.url)

            },

            error: function (e) {

                console.log("ERROR : ", e);

            }

        });

}

     });




Posted by '김용환'
,


Jquery에서 file upload하는 예제이다. 



html 코드


<div class="x-10">

 <input type="text" class="form-control" id="objectUrl" name="objectUrl" value="${actionTagGuide.objectUrl!}" ><br/>

    <label><input type="file" name="file" id="file"/></label>

    <button type="button" class="btn btn-danger btn-upload">파일 업로드</button> 

</div>



자바스크립트는 다음과 같다. 



$(document).ready(function() {

var today = (new Date()).yyyymmdd();

$('.btn-upload').on('click', function (){

if (confirm('Could you upload a file?')) {

var data = new FormData();

data.append("file", $('#file').prop('files')[0]);

console.log(data);

$.ajax({

            type: "POST",

            enctype: 'multipart/form-data',

            url: "/upload/"+today+"/",

            data: data,

            processData: false,

            contentType: false,

            cache: false,

            timeout: 600000,

            success: function (data) {

                $("#objectUrl").text(data);

                console.log("SUCCESS : ", data);

            },

            error: function (e) {

                $("#objectUrl").text(e.responseText);

                console.log("ERROR : ", e);

            }

        });

}

     });


});


Posted by '김용환'
,

과거에 네이버에 재직 중일 때, 지금까지 이해진 대표의 연단 중 괜찮다고 기억나는 부분을 인터넷 데이터를 통해 정리해봤다.



* 네이버(당시는 NHN)는 서비스 기업이다. 


소비자가 무엇을 원하는지 잘 아는 회사는 결코 망하지 않는다.



* 혁신의 핵심


혁신은 사용자 니즈를 찾는 것이다. 니즈를 확실하게 해결해주는 것. 그게 바로 혁신의 초점이다.




* 혁신

혁신에는 creativity가 문제가 아니라 discipline이 필요하다고 본다. 내가 하는 일을 딱 붙잡아야 한다. 이거 하려면 책상에 앉아서 엉덩이 붙이고 붙들어야 한다.

회사에서의 혁신의 방향은 자기 업무를 얼마나 어떻게 혁신할 수 있는 사람들이 있느냐 그게 따라 좌우된다.



* 인터넷 비즈니스


인터넷비즈니스는 브랜드 싸움이 아닌 퀄리티 싸움이다.




* 회사는 조기 축구회가 아니다.


조기 축구 동호회는 져도 되지만 프로축구단은 절대 져선 안됩니다. 우린 프로입니다.

작은 일에도 치열하게 임해야 하는 것입니다.




* 비전


비전이 너무 강하면 조직이 딱딱해질 수 있다. 회사는 빠르게 변화해고 유연성을 가져야 한다.




* 상대를 이길 수 있는 유일한 힘 


적의 군대가 철갑선 300척이라면 우리는 목선 10척밖에 되지 않는다. 


Posted by '김용환'
,


Tom Peters는 초우량 기업의 조건, 미래를 경영하라, 경영혁명이라는 책을 썼고 컨설팅 경영학자 중 한 명이다. 


조금 오래되긴 했지만 Practical한 지혜는 예전이나 지금이나 비슷한 것 같다. 


좋은 내용은 발췌했다.







* 현재 제 목록의 첫 번째 내용은


Fail,

Forward,

Fast


이다. 실수하지 않으면 배울 것도 없다.



* 평점 4.0이 넘는 학생을 절대로 절대로 절대로 회사에서 뽑지 말라.

그렇다고 2.0짜리도 안됩니다. 게으르다거나 멍청하단 것이니까요.




* 성공한 사업가의 12가지의 비밀


Successful Businesses’ Dozen Truths: TP’s 30-Year Perspective 


1. Insanely Great & Quirky Talent. 

미칠정도로 이상한 재능을 가져라


2. Disrespect for Tradition. 

전통을 무시해라


3. Totally Passionate (to the Point of Irrationality) Belief in What We Are Here to Do. 

비이성적인 것을 추구하고(그 정도로 열정을 지녀라) 자신이 할 일을 믿어라


4. Utter Disbelief at the BS that Marks “Normal Industry Behavior.” 

정상적인 행동이라 여기지는 것을 불신해라


5. A Maniacal Bias for Execution ... and Utter Contempt for Those Who Don’t “Get It.” 

철저하게 실행하고 따르지 못한 이들을 경멸하라


6. Speed Demons. 

속도광이 되어라


7. Up or Out. (Meritocracy Is Thy Name. Sycophancy Is Thy Scourge.) 

엘리트를 추구하되, 아첨꾼은 내쫓아라


8. Passionate Hatred of Bureaucracy. 

관료주의를 철저하게 증오하라


9. Willingness to Lead the Customer ... and Take the Heat Associated Therewith. (Mantra: Satan Invented Focus Groups to Derail True Believers.) 

고객을 주도할 의지를 갖고 형성된 관계를 이어가라

(만트라 : 포커스 그룹은 악마가 탈선시킨 사람들이다)


10. “Reward Excellent Failures. Punish Mediocre Successes.” 

훌륭한 실패를 보상하라. 어정쩡한 성공을 벌하라


11. Courage to Stand Alone on One’s Record of Accomplishment Against All the Forces of Conventional Wisdom. 

일반적 상식의 힘에 맞서서 혼자서는 용기를 가져라


12. A Crystal Clear Understanding of the power of a Good Story. (Brand Power.)

브랜드 파워라 불르는 것의 힘을 명확히 이해하라



* 여러분의 인생은 여러분의 것입니다.

멋지게 살아가세요. 

Posted by '김용환'
,


parquet는 성능이 좋은 것으로 알려져 있지만, 일반 텍스트로 볼 수 없다는 단점이 있다..


그러나 기능적으로 봤을 overwrite를 할 수 있다는 점에서.. parquet가 많이 쓰여질 것 같다.




로컬 장비에서 parquet 테스트는 다음처럼 진행 할 수 있다. 



scala> val ds = Seq(1, 2, 3, 4, 5).toDS

ds: org.apache.spark.sql.Dataset[Int] = [value: int]


scala> ds.write.parquet("/usr/local/spark-2.1.0-bin-hadoop2.7/test1")

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".

SLF4J: Defaulting to no-operation (NOP) logger implementation

SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.


scala> val fromParquet = spark.read.parquet("/usr/local/spark-2.1.0-bin-hadoop2.7/test1")

fromParquet: org.apache.spark.sql.DataFrame = [value: int]


scala> fromParquet

res2: org.apache.spark.sql.DataFrame = [value: int]


scala> fromParquet.show

+-----+

|value|

+-----+

|    1|

|    2|

|    3|

|    4|

|    5|

+-----+



Posted by '김용환'
,


일래스틱서치 5.0부터 elasticsearch.yml에 index.routing.allocation.total_shards_per_nod 속성을 저장할 수 없다. 


elasticsearch.yml에 index.routing.allocation.total_shards_per_node 속성을 설정하려 한다면 일래스틱서치 노드의 로그 파일에서 다음과 같은 에러가 나타날 것이다.



[2017-05-25T20:32:09,248][WARN ][o.e.c.s.SettingsModule   ] [5OEGj_a]

*************************************************************************************

Found index level settings on node level configuration.


Since elasticsearch 5.x index level settings can NOT be set on the nodes

configuration like the elasticsearch.yaml, in system properties or command line

arguments.In order to upgrade all indices the settings must be updated via the

/${index}/_settings API. Unless all settings are dynamic all indices must be closed

in order to apply the upgradeIndices created in the future should use index templates

to set default values.


Please ensure all required values are updated on all indices by executing:


curl -XPUT 'http://localhost:9200/_all/_settings?preserve_existing=true' -d '{

  "index.routing.allocation.total_shards_per_node" : "4"

}'

*************************************************************************************



[2017-05-25T20:32:09,252][WARN ][o.e.b.ElasticsearchUncaughtExceptionHandler] [] uncaught exception in thread [main]
org.elasticsearch.bootstrap.StartupException: java.lang.IllegalArgumentException: node settings must not contain any index level settings
at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:127) ~[elasticsearch-5.3.1.jar:5.3.1]
at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:114) ~[elasticsearch-5.3.1.jar:5.3.1]
at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:58) ~[elasticsearch-5.3.1.jar:5.3.1]
at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:122) ~[elasticsearch-5.3.1.jar:5.3.1]
at org.elasticsearch.cli.Command.main(Command.java:88) ~[elasticsearch-5.3.1.jar:5.3.1]
at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:91) ~[elasticsearch-5.3.1.jar:5.3.1]
at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:84) ~[elasticsearch-5.3.1.jar:5.3.1]
Caused by: java.lang.IllegalArgumentException: node settings must not contain any index level settings
at org.elasticsearch.common.settings.SettingsModule.<init>(SettingsModule.java:132) ~[elasticsearch-5.3.1.jar:5.3.1]
at org.elasticsearch.node.Node.<init>(Node.java:342) ~[elasticsearch-5.3.1.jar:5.3.1]
at org.elasticsearch.node.Node.<init>(Node.java:242) ~[elasticsearch-5.3.1.jar:5.3.1]
at org.elasticsearch.bootstrap.Bootstrap$6.<init>(Bootstrap.java:242) ~[elasticsearch-5.3.1.jar:5.3.1]
at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:242) ~[elasticsearch-5.3.1.jar:5.3.1]
at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:360) ~[elasticsearch-5.3.1.jar:5.3.1]
at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:123) ~[elasticsearch-5.3.1.jar:5.3.1]





인덱스이름/_settings api를 동적으로 호출해 노드 당 전체 샤드 개수를 설정할 수 있다.


$ curl -XPUT 'localhost:9200/person/_settings' -d '{

 "index.routing.allocation.total_shards_per_node": "4"

}'




잉ㄹ래스틱서치의 예외에서 나온 내용처럼 모든 인덱스에 대한 설정을 수정하려면 다음처럼 호출할 수 있다. 


curl -XPUT 'http://localhost:9200/_all/_settings?preserve_existing=true' -d '{

  "index.routing.allocation.total_shards_per_node" : "4"

}'



Posted by '김용환'
,



transient 가 있다. 


일래스틱서치에는 단일 호출에 여러 속성을 포함할 수 있다. 


커맨드의 transient라는 이름은 클러스터를 다시 시작한 후에는 해당 속성을 잊어 버린다는 것을 의미한다.


curl -XPUT 'localhost:9200/_cluster/settings' -d '{

 "transient" : {

  "cluster.routing.allocation.require.group": "group1"

 }

}'




재시작 후에 해당 속성을 잊는 것을 피하고 영구적으로 설정하려면 transient 속성 대신 persistent를 사용한다. 


curl -XPUT 'localhost:9200/_cluster/settings' -d '{

 "persistent" : {

  "cluster.routing.allocation.require.group": "group1"

 }

}'





https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-update-settings.html

Posted by '김용환'
,