onsen code monkey

個人的な日記とプログラミング備忘録です

【JavaScript】なるべくシンプルに数秒間待機させる処理

他言語で言うところの wait とか sleep とかをJSでやりたい

すごくよく使うので改めてメモ

ES2017以降なら↓

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// 2秒待機
await sleep(2000);


それより古いバージョンなら↓

function sleep(waitMsec) {
  var startMsec = new Date();    
  // 指定ミリ秒間だけループさせる(CPUは常にビジー状態)
  while (new Date() - startMsec < waitMsec);
}

// 2秒待機
sleep(2000);


丸パクリですみません。
以下、参考サイト様

javascriptでsleep的に処理をwaitさせる方法(コピペでOK) | Hirooooo’s Labo

【JavaScript入門】処理を一時停止するsleep機能の実現方法まとめ | 侍エンジニアブログ

gcc: error: unrecognized command line option を解決する

rails で bcrypt をインストールしようとすると以下のようなエラーが出た

Installing bcrypt 3.1.19 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

current directory: /home/vagrant/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/bcrypt-3.1.19/ext/mri
/home/vagrant/.rbenv/versions/3.2.2/bin/ruby extconf.rb
creating Makefile

current directory: /home/vagrant/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/bcrypt-3.1.19/ext/mri
make DESTDIR\= sitearchdir\=./.gem.20231014-3779-vcohcj sitelibdir\=./.gem.20231014-3779-vcohcj clean

current directory: /home/vagrant/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/bcrypt-3.1.19/ext/mri
make DESTDIR\= sitearchdir\=./.gem.20231014-3779-vcohcj sitelibdir\=./.gem.20231014-3779-vcohcj
compiling bcrypt_ext.c
gcc: error: unrecognized command line option ‘-Wduplicated-cond’
gcc: error: unrecognized command line option ‘-Wmisleading-indentation’
gcc: error: unrecognized command line option ‘-Wimplicit-fallthrough=0’
make: *** [bcrypt_ext.o] Error 1

make failed, exit code 2

~ 中略

An error occurred while installing bcrypt (3.1.19), and Bundler cannot continue.

In Gemfile:
bcrypt

どうやら gcc のバージョンが古いせいでコンパイラコマンドラインオプションを認識できないため bcrypt のインストールに失敗している模様

gcc のバージョンを確認してみる

$ gcc -v

結果

Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.8.5/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-linker-hash-style=gnu --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-initfini-array --disable-libgcj --with-isl=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/isl-install --with-cloog=/builddir/build/BUILD/gcc-4.8.5-20150702/obj-x86_64-redhat-linux/cloog-install --enable-gnu-indirect-function --with-tune=generic --with-arch_32=x86-64 --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)

version 4.8.5 とのこと。2015年のバージョンらしいのでたしかにかなり古そう。
以下、アップデート手順(CentOS/Red Hat用のコマンドのため他を使用している場合は読み替えてください)

gcc アップデートコマンド

$ sudo yum update gcc

これでアップデートできればそれで良し。
僕の場合はさらに以下のエラーメッセージが出ました。

Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: ftp.jaist.ac.jp
* centos-sclo-rh: ftp.jaist.ac.jp
* centos-sclo-sclo: ftp.jaist.ac.jp
* extras: ftp.jaist.ac.jp
* updates: mirrors.163.com
No packages marked for update

よくわからないがとにかくダメそうなので別の方法を調べてみると、どうやら Developer Toolset の新しいバージョンをインストールすれば良いとのことで Developer Toolset 9 をインストールする

$ sudo yum install centos-release-scl
$ sudo yum install devtoolset-9

Developer Toolset 9 を使用するように設定

$ source scl_source enable devtoolset-9

改めて gcc のバージョンを確認

$ gcc -v

Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/lto-wrapper
Target: x86_64-redhat-linux
Configured with: ../configure --enable-bootstrap --enable-languages=c,c++,fortran,lto --prefix=/opt/rh/devtoolset-9/root/usr --mandir=/opt/rh/devtoolset-9/root/usr/share/man --infodir=/opt/rh/devtoolset-9/root/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-shared --enable-threads=posix --enable-checking=release --enable-multilib --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-gcc-major-version-only --with-linker-hash-style=gnu --with-default-libstdcxx-abi=gcc4-compatible --enable-plugin --enable-initfini-array --with-isl=/builddir/build/BUILD/gcc-9.3.1-20200408/obj-x86_64-redhat-linux/isl-install --disable-libmpx --enable-gnu-indirect-function --with-tune=generic --with-arch_32=x86-64 --build=x86_64-redhat-linux
Thread model: posix
gcc version 9.3.1 20200408 (Red Hat 9.3.1-2) (GCC)

9.3.1 にアップデートできたので、あとは bundle install で bcrypt をインストールすれば無事成功

【Ruby on Rails】ruby-profでコードの処理速度を測定する

■やりたいこと

コードの実行中にどの部分が時間を消費しているかを特定したい

■使用ツール

ruby-prof

※プロファイリングツールは ruby-prof の他に stackprof も有力らしい

■手順

1. gemfile に ruby-prof を追加

gem 'ruby-prof'

2. インストール実行

