[컴] mysql/mariadb 에서 timestamp 의 대안

timestamp alternative / db / database / 디비 / 데이터베이스 / 마리아db / 마리아 디비

mysql/mariadb 에서 timestamp 의 대안

timezone 의 마지막일은 2038-01-19T03:14:07Z 이다. 그래서 db 에서 timestamp 를 쓰는 것에 제약이 생겼다.

다음 글에서 처럼 Mysql 은 8.0.19 부터 datetime 에서 timezone literal 을 넣을 수 있다. 그리고 unix time 을 다루는 함수들이 64bit 을 다룰 수 있도록 변경됐다. FROM_UNIXTIME(), UNIX_TIMESTAMP(), and CONVERT_TZ()

datetime with time zone leteral

MySql v8.0.19 부터는 datetime type 일때 '2020-01-01 10:10:10+05:30' 처럼 +00:00 을 넣어서 timezone 을 추가할 수 있게 됐다.

from : ref.1

Beginning with MySQL 8.0.19, you can specify a time zone offset when inserting TIMESTAMP and DATETIME values into a table.

CREATE TABLE dt (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  col DATETIME NOT NULL
) AUTO_INCREMENT = 1;

// SELECT @@system_time_zone;
// @@system_time_zone EST 
SET @@time_zone = 'SYSTEM';
INSERT INTO dt (col) VALUES 
  ('2020-01-01 10:10:10'),
  ('2020-01-01 10:10:10+05:30'),    // 현재 설정된 time zone 과 time zone literal 이 같이 적용된다.
  ('2020-01-01 10:10:10-08:00');

SET @@time_zone = '+00:00';
INSERT INTO dt (col) VALUES 
  ('2020-01-01 10:10:10'),
  ('2020-01-01 10:10:10+05:30'),
  ('2020-01-01 10:10:10-08:00');

SELECT col, UNIX_TIMESTAMP(col) FROM dt ORDER BY id;
+---------------------+---------------------+
| col                 | UNIX_TIMESTAMP(col) |
+---------------------+---------------------+
| 2020-01-01 10:10:10 |          1577891410 |
| 2019-12-31 23:40:10 |          1577853610 |
| 2020-01-01 13:10:10 |          1577902210 |
| 2020-01-01 10:10:10 |          1577891410 |
| 2020-01-01 04:40:10 |          1577871610 |
| 2020-01-01 18:10:10 |          1577920210 |
+---------------------+---------------------+

mariaDB 는 지원하지 않는다

mariaDB 에서는 아직 datetime 에 +00:00 을 사용하는 것을 지원하지 않는다.

SELECT NOW() AS utc_time, CONVERT_TZ(NOW(), @@session.time_zone) AS local_time;

mariadb 에서 대안

time_zone 을 위한 column 을 따로 두라고 하지만, 이값에 대한 개인적인 의견:

  • datetime 을 사용하고,
  • 사용할 때 column 이름에 UTC 를 적어준다.
  • 그리고 timezone 에 영향을 받지 않는 함수를 이용해서 UTC값을 insert 한다.

mariadb 에서 timezone에 영향받지 않는 함수

from: Time Zone Effects on Functions - MariaDB Knowledge Base

  • timezone 에 영향을 받는 함수
    • NOW()
    • SYSDATE()
    • CURDATE()
    • CURTIME()
    • UNIX_TIMESTAMP()
  • timezone에 영향을 받지 않는 함수
    • UTC_DATE()
    • UTC_TIME()
    • UTC_TIMESTAMP()

CONVERT_TZ :

-- '2023-05-11 11:00:00' 시간을 `+00:00` timezone 에서 `+09:00` timezone으로 변경
`SELECT CONVERT_TZ('2023-05-11 11:00:00', '+00:00', '+09:00');`

named timezone

이름으로 된 timezone 을 사용하려면(예를들어, Asia/Seoul), time_zone table들이 load돼야 한다. 다음 글을 참고하자.

Reference

  1. MySQL :: MySQL 8.0 Reference Manual :: 9.1.3 Date and Time Literals
  2. PHP & mySQL: Year 2038 Bug: What is it? How to solve it? - Stack Overflow
  3. Year 2038 problem - Wikipedia

[컴] StartCoder 를 vscode에서 사용하기

