Coding/Java 삽질기2022. 11. 16. 02:00

ImageMatch 는 어떠한 개인 정보도 수집하지 않습니다.

ImageMatch does not collect any personal information.

 

Posted by chobocho
Coding/JavsScript 삽질기2022. 9. 19. 00:58
Posted by chobocho
Coding/JavsScript 삽질기2022. 8. 25. 00:03

Javascript로 만든 계산기 입니다.

Chobocho's Simple Calculator
View
MR M+ M- MC

 

Posted by chobocho
Coding/JavsScript 삽질기2022. 8. 24. 01:32

JsCalculator 는 어떠한 개인 정보도 수집하지 않습니다.

JsCalculator does not collect any personal information.

 

 

Posted by chobocho
Coding/Python 삽질기2022. 7. 12. 21:26

파이썬 싱글톤 패턴

class SingletonMeta(type):
    _instance = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instance:
            cls._instance[cls] = super().__call__(*args, **kwargs)
            print("make first object")
        else:
            print("return a exist object")

        return cls._instance[cls]


class Singleton(metaclass=SingletonMeta):
    def __init__(self):
        print("\nSingleton Init!")


def test_singleton():
    singletone1 = Singleton()
    singletone2 = Singleton()

    print(f'{id(singletone1)} == {id(singletone2)} -> {id(singletone1) == id(singletone2)}')

 

Singleton Init!
make first object
return a exist object
2608647861000 == 2608647861000 -> True

참고

https://refactoring.guru/design-patterns/singleton/python/example

 

Design Patterns: Singleton in Python

Usage examples: A lot of developers consider the Singleton pattern an antipattern. That’s why its usage is on the decline in Python code. Identification: Singleton can be recognized by a static creation method, which returns the same cached object. Naïv

refactoring.guru

https://dojang.io/mod/page/view.php?id=2468 

 

파이썬 코딩 도장: 47.9 메타클래스 사용하기

메타클래스(metaclass)는 클래스를 만드는 클래스인데, 이 메타클래스를 구현하는 방법은 두 가지가 있습니다. type을 사용하여 동적으로 클래스를 생성하는 방식 type을 상속받아서 메타클래스를

dojang.io

 

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] Python 소소한 기능들  (0) 2023.02.04
About Pyscript  (0) 2022.06.10
[Python] C 함수 호출 하기  (0) 2022.04.23
Posted by chobocho
Coding/Python 삽질기2022. 6. 10. 00:05

'Coding > Python 삽질기' 카테고리의 다른 글

[Design Pattern] Singleton pattern  (0) 2022.07.12
[Python] C 함수 호출 하기  (0) 2022.04.23
[PyTorch] CUDA 설치기  (0) 2022.02.21
Posted by chobocho
Coding/Python 삽질기2022. 4. 23. 00:49

C library 작성

#include <stdio.h>
int add(int left, int right) {
    return left+right;
}
 
C library 빌드
gcc -shared -o libaddnumber.so add_number.c
 

Python Code 작성

from ctypes import CDLL
 
def main():
    c_func = CDLL('./libaddnumber.so')
    print(c_func.add(10, 20))
 
if __name__ == '__main__':
    main()
 
 
실행결과
chobocho@Chobocho-Mint:~/github/python/sharedlib$ python3 add_number.py 
30

'Coding > Python 삽질기' 카테고리의 다른 글

About Pyscript  (0) 2022.06.10
[PyTorch] CUDA 설치기  (0) 2022.02.21
생일 문제  (0) 2021.06.21
Posted by chobocho
Coding/좋은 사이트2022. 4. 18. 23:38

'Coding > 좋은 사이트' 카테고리의 다른 글

하트 그리기  (0) 2018.03.07
함수의 그래프를 그려주는 사이트  (0) 2018.03.03
무료 에디터  (1) 2017.07.27
Posted by chobocho
Coding/Python 삽질기2022. 2. 21. 23:37

PyTorch에서 GPU를 사용해보기로 하고, 삽질한 기록을

미래의 나를 위하여, 기록하였습니다.

1. 노트북 그래픽 카드 확인

 

2. Pytorch 사이트에서 CUDA 버전을 확인한다.

https://pytorch.org/get-started/locally/

 

PyTorch

An open source machine learning framework that accelerates the path from research prototyping to production deployment.

pytorch.org

 PyTorch 1.10.2에 Pip로 CUDA 10.2를 선택하면, 아래에 pip3 명령어가 보인다.  이를 사용하여 pytorch를 설치한다.

 

3. CUDA library 설치

PyTorch 사이트에서 확인한 CUDA 10.2 버전을 설치한다.

 

* 간혹 NVIDIA experience가 동작을 안하는 경우에는 아래와 같이

NVIDIA LocalSystem Controller 에서 로컬 시스템 계정 항목을 체크해 준다.

4. 파이썬을 실행해서 확인 해 본다.

 

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] C 함수 호출 하기  (0) 2022.04.23
생일 문제  (0) 2021.06.21
[Python/C] 휴대폰 패턴의 가지수  (0) 2021.02.21
Posted by chobocho

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Mandelbrot</title>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <style>
        canvas {
            height: 100%;
            width: 100%;
        }
    </style>
</head>
<body>
<div align='center'>
    <canvas id="canvas"></canvas>
</div>

