SyntaxError: Non-ASCII character '\xec' in file oncall-bot.py on line 50, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details


이 에러는 한글 때문에 발생한 것이다. mac에는 문제 없으나 linux에서 발생했다. 


code에 utf-8 인코딩 설정을 추가하니 더 이상 문제가 발생하지 않는다. 

# -*- coding: utf-8 -*- 


Posted by '김용환'
,


스칼라의 접근 한정자(access modifier)는 자바와 비슷하다. 그러나 하나 더 추가되는 내용이 있다. 


수식자(qualifier)를 사용해 스칼라의 접근 한정자가 확장될 수 있다. private[X] 또는 protected[X] 타입의 한정자는 각각 접근이 X까지 private 또는 protected임을 의미한다. 여기서 X는 패키지, 클래스, 싱글턴 오브젝트를 나타낸다.


다음 예를 살펴보자.



scala> :paste

// Entering paste mode (ctrl-D to finish)



package Country {

package Professional {

  class Executive {

    private[Professional] var jobTitle = "Engineer"

    private[Country] var friend = "Andrew Ng"

    protected[this] var option = "X"


    def getInfo(another : Executive) {

      println(another.jobTitle) // 동작한다

      println(another.friend) // 동작한다

      println(another.secret) //에러가 발생한다

      println(this.option) // 동작한다

    }

  }

}

}


  • jobTitle 변수는 Professional 패키지 내의 모든 클래스에서 접근할 수 있다.

  • friend 변수는 Country 패키지내의 모든 클래스에서 접근할 수 있다.

  • secret 변수는 인스턴스 메소드(this)의 암시(implicit) 오브젝트에만 접근할 수 있다.



Posted by '김용환'
,



lazy val에 대해 잘 설명된 블로그 글이다.


https://blog.codecentric.de/en/2016/02/lazy-vals-scala-look-hood/




스칼라의 LazyCell 클래스에는 lazy val이 있다. 



final class LazyCell {
  lazy val value: Int = 42
}


자바로 디컴파일 해보면 아래와 같이 변환된다고 블로그 글에 나와 있다.


final class LazyCell {
  @volatile var bitmap_0: Boolean = false                   // (1)
  var value_0: Int = _                                      // (2)
  private def value_lzycompute(): Int = {
    this.synchronized {                                     // (3)
      if (!bitmap_0) {                                      // (4)
        value_0 = 42                                        // (5)
        bitmap_0 = true
      }
    }
    value_0
  }
  def value = if (bitmap_0) value_0 else value_lzycompute() // (6)
}


scala 2.12로 컴파일하고 실제로 jad 로 디컴파일하면 다음과 같다. 거의 동일하다.


내부적으로 volatile과 synchronized를 사용한다. 즉 multiple thread에서 동기화가 보장되도록 되어 있다! 예제2에서 설명하고 있다. 



// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.

// Jad home page: http://www.kpdus.com/jad.html

// Decompiler options: packimports(3)

// Source File Name:   LazyCell.scala



public final class LazyCell

{


    private int value$lzycompute()

    {

        synchronized(this)

        {

            if(!bitmap$0)

            {

                value = 42;

                bitmap$0 = true;

            }

        }

        return value;

    }


    public int value()

    {

        return bitmap$0 ? value : value$lzycompute();

    }


    public LazyCell()

    {

    }


    private int value;

    private volatile boolean bitmap$0;

}





예제 1이다. 참조 블로그의 1번째 예제를 repl에서 실행해 본다.



scala> :paste

// Entering paste mode (ctrl-D to finish)


import scala.concurrent.ExecutionContext.Implicits.global

import scala.concurrent._

import scala.concurrent.duration._


def fib(n: Int): Int = n match {

  case x if x < 0 =>

    throw new IllegalArgumentException(

      "Only positive numbers allowed")

  case 0 | 1 => 1

  case _ => fib(n-2) + fib(n-1)

}


object ValStore {

  lazy val fortyFive = fib(45)                   // (1)

  lazy val fortySix  = fib(46)                   // (2)

}


object Scenario1 {

  def run = {

    val result = Future.sequence(Seq(            // (3)

      Future {

        println(ValStore.fortyFive)

        println("done (45)")

      },

      Future {

        println(ValStore.fortySix)

        println("done (46)")

      }

    ))

    Await.result(result, 1.minute)

  }

}



