[컴] Google cloud platform (GCP) 난잡 정리

google cloud platform



Google cloud platform (GCP) 난잡 정리

구글의 가격정책

  • 서버를 오래 띄워놓으면 할인율이 커진다.
  • vcpu 단위로 계약 한다. / vcpu 단위로 commit 을 매입?
  • preemptive use 에 대한 할인??
  • hour 단위보다 낮은 단위 , 분, 초 에 대한 과금도 가능

billing 정보 분석

  • Billing 정보를 BigQuery 로 export 로 받아 놓으면, 쿼리 를 통해서 정보를 자세하게 뽑아낼 수 있다.

BigQuery(빅쿼리) 과금

  • 읽어드리는 데이터 의 용량으로 과금이 된다.
  • select join 등 할 때 사용하는 데이터 의 양이 크면 큰돈
  • 슬롯 정액제 , 특정 슬롯을 구매하고, 그 안에서 계속 사용 가능

과금

  • GCP 는 나가는 traffic 에 대한 비용에 대해 과금한다. (서버에서 나가는)
  • 대륙간 region 을 이동하는 packet 에 대한 과금도 한다.(리전을 넘어가지 않는한 과금을 하지는 않는다.)
과금종류
  • Per-second billing
  • sustained use discounts
  • committed use discounts

Quota 이슈

  • 서비스 릴리즈 전에 quota 관련 test 필요
  • https://bespinglobal.qwiklabs.com/
    • 여기에서 구글 클라우드 관리 할 수 있게 이 베스핀 애들이 만들어 놨다고 함

quota 종류

  1. 확장 불가능한 qutoa
  2. 요청하면 확장을 할 수 있는 quota

google cloud platform 제품 및 서비스

vm instance

  • startup script 를 bucket 에 올려서 instance 를 띄울때마다 원하는 script 을 실행하게 할 수 있다.

GCP 접속 방법

  • Cloud platform Console
  • Cloud Shell and Cloud SDK (shell 은 GCP 접속하면 기본으로 하나 제공됨,CLI)
    • 보안 이슈로 막아야 하는 케이스 들이 있다 고 함...
  • Cloud Console Mobile App
  • Rest-based API

GCP 계층 구조

  • https://cloud.google.com/resource-manager/docs/cloud-platform-resource-hierarchy?hl=ko
  • 베스핀 글로벌 사이트 에서 왼쪽 위 리스트에서 확인가능
  • 모든 리소스는 프로젝트 에 종속된다.
  • organization 아래 organization 은 불가능
  • 권한(IAM, 정책)은 상속된다. 상위 계층에 권한을 주면, 하위 구조에도 영향이 미친다
  • IAM 은 여러개의 permission 을 갖는 개체 , Role 이라 부르는 듯
    • predefined role 들이 존재한다. 이것을 수정해서 자신의 롤을 만들어도 된다.(primitive, predefined, cutom role 이 가능)

서비스 계정 Service Account

  • application 이 gcp 에 접근 하기 위한 계정(apache 의 nobody 계정 같은 느낌)
  • project 내에서 만들어진다.
  • 계층 구조에 있는 상속 이 동작하기 때문에, 프로젝트 위 폴더에서 사용하도록 서비스 계정 을 만들 수 있다???
  • 하지만 편리하게 관리하는 것은 프로젝트 별로 관리하는 것이 낫다?
  • 이건 그냥 auth key 같은 녀석인듯?

VPC

  • VPC 존재 , 아마존이랑 비슷한듯
  • VPC 는 하나의 LAN 이라고 보면 된다.
  • 여러 region 을 하나의 VPC 을 생성할 수 있다.
  • shared VPC 형식으로 네트워크 A 와 네트워크 B 사이에 A와 B 가 공유하는 네트워크 C 를 만들어 쓰기도 한다???

vm instance

리전 Region

HW 하드웨어

  • standard, SSD, local SSD 가 있는데,
  • local SSD 는 cache 로만 제공한다.
  • 동일단가 대비 disk 성능이 좋다
  • 용량을 늘리면 성능이 올라간다.
  • SSD 는 타사 대비 2배 ?

preemptible instance

  • 이녀석은 매우 저렴
  • preemptible instance 는 24시간 이후에 자동으로 삭제
  • 이녀석은 주위에 instance가 필요하면 가져가 버린다.
  • OS 에서 preemption 을 하는 것처럼 instance 가 GCP 에 의해 preemption 이 가능한 듯 하다. 그래서 구글 맘대로 가져가 버리고, 우리가 그것을 계속 차지 하고 있지 못한다.
  • 항상 ready 해야 하지 않고, 빠른 응답이 중요하지 않은 경우 쓰면 좋을 듯

