Skip to content

Instantly share code, notes, and snippets.

View kawaz's full-sized avatar
🏠
Working from home

Yoshiaki Kawazu kawaz

🏠
Working from home
View GitHub Profile
@kawaz
kawaz / csprng.js
Last active November 30, 2023 20:06
ブラウザのJavascriptで暗号論的にセキュアな疑似乱数を使って指定範囲の整数の乱数を得る方法。
View csprng.js
/**
* a以上b以下の整数の乱数を生成する
* @param {number|bigint} a
* @param {number|bigint} b
* @returns {number|bigint}
*/
function getRandomIntBetween(a, b) {
if (b < a) {
// [a, b] = [b, a]
const t = a; a = b; b = t;
@kawaz
kawaz / install-pam_tid-and-pam_reattach.sh
Last active November 29, 2023 09:05
sudo で TouchID が使えるようにする。tmux 内で使えるようにもする。
View install-pam_tid-and-pam_reattach.sh
#!/bin/bash
set -e
set -o pipefail
# pam_tidの存在チェック(間違えてLinux環境などで実行されたら中断する)
[[ -f /usr/lib/pam/pam_tid.so.2 ]] || exit 1
[[ "${OSTYPE:0:6}" == "darwin" ]] || exit 1
# /etc/pam.d/sudo を念のためターミナルに出力しておく(似非バックアップ)
echo "### /etc/pam.d/sudo (original)"
@kawaz
kawaz / superInterval.js
Last active November 24, 2023 19:40
タブがバックグラウンドになってもサボらない setInterval
View superInterval.js
const superInterval = (cb, interval=1000, ...args) => {
try {
const code = `self.addEventListener('message', msg=>{setInterval(()=>self.postMessage(null), msg.data)})`
const w = new Worker(`data:text/javascript;base64,${btoa(code)}`)
w.onmessage = () => cb(...args)
w.postMessage(interval)
return {stop:()=>w.terminate()}
} catch(_){
// 実装の問題またはCSPによる拒否などで Worker が使えなければ普通の setInterval を使う
const id = setInterval(cb, interval, ...args)
@kawaz
kawaz / tools.js
Last active October 31, 2023 08:21
よく使うJSの便利関数的な奴 tools.js
View tools.js
// タイムアウト付き setInterval
const setIntervalTimeout = (f, interval = 200, timeout = 5000, immediate = false) => {
immediate && setTimeout(f, 0)
const i = setInterval(f, interval)
const t = setTimeout(() => clearInterval(i), timeout)
return () => { clearInterval(i); clearTimeout(t) }
}
// タイムアウト付き setInterval の強化版(タブがバックグラウンドになってもサボらない)
const setIntervalTimeoutSuper = (f, interval = 200, timeout = 5000, immediate = false) => {
try {
@kawaz
kawaz / binconv.js
Last active October 29, 2023 07:44
javascript string text(utf8) base64 hex tool
View binconv.js
const binconv = (()=>{
// base64 <-> binary
const atob = window.atob
const btoa = window.btoa
// binary <-> Uint8Array
const btou8 = b => new Uint8Array([].map.call(b,c=>c.charCodeAt(0))) //new Uint8Array([...b].map(c=>c.charCodeAt(0)))
const u8tob = u8 => String.fromCharCode.apply(null,u8) //String.fromCharCode(...u8)
// string <-> Uint8Array
@kawaz
kawaz / install_neovim_to_amazonlinux.sh
Last active October 17, 2023 23:03
install neovim to amazonlinux
View install_neovim_to_amazonlinux.sh
#!/usr/bin/env bash
sudo yum groups install -y Development\ tools
sudo yum install -y cmake
sudo yum install -y python34-{devel,pip}
sudo pip-3.4 install neovim --upgrade
(
cd "$(mktemp -d)"
git clone https://github.com/neovim/neovim.git
cd neovim
make CMAKE_BUILD_TYPE=Release
@kawaz
kawaz / beep.js
Last active September 5, 2023 02:44
Web Audio API を使って beep 音を鳴らすサンプル。
View beep.js
const beep = (duration=200, frequency=440, gain=1.0) => new Promise((resolve, reject) => {
try {
const audioCtx = new AudioContext()
const oscNode = new OscillatorNode(audioCtx, {frequency, type:"square"})
const gainNode = new GainNode(audioCtx, {gain})
oscNode.onended = resolve
oscNode.connect(gainNode).connect(audioCtx.destination)
oscNode.start(audioCtx.currentTime)
oscNode.stop(audioCtx.currentTime + duration / 1000)
} catch(err){
@kawaz
kawaz / movingAverageFilter.js
Created July 27, 2023 05:06
データ列に対してmapすると移動平均が得られるフィルタ関数。chartjs が移動平均線の描画に対応してないっぽいが、これを噛ましてやれば自力で移動平均用のデータ列が作れる。
View movingAverageFilter.js
const movingAverageFilter = (ws=3) => {
if(!Number.isInteger(ws) || ws < 1) {
throw new Error(`Invalid window size. ws must be >=1. You entered: ws=${ws}.`)
}
let win = []
let sum = 0
let pos = 0
let tail = 0
return (head) => {
sum = sum + head - tail
@kawaz
kawaz / q.js
Last active June 14, 2023 03:16
document.querySelectorAll のショートハンド関数。NodeList じゃなくて配列で返してくれます。::shadow に自前対応済み!
View q.js
// const q = (s,r)=>[...(r||document).querySelectorAll(s)];
const q = (selector,root) =>
selector.split(/::shadow\s*/)
.reduce((parents,selector,idx) =>
parents.flatMap(parent =>
selector=="" ? (idx==0?parent:parent.shadowRoot) : [...(idx==0?parent:parent.shadowRoot).querySelectorAll(selector)]
)
, [root||document]
)
@kawaz
kawaz / base64-cffunctions.js
Last active March 24, 2023 05:42
CloudFront Functions 内でコピペで使えるBASE64実装
View base64-cffunctions.js
// CloudFront Functions 内で利用可能なBASE64実装
function b64enc(b) {
var b64codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".split("").map(s=>s.charCodeAt(0))
var pad = [0, 2, 1][b.length % 3]
// 入力バイト列(本来は 0xFF を超える charCode が含まれていたらエラーにすべきだが省略
var bCodes = (b + '\0'.repeat(pad)).split("").map(s=>s.charCodeAt(0))
// 出力用バイト列
var aCodes = new Uint8Array(bCodes.length / 3 * 4)
for(var i=0,j=0; i<b.length; i+=3,j+=4){