// Exiting paste mode, now interpreting.


import scala.concurrent.ExecutionContext.Implicits.global

import scala.concurrent._

import scala.concurrent.duration._

fib: (n: Int)Int

defined object ValStore

defined object Scenario1


scala> Scenario1.run

1836311903

done (45)

-1323752223

done (46)

res4: Seq[Unit] = List((), ())




처음 실행할 때는 속도가 걸리지만, 다음 번 실행할 때는 무척 빠르다. lazy val의 특성이 있다. 


scala> Scenario1.run

-1323752223

done (46)

1836311903

done (45)

res5: Seq[Unit] = List((), ())


scala> Scenario1.run

1836311903

done (45)

-1323752223

done (46)

res6: Seq[Unit] = List((), ())






2번째 예제는 lazy val의 내부 synchronized를 이용해 deal lock을 유발시키는 코드이다. 여러 쓰레드를 사용하면서 lazy val을 잘 못 쓴다면 dead lock이 발생할 수 있다.



scala> :paste

// Entering paste mode (ctrl-D to finish)


import scala.concurrent.ExecutionContext.Implicits.global

import scala.concurrent._

import scala.concurrent.duration._


object A {

  lazy val base = 42

  lazy val start = B.step

}


object B {

  lazy val step = A.base

}


object Scenario2 {

  def run = {

    val result = Future.sequence(Seq(

      Future { A.start },                        // (1)

      Future { B.step }                          // (2)

    ))

    Await.result(result, 1.minute)

  }

}





dead lock이 발생했다.

scala> Scenario2.run
java.util.concurrent.TimeoutException: Futures timed out after [1 minute]
  at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:255)
  at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:259)
  at scala.concurrent.Await$.$anonfun$result$1(package.scala:215)
  at scala.concurrent.BlockContext$DefaultBlockContext$.blockOn(BlockContext.scala:53)
  at scala.concurrent.Await$.result(package.scala:142)
  at Scenario2$.run(<console>:30)
  ... 29 elided






3번째 예제이다. 참조 블로그를 보면 deadlock 예제로 되어 있다. 


scala> :paste

// Entering paste mode (ctrl-D to finish)


import scala.concurrent.ExecutionContext.Implicits.global

import scala.concurrent._

import scala.concurrent.duration._


trait Compute {

  def compute: Future[Int] =

    Future(this.synchronized { 21 + 21 })        // (1)

}


object Scenario3 extends Compute {

  def run: Unit = {

    lazy val someVal: Int =

      Await.result(compute, 1.minute)            // (2)

    println(someVal)

  }

}



실제로 실행해 보면 deadlock은 발생되지 않는다. 



scala> Scenario3.run

42




lazy val에 synchronized가 된다면 인스턴스는 분명 deadlock 상황에 빠져야 한다. 그러나 컴파일러가 똑똑해져서 문제가 발생하지는 않는다.



 lazy val 다음 단계는 http://docs.scala-lang.org/sips/pending/improved-lazy-val-initialization.html에 있다.

Posted by '김용환'
,



docker container의 로그를 보려면 docker logs를 활용한다.


먼저 docker ps로 container id를 확인한다.


$ docker ps

CONTAINER ID        IMAGE                                                              COMMAND                  CREATED             STATUS              PORTS                      NAMES

3bfaccc746cc        dockerhub.google.com/excel/kami:develop   "/bin/sh -c 'target/u"   4 minutes ago       Up 4 minutes        0.0.0.0:10399->9000/tcp    kami-1


docker logs로 container log를 확인한다. 



$ docker logs 46817472b388

[info] application - Creating Pool for datasource 'default'

[info] p.a.d.DefaultDBApi - Database [default] connected at jdbc:mysql://1.1.1.1:3306/diction??autoReconnect=true&useSSL=false

[info] play.api.Play - Application started (Prod)

[info] p.c.s.AkkaHttpServer - Listening for HTTP on /0:0:0:0:0:0:0:0:9000



tail, 시간대역 별로도 볼 수 있다.


참조

https://docs.docker.com/engine/reference/commandline/logs/#usage




Posted by '김용환'
,