migration

  • instance 는 짧게는 일주일 길게는 한달에 한번 migration 이 구글에 의해 일어난다.
  • gpu instance 를 활용해서 머신러닝 하는게 제일 저렴
  • gpu instance 는 live migration 시점에 서버를 내린다.(하드웨어 종속성이 커서 그렇다)
  • 다른 instance 는 그저 알람 하나를 주는 정도다.

load balancer

proxy

앞단에 google front engine 에 존재(gfe 가 proxy역할), 단일 ip 를 물고 있다.
proxy 기반 load balancer
  • global https
  • global ssl proxy
  • global tcp proxy

regional

도쿄 리전 을 만들고 리전에 위치한 프론트가 그 트래픽을 받아준다. 프록시를 통하지 않는다. 클라이언트 아이피가 직접 도달한다.
DSR 형태로 동작
그래서 리저널은 그냥 라우팅만 해주는 정도이다.(TCP/UDP 단에서 라우팅) 성능 저하가 없다.
특정한 정책을 넣거나, 자동 모니터 등을 제공하진 않는다.
  • regional
  • regional internal : 내부 L4 switch 라고 보면 된다.

DNS

  • 클라우드 DNS
  • internal dns service 도 제공

CDN

  • 대용량 스트리밍 관련 CDN도 제공
  • 백엔드로 붙일 수 있는게, global load balancer 에 대해서만 CDN활성화 가능
  • 버킷에 올라가 있는 것만 가능??
  • 타사대비 가격 경쟁력이 있다고 한다??

interconnect option , vpn

회사 내부 망과 gcp 와의 통신을 위한 여러 interconnect option 을 제공
특정 아이피에서 접속할 때 gcp에 접근할 때 빠르게 해준다.
  • direct peering: 구글이 직접 라우팅
  • carrier peering : 망사업자를 통해 지원 ?
서울 리전 이 들어오고 나야 가능? 하다고 함.
  • dedicated interconncet : 구글 데이터 센터에 직접 전용선을 붙이는 것, 데이터 센터가 인접할 수록 유리
  • partner interconnect : ISP 나 망사업자 를 통하는 방식

GCP web page 에서 instance 에 있는 ssh 버튼 으로 접속시

자세한 내용은 찾아봐야 할 듯
  • 구글의 ssh proxy 를 이용해서
  • 접속 하면서, 그때 키를 받아서 메타데이터를 업데이트 해서 접속?

클라우드 스토리지 Cloud Storage

  • 초당 수만번의 파일을 쓰거나 읽거나, 급격한 요청이 들어오면, 약간의 delay 가 발생할 수 있지만, - 실서버에서 큰 이슈가 된 적은 없다.
  • 퍼포먼스에서 문제는 없다.
  • 스토리지 레벨의 암호화는 되고 있다. 암호화를 할 때 별도의 키 를 세팅할 수 있다.
  • 대량의 데이터를 올릴 때는 그냥 데이터 센터에 보내면 자기내 들이 올리는 서비스 도 제공해 준다.
  • 클라우드 스토리지 파일들은 bucket 으로 구성된다.

Storage class

  • 멀티 리저널(multi regional), 리저널, Nearline, Coldline
  • 리저널은 차이가 없다.
백업용
  • Nearline, Coldline 은 저장용으로 적당
    • Nearline 은 한달에 한번 쓸때
    • Coldline 은 사고날때 쓰는 용도
  • 저장용량당 비용이 싸다. 대신 한번에 읽기 쓰기 할 때의 비용이 비싸다.

클라우드 SQL

  • MySQL, PostgresSQL 만 제공

Cloud BigTable

  • Cloud BigTable 은 NoSQL 에 의해 managed 된다.
  • 대량 처리에 특화된다.
  • 대량의 데이터 insert , select
  • 키 기반으로 빠른 결과 얻을 때
  • HBase API
  • instance 를 많이 늘릴 수록 빨라진다.
  • 클러스터의 노드 수가 많아 질 수록 속도가 올라간다.(반응성이 좋아진단 소린가?)

cloud spanner

  • 국내 게임사는 아직 선택 안했다.
  • 많이 비싸다
  • 자동 복사 가 가능
  • horizontally scalable RDBMS
  • global consistency 를 보장
  • 해외사례는 있지만, 국내 사례는 없다.