<script language="JavaScript">
    // Start: 2022.02.02
    // Update: 2022.02.02

    let cvs;
    let canvas;
    let bufCanvas;
    let bufCtx;
    let imageData;

    let scaleX = 1.0;
    let scaleY = 1.0;
    let mx = 1.0;
    let my = 1.0;

    function InitCanvas() {
        height = window.innerHeight;
        width = window.innerWidth;

        canvas = document.getElementById("canvas");
        canvas.width = width;
        canvas.height = height;
        cvs = canvas.getContext("2d");

        bufCanvas = document.createElement("canvas");
        bufCanvas.width = canvas.width;
        bufCanvas.height = canvas.height;
        bufCtx = bufCanvas.getContext("2d");

        imageData = bufCtx.createImageData(canvas.width, canvas.height);
    }

    function _draw(x1, y1, x2, y2) {
        const MAX_COUNT = 256;

        // X = -3.0 ~ 3.0
        // Y = -2.0 ~ 2.0
        // Z = X + Yi

        mx = x1 < -3.0 ? -3.0 : x1;
        my = y1 < -2.0 ? -2.0 : y1;

        x2 = x2 > 3.0 ? 3.0 : x2;
        y2 = y2 > 2.0 ? 2.0 : y2;

        let mw = x2 - x1;
        let mh = y2 - y1;

        console.log(x1, y1, x2, y2, " : ", mx, my, " : ", mw, mh);

        scaleX = mw / imageData.width;
        scaleY = mh / imageData.height;

        for (let i = 0; i < imageData.height; i++) {
            for (let j = 0; j < imageData.width; j++) {

                let c = 0;
                let x = mx + j * scaleX;
                let y = my + i * scaleY;
                let sx = x;
                let sy = y;

                for (c = 0; c < MAX_COUNT; c++) {
                    if (x**2 + y**2 > 4) {
                        break;
                    }
                    let nx = x**2 - y**2;
                    let ny = 2 * x * y;
                    x = nx + sx;
                    y = ny + sy;
                }

                let pos = 4 * (i * imageData.width + j);
                let color = 3 * c / MAX_COUNT;

                if (color < 1) {
                    imageData.data[pos+0]  = 255 * color;
                    imageData.data[pos+1] = color;
                    imageData.data[pos+2] = color;
                }
                else if (color < 2 ) {
                    imageData.data[pos+0] = 255;
                    imageData.data[pos+1] = color;
                    imageData.data[pos+2] = 0;
                } else {
                    imageData.data[pos+0] = 255;
                    imageData.data[pos+1] = 255;
                    imageData.data[pos+2] = color;
                }

                imageData.data[pos+3] = 255;
            }
        }

        bufCtx.putImageData(imageData, 0, 0);
        console.log("_OnDraw2()");
    }

    function OnDraw() {
        _draw(-3.0, -2.0, 3.0, 2.0);
        cvs.clearRect(0, 0, canvas.width, canvas.height);
        cvs.drawImage(bufCanvas, 0, 0);
    }

    function rectMouseMove(event) {
        // console.log("rectMouseMove");
        var currentPos = getMousePosition(event);
        cvs.beginPath();

        cvs.clearRect(0, 0, canvas.width, canvas.height);
        cvs.drawImage(bufCanvas, 0, 0);

        cvs.strokeStyle = pos.color;
        var box = {
            W: currentPos.X - pos.sx,
            H: currentPos.Y - pos.sy
        };

        cvs.strokeRect(pos.sx, pos.sy, box.W, box.H);

        cvs.stroke();
        cvs.closePath();
    }

    function rectMouseUp(event) {
        if (pos.isDraw) {
            console.log("rectMouseUp");
            var currentPos = getMousePosition(event);

            pos.ex = currentPos.X;
            pos.ey = currentPos.Y;

            if (pos.sx > pos.ex) {
                let t = pos.sx;
                pos.sx = pos.ex;
                pos.ex = t;
            }

            if (pos.sy > pos.ey) {
                let t = pos.sy;
                pos.sy = pos.ey;
                pos.ey = t;
            }

            let sx = mx + pos.sx * scaleX;
            let sy = my + pos.sy * scaleY;
            let ex = mx + pos.ex * scaleX;
            let ey = my + pos.ey * scaleY ;

            _draw(sx, sy, ex, ey);
            cvs.clearRect(0, 0, canvas.width, canvas.height);
            cvs.drawImage(bufCanvas, 0, 0);

            pos.isDraw = false;
        }
    }

    function rectMouseDown(event) {
        console.log("rectMouseDown");
        if (pos.isDraw) {
            return;
        }
        bufCtx.putImageData(imageData, 0, 0);
        //bufCtx.drawImage(canvas, 0, 0);
        pos.isDraw = true;
        var startPos = getMousePosition(event);
        pos.sx = startPos.X;
        pos.sy = startPos.Y;
    }

    function mouseListener(event) {
        switch (event.type) {
            case "mousedown":
                if (!pos.isDraw) {
                    pos.mouseDownAction(event);
                }
                break;
            case "mousemove":
                if (pos.isDraw) {
                    pos.mouseMoveAction(event);
                }
                break;
            case "mouseup":
            case "mouseout":
                if (pos.isDraw) {
                    pos.mouseUpAction(event);
                }
                break;
        }
    }

    function InitMouseEvent() {
        canvas.addEventListener("mousedown", mouseListener);
        canvas.addEventListener("mousemove", mouseListener);
        canvas.addEventListener("mouseout", mouseListener);
        canvas.addEventListener("mouseup", mouseListener);
    }

    function getMousePosition(event) {
        var x = event.pageX - canvas.offsetLeft;
        var y = event.pageY - canvas.offsetTop;
        return { X: x, Y: y };
    }

    var pos = {
        isDraw: false,
        mouseDownAction: rectMouseDown,
        mouseUpAction: rectMouseUp,
        mouseMoveAction: rectMouseMove,
        color: "rgb(255,211,25,255)",
        sx: 0,
        sy: 0,
        ex: 0,
        ey: 0
    }

    function onLoadPage() {
        InitCanvas();
        InitMouseEvent();
        OnDraw();
    }

    window.onload = onLoadPage();
</script>
</body>
</html>
Posted by chobocho