스타코더 / 스타코드 / copilot / 코드

StartCoder 를 vscode에서 사용하기

startcoder는 BigCode project에서 만든 code 관련 large language model 이다.

이것을 vscode extension 으로도 사용할 수 있게 해준다.

vscode extension

사용법

  1. HuggingFace 에 가서 token 을 생성
  2. vscode 에 extension 을 설치
  3. output console 에서 Hugging Face 를 선택하면, input, output 이 어떤 값인지 log를 볼 수 있다.

BigCode Project

BigCode는 code를 위한 LLM(Large Language Model)의 책임감 있는 개발을 위해 노력하는 개방형 과학 협업으로, 개방형 거버넌스를 통해 머신 러닝 및 오픈 소스 커뮤니티에 힘을 실어준다. … 빅코드 프로젝트는 Open Science 정신에 따라 진행된다. 데이터 세트, 모델 및 실험은 개방형 협업을 통해 개발되고 permissive licence를 통해 커뮤니티에 다시 released 된다. 이 프로젝트는 model들과 dataset들을 hosting 하고, 훈련연산(trainnning compute)에 대해서 ServiceNow와 HuggingFace 에게 지원을 받지만, 모든 기술 관리(technical governance)는 커뮤니티 전반의 워킹 그룹들과 태스크포스 내에서 이루어진다.

See Also

  1. 쿠…sal: [컴] codeium

Reference

  1. StarCoder, BigCode 프로젝트가 공개한 코드용 LLM | GeekNews
  2. bigcode (BigCode)

[컴] html/js 에서 어떻게 file path 를 얻을 수 있나?

 

thumbnail / 썸네일

html/js 에서 어떻게 file path 를 얻을 수 있나?

결론부터 이야기하면, user 가 browser 를 통해 올린 file 에 대해서 user 의 local 환경에 대한 file path 를 얻을 수는 없다. 보안상의 이유라는 이야기들이 있다.

그래서 ref. 2 처럼 createObjectURL() 을 이용해서 새로운 object를 만들어서 그 url 을 가져다 쓴다. createObjectURL를 사용하고는 꼭 revokeObjectURL를 해주라고 한다.[ref. 3]


const img = document.createElement("img");
img.src = URL.createObjectURL(this.files[i]);
img.height = 60;
img.onload = () => {
  URL.revokeObjectURL(img.src);
};

See Also

  1. Using files from web applications - Web APIs | MDN : thumbnail 보여주는 법

Reference

  1. How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax? - Stack Overflow
  2. javascript - Preview an image before it is uploaded - Stack Overflow
  3. URL: createObjectURL() static method - Web APIs | MDN
  4. Using files from web applications - Web APIs | MDN

[컴] windows 에서 miniconda 설치 경로 변경

anaconda / 아나콘다 설치 path 변경

windows 에서 miniconda 설치 경로 변경

anaconda(여기서는 miniconda 를 이용했다.) 에서 설치되는 path 를 변경하는 방법을 알아보자.

다음처럼 conda 환경을 create 하면

conda create -n myconda python=3.10

기본값은

  • c:\Users\<user_name>\.conda

에 설치된다.

이 경로를 바꾸려면, .condarc 에 envs_dirs 값을 넣어주면 된다.

  • c:\Users\<user_name>\.condarc

또는 다음처럼 추가해 줘도 된다.

  • conda config --add envs_dirs c:\my\newpath

Reference

  1. Can I choose where my conda environment is stored? - Stack Overflow
  2. Sample .condarc file — conda 0.0.0.dev0+placeholder documentation
  3. Conda configuration — conda 0.0.0.dev0+placeholder documentation

[컴] Typescript 의 Decorator

 

annotation / 어노테이션 / 데코레이터 /

Typescript 의 Decorator

function first() {
  console.log("first(): factory evaluated");
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log("first(): called");
  };
}
 
function second() {
  console.log("second(): factory evaluated");
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log("second(): called");
  };
}
 
class ExampleClass {
  @first()
  @second()
  method() {}
}
first(): factory evaluated
second(): factory evaluated
second(): called
first(): called

build

아래처럼 --experimentalDecorators 를 해줘야 한다. 그렇지 않으면 error 가 생긴다.

tsc --experimentalDecorators