BigQuery

  • 대량의 데이터에 대한 query 등, 데이터 사이언스 쪽에서 필요
  • 다루는 data 양에 따라 과금된다. 결과가 아니라 과정에서 사용되는 data 양

Google Container Registry

  • 사설 컨테이너 저장소 를 제공해준다.

cloud source repository

  • 사설 git
  • 사용용량에 따라 가격

google kubernetes engine

  • 쿠버네티스 엔진 을 이용해서 구글에서 만든 컨테이너 만이 아니라, 로컬에 구성된 컨테이너도 같이 관리 할 수 있는 서비스를 제공을 시작했다.
  • gke 에서는 칼리코(Calico) 를 사용 하고 있다.
현재 클라우드의 인스턴스는 가격 이 중요한 차별점이다. 그래서 인스턴스에 대해서 차별화 에 대한 고민을 하지 않는다. 장애율만 낮으면 된다.
그래서 구글은 쿠버네티스 와 빅데이터 쪽을 차별화 하려하고 있다.

google app engine

  1. standard app engine
    • 자동 scaling
    • local file system 못 쓴다.
    • request 의 timeout 이 1분 (무조건)
    • 3rd party library 설치 제약
    • 신속한 auto scaling
    • flexible 보다 이게 더 비쌈
  2. flexible environment
    • instance 를 우리가 정하고, 여기에 node 를 띄울 수 있다.
    • instance 에 ssh 접속을 허용
    • auto scaling 이 빠르게 되지 않는다. (상당히 느리다)

Cloud Functions

  • aws lambda 같은 것
  • 사용된 computing 정도에 따라 가격

가능한 trigger

  • http request
  • 특정파일이 생길때 : log 가 발생할때 등
  • ...

Deployment Manager

  • instance 배포 등, 인프라 매니지먼트 서비스
  • .yaml 하나 만들어놓고, 한번에 deploy 하는 것
  • terraform 비슷한 서비스
  • api 도 제공

Stack Driver

  • 모니터링
  • 로깅
2개 를 위해 주로 사용
  • 디버그
  • 에러 리포팅
  • 트레이스
  • 프로파일링
에도 사용
  • 로그 저장소로 보면 된다.
  • 임계치가 넘으면 알람을 받을 수 있다.
  • 개인 로그등도 stack driver 로 보내서 모니터링을 할 수 있다.
  • 메트릭은 6주, 로그는 400일, 개인이 개인적으로 쌓은 로그는 1개월 보관
  • 특정 로그들을 받아서 필터링 해서 바로 원하는 곳으로 보낼 수 없다.

사용

pub /sub 에서 받아서 dataflow 에서 처리하고 big query 에 저장하는 식으로 사용

[컴][안드로이드] rootbeer 피하기

rootbeer / rootbeerfresh / root beer



Rootbeer 피하기

updated

이 방식으로는 어려운 듯 하다. 다만 여기 좋은 글이 있다.

Magisk Hide detection

Magisk Hide 에 대한 감지 방법(detection) 으로 32-digit Unix Domain Socket 을 이용한다.

Magisk Hide 가 기존의 32-digit UDS 를 랜덤한 32 character string 으로 변경하는데 그것을 이용해서 detection 을 한다.

자세한 내용은 아래를 참고하자

Magisk Hide detection 피하기

그래서 간단하게 /proc/net/unix 에 접근하지 못하게 막는다. 그외에 다양한 이야기들을 아래 링크에서 확인할 수 있다.
su -c chmod 440 /proc/net/unix


Busybox uninstaller




[컴][웹] tomcat 에서 log 를 영어로 나오게 하는 법

region / locale / language 변경 /

톰캣 / 톰켓

tomcat log 를 영어로 나오게 하는 법

catalina.bat

chocolatey 를 사용해서 tomcat 을 설치했는데, catalina.bat 를 사용해서 실행하니, 한글로그가 깨져서 나왔다. terminal 을 UTF-8 으로 열면 해결 되지만, 그러고 싶지 않았다.

그래서 catalina.bat 를 수정해서 log 를 영어로 나오도록 설정했다.


language, region option 추가

catalina.bat 에서 JAVA_OPTS 가 설정되는 부분을 찾았다.
  • c:\ProgramData\chocolatey\lib\Tomcat\tools\apache-tomcat-9.0.26\bin\catalina.bat

