以下の内容はhttps://htn20190109.hatenablog.com/より取得しました。


k-means


import numpy as np
import matplotlib.pyplot as plt

# ===== k-means本体 =====
def init_centroid(X, n_data, k):
    idx = np.random.permutation(n_data)[:k]
    centroids = X[idx]
    return centroids
def compute_distances(X, k, n_data, centroids):
    distances = np.zeros((n_data, k))
    for idx_centroids in range(k):
        dist = np.sqrt(np.sum((X - centroids[idx_centroids])**2, axis=1))
        distances[:, idx_centroids] = dist
    return distances
def k_means(k, X, max_iter=300):
    n_data, n_features = X.shape
    centroids = init_centroid(X, n_data, k)
    new_cluster = np.zeros(n_data, dtype=int)
    cluster = np.full(n_data, -1, dtype=int)
    for epoch in range(max_iter):
        distances = compute_distances(X, k, n_data, centroids)
        new_cluster = np.argmin(distances, axis=1)
        for idx_centroids in range(k):
            if np.any(new_cluster == idx_centroids):
                centroids[idx_centroids] = X[new_cluster == idx_centroids].mean(axis=0)
        if (new_cluster == cluster).all():
            break
        cluster = new_cluster.copy()
    return cluster, centroids

# ===== テストデータ作成 =====
np.random.seed(0)

# 3つのクラスタを人工生成
X1 = np.random.randn(50, 2) + np.array([0, 0])
X2 = np.random.randn(50, 2) + np.array([5, 5])
X3 = np.random.randn(50, 2) + np.array([0, 5])

X = np.vstack([X1, X2, X3])

# ===== k-means実行 =====
k = 3
labels, centroids = k_means(k, X)

# ===== 結果表示 =====
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis')
plt.scatter(centroids[:, 0], centroids[:, 1], 
            color='red', marker='x', s=200, label='centroids')
plt.title("K-means Clustering Result")
plt.legend()
plt.show()

 

 

音量設定

  • Ubuntu

(24)
https://www.st.itc.keio.ac.jp/ja/faq_linux_audio_mute_st.html


amixer sget Master
amixer sset Master 50%

 

  • Debian

(13)

amixer sget Master
amixer sset Master 50%

※rootユーザで実行すると、下記エラーとなる
amixer: Mixer attach default error: Host is down

 

  • CentOS

(RL9)

amixer sget Master
amixer sset Master 50%

 

  • Windows Server

(2025)
https://ehbtj.com/info/control-volume-mixer-from-command-line/
https://nibikitune.com/pc/nircmd-2

.\nircmd.exe setappvolume thunderbird.exe 0.5
.\nircmd.exe setsysvolume 25000

 

https://www.egao-inc.co.jp/tech/windows_powershell_volume_mute/