bundle install

3. controller を編集

# ruby-prof をロード
require 'ruby-prof'

class TestController
  def test
    result = RubyProf.profile do
      # 測定したい処理をここに記述する
    end

    # 測定結果を出力する
    output_path = './rubyprof.out'
    File.open(output_path , 'w') { | f |
      RubyProf::FlatPrinter.new(result).print(f)
    }
  end
end

4. 測定したい処理を実行後、出力結果を確認する
上記の例では rubyprof.out というファイルが出力されているはずなので確認する。
結果を見やすくしてくれるツール等もあるが面倒くさい場合はテキストエディタでそのまま開いて良し。

出力結果サンプル

Measure Mode: wall_time
Thread ID: 70325959779980
Fiber ID: 93369140
Total: 0.198714
Sort by: self_time

%self total self wait child calls name location
13.07 0.042 0.026 0.016 0.000 53 Mysql2::Client#_query
4.54 0.009 0.009 0.000 0.000 122 IO#write
4.29 0.009 0.009 0.000 0.000 61 Kernel#caller
3.65 0.007 0.007 0.000 0.000 8336 String#sub
3.61 0.117 0.007 0.002 0.108 932 *Array#each
1.40 0.136 0.003 0.000 0.133 743 *#handle_interrupt
1.18 0.009 0.002 0.003 0.003 2169 *Class#new
0.96 0.002 0.002 0.000 0.000 254 Regexp#===
0.69 0.003 0.001 0.000 0.002 284 Array#map
0.65 0.001 0.001 0.000 0.000 2417 Regexp#match?

%self - The percentage of time spent in this method, derived from self_time/total_time.
total - The time spent in this method and its children.
self - The time spent in this method.
wait - The amount of time this method waited for other threads.
child - The time spent in this method's children.
calls - The number of times this method was called.
name - The name of the method.
location - The location of the method.

総処理時間0.198714秒のうちクエリの実行で0.042秒(13.07%)使ってるなとか、53回呼び出されてるな等読み取れる

【Ruby on Rails】一時ファイルとして作成したファイルをブラウザに送信した後に削除する

一時ファイルとしてダウンロードしたファイルをブラウザに送信した後に削除がしたかった時のメモ

結論:send_fileでなくsend_dataを使うと削除できました

ルーティングの設定
routes.rb

resources :hoges do
  get "download", on: :member
end

または

get  'hoges/download'  => 'hoges#download'


view側ボタン

<%= button_to "ダウンロード", {controller: 'hoges', action: 'download'}, {method: :get} %>


失敗例:controller側(send_fileの場合)

class HogeController < ApplicationController

  def download
    file_name = "file_name_#{params[:id]}.mp3"
    tmp_file_path = "tmp/" + file_name
    File.new(tmp_file_path, 'w') // 一時ファイル作成
    send_file tmp_file_path
    File.delete tmp_file_path // ここでエラーになる
  end
end

成功例:controller側(send_dataの場合)

class HogeController < ApplicationController

  def download
    file_name = "file_name_#{params[:id]}.mp3"
    tmp_file_path = "tmp/" + file_name
    File.new(tmp_file_path, 'w') // 一時ファイル作成
    send_data(File.read(tmp_file_path), :filename => file_name)
    File.delete tmp_file_path
  end
end

【Ruby on Rails】rails s でエラーになった時の対処法

原因と対処:yarnがインストールされていなかったのでインストールした

yarnインストール(npmの場合)

$ npm install -g yarn

yarnインストール(brewの場合)

$ brew install yarn


yarnがインストールされたことを確認

$ yarn -v

webpackerインストール

$ rails webpacker:install

改めてサーバー起動

$ rails s


参考記事様
Rails6 Webpackerでエラーが出た - Qiita

【PostgreSQL】プレーンテキストのbackupファイルをリストアする方法

お客さんにもらったポスグレのbackupファイルをPgAdmin3でリストアしようとしたらなぜかできなくて4時間くらいハマった。
調べれば解決策は何パターンか出てくるもののなぜかうまくいかず、自分と同じ状態の人の手助けになれることを願ってシェアします。

手順1.プレーンテキストのbackupファイル(backup.txtとか)の拡張子をsqlに変更(backup.sql
手順2.コマンドプロンプトで以下を実行

$ psql -h [ホスト名] -p [ポート番号] -U [ユーザ名] -d [DB名] -f [バックアップファイルのフルパス]

※パスが通っていない場合はパスを通すかpsql.exeの場所まで移動すること。

手順3.パスワードを求められたら入力する

おわり

【Spring】Tomcatが起動できなかった時のメモ

Spring BootでTomcat立ち上げようとしたら下記のエラーが出た

***************************
APPLICATION FAILED TO START
***************************

Description:

The Tomcat connector configured to listen on port 8080 failed to start. The port may already be in use or the connector may be misconfigured.

Action:

Verify the connector's configuration, identify and stop any process that's listening on port 8080, or configure this application to listen on another port.

netstatでポート8080を調べる

$ netstat -nao | findstr 8080

f:id:hitoto28:20191024110503p:plain

あとはタスクマネージャーでPID6040のサービスを探して停止するだけ