그리고는 아래처럼 language 와 region 부분을 추가해 줬다.
if not "%JSSE_OPTS%" == "" goto gotJsseOpts
set "JSSE_OPTS=-Djdk.tls.ephemeralDHKeySize=2048 -Duser.language=en -Duser.region=US" 
:gotJsseOpts
set "JAVA_OPTS=%JAVA_OPTS% %JSSE_OPTS%"




References

  1. Set Tomcat’s Default Locale – Knowm.org


[컴][머신러닝] Recurrent Neural Networks 예제

ML / machine learning


Recurrent Neural Networks, RNN


관련글 :  The Unreasonable Effectiveness of Recurrent Neural Networks


원본 소스 : https://gist.github.com/karpathy/d4dee566867f8291f086

python 3 버전

# encoding=utf8

"""
Minimal character-level Vanilla RNN model. Written by Andrej Karpathy (@karpathy)
BSD License
"""
import numpy as np
import codecs

# data I/O
with codecs.open('input.txt', 'r', encoding='utf-8') as fp:
    data = fp.read()
    # data = open('input.txt', 'r').read() # should be simple plain text file
    chars = list(set(data))
    data_size, vocab_size = len(data), len(chars)
    print ('data has %d characters, %d unique.' % (data_size, vocab_size))
    char_to_ix = { ch:i for i,ch in enumerate(chars) }
    ix_to_char = { i:ch for i,ch in enumerate(chars) }

    # hyperparameters
    hidden_size = 100 # size of hidden layer of neurons
    seq_length = 25 # number of steps to unroll the RNN for
    learning_rate = 1e-1

    # model parameters
    Wxh = np.random.randn(hidden_size, vocab_size)*0.01 # input to hidden
    Whh = np.random.randn(hidden_size, hidden_size)*0.01 # hidden to hidden
    Why = np.random.randn(vocab_size, hidden_size)*0.01 # hidden to output
    bh = np.zeros((hidden_size, 1)) # hidden bias
    by = np.zeros((vocab_size, 1)) # output bias

    def lossFun(inputs, targets, hprev):
      """
      inputs,targets are both list of integers.
      hprev is Hx1 array of initial hidden state
      returns the loss, gradients on model parameters, and last hidden state
      """
      xs, hs, ys, ps = {}, {}, {}, {}
      hs[-1] = np.copy(hprev)
      loss = 0
      # forward pass
      for t in range(len(inputs)):
        xs[t] = np.zeros((vocab_size,1)) # encode in 1-of-k representation
        xs[t][inputs[t]] = 1
        hs[t] = np.tanh(np.dot(Wxh, xs[t]) + np.dot(Whh, hs[t-1]) + bh) # hidden state
        ys[t] = np.dot(Why, hs[t]) + by # unnormalized log probabilities for next chars
        ps[t] = np.exp(ys[t]) / np.sum(np.exp(ys[t])) # probabilities for next chars
        loss += -np.log(ps[t][targets[t],0]) # softmax (cross-entropy loss)
      # backward pass: compute gradients going backwards
      dWxh, dWhh, dWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
      dbh, dby = np.zeros_like(bh), np.zeros_like(by)
      dhnext = np.zeros_like(hs[0])
      for t in reversed(range(len(inputs))):
        dy = np.copy(ps[t])
        dy[targets[t]] -= 1 # backprop into y. see http://cs231n.github.io/neural-networks-case-study/#grad if confused here
        dWhy += np.dot(dy, hs[t].T)
        dby += dy
        dh = np.dot(Why.T, dy) + dhnext # backprop into h
        dhraw = (1 - hs[t] * hs[t]) * dh # backprop through tanh nonlinearity
        dbh += dhraw
        dWxh += np.dot(dhraw, xs[t].T)
        dWhh += np.dot(dhraw, hs[t-1].T)
        dhnext = np.dot(Whh.T, dhraw)
      for dparam in [dWxh, dWhh, dWhy, dbh, dby]:
        np.clip(dparam, -5, 5, out=dparam) # clip to mitigate exploding gradients
      return loss, dWxh, dWhh, dWhy, dbh, dby, hs[len(inputs)-1]

    def sample(h, seed_ix, n):
      """ 
      sample a sequence of integers from the model 
      h is memory state, seed_ix is seed letter for first time step
      """
      x = np.zeros((vocab_size, 1))
      x[seed_ix] = 1
      ixes = []
      for t in range(n):
        h = np.tanh(np.dot(Wxh, x) + np.dot(Whh, h) + bh)
        y = np.dot(Why, h) + by
        p = np.exp(y) / np.sum(np.exp(y))
        ix = np.random.choice(range(vocab_size), p=p.ravel())
        x = np.zeros((vocab_size, 1))
        x[ix] = 1
        ixes.append(ix)
      return ixes

    n, p = 0, 0
    mWxh, mWhh, mWhy = np.zeros_like(Wxh), np.zeros_like(Whh), np.zeros_like(Why)
    mbh, mby = np.zeros_like(bh), np.zeros_like(by) # memory variables for Adagrad
    smooth_loss = -np.log(1.0/vocab_size)*seq_length # loss at iteration 0
    while True:
      # prepare inputs (we're sweeping from left to right in steps seq_length long)
      if p+seq_length+1 >= len(data) or n == 0: 
        hprev = np.zeros((hidden_size,1)) # reset RNN memory
        p = 0 # go from start of data
      inputs = [char_to_ix[ch] for ch in data[p:p+seq_length]]
      targets = [char_to_ix[ch] for ch in data[p+1:p+seq_length+1]]

      # sample from the model now and then
      if n % 100 == 0:
        sample_ix = sample(hprev, inputs[0], 200)
        txt = ''.join(ix_to_char[ix] for ix in sample_ix)
        print ('----\n %s \n----' % (txt, ))

      # forward seq_length characters through the net and fetch gradient
      loss, dWxh, dWhh, dWhy, dbh, dby, hprev = lossFun(inputs, targets, hprev)
      smooth_loss = smooth_loss * 0.999 + loss * 0.001
      if n % 100 == 0: print ('iter %d, loss: %f' % (n, smooth_loss)) # print progress
      
      # perform parameter update with Adagrad
      for param, dparam, mem in zip([Wxh, Whh, Why, bh, by], 
                                    [dWxh, dWhh, dWhy, dbh, dby], 
                                    [mWxh, mWhh, mWhy, mbh, mby]):
        mem += dparam * dparam
        param += -learning_rate * dparam / np.sqrt(mem + 1e-8) # adagrad update

      p += seq_length # move data pointer
      n += 1 # iteration counter 