sbt를 사용하면서 hbase 연동시 만난 library 의존성 라이브러리를 만나며 부딪힌 문제를 정리했다. 



1.

"org.apache.hadoop" % "hadoop-core" % "1.2.1",


hadoop-core는 예전 버전이고, hadoop-common으로 넘어갔음. 안쓰는게 좋음.ㅠㅠ







2. 



Caused by: java.lang.UnsupportedOperationException: Not implemented by the DistributedFileSystem FileSystem implementation


다음 라이브러리를 읽으면 에러가 발생되지 않는다.

"org.apache.hadoop" % "hadoop-hdfs" % "2.7.1",



3. 


Caused by: java.lang.NoSuchMethodError: org.apache.hadoop.net.NetUtils.getInputStream(Ljava/net/Socket;)Lorg/apache/hadoop/net/SocketInputWrapper;


다음 라이브러리를 읽으면 에러가 발생되지 않는다.

"org.apache.hadoop" % "hadoop-client" % "2.7.1",




4.


Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.fs.GlobalStorageStatistics$StorageStatisticsProvider


다음 라이브러리를 읽으면 에러가 발생되지 않는다.

"org.apache.hadoop" % "hadoop-common" % "2.8.0"


'scala' 카테고리의 다른 글

스칼라의 접근 한정자  (0) 2017.11.07
lazy val의 내부(volatile/synchronized)  (0) 2017.11.06
[play2] globalsetting  (0) 2017.11.02
play2에서 apache phoenix 드라이버 사용 이슈.  (0) 2017.10.31
[play2] import play.db.Database 에러  (0) 2017.10.30
Posted by '김용환'
,



kafka 업글 또는 운영할 때 server.properties에 아래 설정을 잘 저장해야 한다. 


버전업할 때는 특히 아래 설정을 잘 조정하면서 진행할 수 있다. 

inter.broker.protocol.version=0.10.1.0

log.message.format.version=0.10.1.0



참조

https://kafka.apache.org/documentation/

http://christianposta.com/kafka-docs/_book/getting-started/upgrading.html

Posted by '김용환'
,



hadoop & hbase간의 의존성/연관성(compatible) 버전 찾기.



https://hbase.apache.org/book.html#hadoop


Hadoop version support matrix
  • "S" = supported

  • "X" = not supported

  • "NT" = Not tested




Posted by '김용환'
,




mesos에서 chronos 프레임워크를 사용할 때 ISO 8601 - duration 정책을 사용한다. 




https://mesos.github.io/chronos/docs/api.html



schedule: The scheduling for the job, in ISO 8601 format. Consists of 3 parts separated by /:
  • The number of times to repeat the job: Rn to repeat n times, or R to repeat forever
  • The start time of the job. An empty start time means start immediately. Our format is ISO 8601YYYY-MM-DDThh:mm:ss.sTZD (e.g., 1997-07-16T19:20:30.45+01:00) where:
    • YYYY = four-digit year
    • MM = two-digit month (01 = January, etc.)
    • DD = two-digit day of month (01 through 31)
    • hh = two-digit hour in 24-hour time (00 through 23)
    • mm = two-digit minute (00 through 59)
    • ss = two-digit second (00 through 59)
    • s = one or more digits representing a decimal fraction of a second
    • TZD = time zone designator (Z for UTC or +hh:mm or -hh:mm for UTC offset)
  • The run interval, defined following the “Duration” component of the ISO 8601 standard. P is required. T is for distinguishing M(inute) and M(onth)––it is required when specifying Hour/Minute/Second. For example:
    • P10M = 10 months
    • PT10M = 10 minutes
    • P1Y12M12D = 1 year, 12 months, and 12 days
    • P12DT12M = 12 days and 12 minutes
    • P1Y2M3DT4H5M6S = 1 year, 2 months, 3 days, 4 hours, and 5 minutes




Here is an example job hash: json { "schedule": "R10/2012-10-01T05:52:00Z/PT2S", "name": "SAMPLE_JOB1", "epsilon": "PT15M", "command": "echo 'FOO' >> /tmp/JOB1_OUT", "owner": "bob@airbnb.com", "async": false }



Durations[edit]

PnYnMnDTnHnMnS
PnW
P<date>T<time>