Add-Type -TypeDefinition @'
using System.Runtime.InteropServices;
[Guid("5CDF2C82-841E-4546-9722-0CF74078229A"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IAudioEndpointVolume
{
    // f(), g(), ... are unused COM method slots. Define these if you care
    int f(); int g(); int h(); int i();
    int SetMasterVolumeLevelScalar(float fLevel, System.Guid pguidEventContext);
    int j();
    int GetMasterVolumeLevelScalar(out float pfLevel);
    int k(); int l(); int m(); int n();
    int SetMute([MarshalAs(UnmanagedType.Bool)] bool bMute, System.Guid pguidEventContext);
    int GetMute(out bool pbMute);
}
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDevice
{
    int Activate(ref System.Guid id, int clsCtx, int activationParams, out IAudioEndpointVolume aev);
}
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IMMDeviceEnumerator
{
    int f(); // Unused
    int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
}
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorComObject { }
public class AudioControl
{
    static IAudioEndpointVolume Vol()
    {
        var enumerator = new MMDeviceEnumeratorComObject() as IMMDeviceEnumerator;
        IMMDevice dev = null;
        Marshal.ThrowExceptionForHR(enumerator.GetDefaultAudioEndpoint(/*eRender*/ 0, /*eMultimedia*/ 1, out dev));
        IAudioEndpointVolume epv = null;
        var epvid = typeof(IAudioEndpointVolume).GUID;
        Marshal.ThrowExceptionForHR(dev.Activate(ref epvid, /*CLSCTX_ALL*/ 23, 0, out epv));
        return epv;
    }
    public static float Volume
    {
        get { float v = -1; Marshal.ThrowExceptionForHR(Vol().GetMasterVolumeLevelScalar(out v)); return v; }
        set { Marshal.ThrowExceptionForHR(Vol().SetMasterVolumeLevelScalar(value, System.Guid.Empty)); }
    }
    public static bool Mute
    {
        get { bool mute; Marshal.ThrowExceptionForHR(Vol().GetMute(out mute)); return mute; }
        set { Marshal.ThrowExceptionForHR(Vol().SetMute(value, System.Guid.Empty)); }
    }
}
'@

[AudioControl]::Volume  = 0.5 # 0.2 = 20%, etc.
[AudioControl]::Mute = $false  # Set to $false to un-mute

 

 

 

{16 追加}フレックスディスクグループ

https://docs.oracle.com/cd/F19136_01/ostmg/asm-filegroups.html#GUID-1A056184-65E1-449C-B36A-83AF259A2309

 


フレックスディスクグループ作成
割当制限グループ作成
PDB11用ファイルグループを作成
PDB11作成

 

CREATE DISKGROUP flex_data FLEX REDUNDANCY DISK '/dev/sdd','/dev/sde','/dev/sdf';


SELECT name, type FROM V$ASM_DISKGROUP;

select * from v$asm_diskgroup order by group_number;
select * from v$asm_disk order by group_number,disk_number;

select
NAME,
LABEL,
PATH,
GROUP_NUMBER,
DISK_NUMBER,
STATE,
OS_MB,
TOTAL_MB
from v$asm_disk order by group_number,disk_number;


lsfg
lsqg


ALTER DISKGROUP flex_data ADD QUOTAGROUP QG1
     SET 'quota'= 100G;


ALTER DISKGROUP flex_data ADD FILEGROUP FileGroup_PDB11
    DATABASE CRM_PDB11
    SET 'quota_group' = 'QG1';

※PDBをFGに紐づける場合、<CDB名>_<PDB名> と指定する模様

alter session set db_create_file_dest='+FLEX_DATA';

CREATE PLUGGABLE DATABASE PDB11 ADMIN USER pdbadm IDENTIFIED BY oracle;

 

 

Sigmoid and NLL

import numpy as np

class Sigmoid:
    def forward(self, x, w, b):
        """
        x: (N, D)
        w: (D,)
        b: scalar
        """
        self.x = x
        self.w = w
        z = np.dot(x, w) + b   # ← こっちの方が安全
        self.y_pred = 1 / (1 + np.exp(-z))
        return self.y_pred
    def backward(self, dy):
        """
        dy: (N,)
        """
        dz = dy * (1.0 - self.y_pred) * self.y_pred  # (N,)
        # 勾配計算
        dw = np.dot(self.x.T, dz)   # (D,)
        db = np.sum(dz)             # scalar
        return dw, db

class NegativeLogLikelihood:
    def forward(self, y_pred, y_true):
        """
        y_pred: (N,)
        y_true: (N,)
        """
        self.y_pred = y_pred
        self.y_true = y_true
        # 数値安定化(log(0)防止)
        eps = 1e-7
        y_pred = np.clip(y_pred, eps, 1 - eps)
        loss = - (y_true * np.log(y_pred) +
                  (1 - y_true) * np.log(1 - y_pred))
        return np.sum(loss)
    def backward(self):
        eps = 1e-7
        y_pred = np.clip(self.y_pred, eps, 1 - eps)
        dy = - (self.y_true / y_pred) + ((1 - self.y_true) / (1 - y_pred))
        return dy


np.random.seed(0)

# ダミーデータ
x = np.random.randn(5, 3)  # (N=5, D=3)
w = np.random.randn(3)
b = 0.1
y_true = np.array([1, 0, 1, 0, 1])

# モデル
sigmoid = Sigmoid()
loss_fn = NegativeLogLikelihood()

# forward
y_pred = sigmoid.forward(x, w, b)
loss = loss_fn.forward(y_pred, y_true)

print("loss:", loss)

# backward
dy = loss_fn.backward()
dw, db = sigmoid.backward(dy)

print("dw:", dw)
print("db:", db)

 

 

IPがサブネットに含まれるか確認するシェル

https://jiro4989.github.io/tech/2024/04/21/check-ip-cidr.html

 

cat <<-'EOF' > "ip.txt"
192.166.1.1
192.170.1.1
192.177.1.1
EOF

cat <<-'EOF' > "cidr.txt"
192.168.0.0/13
10.0.0.0/8
EOF

ls -l
cat ip.txt
cat cidr.txt


cat <<-'EOF' > checkcidr.sh

#!/bin/bash

ip_to_int() {
  local IFS=.
  read -r o1 o2 o3 o4 <<< "$1"
  echo $(( (o1 << 24) + (o2 << 16) + (o3 << 8) + o4 ))
}


for ip in $(cat "$1") ; do
  for cidr in $(cat "$2") ; do
    network="${cidr%/*}"
    maskbits="${cidr#*/}"

    ip_int=$(ip_to_int "$ip")
    network_int=$(ip_to_int "$network")
    mask_int=$(( 0xFFFFFFFF << (32 - maskbits) & 0xFFFFFFFF ))

    if (( (ip_int & mask_int) == (network_int & mask_int) )); then
      echo ip="$ip" cidr="$cidr" "included=yes"
    else
      echo ip="$ip" cidr="$cidr" "included=no"
    fi
  done
done
EOF

 

ls -l
cat checkcidr.sh
chmod 777 checkcidr.sh

./checkcidr.sh ip.txt cidr.txt

 

 

 

VBA(Word 新規ファイル作成)


https://akira55.com/excel_word/
https://morinokabu.com/2025/08/09/excel-vba-create-word-document/


-- 1. 開発タブの挿入でボタンを作成
※ActiveXコントロールのものを使用する

-- 2. デザインモードONで作成したボタンをダブルクリックするとエディタが開くので下記コードを記載。デザインモードOFFで実行

※ 下記設定必要
「Microsoft Word 16.0 Object Library」の参照設定


Option Explicit


Private Sub CommandButton1_Click()

    
    '画面を更新しない
    Application.ScreenUpdating = False
    '確認メッセージを表示しない
    Application.DisplayAlerts = False
    
    Dim Wd As New Word.Application
    Dim Doc As Word.Document
    

    If Dir(ThisWorkbook.Path & "\" & "test.docx") <> "" Then
        Kill ThisWorkbook.Path & "\" & "test.docx"
    End If
    
    Set Doc = Wd.Documents.Add
    
    Wd.Selection.Font.Size = 11
    Wd.Selection.ParagraphFormat.Alignment = wdAlignParagraphLeft
    
    Wd.Selection.TypeText "test1" & vbCrLf
    
    
    Wd.Selection.Font.Size = 18
    Wd.Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
    
    Wd.Selection.TypeText "test2" & vbCrLf
    
    Wd.Selection.Font.Size = 11
    Wd.Selection.ParagraphFormat.Alignment = wdAlignParagraphLeft
    
    Wd.Selection.TypeText vbCrLf
    Wd.Selection.TypeText vbCrLf
    
    Doc.SaveAs ThisWorkbook.Path & "\test.docx"
    Doc.Close
    


    Set Doc = Wd.Documents.Open(ThisWorkbook.Path & "\test.docx")
    
    Doc.Bookmarks("\EndOfDoc").Select
    
    Wd.Selection.TypeText "hoge2" & vbCrLf
    
    
    Dim tbl As Table
    Set tbl = Doc.Tables.Add(Range:=Wd.Selection.Range, NumRows:=3, NumColumns:=4)
    
    
    Dim Cell As Cell
    Dim count As Long
    
    count = 1
    
    For Each Cell In tbl.Range.Cells
        Cell.Range.InsertAfter "セル " & count
        count = count + 1
    Next Cell
    
    Doc.Close wdSaveChanges
    
    
    
    
    Wd.Quit
    Set Doc = Nothing
    Set Wd = Nothing
    
    
    MsgBox "処理完了"
    
    
    '確認メッセージを表示する
    Application.DisplayAlerts = True
    '画面を更新する
    Application.ScreenUpdating = True


End Sub

 

VBA(Enumによる要素番号管理)

 

https://excel-ubara.com/excelvba1/EXCELVBA409.html

-- 1. 開発タブの挿入でボタンを作成
※ActiveXコントロールのものを使用する

-- 2. デザインモードONで作成したボタンをダブルクリックするとエディタが開くので下記コードを記載。デザインモードOFFで実行

※ 下記設定必要
「Microsoft Scripting Runtime」の参照設定

 


Option Explicit

Enum en
    No = 1
    Name = 2
    Language = 3
End Enum

Dim myArr(1 To 3) As String

Dim myDic As New Dictionary

Private Sub CommandButton1_Click()
    
    '画面を更新しない
    Application.ScreenUpdating = False
    '確認メッセージを表示しない
    Application.DisplayAlerts = False
    
    
    
    Erase myArr
    
    
    myArr(en.No) = "番号"
    myArr(en.Name) = "名前"
    myArr(en.Language) = "言語"
    
    Dim i As Long
    
    For i = LBound(myArr, 1) To UBound(myArr, 1)
        Debug.Print "myArr(" & i & ")= " & myArr(i)
    Next i
    
    
    
    Set myDic = Nothing
    
    myDic.Add en.No, "番号"
    myDic.Add en.Name, "名前"
    myDic.Add en.Language, "言語"
    
    Dim vkey As Variant
    
    For Each vkey In myDic
        Debug.Print "myDic(" & vkey & ")= " & myDic(vkey)
    Next vkey
    
    
    
    MsgBox "処理完了"
    
    
    
    '確認メッセージを表示する
    Application.DisplayAlerts = True
    '画面を更新する
    Application.ScreenUpdating = True
    


End Sub

 

VBA(Word テキストファイルに出力)

-- 1. 開発タブの挿入でボタンを作成
※ActiveXコントロールのものを使用する

-- 2. デザインモードONで作成したボタンをダブルクリックするとエディタが開くので下記コードを記載。デザインモードOFFで実行

※ 下記設定必要
「Microsoft Word 16.0 Object Library」の参照設定

 

Option Explicit


Private Sub CommandButton1_Click()

    
    '画面を更新しない
    Application.ScreenUpdating = False
    '確認メッセージを表示しない
    Application.DisplayAlerts = False
    
    Dim wd As New Word.Application
    
    
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    Dim strFolderPath As String
    strFolderPath = ThisWorkbook.Path & "\WORK"
    
    
    'フォルダ選択
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = True Then
            strFolderPath = .SelectedItems(1)
        End If
    End With
    
    Debug.Print "strFolderPath=" & strFolderPath
    
    
    Dim file As Object
    Dim files As Object
    
    
    Set files = fso.GetFolder(strFolderPath).files
    
    For Each file In files
    
        If file.Name Like "*.docx" Then
        
            Debug.Print "file.Name=" & file.Name
            
            Dim textfile As String
            textfile = Replace(file.Name, ".docx", ".txt")
            
            If Dir(strFolderPath & "\" & textfile) <> "" Then
                Kill strFolderPath & "\" & textfile
            End If
            
            With wd
                .Documents.Add
                .Documents.Open Filename:=strFolderPath & "\" & file.Name, ReadOnly:=True
                .ActiveDocument.SaveAs2 Filename:=strFolderPath & "\" & textfile, FileFormat:=wdFormatText
            End With
        
        
        End If
    
    Next file
    
    wd.Quit
    Set wd = Nothing
    
    MsgBox "処理完了"
    
    
    '確認メッセージを表示する
    Application.DisplayAlerts = True
    '画面を更新する
    Application.ScreenUpdating = True


End Sub

 

 

Standardization

import numpy as np

class Standardization:
    def __init__(self):
        self.mean_ = None
        self.std_ = None
    def fit(self, X):
        X = np.asarray(X)
        self.mean_ = X.mean(axis=0)
        self.std_ = X.std(axis=0)
        # ゼロ除算防止
        self.std_[self.std_ == 0] = 1.0
    def transform(self, X):
        X = np.asarray(X)
        return (X - self.mean_) / self.std_
    def fit_transform(self, X):
        self.fit(X)
        return self.transform(X)
    def inverse_transform(self, Xsd):
        Xsd = np.asarray(Xsd)
        return (Xsd * self.std_) + self.mean_


X = np.array([[1, 2], [3, 4], [5, 6]])

scaler = Standardization()

X_std = scaler.fit_transform(X)
print(X_std)

X2 = scaler.inverse_transform(X_std)
print(X2)

 

VBA(Word PDF読込)


https://qiita.com/NoguchiMasafumi/items/a9aceab5bb9c4e3caa82


-- 1. 開発タブの挿入でボタンを作成
※ActiveXコントロールのものを使用する

-- 2. デザインモードONで作成したボタンをダブルクリックするとエディタが開くので下記コードを記載。デザインモードOFFで実行

※ 下記設定必要
「Microsoft Word 16.0 Object Library」の参照設定

 

Option Explicit


Private Sub CommandButton1_Click()


'画面を更新しない
Application.ScreenUpdating = False
'確認メッセージを表示しない
Application.DisplayAlerts = False

Dim wd As New Word.Application

If Dir(ThisWorkbook.Path & "\" & "test.txt") <> "" Then
    Kill ThisWorkbook.Path & "\" & "test.txt"
End If


With wd
    .Documents.Add
    .Documents.Open Filename:=ThisWorkbook.Path & "\" & "test.pdf", ReadOnly:=True
    .ActiveDocument.SaveAs2 Filename:=ThisWorkbook.Path & "\" & "test.txt", FileFormat:=wdFormatText
End With

wd.Quit
Set wd = Nothing

 

MsgBox "処理完了"

'確認メッセージを表示する
Application.DisplayAlerts = True
'画面を更新する
Application.ScreenUpdating = True


End Sub

VBA(Word 検索箇所before/after置換)

https://www.relief.jp/docs/word-vba-selection-goto-table.html


-- 1. 開発タブの挿入でボタンを作成
※ActiveXコントロールのものを使用する

-- 2. デザインモードONで作成したボタンをダブルクリックするとエディタが開くので下記コードを記載。デザインモードOFFで実行

※ 下記設定必要
「Microsoft Word 16.0 Object Library」の参照設定


Option Explicit


Private Sub CommandButton1_Click()


'画面を更新しない
Application.ScreenUpdating = False
'確認メッセージを表示しない
Application.DisplayAlerts = False


Dim Wd As New Word.Application
Dim Doc As Word.Document


If Dir(ThisWorkbook.Path & "\" & "test2.docx") <> "" Then
    Kill ThisWorkbook.Path & "\" & "test2.docx"
End If

FileCopy ThisWorkbook.Path & "\" & "test.docx", ThisWorkbook.Path & "\" & "test2.docx"

Set Doc = Wd.Documents.Open(ThisWorkbook.Path & "\" & "test2.docx")

 

Const Cnum As String = ".1234567890"


Dim info1 As Long
Dim info2 As Long
Dim info3 As Long

Dim i  As Long
Dim i2 As Long

Dim i2_save As Long

Dim s As String
Dim s2_bf As String
Dim s2_af As String

Dim j As Long

'beforeの修正

With Doc.ActiveWindow
    .Selection.Find.Text = "%"

    .Selection.HomeKey Unit:=wdStory, Extend:=wdMove

    .Selection.GoTo What:=wdGoToTable, Which:=wdGoToNext
    .Selection.GoTo What:=wdGoToTable, Which:=wdGoToNext


    i2_save = 0

    Do While .Selection.Find.Execute

        .Selection.Range.HighlightColorIndex = wdBrightGreen

        info1 = .Selection.Range.Information(wdActiveEndAdjustedPageNumber)
        info2 = .Selection.Range.Information(wdStartOfRangeRowNumber)
        info3 = .Selection.Range.Information(wdStartOfRangeColumnNumber)

        i = .Selection.Range.Start
        i2 = .Selection.Range.End


        Debug.Print "(1)info1=" & info1
        Debug.Print "(1)info2=" & info2
        Debug.Print "(1)info3=" & info3
        Debug.Print "(1)i=" & i
        Debug.Print "(1)i2=" & i2
        Debug.Print "(1)i2_save=" & i2_save

        s = ""
        s2_bf = ""
        s2_af = ""

        '巻き戻りによる重複判定回避
        If i >= i2_save Then

            If (info1 = 2 And info2 = 8 And info3 = 2) Or _
            (info1 = 2 And info2 = 10 And info3 = 2) Then


                j = i - 5

                Do While j < i

                    Doc.Range(j, j + 1).HighlightColorIndex = wdYellow

                    s = Doc.Range(j, j + 1).Text
                    If InStr(Cnum, s) = 0 Then
                        s = ""
                    End If
                    s2_bf = s2_bf & s
                    j = j + 1
                Loop

                j = 1
                Do While j <= Len(s2_bf)

                    Doc.Range(i - 1, i).Text = ""
                    j = j + 1

                    i = i - 1

                Loop


                s2_af = "99"

                .Selection.InsertBefore (s2_af)

 

            End If


        End If

        i2_save = i2 + WorksheetFunction.Max(-1 * Len(s2_bf) + Len(s2_af), 0)


    Loop
End With


'afterの修正

With Doc.ActiveWindow
    .Selection.Find.Text = "最大となる日は"

    .Selection.HomeKey Unit:=wdStory, Extend:=wdMove
    
    .Selection.GoTo What:=wdGoToTable, Which:=wdGoToNext
    .Selection.GoTo What:=wdGoToTable, Which:=wdGoToNext
    
    i2_save = 0

    Do While .Selection.Find.Execute

        .Selection.Range.HighlightColorIndex = wdBrightGreen


        info1 = .Selection.Range.Information(wdActiveEndAdjustedPageNumber)
        info2 = .Selection.Range.Information(wdStartOfRangeRowNumber)
        info3 = .Selection.Range.Information(wdStartOfRangeColumnNumber)

        i = .Selection.Range.Start
        i2 = .Selection.Range.End

        Debug.Print "(2)info1=" & info1
        Debug.Print "(2)info2=" & info2
        Debug.Print "(2)info3=" & info3
        Debug.Print "(2)i=" & i
        Debug.Print "(2)i2=" & i2
        Debug.Print "(2)i2_save=" & i2_save


        s = ""
        s2_bf = ""
        s2_af = ""

        '巻き戻りによる重複判定回避
        If i >= i2_save Then
            If (info1 = 2 And info2 = 7 And info3 = 2) Or _
            (info1 = 2 And info2 = 9 And info3 = 2) Then


                j = i2

                Do While j < i2 + 10

                    Doc.Range(j, j + 1).HighlightColorIndex = wdYellow

                    s = Doc.Range(j, j + 1).Text

                    s2_bf = s2_bf & s
                    If InStr("日", s) > 0 Then
                        Exit Do
                    End If
                    j = j + 1
                Loop

                j = 1
                Do While j <= Len(s2_bf)

                    Doc.Range(i2, i2 + 1).Text = ""

                    j = j + 1

                Loop


                s2_af = "11月1日"

                .Selection.InsertAfter (s2_af)


            End If
        End If


        i2_save = i2 + WorksheetFunction.Max(-1 * Len(s2_bf) + Len(s2_af), 0)

    Loop
End With

Doc.Save
Doc.Close


Wd.Quit
Set Doc = Nothing
Set Wd = Nothing


MsgBox "処理完了"

'確認メッセージを表示する
Application.DisplayAlerts = True
'画面を更新する
Application.ScreenUpdating = True


End Sub

 

 

VBA(Word WdInformation取得)


https://learn.microsoft.com/ja-jp/office/vba/api/word.wdinformation
https://tonari-it.com/word-vba-find-execute/
https://qiita.com/t-yama-3/items/89300fbab045738b604e


-- 1. 開発タブの挿入でボタンを作成
※ActiveXコントロールのものを使用する

-- 2. デザインモードONで作成したボタンをダブルクリックするとエディタが開くので下記コードを記載。デザインモードOFFで実行

※ 下記設定必要
「Microsoft Word 16.0 Object Library」の参照設定

Option Explicit


Private Sub CommandButton1_Click()


'画面を更新しない
Application.ScreenUpdating = False
'確認メッセージを表示しない
Application.DisplayAlerts = False


Dim Wd As New Word.Application
Dim Doc As Word.Document


If Dir(ThisWorkbook.Path & "\" & "test2.docx") <> "" Then
    Kill ThisWorkbook.Path & "\" & "test2.docx"
End If

FileCopy ThisWorkbook.Path & "\" & "test.docx", ThisWorkbook.Path & "\" & "test2.docx"

Set Doc = Wd.Documents.Open(ThisWorkbook.Path & "\" & "test2.docx")

 

Const Cnum As String = ".1234567890"

With Doc.ActiveWindow
    .Selection.Find.Text = "GB"
    
    Do While .Selection.Find.Execute
    
        .Selection.Range.HighlightColorIndex = wdBrightGreen
        
        
        Dim info1 As Long
        Dim info2 As Long
        Dim info3 As Long
        Dim info4 As Long
        Dim info5 As Long
        Dim info6 As Long
        Dim info7 As Long
        Dim info8 As Long
        Dim info9 As Long
        Dim i  As Long
        Dim i2 As Long
        
        info1 = .Selection.Range.Information(wdActiveEndAdjustedPageNumber)
        
        info2 = .Selection.Range.Information(wdStartOfRangeRowNumber)
        info3 = .Selection.Range.Information(wdStartOfRangeColumnNumber)
        
        info4 = .Selection.Range.Information(wdEndOfRangeRowNumber)
        info5 = .Selection.Range.Information(wdEndOfRangeColumnNumber)
        
        info6 = .Selection.Range.Information(wdFirstCharacterLineNumber)
        info7 = .Selection.Range.Information(wdFirstCharacterColumnNumber)
        
        info8 = .Selection.Range.Information(wdMaximumNumberOfRows)
        info9 = .Selection.Range.Information(wdMaximumNumberOfColumns)
        
        i = .Selection.Range.Start
        i2 = .Selection.Range.End
        
        Debug.Print "info1= " & info1
        Debug.Print "info2= " & info2
        Debug.Print "info3= " & info3
        Debug.Print "info4= " & info4
        Debug.Print "info5= " & info5
        Debug.Print "info6= " & info6
        Debug.Print "info7= " & info7
        Debug.Print "info8= " & info8
        Debug.Print "info9= " & info9
        
        Debug.Print "i= " & i
        Debug.Print "i2= " & i2
        
        
        Dim s As String
        Dim s2 As String
        Dim s3 As String
        
        Dim j As Long
        
        s = ""
        s2 = ""
        
        
        j = i - 5
        
        Do While j < i
        
            Doc.Range(j, j + 1).HighlightColorIndex = wdYellow
            
            s = Doc.Range(j, j + 1).Text
            If InStr(Cnum, s) = 0 Then
                s = ""
            End If
            s2 = s2 & s
            j = j + 1
        Loop
        
        Debug.Print "s2=" & s2
        
        s = ""
        s3 = ""
        
        j = i2
        
        Do While j < i2 + 5
            Doc.Range(j, j + 1).HighlightColorIndex = wdRed
            
            s = Doc.Range(j, j + 1).Text
            If InStr(Cnum, s) = 0 Then
                s = ""
            End If
            s3 = s3 & s
            j = j + 1
        Loop
        
        Debug.Print "s3=" & s3
        
    
    Loop
End With

 

 

Doc.Save
Doc.Close


Wd.Quit
Set Doc = Nothing
Set Wd = Nothing


MsgBox "処理完了"

'確認メッセージを表示する
Application.DisplayAlerts = True
'画面を更新する
Application.ScreenUpdating = True


End Sub

 

 

VBA(Word 検索文字を着色して別名保存)


https://zenn.dev/zhizhiarv/articles/3f75f8e2c75345
https://m32006400n.xsrv.jp/infrastructure/word-1485/
https://www.excel.studio-kazu.jp/kw/20210423124612.html


-- 1. 開発タブの挿入でボタンを作成
※ActiveXコントロールのものを使用する

-- 2. デザインモードONで作成したボタンをダブルクリックするとエディタが開くので下記コードを記載。デザインモードOFFで実行

※ 下記設定必要
「Microsoft Word 16.0 Object Library」の参照設定


Option Explicit


Private Sub CommandButton1_Click()


'画面を更新しない
Application.ScreenUpdating = False
'確認メッセージを表示しない
Application.DisplayAlerts = False


Dim Wd As New Word.Application
Dim Doc As Word.Document


If Dir(ThisWorkbook.Path & "\" & "test2.docx") <> "" Then
    Kill ThisWorkbook.Path & "\" & "test2.docx"
End If

FileCopy ThisWorkbook.Path & "\" & "test.docx", ThisWorkbook.Path & "\" & "test2.docx"

Set Doc = Wd.Documents.Open(ThisWorkbook.Path & "\" & "test2.docx")

With Doc.Content.Find

    .Text = "%"
    '.Replacement.Text = "XXX"
    .Replacement.Font.ColorIndex = wdRed
    .Execute Replace:=wdReplaceAll

End With


Doc.Save
Doc.Close


Wd.Quit
Set Doc = Nothing
Set Wd = Nothing


MsgBox "処理完了"

'確認メッセージを表示する
Application.DisplayAlerts = True
'画面を更新する
Application.ScreenUpdating = True


End Sub

 

ベイズの定理

ベイズの定理導出

 
\displaystyle
P(A|B) = \dfrac{P(A,B)}{P(B)}
 
\displaystyle
P(B|A) = \dfrac{P(A,B)}{P(A)}

 
\displaystyle
P(A,B) = P(A|B)P(B)=P(B|A)P(A)

 
\displaystyle
P(A|B) = \dfrac{P(B|A)P(A)}{P(B)}
 
\displaystyle
P(B|A) = \dfrac{P(A|B)P(B)}{P(A)}


ベイズの定理活用

 
\displaystyle
P(A|B) = \dfrac{P(B|A)P(A)}{P(B)}
 
\displaystyle
\quad \quad \quad \quad   = \dfrac{P(B|A)P(A)}{P(B|A)P(A) + P(B|\overline{A})P(\overline{A})}

一変量正規分布

σ固定の場合

一変量正規分布の確率関数:
 
\displaystyle
f(x;μ) =  \dfrac{1}{\sqrt{2πσ^{2}}} \exp(- \dfrac{1}{2σ^{2}} (x-μ)^{2})


一変量正規分布の尤度関数:
 
\displaystyle
L_{D}(μ)=\prod_{i=1}^n \dfrac{1}{\sqrt{2πσ^{2}}} \exp(- \dfrac{1}{2σ^{2}} (x_{i}-μ)^{2})


一変量正規分布の負の対数尤度:
 
\displaystyle
 - \log L_{D}(μ) = - n \log(\dfrac{1}{\sqrt{2πσ^{2}}} ) + \dfrac{1}{2σ^{2}} \sum_{i=1}^n (x_{i} - μ )^{2}


一変量正規分布の最尤推定量:
 
\displaystyle
 \hat{μ} = \dfrac{1}{n} \sum_{i=1}^n x_{i}




以上の内容はhttps://htn20190109.hatenablog.com/より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14