logo

code summary 📂プログラミング

code summary

matplotlib

画像サイズ

  • 設定したサイズでフィギュアを作成する方法: plt.figure(figsize=(w,h))

  • デフォルトサイズ: plt.figure(figsize=(6.4,4.8))

  • デフォルトのプロットサイズを調整する:

    import matplotlib
    plt.rcParams['figure.figsize'] = [width, height]
    

tmux

  • tmux attach -t 0: 0番セッションに接続
  • Ctrl + b + 方向キー: 該当方向のセッションに切り替え
  • Ctrl + b + 数字: 該当番号のセッションに切り替え
  • Ctrl + b + d: (セッションを生かしたまま) 通常のシェルに戻る
  • Ctrl + c + Ctrl + c: emacs 終了

Python

実行ファイルのパス os.getcwd()

  • main.__file__: ファイル名と拡張子を含むパスを取得する。

  • os.path.dirname(os.path.realpath(__file__)): ファイルが含まれるフォルダのパスを取得する。ターミナルからPythonファイルを実行する時も意図通りに機能させるにはこれを使う必要がある。

  • os.getcwd(): 現在の作業ディレクトリを取得する。エクスプローラーから *.py ファイルを実行すると意図通り動作するが、ターミナルで実行するとターミナルのパスを取得する。

>>> import os
>>> import __main__ as main

>>> x = main.__file__
>>> print(x, "\n")
C:/Users/admin/Desktop/Python/test.py

>>> y = os.path.dirname(os.path.realpath(__file__))
>>> print(y, "\n")
C:/Users/admin/Desktop/Python

>>> z = os.getcwd()
>>> print(z)
C:/Users/admin/Desktop/Python

パスの存在確認 os.path.exists(directory)

  • os.path.exists(directory): パスが存在するかに応じて True または False を返す。

フォルダ作成 os.makedirs(directory)

  • os.makedirs(directory): 入力したパスがなければフォルダを作成するコード。
    def create_directory(directory):
        try:
            if not os.path.exists(directory):
                os.makedirs(directory)
        except OSError:
            print("Error: Failed to create the directory.")
    

フォルダ削除

サブフォルダを探索しながら空のフォルダなら削除するコード。

import os

directory = os.path.dirname(os.path.realpath(__file__))

for (path, dir, files) in os.walk(directory):
    try:
        os.removedirs(str(path))
    except:
        print("디렉토리가 비어있지 않습니다.")

実行ファイルのサブパスの特定ファイル全てを探す

実行ファイルが位置するフォルダを含むサブパスのPythonファイル*.pyを全て探すコード。実行ファイルが位置するフォルダも探索範囲に含まれるため、実行ファイル自体も file_listに含まれる。

directory = os.getcwd()
file_list = []

for (path, dir, files) in os.walk(directory):
    for filename in files:
        ext = os.path.splitext(filename)[-1]
        if ext == '.py':
            file_list.append("%s\\%s" % (path, filename))

実行変数 sys.argv

python 以降の部分foosys.argv = foo.split() で受け取る。

# 파일 실행
import os 

os.system("python " + "file_directory/foo.py " + argv1 + " " + argv2)

## foo.py 내부 코드
import sys

# sys.argv[0]는 "file_directory/foo.py "임
variable1 = sys.argv[1]
variable2 = sys.argv[2]

ファイルの読み書き

読み込みと書き込みは別々に行う。後ろに “t” を付けるとテキストモード、“b” を付けるとバイナリーモード。

  • “rt” は読み込みテキストモード、読み込み専用、ファイルがなければエラー。
  • “w” は書き込みモード、ファイルの有無に関わらず新しく作成する。
  • “a” は追記モード、ファイルがなければ新しく作成し、あれば既存ファイルの最後に内容を追加する。
  • “x” は作成モード、すでにファイルがあるとエラー。
# 텍스트 파일 열고 내용 가져오기, 그리고 닫기
foo_read = open(file_directory + "foo.txt", "rt", encoding="utf-8")
lines = foo_read.readlines()
foo_read.close()

readlines() はテキストファイルの各行をリストの要素(文字列)として受け取る。改行があれば最後に '\n' も含まれる。 .strip() で最後の '\n' を削除することができる。

