내부적으로 이렇게 처리할 줄이야..

 

A number literal like 37 in JavaScript code is a floating-point value, not an integer. There is no separate integer type in common everyday use. (JavaScript also has a BigInt type, but it's not designed to replace Number for everyday uses. 37 is still a number, not a BigInt.)

[링크 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number]

'Programming > javascript & HTML' 카테고리의 다른 글

canvas 없는 getcontext  (0) 2023.07.12
html canvas와 시간 그래프 흘리기  (0) 2023.07.06
websocket binarytype  (0) 2023.04.04
자바스크립트 소수점 자르기  (0) 2023.03.13
Math.min.apply()  (0) 2023.02.07
Posted by 구차니

웹 브라우저에서 웹 소켓을 열면 기본값은 blob 으로 열리는데

Value
A string:

"blob"
Use Blob objects for binary data. This is the default value.

"arraybuffer"
Use ArrayBuffer objects for binary data.

 

binaryType을 지정하면 blob이 아닌 arraybuffer로 열 수 있다.

// Create WebSocket connection.
const socket = new WebSocket("ws://localhost:8080");

// Change binary type from "blob" to "arraybuffer"
socket.binaryType = "arraybuffer";

[링크 : https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/binaryType]

 

웹 소켓에서 blob이나 arraybuffer로 받는데

blob은 slice를 통해 자를수 있긴 한데 이래저래 행렬 처리가 아니다 보니 번거롭고

개인적인 취향으로는 blob을 받아서 arraybuffer로 변환하기 보다는 arraybuffer로 받아서 적당히 잘라쓰는 쪽 일 듯

blob은 contentType을 멀 지정해야 하나 조금 귀찮은 듯.. (타입이다 보니 int32, float64 이런게 아닐 것 같으니)

Syntax
slice()
slice(start)
slice(start, end)
slice(start, end, contentType)

[링크 : https://developer.mozilla.org/en-US/docs/Web/API/Blob/slice]

 

Convert an ArrayBuffer or typed array to a Blob
#
var array = new Uint8Array([0x04, 0x06, 0x07, 0x08]);
var blob = new Blob([array]);

[링크 : https://riptutorial.com/javascript/example/1390/converting-between-blobs-and-arraybuffers]

[링크 : https://velog.io/@chltjdrhd777/ArrayBuffer-와-Blob]

[링크 : https://heropy.blog/2019/02/28/blob/]

 

strToAB = str =>
  new Uint8Array(str.split('')
    .map(c => c.charCodeAt(0))).buffer;

ABToStr = ab => 
  new Uint8Array(ab).reduce((p, c) =>
  p + String.fromCharCode(c), '');

console.log(ABToStr(strToAB('hello world!')));

[링크 : https://stackoverflow.com/questions/39725716/]

[링크 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Int32Array]

 

[링크 : http://mohwa.github.io/blog/javascript/2015/08/31/binary-inJS/]

 

'Programming > javascript & HTML' 카테고리의 다른 글

html canvas와 시간 그래프 흘리기  (0) 2023.07.06
javascript 정수는 정수가 아니다  (0) 2023.04.06
자바스크립트 소수점 자르기  (0) 2023.03.13
Math.min.apply()  (0) 2023.02.07
web 렌더러 벤치마크  (0) 2022.12.22
Posted by 구차니
Programming/web 관련2023. 3. 31. 12:15

'Programming > web 관련' 카테고리의 다른 글

Canvas2D: Multiple readback operations using getImageData  (0) 2023.07.24
webGPU  (0) 2023.05.18
chatGPT님 가라사대 Server-Sent Events (SSE)  (0) 2023.03.15
JWT 로그인 예제  (0) 2022.08.24
quirks mode  (0) 2022.08.08
Posted by 구차니
Programming/golang2023. 3. 28. 10:36

웹소켓을 통해 데이터를 JSON으로 변환해서 보내니 웹서버에 부하가 걸리는 것 같아서

binary 데이터 그대로~ 보내고 웹에서 binary를 처리하도록 하려고 찾아보는 중

 

서버 사이드(golang)

for {
    messageType, p, err := conn.ReadMessage()
    if err != nil {
        log.Println(err)
        return
    }
    if err := conn.WriteMessage(messageType, p); err != nil {
        log.Println(err)
        return
    }
}
In above snippet of code, p is a []byte and messageType is an int with value websocket.BinaryMessage or websocket.TextMessage.

[링크 : https://pkg.go.dev/github.com/gorilla/websocket#section-readme]

[링크 : https://kiwitrip.tistory.com/5]

 

클라이언트 사이드(웹 브라우저)

webSocket.onmessage = function (message) {
    var blob = message.data;
    var fileReader = new FileReader();
    fileReader.onload = function (event) {
        var arrayBuffer = event.target.result;
        var dataview = new DataView(arrayBuffer);
        var answer = dataview.getFloat64(0);
        alert("Server> : " + answer);
    };
    fileReader.readAsArrayBuffer(blob);
};

[링크 : http://www.gisdeveloper.co.kr/?p=5594]

 

+

23.04.04

var wsHost = "http://my-sites-url.com/path/to/echo-web-socket-handler";
var ws = new WebSocket(wsHost);
var buffer = new ArrayBuffer(5); // 5 byte buffer
var bufferView = new DataView(buffer);

bufferView.setFloat32(0, Math.PI);
bufferView.setUint8(4, 127);

ws.binaryType = 'arraybuffer';

ws.onmessage = function(message) {
    var view = new DataView(message.data);
    console.log('Uint8:', view.getUint8(4), 'Float32:', view.getFloat32(0))
};

ws.onopen = function() {
    ws.send(buffer);
};

[링크 : https://riptutorial.com/javascript/example/6661/working-with-binary-messages]

'Programming > golang' 카테고리의 다른 글

go 포맷터  (0) 2023.05.11
golang echo directory listing  (0) 2023.05.08
golang 크로스 컴파일 GOARM GOARCH  (0) 2023.02.03
golang map 에 데이터 추가하기  (0) 2023.01.13
golang reflect  (0) 2023.01.03
Posted by 구차니
Programming/web 관련2023. 3. 15. 11:25

chatGPT 님에게 server push 예제를 알려줘라고 했더니 아래와 같이 알려주신다.

Server push is a technique that allows a server to push data to a client without the client first making a request for the data. In JavaScript, this can be achieved using the Server-Sent Events (SSE) API.
Here's an example of how you can use SSE to implement server push in JavaScript:
On the server side, you need to create an endpoint that will send the SSE messages. In this example, we'll create a simple Node.js server:
const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/sse') {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive'
    });

    setInterval(() => {
      res.write(`data: ${new Date().toISOString()}\n\n`);
    }, 1000);
  } else {
    res.writeHead(404);
    res.end();
  }
});

server.listen(3000);
const source = new EventSource('/sse');

source.onmessage = (event) => {
  console.log(event.data);
};

 

아무튼 SSE를 검색해보는데.. jquery 연관은 잘 안보이고

EventSource.onmessage() 로 처리 가능만 하다면야 머...

[링크 : https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events]

 

 

+

golang의 REST / websocket 제거하고 cgi로 돌리려는 어마어마한 음모가! ㅠㅠ

'Programming > web 관련' 카테고리의 다른 글

webGPU  (0) 2023.05.18
chart.js log 스케일  (0) 2023.03.31
JWT 로그인 예제  (0) 2022.08.24
quirks mode  (0) 2022.08.08
grid와 flex  (0) 2022.07.04
Posted by 구차니

'Programming > javascript & HTML' 카테고리의 다른 글

javascript 정수는 정수가 아니다  (0) 2023.04.06
websocket binarytype  (0) 2023.04.04
Math.min.apply()  (0) 2023.02.07
web 렌더러 벤치마크  (0) 2022.12.22
웹에서 f5 갱신 막기  (0) 2019.06.04
Posted by 구차니
Programming/chart.js2023. 3. 10. 16:23

클릭하면 당연히(?) 줄 그어져서 죽는데

코드로 처음부터 해당 항목을 hidden 상태로 표시하려니 먼가 묘하게 어렵다?

 

function(e, legendItem, legend) {
    const index = legendItem.datasetIndex;
    const ci = legend.chart;
    if (ci.isDatasetVisible(index)) {
        ci.hide(index);
        legendItem.hidden = true;
    } else {
        ci.show(index);
        legendItem.hidden = false;
    }
}

[링크 : https://www.chartjs.org/docs/latest/configuration/legend.html]

 

매우 귀찮으니(!)

chart 라는 변수에 chart.js 객체가 존재한다면

아래의 legned.chart.hide(index) 로 끄고 legned.chart.show(index) 로 표시할 수 있다.

index 이니 0부터 시작함에 주의!

//var chart = new chart()
chart.legend.chart.hide(1)
chart.legend.chart.show(1)

'Programming > chart.js' 카테고리의 다른 글

chart.js 반응형 설정시 작아지는데 안커지는 문제  (0) 2024.06.27
chart.js multi y axis  (0) 2023.09.27
chart.js 수직 도움선  (0) 2023.01.27
Posted by 구차니

matplotlib을 이용하여 python 에서 그래프를 그리려고 하는데 그려지지 않아서 고생 -_-

그냥 설치하면 이상한(?) 에러가 발생하면서 중단되는데

나의 경우에는 jpeg 라이브러리 없다고 배쨰는 중. 그래서 libjpeg 등을 설치하고 Pillow 라는 python 패키지를 설치후

matplotlib을 설치하니 해결되었다.

 

sudo apt install libjpeg-dev zlib1g-dev
pip install Pillow

[링크 : https://stackoverflow.com/questions/44043906/the-headers-or-library-files-could-not-be-found-for-jpeg-installing-pillow-on]

pip3 install matplotlib

[링크 : https://www.zinnunkebi.com/python-modulenotfounderror-matplotlib/]

'Programming > python(파이썬)' 카테고리의 다른 글

matplotlib  (0) 2023.10.04
pyplot  (0) 2023.10.04
python openCV / PIL 포맷 변경  (0) 2022.04.12
파이썬 딕셔너리 변수 생성과 리턴 enumerate, zip  (0) 2022.04.12
python interactive mode  (0) 2022.03.15
Posted by 구차니
Programming/C++ STL2023. 2. 9. 11:31

cpp랑은 안친하다 보니.. 그나저나 템플릿을 저런식으로도 쓰나 싶긴 한데..

 

static_cast, dynamic_cast, reinterpret_cast, const_cast

[링크 : https://blockdmask.tistory.com/236]

[링크 : https://hwan-shell.tistory.com/211]

 

표준 C++에서는 변환의 안전성을 보장하기 위해 런타임 형식 검사가 수행되지 않습니다. C++/CX에서는 컴파일 시간 및 런타임 검사가 수행됩니다. 

[링크 : https://learn.microsoft.com/ko-kr/cpp/cpp/static-cast-operator?view=msvc-170]

 

캐스트 연산자에는 C++ 언어 전용 연산자가 몇 가지 있습니다. 이 연산자는 예전 스타일의 C 언어 캐스트에 있는 일부 모호함과 위험성을 제거하는 데 목적이 있습니다. 그 종류는 다음과 같습니다.
  • Dynamic_cast 다형 형식의 변환에 사용됩니다.
  • Static_cast 비포형 형식의 변환에 사용됩니다.
  • const_cast , volatile __unaligned 특성을 제거하는 const데 사용됩니다.
  • reinterpret_cast 비트의 간단한 재해석에 사용됩니다.
  • safe_cast C++/CLI에서 확인 가능한 MSIL을 생성하는 데 사용됩니다.

[링크 : https://learn.microsoft.com/ko-kr/cpp/cpp/casting-operators?view=msvc-170]

'Programming > C++ STL' 카테고리의 다른 글

RAII (Resource Acquisition Is Initialization)  (0) 2024.11.28
cpp lambda  (0) 2024.11.22
::open()  (0) 2021.11.10
vector 값 비우기  (0) 2021.10.02
cpp 부모타입으로 업 캐스팅 된 객체의 원래 클래스 알기  (0) 2021.09.30
Posted by 구차니

배열에서 최소, 최대값 계산하기 함수

 

Math.min.apply(null, arr)
Math.max.apply(null, arr)

[링크 : https://rutgo-letsgo.tistory.com/96]

 

Syntax
apply(thisArg, argsArray)

Parameters
thisArg
The value of this provided for the call to func. If the function is not in strict mode, null and undefined will be replaced with the global object, and primitive values will be converted to objects.

argsArray Optional
An array-like object, specifying the arguments with which func should be called, or null or undefined if no arguments should be provided to the function.

[링크 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply]

'Programming > javascript & HTML' 카테고리의 다른 글

websocket binarytype  (0) 2023.04.04
자바스크립트 소수점 자르기  (0) 2023.03.13
web 렌더러 벤치마크  (0) 2022.12.22
웹에서 f5 갱신 막기  (0) 2019.06.04
cose network graph  (0) 2019.06.03
Posted by 구차니