Durations define the amount of intervening time in a time interval and are represented by the format P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W as shown to the right. In these representations, the [n] is replaced by the value for each of the date and time elements that follow the [n]. Leading zeros are not required, but the maximum number of digits for each element should be agreed to by the communicating parties. The capital letters PYMWDTHM, and S are designators for each of the date and time elements and are not replaced.

  • P is the duration designator (for period) placed at the start of the duration representation.
  • Y is the year designator that follows the value for the number of years.
  • M is the month designator that follows the value for the number of months.
  • W is the week designator that follows the value for the number of weeks.
  • D is the day designator that follows the value for the number of days.
  • T is the time designator that precedes the time components of the representation.
    • H is the hour designator that follows the value for the number of hours.
    • M is the minute designator that follows the value for the number of minutes.
    • S is the second designator that follows the value for the number of seconds.

For example, "P3Y6M4DT12H30M5S" represents a duration of "three years, six months, four days, twelve hours, thirty minutes, and five seconds".

Date and time elements including their designator may be omitted if their value is zero, and lower order elements may also be omitted for reduced precision. For example, "P23DT23H" and "P4Y" are both acceptable duration representations. However, at least one element must be present, thus "P" is not a valid representation for a duration of 0 seconds. "PT0S" or "P0D", however, are both valid and represent the same duration.

To resolve ambiguity, "P1M" is a one-month duration and "PT1M" is a one-minute duration (note the time designator, T, that precedes the time value). The smallest value used may also have a decimal fraction, as in "P0.5Y" to indicate half a year. This decimal fraction may be specified with either a comma or a full stop, as in "P0,5Y" or "P0.5Y". The standard does not prohibit date and time values in a duration representation from exceeding their "carry over points" except as noted below. Thus, "PT36H" could be used as well as "P1DT12H" for representing the same duration. But keep in mind that "PT36H" is not the same as "P1DT12H" when switching from or to Daylight saving time.

Alternatively, a format for duration based on combined date and time representations may be used by agreement between the communicating parties either in the basic format PYYYYMMDDThhmmss or in the extended format P[YYYY]-[MM]-[DD]T[hh]:[mm]:[ss]. For example, the first duration shown above would be "P0003-06-04T12:30:05". However, individual date and time values cannot exceed their moduli (e.g. a value of 13 for the month or 25 for the hour would not be permissible).[30]

Although the standard describes durations as part of time intervals, which are discussed in the next section, the duration format is widely used independent of time intervals, as with the Java 8 Duration class[31][32].

Posted by '김용환'
,



참고 자료


http://www.riss.kr/search/detail/DetailView.do?p_mat_type=1a0202e37d52c72d&control_no=116dc9ff4db503dbd18150b21a227875#redirect



스마트폰 사용이 보편화 되면서, 모바일 인스턴트 메신저(MIM)의 사용 역시 대중화 되고 있다. 최근 MIM 내 그래픽 이모티콘은 사용자들 간 의사소통을 원활하게 하기 위한 도구로서의 역할을 하고 있는 동시에, 기업 입장에서는 이모티콘의 판매가 주요 비즈니스 모델 중 하나로 인식되고 있다. 이렇듯 이모티콘이 하나의 상품으로 MIM 서비스의 주요 비즈니스 모델로 인식, 개발되고 있는 현 시점에서 이모티콘 구매의도에 직접적으로 영향을 미치는 요인들에 대해 탐색한 연구는 매우 드문 실정이다. 따라서 본 연구는 이러한 학문적, 실무적 간극(gap)을 메우고자 이모티콘의 사용동기, 사용태도 및 구매의도에 영향을 미치는 요인들 간 관계에 대해 탐색해보고자 하였다. 본 연구의 실증분석 결과, MIM 내의 이모티콘 사용동기는 크게 이모티콘 사용에 대한 지각된 유용성과 지각된 즐거움으로 구성될 수 있으며, 지각된 유용성과 지각된 즐거움은 이모티콘을 사용한 대화 시, 몰입의 정도와 사회적 영향력에 모두 정(+)의 영향을 미치는 것으로 나타났다. 또한 이러한 이모티콘 사용동기와 플로우, 그리고 사회적 영향력은 최종적으로 이모티콘 사용태도에 긍정적 영향을 미쳤으며, 이모티콘 사용태도가 호의적일수록 이모티콘 구매의도도 높게 나타나는 것으로 밝혀졌다. 그러나 플로우(flow)와 사회적 영향력(social influence)은 구매의도에 직접적인 영향을 미치지는 않았다. 본 연구는 아직 그 연구가 활발하게 진행되지 않은 폐쇄형 SNS 내의 상품으로서의 이모티콘에 대한 구매의도와 그 동기 간 관계를 실증적으로 검증했다는 점에서 그 의의가 있다.