fdsfds


결과

무한 loop 이라, 적정한 시점에 알아서 멈추면 된다.

아래 결과는 대략 12시간 정도를 돌렸다. 컴퓨터 스펙은 아래와 같다.

  • CPU:  i7-6700, 3.40GHz
  • RAM: 16GB
----
 beahngy
amo k ns aeo?cdse nh a taei.rairrhelardr nela haeiahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cdse nh a taei.rairrhelardr nol e iohahenasen
----
iter 9309400, loss: 0.000086
----
 e nh a taei.rairrhelardr naioa aneaa ayio pe e bhnte ayio pe e h’e btentmuhgehi bcgdltt. gey heho grpiahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cds
----
iter 9309500, loss: 0.000086
----
 jCTCnhoofeoxelif edElobe negnk e iohehasenoldndAmdaI ayio pe e h’e btentmuhgehi bcgdltt. gey heho grpiahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cds
----
iter 9309600, loss: 0.000086
----
 negnk e iohehasenoldndAmdaI ayio pe e h’e btentmuhgehi bcgdltt. gey heho grpiahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cdse nh a taei.rairrhelardr
----
iter 9309700, loss: 0.000086
----
 aI ayio pe e h’e btentmuhgehi bcgdltt. gey heho grpiahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cdse nh a taei.rairrhelardr neli ae e angnI hyho gben
----
iter 9309800, loss: 0.000086
----
 gehi bcgdltt. gey heho grpiahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cdse nh a taei.rairrhelardr nela dr iohecgrpiahe.
Ddelnss.eelaishaner” cot AA
----
iter 9309900, loss: 0.000086
----
 piahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cdse nh a taei.rairrhelardr nol e iohahenasenese hbea bhnte ectrsnae abeahngy
amo k ns aeo?cdse nh a t
----
iter 9310000, loss: 0.000086
----
 er” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cdse nh a taei.rairrhelardr nela hamnaI ayio pe e h’e btentmuhgnhi beahe
Ddabealohe bee amoi bcgdltt. gey heho grpiahe.
Ddeln
----
iter 9310100, loss: 0.000086
----
 bih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cdse nh a taei.rairrhelardr nol gyio pe e h’e btentmuhgehi bcgdltt. gey heho grpiahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae
----
iter 9310200, loss: 0.000086
----
 beahngy
amo k ns aeo?cdse nh a taei.rairrhelardr ntlhnegnns. e
amo k ns aeh?cdse nh a taei.rairrhelardr nol e iohehengrpiahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeah
----
iter 9310300, loss: 0.000086
----
 e nh a taei.rairrhelardr nol’e btentmuhgehi gcdslatha arenbggcodaeta tehr he ni.rhelaney gehnha e ar i ho  bee amote ectrsnae abeahngy