See Also

  1. 쿠…sal: [컴] 간단하게 typescript 시작하기 2
  2. 쿠…sal: [컴][TypeScript] typescript 기본 setup + visual studio code
  3. 쿠…sal: [컴][디자인패턴] Decorator Pattern
  4. 쿠…sal: [컴][파이썬] python decorator

Reference

  1. TypeScript: Documentation - Decorators

[컴][웹] vendure server 에서 회원가입, 유저생성, create user

vendure server 에서 회원가입, 유저생성, create user

아래 링크에서 vendure 에서 회원가입을 구현하는 방법을 알 수 있다.

3가지를 언급하는데

authOptions.requireVerification = true 인 경우:

  1. password 와 같이 회원가입 –> email통해서 verfication token 을 전달 –> password 없이 verifyCustomerAccount을 호출.
  2. password 없이 회원가입 –> email통해서 verfication token 을 전달 –> password 와 같이 verifyCustomerAccount을 호출.

authOptions.requireVerification = false 인 경우:

  1. password 와 같이 회원가입을 해야만 한다. 그러면 끝.

registerCustomerAccount

위처럼 유저를 생성하고 verification token 을 만들어 보내기 위해서 registerCustomerAccount 가 쓰인다.

request from client

client 에서 다음과 같은 graphql query 를 보내게 된다.

"{"query":"
  mutation signup($input: RegisterCustomerInput!) {
    registerCustomerAccount(input: $input) {
      __typename
      ... on Success {
        success
      }
      ... on ErrorResult {
        errorCode
        message
      }
    }
  }
  ","variables":{"input":{"firstName":"ff","lastName":"rr","emailAddress":"gaedduck@gmail.com","password":"namhunnamhunnamhun"}}}"

{"query":"
  query activeCustomer {
    activeCustomer {
      id
      firstName
      lastName
      emailAddress
    }
  }
  "}

See Also

  1. 쿠…sal: [컴][웹] next.js commerce + vendure 서버 실행

[컴] terraform 에서 cloud-init 사용

테라폼 / 초기 설정 / init / cloud init / terraform cloud

terraform 에서 cloud-init 사용

terraform 에서 docker 설치와 swap file 생성을 instance 생성시에 하려한다. cloud-init 에 사용한 명령어들에 대한 자세한 설명은 아래 링크들을 참고하면 된다.

# init-cloud.yml

packages:
  - ca-certificates
  - curl
  - gnupg

# create the docker group
groups:
  - docker

# Add default auto created user to docker group
system_info:
  default_user:
    groups: [docker]

# ----------------------------------------
# Mount attached disk
#
# '/dev/sdf' should exist
#
bootcmd:
 - test -z "$(blkid /dev/sdf)" && mkfs -t ext4 -L mylabel /dev/sdf
 - mkdir -p /mydata

mounts:
 - [ "/dev/sdf", "/mydata", "ext4", "defaults,nofail", "0", "2" ]
# ----------------------------------------

runcmd:
# Install Docker, for production, consider pinning to stable versions  
  - install -m 0755 -d /etc/apt/keyrings
  - curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
  - chmod a+r /etc/apt/keyrings/docker.gpg
  - echo "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
  - apt-get update -y
  - apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  - systemctl start docker
  - systemctl enable docker
# Enable and activate the swap file
  - dd if=/dev/zero of=/swapfile bs=128M count=16 # 2GB = 128M x 16
  - chmod 600 /swapfile
  - mkswap /swapfile
  - swapon /swapfile
  - echo '/swapfile swap swap defaults 0 0' >> /etc/fstab
# ----------------------------------------------------
#
# data
#
# ----------------------------------------------------
data "template_file" "my_cloud_userdata" {
  template = file("./scripts/init-cloud.yml")
}

# ----------------------------------------------------
#
# resource
#
# ----------------------------------------------------

resource "aws_instance" "tf-test" {
  ...

  # This only works at the time the aws_inatance is created.
  # So if you want to use a new init script, 
  # you may need to destroy and recreate the instance.
  user_data = data.template_file.my_cloud_userdata.rendered
}

See Also

  1. 쿠…sal: [컴] Terraform 사용법
  2. Testing and debugging cloud-init — cloud-init 20.4.1 documentation