http://www.riss.kr/search/detail/DetailView.do?p_mat_type=1a0202e37d52c72d&control_no=4ea847cdd9c9a625d18150b21a227875



본 연구는 애니메이션 이모티콘의 표현유형(일러스트와 사진)에 따라 이모티콘에 대한 의미해석과 사용자 평가의 차이가 있는지, 그리고 이모티콘 표현유형에 따라 이모티콘 사용자 평가 요인이 지속사용의도에 미치는 영향에 차이가 있는가를 알아보기 위한 것이다. 연구의 진행을 위하여 20대~30대 중국인 234명에게 12가지의 일러스트와 사진 이모티콘을 제시하고 의미해석에 대한 12개 문항과 ①심미성, ②유희성, ③유용성, ④명확성, ⑤효율성, ⑥지속사용의도 6개 변인 총 22개 문항을 측정하였다. 연구 결과는 다음과 같다. 1)일러스트 애니메이션 이모티콘에 대한 의미해석에서 행위적 의미에서 사진 이모티콘의 의미해석 일치 정도는 일러스트 이모티콘보다 매우 높게 나타났으나, 감정적 의미 측면에서는 일러스트 이모티콘이 사진 이모티콘보다 일치 정도가 비교적 높게 나타났다. 2)이모티콘의 특성이 지속사용의도에 영향을 미치는가에 대한 검증에서는 명확성 외에 나머지 4개 이모티콘 특성 요인인 심미성, 유희성, 유용성과 효율성이 지속사용의도에 유의미한 영향을 미치는 것으로 나타났다. 각 요인들의 효과크기를 살펴보면 이모티콘 특성 중 효율성이 지속사용의도에 가장 큰 영향을 미치는 것으로 나타나 효율성이 지속사용의도를 야기하는 중요한 요소임을 알 수 있다. 그러나 일러스트 표현과 사진 표현을 나누어 검증해보면, 일러스트 애니메이션 이모티콘의 경우에는 효율성을 중심으로 하여 유희성이 지속사용의도를 형성하는데 영향을 미치는 것으로 나타나는 반면에, 사진 애니메이션 이모티콘의 경우에는 심미성만이 높은 영향력을 보이는 것으로 나타났다.




페이스북 버전

https://www.google.co.kr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwj-tLH29p7XAhUMbrwKHeSTAkEQFgglMAA&url=https%3A%2F%2Fblogs.cornell.edu%2Fsocialmedialab%2Ffiles%2F2013%2F12%2FSocial-sharing-of-emotions-on-Facebook.pdf&usg=AOvVaw2cMix4WrtkxcQsHyL5WnNF


ABSTRACT People often share emotions with others in order to manage their emotional experiences. We investigate how social media properties such as visibility and directedness affect how people share emotions in Facebook, and their satisfaction after doing so. 141 participants rated 1,628 of their own recent status updates, posts they made on others’ timelines, and private messages they sent for intensity, valence, personal relevance, and overall satisfaction felt after sharing each message. For network-visible channels— status updates and posts on others’ timelines—they also rated their satisfaction with replies they received. People shared differently between channels, with more intense and negative emotions in private messages. People felt more satisfied after sharing more positive emotions in all channels and after sharing more personally relevant emotions in network-visible channels. Finally, people’s overall satisfaction after sharing emotions in networkvisible channels is strongly tied to their reply satisfaction. Quality of replies, not just quantity, matters, suggesting the need for designs that help people receive valuable responses to their shared emotions.

Posted by '김용환'
,

[play2] globalsetting

scala 2017. 11. 2. 12:02



play2 2.4까지 잘 사용했던 globalsetting는 deprecated되었다.


eager bindings로 변경해야 한다. 


https://www.playframework.com/documentation/2.6.x/ScalaDependencyInjection#Eager-bindings

Posted by '김용환'
,