`(blog ,garaemon)

ポップカルチャーを摂取して、コードを吐き出す機械

pythonでjsonのutf8の文字をescapeしない

pythonでdictオブジェクトを文字列に変換すると、utf8の文字がエスケープされてしまう.

'hoge: %s' % json.dumps({'text': 'ほげ'})
=> 'hoge: {"text": "\\u307b\\u3052"}'

これをエスケープしないようにするにはensure_ascii=Falseにすれば良い.

'hoge: %s' % json.dumps({'text': 'ほげ'}, ensure_ascii=False)
=> 'hoge: {"text": "ほげ"}'

micropythonのusocketで大きなファイルをHTTP越しに読む

micropythonを動かす環境はm5stackといったメモリが貧弱であることが多く, 普段は気にならないサイズでもMemory Allocation Errorが発生して読み込めないことがある.

micropythonのurequestsパッケージは便利だけど、データを逐次的に読み出すインタフェイスがないのが問題. なので直接usocketオブジェクトに触ってサイズを区切って読み出すようにすればいい. 最後に忘れずにrequestをcloseするのを忘れないように。これを忘れるとmemory allocation errorを引き起こす.

from m5stack import lcd
import urequests

def download_to_file(image_url, filename, step_size=1024):
    r = urequests.get(image_url)
    try:
        with open(filename, 'wb') as f:
            while True:
                c = r.raw.read(step_size)
                if c:
                    f.write(c)
                else:
                    return
    except Exception as e:
        lcd.println('Exception(download_image): ' + str(e))
        raise e
    finally:
        r.close()

新iPad(2018年モデル)でApple Pencilをつけられるカバー

iPad (2018年モデル)を購入したので、Apple Pencilをつけられるカバーということで以下のものを購入して利用している.

https://www.amazon.co.jp/gp/product/B07C4RZMS9

Apple Pencilもしっかり収納できて良い感じ. 少し重いのと、Apple Pencilを立てる穴はちょっと使いにくいかも.

javascript版jupyterのようなobservable

beta.observablehq.com

observableはjavascript版のjupyterのようなサービス. d3.jsを利用した美しい可視化が特徴的.

どうやら今年の1月31日にサービスインしたらしい.

ここから基本的なサンプルを色々見ることができる. jupyterと正面から勝負するのは大変そうな気もするけど、出力となるノートはobservableの方がきれいなので注目している.

ちなみに、d3.expressというURLからも飛ぶことができる.

emacsでカーソル位置の単語をispellの辞書に追加する

emacsでカーソル位置の単語をispellの辞書に追加するelispコード

(require 'thingatpt)

(defun add-word-to-ispell-dictionary ()
  "Add word to dictionary file for ispell."
  (interactive)
  (let ((user-dictionary-file (expand-file-name "~/.aspell.en.pws")))
    (let ((buf (find-file-noselect user-dictionary-file)))
      (if (not (file-exists-p user-dictionary-file))
          (with-current-buffer buf
            (insert "personal_ws-1.1 en 0\n")
            (save-buffer)))
      (let ((theword (thing-at-point 'word)))
        (if theword
            (with-current-buffer buf
              (goto-char (point-max))
              (insert (format "%s\n" theword))
              (save-buffer))))
      )))

(global-set-key "\M-." 'add-word-to-ispell-dictionary)