foo_write = open(file_directory + "foo.txt", "wt", encoding="utf-8")

foo_write.write("bar\n") # 한 줄 쓰기

lines = ["bar1\n", "bar2\n", "bar3\n"]
foo_write.lines(lines) # 여러 줄 쓰기
foo_write.close()

文字列

  • strip(): 前後の文字列を削除する。引数がない場合は(改行等を含む)空白を削除する。したがって、文字列の始めと終わりの空白を削除する際に便利。
  • sort(): アルファベット順に文字列を並べ替え。逆順にするには reverse=True を指定。
  • replace(): 文字列を置換。
  • translate(): 文字を置換。

    replaceとtranslateの違い1

    replace(‘置換文字列’, ‘新文字列’) は文字列内の文字列を他の文字列に置換する(文字列自体は変更せず、置換結果を返す)。次は文字列 ‘Hello, world!’ で ‘world’ を ‘Python’ に置換した後の結果を返します。 replaceは文字列を置換するが、文字を置換する方法もある。 translateは文字列内の文字を他の文字に置換する。まず str.maketrans(‘置換文字’, ‘新文字’) で変換テーブルを作る。その後 translate(テーブル) を使って文字を置換した結果を返す。次は文字列 ‘apple’ で aを1, eを2, iを3, oを4, uを5に置換します。

    >>> table = str.maketrans('aeiou', '12345')
    >>> 'apple'.translate(table)
    '1ppl2'
    
  • split(): 入力変数を基準に文字列を分割してリストで返す
    >>> x.split(',')
    ['1', '3', '4']
    

整理されたサイト

リスト

  • .sorted(): アルファベット順に文字列を並べ替え。逆順にするには reverse=True を指定。

  • リストの保存と読み込み

import pickle

list = [1, 2, 3, 4]

# 리스트 저장
with open("list.pkl", "wb") as f:
    pickle.dump(list, f)

# 리스트 불러오기
with open("list.pkl", "rb") as f:
    list = pickle.load(f)

Julia

LaTeX\LaTeX

文字サイズ

AB\Huge AB \Huge AB

AB\huge AB \huge AB

AB\LARGE AB \LARGE AB

AB\Large AB \Large AB

AB\large AB \large AB

AB\normalsize AB \normalsize AB

AB\small AB \small AB

AB\footnotesize AB \footnotesize AB

AB\scriptsize AB \scriptsize AB

AB\tiny AB \tiny AB

PyTorch and TensorFlow

GPU

GPU確認

  • P: torch.cuda.is_available()

配列

定数

  • P: torch.tensor([1,2,3])
  • TF: tf.constant([1,2,3])

パラメータ

  • P: torch.tensor([1,2,3], requires_grad=True)
  • TF: tf.Variable([1,2,3])

モデル

クラス

  • P: class model(nn.Module)
  • TF: class model(tf.keras.Model)

TF: model.compile()

TF: model.fit(data, label, epochs, batch_size, verbose)

  • verbose: 整数。0, 1, または 2. (訓練結果の出力方式)
    • 0 = 無言,
    • 1 = プログレスバー,
    • 2 = 各エポックごとに1行。

TF: model.compile()

VS Code

MarkdownAllinOne

マークダウンテーブルを自動でフォーマットする機能 Shift + Alt + F

  • ファイルを開くときにフォルダが展開されないようにする: Explorer: Auto Reveal

自動折り返しオプション

コードの自動折り返し: Editor: Word Wrap

  • Ctrl + Shift + P \to word wrap 検索後に有効化
  • トグルキーは Alt + z

タブバーの自動折り返し: Editor: Wrap Tabs

ショートカットキーの設定: keybindings.json

  • パス: C:/Users/user/AppData/Roaming/Code/User/keybindings.json

  • マークダウン環境で上付き文字を自動で囲む:

    {
      "key": "shift+6",
      "command": "editor.action.insertSnippet",
      "when": "editorTextFocus && editorLangId == 'markdown'",
      "args": {
        "snippet": "^{$0\\}"
      }
    }
    
    • TEXファイルの場合に適用するには editorLangId == 'latex' を使用