amo k ns aeo?cdse nh a taei.rairrhelardr nol nyio chge heiohecgr
----
iter 9310400, loss: 0.000086
----
 jCTCnhoofeoxelif edElobe negnk e iohehasenoldndAmdaI ayio pe e h’e btentmuhgehi bcgdltt. gey heho grpiahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cds
----
iter 9310500, loss: 0.000086
----
 negnk e iohehasenoldndAmdaI ayio pe e h’e btentmuhgehi bcgdltt. gey heho grpiahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cdse nh a taei.rairrhelardr
----
iter 9310600, loss: 0.000086
----
 aI ayio pe e h’e btentmuhgehi bcgdltt. gey heho grpiahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cdse nh a taei.rairrhelardr nelardae abeahngy
amo k
----
iter 9310700, loss: 0.000086
----
 gehi bcgdltt. gey heho grpiahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cdse nh a taei.rairrhelardr ntl negnk t hi rsnse nhk br ne” a naeiarairr elirs
----
iter 9310800, loss: 0.000086
----
 piahe.
Ddelnss.eelaishaner” cot AAfhB ht ltny
ehbih a”on bhnte ectrsnae abeahngy
amo k ns aeo?cdse nh a taei.rairrhelardr nelardaenabeahngelareierhi. aif edElobe negrcih gey gey heho grpiahe.
Ddel
----



[컴] app 에서 firebase 사용하기

파이어베이스 / fire base /


Firebase 를 app 에서 사용하기

자세한 내용은 여기 를 참고 하자.
  1. firebase project 생성
  2. app 등록
    1. 앱 닉네임 등록 : 자신의 app 이름을 적자
    2. 그러면 아래 같은 code 를 얻게 된다.
  3. sdk 를 app 에 설치 후 initialize
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.6.2/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use
     https://firebase.google.com/docs/web/setup#available-libraries -->

<script>
  // Your web app's Firebase configuration
  var firebaseConfig = {
    apiKey: "AsdfDQ3uOXYZp_MrNQPSauO4sdfsPn4OU8",
    authDomain: "coreal.firebaseapp.com",
    databaseURL: "https://coreal.firebaseio.com",
    projectId: "coreal",
    storageBucket: "",
    messagingSenderId: "997454353605",
    appId: "1:997454353605:web:5354b7543a6d9e68fdcad2"  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
</script>


관련 에러

app 등록을 안하면 아래같은 warning 이 보인다.

@firebase/database: FIREBASE WARNING: Provided authentication credentials for the app named "[DEFAULT]" are invalid. This usually indicates your app was not initialized correctly. Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.




[컴][js] nodejs 에서 euc-kr 인코딩 사용법

한글 사용법 / euc-kr / mbcs / convert encoding / decoding / 인코딩 변경 방법 / nodejs / node / 노드에서 인코딩 변경 / euckr / korean / utf8 / 한글파일 읽기 / 한글 읽는 법 / 파일 읽기 / read 하는 법 / write 하는 법 / euc-kr 읽기 /euckr 읽기 / euc kr excel / 엑셀 읽기

nodejs 에서 euc-kr 인코딩 사용법

iconv

iconv 를 설치하려면 build 환경(native code compilation)이 구성되어야 한다.

npm i iconv

iconv-lite

이녀석은 순수 js 로 구성되었다. README 에서는 어떤 경우에는 iconv 보다 빠르다고 이야기 한다.

npm i iconv-lite

사용법

아래처럼 사용할 수 있다.

const iconv = require('iconv-lite');


const stream = fs.createWriteStream(filename);
const header = ['이름', '주소'];

const buf = iconv.encode(header.join(','), 'euc-kr');
stream.write(buf);
stream.end();

euc-kr 로 된 file을 read 할 때는 아래처럼 하면 된다.


import * as fs from 'fs';
import iconv from 'iconv-lite'

try {
    // readFileEncoding
    const data = await fs.promises.readFile(inputPath)
    const utf8Data = iconv.decode(data, 'euc-kr')
    console.log(utf8Data)
} catch (err) {
    return console.error('Error reading file:', err);
}

References

  1. node-iconv git : GitHub - bnoordhuis/node-iconv: node.js iconv bindings - text recoding for fun and profit!
  2. GitHub - ashtuchkin/iconv-lite: Convert character encodings in pure javascript.