question
dict | answers
list | id
stringlengths 2
5
| accepted_answer_id
stringlengths 2
5
⌀ | popular_answer_id
stringlengths 2
5
⌀ |
---|---|---|---|---|
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "AWSにて踏み台とインターネット経由(ALB)で参照可能なCMSサーバを構築しています。 \n開発者は踏み台経由、使用者はインターネット経由での接続を想定しております。 \nインターネット経由の場合、ログインし、詳細ページを開くと以下のエラーが発生し参照できません。 \n踏み台経由ではエラーとならず参照可能です。\n\n踏み台経由での接続時は参照できるためアプリ側の問題ではないと判断していますが \nインターネット経由ではタイムアウトする理由・対応方法をご教授ください。\n\n**実行環境:**\n\nApache:2.4.6 \ntomcat:8.5.34 \nJava:11\n\n**実施したが改善されなかった対応**\n\n * Proxypassに「Keepalive=on」を設定\n * timeoutと同じ値をProxyTimeoutに設定\n * MaxKeepAliveRequestsを100から200に設定\n * KeepAliveTimeoutを5から60に設定\n\nerror.log\n\n```\n\n [Fri Jun 11 17:57:53.789818 2021] [proxy_ajp:error] [pid 23603:tid 139646499485440] (70007)The timeout specified has expired: AH01030: ajp_ilink_receive() can't receive header\n \n```\n\n追加情報が必要でしたらご連絡ください。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-11T11:01:27.337",
"favorite_count": 0,
"id": "77489",
"last_activity_date": "2021-06-11T11:15:23.553",
"last_edit_date": "2021-06-11T11:15:23.553",
"last_editor_user_id": "3060",
"owner_user_id": "46818",
"post_type": "question",
"score": 0,
"tags": [
"apache"
],
"title": "tomcatとの接続でタイムアウトする",
"view_count": 2741
} | [] | 77489 | null | null |
{
"accepted_answer_id": "77491",
"answer_count": 1,
"body": "Javaでローカルでデータベースを立ち上げ、name num\npriceの三つの項目が入っているTestテーブルがあるとして、このテーブルから`num*price`の売上金額が一番多いもののnameを取り出したいのですが、`num*price`の売上金額が同額で一番多いものが二つ以上ある場合には、その二つを取り出せるようにしたいです。これはSQL文だけで実行可能でしょうか。それともJavaのプログラムで実行することしかできないでしょうか。SQLで実行可能な場合はどのような書き方になるか教えていただきたいです。",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-11T11:39:11.950",
"favorite_count": 0,
"id": "77490",
"last_activity_date": "2021-06-12T12:52:52.563",
"last_edit_date": "2021-06-12T12:52:52.563",
"last_editor_user_id": "2808",
"owner_user_id": "41769",
"post_type": "question",
"score": -1,
"tags": [
"java",
"sql"
],
"title": "Javaでのデータベース操作のSQL文の書き方",
"view_count": 266
} | [
{
"body": "metropolis さんのコメントより、テーブル名を goods だとして、以下の通り実行することで実現できました。\n\n```\n\n SELECT name FROM goods WHERE (num*price) = (SELECT MAX(num*price) FROM goods);\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-11T12:55:49.567",
"id": "77491",
"last_activity_date": "2021-06-11T16:51:32.333",
"last_edit_date": "2021-06-11T16:51:32.333",
"last_editor_user_id": "3060",
"owner_user_id": "41769",
"parent_id": "77490",
"post_type": "answer",
"score": 0
}
] | 77490 | 77491 | 77491 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "openpyxlを使用したExcel自動入力アプリを作成したのですが、作成されたxlsxファイルをExcel365(Windows)で開くと、文字化けします(#になる)。 \n[](https://i.stack.imgur.com/QeOE6.png) \n原因を色々と探り、フォントが問題(Droid Sans\nFallback)なのかと思い、游ゴシックで入力されるようにソースコードを書き換えてみましたが、それでも文字化けは残っていました。 \n他に、文字数が一定を超えると文字化けする等書かれた記事も見つけましたが、1つのセルに対して2〜4文字までしか入力していません。\n\nopenpyxlで作成後のファイルを、Excelの書式設定で分類を違うものに一度変えてやると解消できるのですが(入力時の分類は数値)、毎回その作業を行うのは面倒なので、文字化けしないファイルを作成できるようにしたいです。良い解決方法がございましたら教えていただきたいです。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-11T17:26:16.883",
"favorite_count": 0,
"id": "77496",
"last_activity_date": "2021-06-11T20:05:22.693",
"last_edit_date": "2021-06-11T20:05:22.693",
"last_editor_user_id": "4236",
"owner_user_id": "44989",
"post_type": "question",
"score": 0,
"tags": [
"excel",
"openpyxl"
],
"title": "Python+openpyxlで作成したxlsxファイルが文字化けする。",
"view_count": 622
} | [
{
"body": "単に列幅が狭くて表示できない時に [##### と表示された](https://support.microsoft.com/ja-\njp/office/-%E3%82%A8%E3%83%A9%E3%83%BC%E3%81%AE%E4%BF%AE%E6%AD%A3%E6%96%B9%E6%B3%95-bf801d0a-2a6e-44bd-a70e-0f780ae8f11e)だけではありませんか?\nそうであれば、列幅を広くしてください。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-11T20:04:32.920",
"id": "77497",
"last_activity_date": "2021-06-11T20:04:32.920",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "4236",
"parent_id": "77496",
"post_type": "answer",
"score": 1
}
] | 77496 | null | 77497 |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "パソコン版Googleドライブを使ってG:にGoogleドライブをマウントした。\n\n[パソコン版 Google ドライブを導入する](https://support.google.com/a/answer/7491144?hl=ja)\n\nNVIM 0.4.4 での通りコマンドを実行しても開くことができない。\n\n```\n\n :e G:\\\n :e G:\\マイドライブ\\\n \n```\n\nファイルを直接指定した場合、一つ目は開くが二つ目は開かないのか、バッファが切り替わらない。\n\n```\n\n :e G:\\マイドライブ\\a\n :e G:\\マイドライブ\\b\n \n```\n\nvimでは問題なく開くことができる。\n\n * 同様の事象が発生している方はいますか\n * neovimでGoogleDriveを開ける方はいますか\n * 解決策を教えてください",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-12T04:35:13.103",
"favorite_count": 0,
"id": "77499",
"last_activity_date": "2022-08-19T01:52:30.770",
"last_edit_date": "2022-08-19T01:52:30.770",
"last_editor_user_id": "3060",
"owner_user_id": "23564",
"post_type": "question",
"score": 0,
"tags": [
"vim",
"neovim"
],
"title": "NeovimでG:にマウントしたGoogleドライブを開くことができない",
"view_count": 113
} | [] | 77499 | null | null |
{
"accepted_answer_id": null,
"answer_count": 2,
"body": "**質問1**\n\n「ゼロから作るディープラーニング」を勉強していて、182pのところを読んでいたら、そもそもなんで、重みWの初期値を今までnp.random.randnというものにしていたのかがわからなくなりました。なのでなぜnp.random.randnを重みの初期値にするのかを教えていただきたいです。\n\n**質問2** \nnp.random.randnは「平均0、分散1(標準偏差1)の正規分布(標準正規分布)に従う乱数を返す。」とネットに書いてあったのですが、この意味もよくわかりません。試しに下のようにコードを実行して、平均が0になるのかと思ったら0になりませんでした。この文章の意味を教えていただきたいです。\n\n```\n\n tu = np.random.randn(1,100)\n \n tuuu=0\n \n for i in range(100):\n tuuu += tu[0][i]\n print(tuuu/100)\n # 出力0.22453386331188382 ※毎回違う、平均0じゃないじゃんと思いました。\n \n```",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-12T07:44:07.263",
"favorite_count": 0,
"id": "77501",
"last_activity_date": "2021-06-13T20:43:31.010",
"last_edit_date": "2021-06-12T08:51:19.283",
"last_editor_user_id": "19110",
"owner_user_id": "46838",
"post_type": "question",
"score": 1,
"tags": [
"python",
"機械学習",
"ニューラルネットワーク"
],
"title": "なぜ重みの初期値にnp.random.randnを用いるのか?",
"view_count": 516
} | [
{
"body": "#### 重み (Weight) の初期値をなぜ np.random.randn にするのか\n\n[ゼロから作るDeepLearning 6章を学ぶ\n〜重みの初期値について〜](https://www.takapy.work/entry/2018/06/14/221633) の記事が詳しいかも \n勾配がゼロになると学習が進まなくなるので, 勾配損失が起きないような初期値を与えることは大切です\n\n[ニューラルネットワークの学習でしていること](https://www.atmarkit.co.jp/ait/articles/2004/27/news020.html)\nなども参考になるかも?\n\n* * *\n\n#### np.random.randnは「平均0、分散1(標準偏差1)の正規分布(標準正規分布)」\n\nサイコロ振って 5回とも違う目が出て, 6回目は残ってる最後のひとつに決まってる … などということはありません。 \n99回の乱数出たあと, 残りひとつでちょうど平均ゼロになったなら, 「numpy.random さん, 仕事しろ !!」って話になります\n\n```\n\n import matplotlib.pyplot as plt\n import numpy as np\n \n fig, ax = plt.subplots()\n num = []\n mean = []\n std = []\n for cnt in range(1, 1200):\n data = np.random.randn(cnt)\n num.append(cnt)\n mean.append(data.mean())\n std.append(data.std())\n \n ax.scatter(num, mean, label='mean')\n ax.set_xlabel('count')\n ax.set_ylabel('mean')\n ax.legend(loc=4)\n ax2 = ax.twinx()\n ax2.scatter(num, std, color='r', label='std')\n ax2.set_ylabel('std')\n ax2.legend(loc=1)\n \n```\n\n試しに作ってみました。5万とか 10万くらいで, 滑らかに, 平均0、分散1 に **近づいて** いきます\n\n[](https://i.stack.imgur.com/bd8HA.png)",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-12T11:47:19.457",
"id": "77508",
"last_activity_date": "2021-06-12T20:30:46.817",
"last_edit_date": "2021-06-12T20:30:46.817",
"last_editor_user_id": "43025",
"owner_user_id": "43025",
"parent_id": "77501",
"post_type": "answer",
"score": 3
},
{
"body": "[このサイト](https://teratail.com/questions/343724)を見ればわかると思います。teratailで回答をしてくださった方がいます。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T20:43:31.010",
"id": "77535",
"last_activity_date": "2021-06-13T20:43:31.010",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "46838",
"parent_id": "77501",
"post_type": "answer",
"score": -1
}
] | 77501 | null | 77508 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "# 問題\n\nスクレイピングをしていまして、以下のデータから「新宿」を抜き出したいです。\n\n```\n\n <td>1</td>, <td class=\"stationName\"><a href=\"http://www.jreast.co.jp/estation/station/info.aspx?StationCD=866\">新宿</a></td>, <td>355,778</td>, <td>419,608</td>, <td>775,386</td>, <td>△ 1.8</td>,\n \n```\n\nそこで、[こちら](https://www-creators.com/tool/regex-\nchecker?r=\\(%3F%3C%3D\\(%3Ctd%20class%3D%22stationName%22%3E%3Ca%20href%3D%22.*%22%3E\\)\\)\\(.*%3F\\)\\(%3F%3D%3C%2Fa%3E\\))の正規表現チェッカーで作成した正規表現を確認しました。\n\n[](https://i.stack.imgur.com/VXdWp.jpg)\n\nそして、取得できることを確認したあとに以下のコードを実行しました。\n\n```\n\n import re\n data = '<td>1</td>, <td class=\"stationName\"><a href=\"http://www.jreast.co.jp/estation/station/info.aspx?StationCD=866\">新宿</a></td>, <td>355,778</td>, <td>419,608</td>, <td>775,386</td>, <td>△ 1.8</td>'\n \n r = re.findall('(?<=(<td class=\"stationName\"><a href=\".*\">))(.*?)(?=</a>)', data)\n \n```\n\nすると`findall`で以下のようなエラーがでます。\n\n```\n\n ---------------------------------------------------------------------------\n error Traceback (most recent call last)\n <ipython-input-24-a625cd10ed2c> in <module>()\n 1 # station_name_list = []\n ----> 2 r = re.findall('(?<=(<td class=\"stationName\"><a href=\".*\">))(.*?)(?=</a>)', data2[0])\n 3 \n 4 for num in r:\n 5 station_name_list.append(num[1])\n \n 4 frames\n /usr/lib/python3.7/sre_compile.py in _compile(code, pattern, flags)\n 180 lo, hi = av[1].getwidth()\n 181 if lo != hi:\n --> 182 raise error(\"look-behind requires fixed-width pattern\")\n 183 emit(lo) # look behind\n 184 _compile(code, av[1], flags)\n \n error: look-behind requires fixed-width pattern\n \n```\n\n正規表現に慣れておらず、後読みの固定幅の設定が必要なのですが、どのようにすればいいのかわかりませんでした。\n\nわかる方教えていただきたいです。よろしくお願いします。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-12T08:38:59.330",
"favorite_count": 0,
"id": "77502",
"last_activity_date": "2022-09-03T13:05:20.560",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "44467",
"post_type": "question",
"score": -1,
"tags": [
"python",
"正規表現"
],
"title": "正規表現でエラーがでるのですが、後読みの固定幅について教えていただきたいです。",
"view_count": 1030
} | [
{
"body": "先読み後読みする必要がなかったため以下に変更したところ動きました。\n\n```\n\n import re\n data = '<td>1</td>, <td class=\"stationName\"><a href=\"http://www.jreast.co.jp/estation/station/info.aspx?StationCD=866\">新宿</a></td>, <td>355,778</td>, <td>419,608</td>, <td>775,386</td>, <td>△ 1.8</td>'\n \n r = re.findall('<td class=\"stationName\"><a href=\".*?\">(.*?)</a>', page)\n \n # 新宿と表示\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-12T11:57:31.383",
"id": "77510",
"last_activity_date": "2021-06-12T11:57:31.383",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "44467",
"parent_id": "77502",
"post_type": "answer",
"score": 1
}
] | 77502 | null | 77510 |
{
"accepted_answer_id": "77506",
"answer_count": 2,
"body": "以下のようなログデータに対してpandasでセッションIDを付与したいのですがやり方がわかりません。\n\n```\n\n user time \n 0 2020-05-23 00:01:19\n 0 2020-05-23 00:13:32\n 1 2020-05-23 00:13:45\n 0 2020-05-23 12:59:45\n 2 2020-05-23 13:13:13\n 1 2020-05-23 15:13:45\n \n```\n\nuserはユーザを識別するための一意なID、timeはユーザーがアクセスした時間を表します。 \n同じユーザーの6時間以内のアクセスであれば同じセッションIDが割り振られます。 \nユーザーが異なればセッションIDも異なります。\n\nそのため上記の例を補完すると以下のようになります。\n\n```\n\n user time session_id\n 0 2020-05-23 00:01:19 0\n 0 2020-05-23 00:13:32 0\n 1 2020-05-23 00:13:45 1\n 0 2020-05-23 12:59:45 2\n 2 2020-05-23 13:13:13 3\n 1 2020-05-23 15:13:45 4\n \n```\n\n教えていただけますと幸いです。 \nよろしくお願いします。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-12T09:10:22.117",
"favorite_count": 0,
"id": "77503",
"last_activity_date": "2021-06-13T08:21:29.360",
"last_edit_date": "2021-06-12T16:59:44.643",
"last_editor_user_id": "3060",
"owner_user_id": "46840",
"post_type": "question",
"score": 0,
"tags": [
"python",
"pandas"
],
"title": "pandasでログデータに対してセッションIDを付与したい",
"view_count": 343
} | [
{
"body": "一応、[本家の方で解決](https://stackoverflow.com/questions/67948917)となった様ですが、、、\n\nどうも `freq='6H'` という指定に問題がありそうです。\n\n```\n\n import pandas as pd\n \n df = pd.DataFrame({\n 'user': [0, 0, 1, 0, 2, 1],\n 'time': map(pd.Timestamp, [\n '2020-05-23 00:01:19',\n '2020-05-23 00:13:32',\n '2020-05-23 00:13:45',\n '2020-05-23 06:10:45', \n '2020-05-23 13:13:13',\n '2020-05-23 15:13:45',\n ]),\n })\n \n df['session_id'] = (\n df.groupby(['user', pd.Grouper(key='time', freq='6H')], sort=False)\n .ngroup())\n \n print(df)\n \n ## 処理結果\n user time session_id\n 0 0 2020-05-23 00:01:19 0\n 1 0 2020-05-23 00:13:32 0 <== user 0\n 2 1 2020-05-23 00:13:45 1\n 3 0 2020-05-23 06:10:45 2 <== user 0\n 4 2 2020-05-23 13:13:13 3\n 5 1 2020-05-23 15:13:45 4\n \n```\n\n3 行目の session_id が `2` になっています。前回の session は `00:13:32` なので 6 時間以内のはずです。\n\nそれでは「6 時間以内の差」でグループ化してみます。\n\n```\n\n s = df.sort_values(['user', 'time']).groupby('user').time.diff()\\\n .gt(pd.Timedelta('6h')).cumsum().sort_index()\n \n df['session_id'] = df.groupby(['user', s], sort=False).ngroup()\n \n print(df)\n \n ## 処理結果\n user time session_id\n 0 0 2020-05-23 00:01:19 0\n 1 0 2020-05-23 00:13:32 0 <== user 0\n 2 1 2020-05-23 00:13:45 1\n 3 0 2020-05-23 06:10:45 0 <== user 0\n 4 2 2020-05-23 13:13:13 2\n 5 1 2020-05-23 15:13:45 3\n \n```\n\nこちらでは 3 行目の session_id が `0` になります。\n\nつまり、`freq='6H'` は一日を `00:00〜06:00`, `06:00〜12:00`, `12:00〜18:00`,\n`18:00〜24:00` で区切ってグループ化するという事なのでした。\n\nなお、この処理方法は以下を参考に(というかコピペ)しました。\n\n[How to assign a unique ID for different groups in pandas\ndataframe?](https://stackoverflow.com/questions/56978362)",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-12T11:35:14.100",
"id": "77506",
"last_activity_date": "2021-06-13T08:21:29.360",
"last_edit_date": "2021-06-13T08:21:29.360",
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77503",
"post_type": "answer",
"score": 0
},
{
"body": "コメントで確認したのは、以下のような処理を考えていたためです。 \n最初に`user`を主キー、`time`を副キーとしてソートしておき、あとはループで順次直前の行と比較して`session_id`を埋めていく方法です。 \n最後は`time`でソートし直します。`session_id`は質問例のような時刻順にはなっていません。\n\n```\n\n # 初期化処理は metropolis さん回答からコピー\n import pandas as pd\n \n df = pd.DataFrame({\n 'user': [0, 0, 1, 0, 2, 1],\n 'time': map(pd.Timestamp, [\n '2020-05-23 00:01:19',\n '2020-05-23 00:13:32',\n '2020-05-23 00:13:45',\n '2020-05-23 12:59:45',\n '2020-05-23 13:13:13',\n '2020-05-23 15:13:45',\n ]),\n })\n \n df = df.sort_values(['user','time'],ascending=[True,True]) # userを主キー、timeを副キーでソート\n df['session_id'] = None # session_id列追加\n id_index = list(df.columns.values).index('session_id') # session_idの列番号取得\n \n session_timeout = 6 * 60 * 60 # 6時間の秒数\n session_id = 0 # session_id初期値\n \n df.iat[0, id_index] = session_id\n prev = df.iloc[0]\n for i in range(1,len(df)):\n curr = df.iloc[i]\n # userが変わるか、前回より6時間経過していたら新しいsession_id\n if prev.user != curr.user or (curr.time - prev.time).total_seconds() > session_timeout:\n session_id += 1\n df.iat[i, id_index] = session_id # session_id設定\n prev = curr\n \n df = df.sort_values('time',ascending=True).reset_index(drop=True) # timeでソート、indexも振り直し\n print(df)\n \n # 以下が実行結果\n user time session_id\n 0 0 2020-05-23 00:01:19 0\n 1 0 2020-05-23 00:13:32 0\n 2 1 2020-05-23 00:13:45 2\n 3 0 2020-05-23 12:59:45 1\n 4 2 2020-05-23 13:13:13 4\n 5 1 2020-05-23 15:13:45 3\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-12T15:43:33.430",
"id": "77511",
"last_activity_date": "2021-06-12T15:43:33.430",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "26370",
"parent_id": "77503",
"post_type": "answer",
"score": 1
}
] | 77503 | 77506 | 77511 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "環境 \nlinux(ubuntu) \nroswell上のemacs上のslime (SBCL)\n\n和書ではデバッガーの使い方がほとんど書いていないかマイナー処理系をつかっていて、英語ページもどこをみたらよいのか。(slime公式を見てもいまいちわからず。)\n\n詳しい解説のあるWEBや書籍はありませんでしょうか。 \nslimeではなくても、CLISPやSBCLのデバッガーの使い方など、参考になるものであれば、歓迎です。\n\n一応自己レスですが、\n\n<https://malisper.me/category/debugging-common-lisp/> \nここは良さそうだと思いました。\n\n書籍ではCommon Lisp Recipesという本に、参考になる章立てがありました。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-12T09:19:08.583",
"favorite_count": 0,
"id": "77504",
"last_activity_date": "2022-06-11T06:36:49.480",
"last_edit_date": "2021-06-13T01:49:14.530",
"last_editor_user_id": "40961",
"owner_user_id": "40961",
"post_type": "question",
"score": 1,
"tags": [
"common-lisp"
],
"title": "common lispのデバッガーの使い方を教えて下さい。",
"view_count": 245
} | [
{
"body": "既に参考文献のなかに挙げられていますが、Debugging Lispには邦訳があり、対話的/非対話的な使い方の双方が解説されています。 \n日常的に使う範囲はほぼ網羅されていると思いますので、かなり有用かと思います。 \n<https://glider-gun.github.io/blog/2015/12/19/debugging-lisp-part-1-zai-\nkonpairu/>\n\nまた、Common\nLispにおいてデバッガはコンディションシステムを構成するツールの一つという位置付けですが、コンディションシステムをテーマにした書籍も出版されています。\n\n * [The Common Lisp Condition System - Beyond Exception Handling with Control Flow Mechanisms](https://link.springer.com/book/10.1007/978-1-4842-6134-7)\n\nただし個人的な感想ですが、こちらの書籍はLisp系書籍にありがちな「作って学ぶ」系の解説がベースのため具体的なツールの使い方の解説という感じではなく、コンディションシステムという概念を学ぶ方向の書籍かと思いました。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2022-06-11T06:36:49.480",
"id": "89329",
"last_activity_date": "2022-06-11T06:36:49.480",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "3510",
"parent_id": "77504",
"post_type": "answer",
"score": 1
}
] | 77504 | null | 89329 |
{
"accepted_answer_id": "77507",
"answer_count": 1,
"body": "おそらくPython関係のドキュメントの読み方がわかっていないせいかと思うのですが、 \n<https://seaborn.pydata.org/generated/seaborn.histplot.html> \nの\n\n引用:\n\n```\n\n seaborn.histplot(data=None, *, x=None, y=None, hue=None, weights=None, stat='count', bins='auto', binwidth=None, binrange=None, discrete=None, cumulative=False, common_bins=True, common_norm=True, multiple='layer', element='bars', fill=True, shrink=1, kde=False, kde_kws=None, line_kws=None, thresh=0, pthresh=None, pmax=None, cbar=False, cbar_ax=None, cbar_kws=None, palette=None, hue_order=None, hue_norm=None, color=None, log_scale=None, legend=True, ax=None, **kwargs)\n \n```\n\nの部分と実際の挙動と照らし合わせてわからないところがあります。\n\nネットの記事や他言語での勘で、思いつきで引数にデータを渡すとそれっぽく動くのですが、理解したいことがあります。\n\n```\n\n import matplotlib.pyplot as plt\n import matplotlib.ticker as ticker\n import seaborn as sns\n \n ax = sns.histplot([\n 5060,5000, 4400, 4001,2500, 1100, 1000, 900, 800\n ], kde=False, binwidth=500, binrange=(0,5500))\n ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n \n```\n\nを実行すると\n\n[](https://i.stack.imgur.com/168Wh.png)\n\nとなります。\n\n【質問1】 \n第1引数に渡した配列\n\n```\n\n [\n 5060,5000, 4400, 4001,2500, 1100, 1000, 900, 800\n ]\n \n```\n\nは、histplotのどの引数に渡したことになるんでしょう?(`data=`のところ?, `*`のところ?, `x=`のところ?、それ以外?)\n\n【質問2】 \n縦軸の`Count`はなぜ表示されたんでしょう? \n自動集計されているような旨はドキュメントのどこかに記載されているのでしょうか? \nそれとも、それくらいは分析する人ならわかっているだろうということで説明が省略されていたりするのでしょうか?",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-12T10:57:49.017",
"favorite_count": 0,
"id": "77505",
"last_activity_date": "2021-06-12T14:38:57.817",
"last_edit_date": "2021-06-12T14:38:57.817",
"last_editor_user_id": "9008",
"owner_user_id": "9008",
"post_type": "question",
"score": 0,
"tags": [
"python",
"matplotlib",
"seaborn"
],
"title": "seabornのドキュメントの読み方がわからない",
"view_count": 138
} | [
{
"body": "【回答1】\n\n`data=`のところです。\n\n> seaborn.histplot(data=None, *, x=None, y=None, hue=None, weights=None,\n> stat='count', bins='auto', binwidth=None, binrange=None, discrete=None,\n> cumulative=False, common_bins=True, common_norm=True, multiple='layer',\n> element='bars', fill=True, shrink=1, kde=False, kde_kws=None, line_kws=None,\n> thresh=0, pthresh=None, pmax=None, cbar=False, cbar_ax=None, cbar_kws=None,\n> palette=None, hue_order=None, hue_norm=None, color=None, log_scale=None,\n> legend=True, ax=None, **kwargs)\n\n2つ目パラメータ`*`は以後のパラメータがキーワードを付けて指定する必要があることを示すものです。\n\n[4.7.3.1.\n位置またはキーワード引数](https://docs.python.org/ja/3/tutorial/controlflow.html#positional-\nor-keyword-arguments)\n\n> 関数定義に `/` も `*` もない場合は、引数は位置またはキーワードで関数に渡されます。\n\n[4.7.3.2.\n位置専用引数](https://docs.python.org/ja/3/tutorial/controlflow.html#positional-\nonly-parameters)\n\n> これをもう少し詳しく見てみると、特定の引数を 位置専用 と印を付けられます。 位置専用 の場合、引数の順序が重要であり、キーワードで引数を渡せません。\n> 位置専用引数は `/` (スラッシュ)の前に配置されます。 `/` は、位置専用引数を残りの引数から論理的に分離するために使用されます。 関数定義に\n> `/` がない場合、位置専用引数はありません。\n\n[4.7.3.3.\nキーワード専用引数](https://docs.python.org/ja/3/tutorial/controlflow.html#keyword-\nonly-arguments)\n\n> 引数をキーワード引数で渡す必要があることを示す キーワード専用 として引数をマークするには、引数リストの最初の キーワード専用 引数の直前に `*`\n> を配置します。\n\nキーワードを付けなくて良いパラメータは`data`だけです。\n\n* * *\n\n【回答2】\n\n説明の最初の2つの文に記述されている内容でしょう。\n\n> Plot univariate or bivariate histograms to show distributions of datasets. \n> データセットの分布を示すために、単変量または二変量のヒストグラムをプロットします。\n>\n> A histogram is a classic visualization tool that represents the distribution\n> of one or more variables by counting the number of observations that fall\n> within disrete bins. \n> ヒストグラムは、個別のビンに含まれる観測値の数をカウントすることにより、1つ以上の変数の分布を表す古典的な視覚化ツールです。\n\nつまり、0から5500まで(5500を含まず)の500毎に、指定された数値をカウントし、その数をグラフに表したということになります。\n\n```\n\n 500 - 999 : 800, 900 : 2個\n 1000 - 1499 : 1000, 1100 : 2個\n 2500 - 2999 : 2500 : 1個\n 4000 - 4499 : 4001, 4400 : 2個\n 5000 - 5499 : 5000, 5060 : 2個\n 他は0個\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-12T11:45:17.423",
"id": "77507",
"last_activity_date": "2021-06-12T12:58:16.003",
"last_edit_date": "2021-06-12T12:58:16.003",
"last_editor_user_id": "26370",
"owner_user_id": "26370",
"parent_id": "77505",
"post_type": "answer",
"score": 2
}
] | 77505 | 77507 | 77507 |
{
"accepted_answer_id": "77515",
"answer_count": 1,
"body": "まず、`pandas`は関係なく`matplotlib`にシンプルにデータを渡す書き方だと下記になると思います。\n\n該当ドキュメントはおそらくこちら \n<https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html>\n\n書いてみたコード:\n\n```\n\n import matplotlib.pyplot as plt\n import pandas as pd\n \n df = pd.DataFrame({\n 'name': ['A', 'B', 'C', 'D', 'E'],\n 'value': [10000, 5000, 1000, 500, 100]\n })\n \n plt.bar(df['name'], df['value'])\n \n```\n\n上記ドキュメントに、\n\n```\n\n x: float or array-like\n The x coordinates of the bars. See also align for the alignment of the bars to the coordinates.\n \n height: float or array-like\n The height(s) of the bars.\n \n```\n\nとあるので、`x`に`array-like`なもの、`height`にも`array-like`なものを渡したという認識です。\n\nさて、`pandas`には`plot`メソッド(?)が生えているようで、下記のようにも書けます。\n\n```\n\n import matplotlib.pyplot as plt\n import pandas as pd\n \n df = pd.DataFrame({\n 'name': ['A', 'B', 'C', 'D', 'E'],\n 'value': [10000, 5000, 1000, 500, 100]\n })\n \n df.plot.bar(x='name')\n \n```\n\nおそらくこれに関するドキュメントは、 \n<https://pandas.pydata.org/pandas-\ndocs/stable/reference/api/pandas.DataFrame.plot.html> \nだと思うのですが、デフォルトで`matplotlib`を使っていることと`Parameters`の記載はあるように思うのですが、インスタンス変数にあたる`df`の状態に応じて振る舞いが変わることには言及がないように思います(Pythonの詳しい文法はあまり理解していないので間違えているかも?)。\n\n本来`matplotlib`を使うのであれば、引数に`x`と`height`を渡す必要があるが、それが`df`から自明に決められているように思います。\n\nこれらの振る舞いについて記載されているところはありますか?(ないのであれば、どのように振る舞うと知られているのでしょうか?ドキュメントにはソースコードへのリンクがありますが、ソースコードを読んで理解するのでしょうか?)",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T01:01:21.380",
"favorite_count": 0,
"id": "77512",
"last_activity_date": "2021-06-13T02:58:01.980",
"last_edit_date": "2021-06-13T01:31:42.390",
"last_editor_user_id": "9008",
"owner_user_id": "9008",
"post_type": "question",
"score": 0,
"tags": [
"python",
"pandas",
"matplotlib"
],
"title": "pandasオブジェクトとmatplotlibの関係がわからない",
"view_count": 213
} | [
{
"body": "より明確なのはこちらのページでしょう。 \n以下の`####`で訳した部分が該当すると思われます。 \n[pandas.DataFrame.plot.bar](https://pandas.pydata.org/pandas-\ndocs/stable/reference/api/pandas.DataFrame.plot.bar.html)\n\n>\n```\n\n> DataFrame.plot.bar(x=None, y=None, **kwargs) [source]\n> Vertical bar plot.\n> \n> A bar plot is a plot that presents categorical data with rectangular\n> bars with lengths proportional to the values that they represent. A bar plot\n> shows comparisons among discrete categories. One axis of the plot shows the\n> specific categories being compared, and the other axis represents a measured\n> value.\n> #### プロットの一方の軸は比較されている特定のカテゴリを示し、もう一方の軸は測定値を表します。\n> \n> Parameters:\n> x : label or position, optional\n> Allows plotting of one column versus another. If not specified,\n> the index of the DataFrame is used.\n> #### 指定しない場合、DataFrameのインデックスが使用されます。\n> \n> y : label or position, optional\n> Allows plotting of one column versus another. If not specified,\n> all numerical columns are used.\n> #### 指定しない場合、すべての数値列が使用されます。\n> \n```\n\nそのページの下の方に色々と例が示されています。\n\n> Plot a whole dataframe to a bar plot. Each column is assigned a distinct\n> color, and each row is nested in a group along the horizontal axis. \n> データフレーム全体を棒グラフにプロットします。各列には異なる色が割り当てられ、各行は横軸に沿ってグループにネストされます。\n>\n> Plot only selected categories for the DataFrame. \n> DataFrameの選択されたカテゴリのみをプロットします。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T02:58:01.980",
"id": "77515",
"last_activity_date": "2021-06-13T02:58:01.980",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "26370",
"parent_id": "77512",
"post_type": "answer",
"score": 1
}
] | 77512 | 77515 | 77515 |
{
"accepted_answer_id": "77518",
"answer_count": 1,
"body": "以前に\n[累積比率(線グラフを棒グラフに重ねる方法がわかりません](https://ja.stackoverflow.com/questions/77465/%E7%B4%AF%E7%A9%8D%E6%AF%94%E7%8E%87-%E7%B7%9A%E3%82%B0%E3%83%A9%E3%83%95-%E3%82%92%E6%A3%92%E3%82%B0%E3%83%A9%E3%83%95%E3%81%AB%E9%87%8D%E3%81%AD%E3%82%8B%E6%96%B9%E6%B3%95%E3%81%8C%E3%82%8F%E3%81%8B%E3%82%8A%E3%81%BE%E3%81%9B%E3%82%93)\nの質問をしました。\n\nこちら重ねることはできましたが、右側の縦軸が`0.6`あたりから始まります。 \n右側の縦軸を`0`から始めると、ひとつめのデータが多くの割合を占めていることがよりわかると思うのですが、どうすれば`0`から始められますか?\n\n上記質問、[回答](https://ja.stackoverflow.com/a/77467/9008)から本質問に必要そうな最低限のコードを下記に書きます。\n\n```\n\n import matplotlib.pyplot as plt\n import matplotlib.ticker as ticker\n import pandas as pd\n import seaborn as sns\n \n df = pd.DataFrame({\n 'name': ['A', 'B', 'C', 'D', 'E'],\n 'value': [10000, 5000, 1000, 500, 100]\n })\n \n # set graph style\n sns.set_style(sns.axes_style(style='darkgrid'))\n sns.set_palette('muted')\n sns.set_color_codes('dark')\n \n # set accumulative ratio\n df['accumulative_ratio'] = df['value'].cumsum() / df['value'].sum()\n \n # plotting\n ax_val = df['value'].plot.bar()\n ax_acc = df['accumulative_ratio'].plot.line(\n ls='--', marker='o', color='red', secondary_y=True, label='acc. ratio')\n \n # value axes attributes\n ax_val.set_xlabel('Group')\n ax_val.set_ylabel('Value')\n ax_val.set_xticklabels(df.name)\n ax_val.grid(True)\n \n # accumulative ratio axes attributes\n ax_acc.set_ylabel('Accumulative ratio')\n ax_acc.yaxis.set_major_locator(ticker.MultipleLocator(0.1))\n ax_acc.grid(False)\n \n # show\n plt.show()\n \n```\n\n[](https://i.stack.imgur.com/xyW6B.png)",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T01:48:06.117",
"favorite_count": 0,
"id": "77513",
"last_activity_date": "2021-06-13T03:18:37.597",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "9008",
"post_type": "question",
"score": -1,
"tags": [
"python",
"pandas",
"seaborn"
],
"title": "右側縦軸を0から表示するにはどうしたらよいのでしょうか?",
"view_count": 779
} | [
{
"body": "以下の`Axes.set_ylim(bottom, top)`が使えるでしょう。 \n[6.3. 軸の最小値・最大値の設定 -\nmatplotlibのめっちゃまとめ](https://qiita.com/nkay/items/d1eb91e33b9d6469ef51#63-%E8%BB%B8%E3%81%AE%E6%9C%80%E5%B0%8F%E5%80%A4%E6%9C%80%E5%A4%A7%E5%80%A4%E3%81%AE%E8%A8%AD%E5%AE%9A)\n\nこんな風にすれば出来ます。\n\n```\n\n # accumulative ratio axes attributes\n ax_acc.set_ylabel('Accumulative ratio')\n ax_acc.set_ylim(0.0, 1.05) #### ←これを追加する ####\n ax_acc.yaxis.set_major_locator(ticker.MultipleLocator(0.1))\n ax_acc.grid(False)\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T03:18:37.597",
"id": "77518",
"last_activity_date": "2021-06-13T03:18:37.597",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "26370",
"parent_id": "77513",
"post_type": "answer",
"score": 1
}
] | 77513 | 77518 | 77518 |
{
"accepted_answer_id": null,
"answer_count": 2,
"body": "## わからないこと\n\nRailsでローカルサーバーを立ち上げたときに`http://fogefoge.localhost.local:3200/~`へアクセスして、開発を行っていますが、urlの中に含まれる`.local`の部分を削除するとエラーになります。\n\nhostsファイルの中で下記のように定義することで、IPアドレスと紐付けているということはわかりますが、末に`.local`をつけなければならない理由が分かりません。\n\n```\n\n (/etc/hosts)\n 127.0.0.1 fogefoge.localhost.local\n \n```\n\n下記のように`.local`を除外してhostsファイルを編集後にサーバー立ち上げて、`http://fogefoge.localhost:3200/~`へアクセスしてもRouting\nErrorになってしまいます。\n\n```\n\n (/etc/hosts)\n 127.0.0.1 fogefoge.localhost\n \n```\n\n何か分かるかたいらっしゃいましたら、教えていただけると助かります。 \nよろしくお願いします。",
"comment_count": 5,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T02:47:23.187",
"favorite_count": 0,
"id": "77514",
"last_activity_date": "2021-06-14T14:54:51.913",
"last_edit_date": "2021-06-14T14:54:51.913",
"last_editor_user_id": "43337",
"owner_user_id": "43337",
"post_type": "question",
"score": 1,
"tags": [
"ruby-on-rails",
"hosts"
],
"title": "hostsファイルのlocalhost.localの末につくlocalとは何か",
"view_count": 487
} | [
{
"body": "たんにローカル用のネットワーク(アドレス)、という意味合いかと",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T08:37:55.227",
"id": "77547",
"last_activity_date": "2021-06-14T08:37:55.227",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "27481",
"parent_id": "77514",
"post_type": "answer",
"score": -1
},
{
"body": "詳しくないので端折りますが\n\n`.local` というのは TLD(top-level domain) です。ドメイン名の一部を取り除くなら先頭側の方かも。\n\n* * *\n\nPDF (2016年12月1日)\n[IETF事情(DNS関係)](https://www.nic.ad.jp/ja/materials/iw/2016/proceedings/d3/d3-2-fujiwara.pdf)\nによると\n\n> Multicast DNS (.local)の標準化は dnsextでは好まれなかった \n> • A社のプロトコル\n>\n> dnsext, dnsopとは無関係に標準化 \n> • IETF Last Callなども通過 \n> • だれも文句をつけなかった(気付かなかった?) \n> • サブマリンRFC?\n>\n> RFC 6762 Multicast DNSで.local予約 \n> • 「A社はタダで.local を手にいれた」という声\n\n参考:\n\n * wikipedia.org (英語) [.local](https://en.wikipedia.org/wiki/.local)\n * ja.wikipedia.org [マルチキャストDNS](https://ja.wikipedia.org/wiki/%E3%83%9E%E3%83%AB%E3%83%81%E3%82%AD%E3%83%A3%E3%82%B9%E3%83%88DNS)\n * RFC 6762 について [RFC 6762 - Multicast DNS 日本語訳](https://tex2e.github.io/rfc-translater/html/rfc6762.html)",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T10:08:25.590",
"id": "77552",
"last_activity_date": "2021-06-14T10:08:25.590",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "43025",
"parent_id": "77514",
"post_type": "answer",
"score": -1
}
] | 77514 | null | 77547 |
{
"accepted_answer_id": "77520",
"answer_count": 1,
"body": "AWSのドキュメントで見たような覚えがあるのですが、IPアドレスだけを教えてくれるシンプルなWebサイトってありませんでしたっけ?\n\n<https://checkip.org> などの超シンプル版で、本当にHTMLの中にIPアドレスしか入っていないサイトです。\n\n検索しようにも類似サイトか関係ないAWSドキュメントしか出てこず、弱っております。 \nURLをお持ちの方、教えていただけないでしょうか?\n\nまたは、類似サイトでも結構です(信頼できる運営元による、HTTPの問い合わせでこちらのIP「だけ」を教えてくれるサイト)(https://ipinfo.io\nなどはIP以外の情報が多いので除外)",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T03:23:10.280",
"favorite_count": 0,
"id": "77519",
"last_activity_date": "2021-06-13T04:20:13.400",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "26110",
"post_type": "question",
"score": 2,
"tags": [
"aws",
"network"
],
"title": "AWSがホスティングしている、シンプルにIPアドレスだけを教えてくれるWebサイトのURLってなんでしたっけ?",
"view_count": 222
} | [
{
"body": "<https://checkip.amazonaws.com/>\n\nでは、ないでしょうか。\n\n<https://docs.aws.amazon.com/ja_jp/batch/latest/userguide/get-set-up-for-aws-\nbatch.html>\n\nに説明が掲載されているようです。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T04:20:13.400",
"id": "77520",
"last_activity_date": "2021-06-13T04:20:13.400",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "46847",
"parent_id": "77519",
"post_type": "answer",
"score": 4
}
] | 77519 | 77520 | 77520 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "私は現在、PyQt5を用いて自作のブラウザを作成しています。 \nその過程で何個か(例えばPrivateBrowsingなど)のQWebSettingsを使用する必要性が出てきました。 \nそして、私はインターネットで調べた結果を何個か試してみましたがそれはどれもうまくいきませんでした。\n\n```\n\n from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings\n \n self.webEngineView = QtWebEngineWidgets.QWebEngineView(self.centralwidget)\n self.webEngineView.page().settings().WebAttribute(QWebSettings.DeveloperExtrasEnabled, True)\n \n```\n\nが私が最後に試したコードです。ですがこのコードはQWebSettingsが存在しないと言われエラーが出てしまいました。\n\n私は一通り、考えてみましたがどれもうまくいきませんでした\n\nどうしたら私はQWebSettingsを使うことが出来ますか?",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T07:16:21.010",
"favorite_count": 0,
"id": "77521",
"last_activity_date": "2021-06-13T12:58:34.603",
"last_edit_date": "2021-06-13T10:40:39.777",
"last_editor_user_id": "3060",
"owner_user_id": "46849",
"post_type": "question",
"score": 0,
"tags": [
"python",
"python3",
"pyqt5",
"pyqt",
"browser"
],
"title": "PyQt5 でPrivateBrowsingを有効化したい",
"view_count": 156
} | [
{
"body": "PyQt5の5.15であれば、`PyQtWebEngine`パッケージをインストールするのはいかがでしょうか? \n(コマンドラインは以下の通り)\n\n```\n\n pip install PyQtWebEngine\n \n```\n\n参考: <https://pypi.org/project/PyQtWebEngine/>",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T12:58:34.603",
"id": "77528",
"last_activity_date": "2021-06-13T12:58:34.603",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "20098",
"parent_id": "77521",
"post_type": "answer",
"score": 0
}
] | 77521 | null | 77528 |
{
"accepted_answer_id": "77524",
"answer_count": 2,
"body": "# 概要\n\nパッケージ内でファイルをimportする実験のため、 \n下記の構成にて`m.py`を実行すると、エラー `cannot import name 'xxx' from partially initialized\nmodule`が発生しました。\n\nしかし`__init__.py`の行の順番を入れ替えるとエラーが消滅し、正常に動作します。\n\n## ファイル内容\n\n### __init__.py\n\n```\n\n from tsmod.m import ModuleM\n from tsmod.p import ModuleP\n \n```\n\n### m.py\n\n```\n\n from tsmod import ModuleP\n \n \n class ModuleM:\n pass\n \n```\n\n### p.py\n\n```\n\n class ModuleP:\n pass\n \n```\n\n## ディレクトリ構成\n\n```\n\n tsmod\n L __init__.py\n L m.py\n L p.py\n \n```\n\n# 実行条件\n\n## 実行環境\n\nOS: Ubuntu 20.04.2 LTS \nPythonバージョン: 3.8.5\n\nPyCharm2021.1.2にて実行 \n[](https://i.stack.imgur.com/SSBDl.png)\n\n## コマンド\n\n```\n\n /usr/bin/python3.8 /home/USER/XXX/XXXX/tsmod/m.py\n \n```\n\n## エラー内容\n\n```\n\n Traceback (most recent call last):\n File \"/home/USER/XXX/XXXX/tsmod/m.py\", line 1, in <module>\n from tsmod import ModuleP\n File \"/home/USER/XXX/XXXX/tsmod/__init__.py\", line 1, in <module>\n from tsmod.m import ModuleM\n File \"/home/USER/XXX/XXXX/tsmod/m.py\", line 1, in <module>\n from tsmod import ModuleP\n ImportError: cannot import name 'ModuleP' from partially initialized module 'tsmod' (most likely due to a circular import) (/home/USER/XXX/XXXX/tsmod/__init__.py)\n \n Process finished with exit code 1\n \n```\n\n## __init__.py (正常動作版)\n\n1行目と2行目を入れ替え。\n\n```\n\n from tsmod.p import ModuleP\n from tsmod.m import ModuleM\n \n```\n\n# 疑問\n\n 1. なぜエラーが発生しているのか?\n 2. なぜ`__init__.py`の順番を入れ替えることでエラーが消滅するのか?\n\n# 補足\n\npycharm上でなくターミナルにて`m.py`を実行した場合、ModuleNotFoundErrorが出ました。\n\n## コマンド\n\n```\n\n /usr/bin/python3.8 /home/USER/XXX/XXXX/tsmod/m.py\n \n```\n\n## エラー内容\n\n```\n\n Traceback (most recent call last):\n File \"/home/USER/XXX/XXXX/tsmod/m.py\", line 1, in <module>\n from tsmod import ModuleP\n ModuleNotFoundError: No module named 'tsmod'\n \n```",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T09:36:59.473",
"favorite_count": 0,
"id": "77522",
"last_activity_date": "2021-06-13T14:41:30.973",
"last_edit_date": "2021-06-13T11:59:56.133",
"last_editor_user_id": "9616",
"owner_user_id": "9616",
"post_type": "question",
"score": 0,
"tags": [
"python"
],
"title": "cannot import name 'xxx' from partially initialized moduleの発生条件",
"view_count": 9782
} | [
{
"body": "たぶん `m.py` 部分かも? (以下のように修正すれば OK)\n\n```\n\n from tsmod import ModuleP\n \n```\n\n```\n\n from tsmod.p import ModuleP\n \n```\n\n行の入れ替え前でも, 入れ替え後でも, 同様にエラーになりそうに思えるけど, \nPythonでは, 実際にモジュールを必要とするまで loadを遅延する機能があり, \n先に `ModuleP` を読み込んだあとでの, `m.py`内の `import`は保留されたのかもしれない? \n(動作の詳細は分かりません)\n\n* * *\n\n(VS Code の Python拡張では, このような `import` 指定ミスは警告?が出ます) \n(その様な機能を持つ エディターか開発環境を活用し, 問題特定に繋げると便利です)",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T10:54:30.350",
"id": "77523",
"last_activity_date": "2021-06-13T12:12:36.607",
"last_edit_date": "2021-06-13T12:12:36.607",
"last_editor_user_id": "43025",
"owner_user_id": "43025",
"parent_id": "77522",
"post_type": "answer",
"score": 0
},
{
"body": "**1\\. なぜエラーが発生しているのか?**\n\n状況とエラーメッセージ内容を見ると、メッセージに書いてある通り`circular import`が発生しているためでしょう。\n\n```\n\n ImportError: cannot import name 'ModuleP' from partially initialized module 'tsmod' (most likely due to a circular import) (/home/USER/XXX/XXXX/tsmod/__init__.py)\n \n```\n\ncannot import name 'ModuleP' from partially initialized module 'tsmod' \n→部分的に初期化されたモジュール「tsmod」から名前「ModuleP」をインポートできません。\n\n* * *\n\n(Ubuntu上の?)PyCharmでモジュール内のあるスクリプトを実行すると、モジュールをインポートしたように見えるのは謎ですが、エラーのスタックトレースを見る限り以下のような状況でしょう。\n\n 1. `m.py`の1行目の`from tsmod import ModuleP`が処理される\n 2. `tsmod`モジュールの`__init__.py`の1行目の`from tsmod.m import ModuleM`が処理される\n 3. この時点で`tsmod`モジュールの情報が(おそらくモジュール名だけ)部分的にPythonに登録される\n 4. `m.py`の1行目の`from tsmod import ModuleP`が処理される\n 5. Pythonに登録された部分的な`tsmod`モジュール情報内に`ModuleP`が存在しないのでエラーになる\n\n* * *\n\n**2\\. なぜ`__init__.py`の順番を入れ替えることでエラーが消滅するのか?**\n\n`__init__.py`内の行を逆にすると、以下のように動作すると思われます。\n\n 1. `m.py`の1行目の`from tsmod import ModuleP`が処理される\n 2. `tsmod`モジュールの`__init__.py`の1行目の`from tsmod.p import ModuleP`が処理される\n 3. `p.py`の`ModuleP`が処理され、`tsmod`モジュールに登録される\n 4. `tsmod`モジュールの`__init__.py`の2行目の`from tsmod.m import ModuleM`が処理される\n 5. `m.py`の1行目の`from tsmod import ModuleP`が処理される\n 6. `tsmod`モジュールには既に`ModuleP`が登録されているので、正常にインポートされる\n 7. `m.py`の`ModuleM`が処理され、`tsmod`モジュールに登録される\n 8. この時点で`tsmod`モジュールの情報が完全にPythonに登録される==`__init__.py`の処理が終了する\n 9. `m.py`の`ModuleM`が処理され、`tsmod`モジュールに登録される???(どうなっているかは不明)\n\n* * *\n\nそしておそらく @oriri さん回答のように`from tsmod.p import\nModuleP`とした場合は、以下のようにPython上に登録された情報ではなく`p.py`ファイルを直接見に行くのでしょう。\n\n 1. `m.py`の1行目の`from tsmod.p import ModuleP`が処理される\n 2. `tsmod`フォルダ?の`p.py`が読み込まれて`ModuleP`が処理・登録される\n 3. `m.py`の`ModuleM`が処理・登録される\n\n* * *\n\n例えば`__init__.py`を含む各ファイルの各行の前後・間に`print('何か挿入箇所の位置情報')`を挿入してどの順番で実行されているかを調べると、状況が分かると思われます。\n\n* * *\n\nこちらの記事等を参考に`circular import`となるような設計は見直した方が良いでしょう。 \n[python import動作](https://ja.stackoverflow.com/q/73880/26370)",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T11:07:03.407",
"id": "77524",
"last_activity_date": "2021-06-13T14:41:30.973",
"last_edit_date": "2021-06-13T14:41:30.973",
"last_editor_user_id": "26370",
"owner_user_id": "26370",
"parent_id": "77522",
"post_type": "answer",
"score": 1
}
] | 77522 | 77524 | 77524 |
{
"accepted_answer_id": "77526",
"answer_count": 1,
"body": "VBで書いていたコードをC#に移植しています.VBで動いていた配列の拡張関数がC#ではエラーになってしまいます.解決方法わかりましたらご教示ください.(ちなみにずっとVB頭で、C#はほとんどやっておりません)\n\n※ コード長くなっちゃうんで諸処省いております.ご了解ください.\n\n## VBでの拡張関数の定義 (動いておりました)\n\n```\n\n Imports System.Runtime.CompilerServices\n \n ''' <summary>\n ''' Extend two dimensional array function: get IEnumerble or list of column/row \n ''' </summary>\n Public Module ArrayEx\n ''' <summary>\n ''' Apply row/column filtering to source array row and get the result as new array.\n ''' </summary>\n ''' <typeparam name=\"T\"></typeparam>\n ''' <param name=\"srcArray\"></param>\n ''' <param name=\"rowSelectFunc\"></param>\n ''' <returns></returns>\n <Extension()>\n Public Function GetFilteredArray(Of T)(ByVal srcArray As T(,), rowSelectFunc As Func(Of IEnumerable(Of T), Boolean), columnSelectFunc As Func(Of IEnumerable(Of T), Boolean)) As T(,)\n If IsNothing(srcArray) Then\n Throw New ArgumentNullException(\"Two dimensional array: T(,) is null.\")\n End If\n If IsNothing(rowSelectFunc) Then\n Throw New ArgumentNullException(\"rowSelectFunc as Func(Of IEnumerable(Of T), Boolean) is null.\")\n End If\n If IsNothing(columnSelectFunc) Then\n Throw New ArgumentNullException(\"columnSelectFunc as Func(Of IEnumerable(Of T), Boolean) is null.\")\n End If\n Dim columnIndex As Integer() = srcArray.GetColumnIndex(columnSelectFunc)\n Dim filteredRows As IEnumerable(Of IEnumerable(Of T)) = srcArray.GetRows(rowSelectFunc, columnIndex)\n Dim filteredArray As Array = filteredRows.ToArray\n Return filteredArray\n End Function\n \n End Module\n \n \n```\n\n## VBでの拡張関数の呼び出し(動いておりました)\n\n```\n\n ' Make original title/data array from Excel range object\n Dim rangeArray As Array = Array.CreateInstance(GetType(ATLCellInfo), mRowCount, mColumnCount)\n ' ... 配列の内容を設定\n ' Remove empty rows and columns\n Dim filteredArray As ATLCellInfo(,) = DirectCast(rangeArray, ATLCellInfo(,)).GetFilteredArray(Function(row As IEnumerable(Of ATLCellInfo))\n Return row.OneOrMore(Function(cell As ATLCellInfo)\n Return cell.HasValue\n End Function)\n End Function,\n Function(column As IEnumerable(Of ATLCellInfo))\n Return column.First.HasValue\n End Function)\n \n```\n\n## 移植したC#の拡張関数\n\n```\n\n namespace ArrayExNs\n {\n /// <summary>\n /// ''' Extend two dimensional array function: get IEnumerble or list of column/row \n /// ''' </summary>\n public static class ArrayEx\n {\n /// <summary>\n /// Apply row/column filtering to source array row and get the result as new array.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"srcArray\"></param>\n /// <param name=\"rowSelectFunc\"></param>\n /// <param name=\"columnSelectFunc\"></param>\n /// <returns></returns>\n public static T[,] GetFilteredArray<T>(this T[,] srcArray, Func<IEnumerable<T>, bool> rowSelectFunc, Func<IEnumerable<T>, bool> columnSelectFunc)\n {\n if (srcArray == null)\n throw new ArgumentNullException(\"Two dimensional array: T(,) is null.\");\n if (rowSelectFunc == null)\n throw new ArgumentNullException(\"rowSelectFunc as Func(Of IEnumerable(Of T), Boolean) is null.\");\n if (columnSelectFunc == null)\n throw new ArgumentNullException(\"columnSelectFunc as Func(Of IEnumerable(Of T), Boolean) is null.\");\n int[] columnIndex = srcArray.GetColumnIndex(columnSelectFunc);\n IEnumerable<IEnumerable<T>> filteredRows = srcArray.GetRows(rowSelectFunc, columnIndex);\n Array filteredArray = filteredRows.ToArray();\n return (T[,])filteredArray;\n }\n }\n }\n \n```\n\n## C#での拡張関数の呼び出し(コンパイルエラーです)\n\n```\n\n using ArrayExNs;\n ...\n // Make original title/data array from Excel range object\n Array rangeArray = Array.CreateInstance(typeof(ATLCellInfo), mRowCount, mColumnCount);\n // ... 配列の内容を設定\n // Remove empty rows and columns\n ATLCellInfo[,] filteredArray = (ATLCellInfo[,])rangeArray.GetFilteredArray((row) =>\n {\n return row.OneOrMore(cell =>\n {\n return cell.HasValue;\n });\n }, (column) =>\n {\n return column.First.HasValue;\n }\n );\n \n```\n\nGetFilteredArrayの箇所に以下のエラーが出てしまいます.\n\n```\n\n Error CS1061 'Array' does not contain a definition for 'GetFilteredArray' and no accessible extension method 'GetFilteredArray' accepting a first argument of type 'Array' could be found (are you missing a using directive or an assembly reference?)\n \n```\n\nちなみに「移植した」といいつつも、VB⇒C#のコンバータにかけて、エラーを取ったレベルです.\n\n以上 よろしくお願いいたします.",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T11:10:49.687",
"favorite_count": 0,
"id": "77525",
"last_activity_date": "2021-06-13T16:57:04.660",
"last_edit_date": "2021-06-13T16:57:04.660",
"last_editor_user_id": "3060",
"owner_user_id": "9503",
"post_type": "question",
"score": 0,
"tags": [
"c#"
],
"title": "C#での配列の拡張関数の書き方",
"view_count": 152
} | [
{
"body": "キャスト演算子`(T)`とメンバーアクセス演算子`.`では、メンバーアクセス演算子のほうが優先順位は上です。\n\n * [C# operators and expressions - C# reference | Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/#operator-precedence)\n\n要するに、`(ATLCellInfo[,])rangeArray.GetFilteredArray(...)`は誤りで、 \n単純に`((ATLCellInfo[,])rangeArray).GetFilteredArray(...)`とすればいいんじゃないでしょうか。\n\nエラーメッセージをよく読めば、わざわざ誰かに聞くまでもなく、何が間違っているのかすぐに分かるはずです。\n\n * [ペアプログラミングして気がついた新人プログラマの成長を阻害する悪習 - Qiita](https://qiita.com/hirokidaichi/items/27c757d92b6915e8ecf7#%E3%82%A8%E3%83%A9%E3%83%BC%E3%83%A1%E3%83%83%E3%82%BB%E3%83%BC%E3%82%B8%E3%83%AD%E3%82%B0%E3%82%92%E8%AA%AD%E3%81%BE%E3%81%AA%E3%81%84)\n * [プログラミング言語 - エラー文って読まないの?|teratail](https://teratail.com/questions/76445)\n * [エラーメッセージの読み方と対処, 検索や質問の原則 - Qiita](https://qiita.com/cannorin/items/eb062aae88bfe2ad6fe5)",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T11:44:53.987",
"id": "77526",
"last_activity_date": "2021-06-13T11:57:40.637",
"last_edit_date": "2021-06-13T11:57:40.637",
"last_editor_user_id": "15413",
"owner_user_id": "15413",
"parent_id": "77525",
"post_type": "answer",
"score": 0
}
] | 77525 | 77526 | 77526 |
{
"accepted_answer_id": "77557",
"answer_count": 1,
"body": "Twitter\nAPIで複数回のリクエストを繰り返してツイートを取得しようとしているのですが、リクエスト制限となりました。これを回避するためにはどうすれば良いのか教えていただけますでしょうか。\n\nコードは以下の通りです。\n\n```\n\n import json\n from requests_oauthlib import OAuth1Session\n \n twitter = OAuth1Session(consumer_key, consumer_secret, access_token_key, access_token_secret)\n \n url = \"https://api.twitter.com/2/tweets/search/all/prod.json\"\n \n #paramsに検索ワードや件数、日付などを入力\n params = {'query':'(#abc)', \n 'start_time': \"2017-10-17T00:00:00Z\",\n 'end_time': \"2017-10-18T00:00:00Z\", 'tweet.fields':'created_at'}\n \n #上記で設定したパラメーターをget関数を使い指定URLから取得\n res = twitter.get(url, params = params)\n \n if res.status_code == 200:\n \n #後でpandasで処理するためリスト化\n created_at = []\n text = []\n retweet_count = []\n favorite_count = []\n \n #100件を超えるデータ用に繰り返し処理で対応\n while True:\n res = twitter.get(url, params = params)\n tweets = json.loads(res.text)\n tweet_list = tweets[\"results\"]\n \n for tweet in tweet_list:\n created_at.append(tweet[\"created_at\"]) #投稿日時\n text.append(tweet[\"text\"]) #投稿本文\n retweet_count.append(tweet[\"retweet_count\"]) #リツイート数\n favorite_count.append(tweet[\"favorite_count\"]) #いいね数\n user = tweet[\"user\"]\n \n #対象Tweetが101件以上となりnextページがある場合\n if \"next\" in tweets.keys():\n #nextの値をパラメータに追加する\n params['next'] = tweets[\"next\"]\n print(params)\n tweet_list = tweets[\"results\"]\n \n #nextページがない場合(100件以内の場合と最終ページ用)\n else:\n print(\"最終ページなので取得終了\")\n break \n \n```\n\n以下のようにリクエスト制限がかかりました。\n\n```\n\n {'title': 'Too Many Requests',\n 'type': 'about:blank',\n 'status': 429,\n 'detail': 'Too Many Requests'}\n \n```",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T11:53:57.260",
"favorite_count": 0,
"id": "77527",
"last_activity_date": "2021-06-27T06:53:12.490",
"last_edit_date": "2021-06-27T06:53:12.490",
"last_editor_user_id": "3060",
"owner_user_id": "45479",
"post_type": "question",
"score": 1,
"tags": [
"python",
"twitter",
"webapi"
],
"title": "Twitter API でのリクエスト制限に対応するには?",
"view_count": 2142
} | [
{
"body": "`Too Many Requests`というメッセージから、Twitter\nAPIの利用制限にひっかかっているとわかります。[公式のドキュメント](https://developer.twitter.com/en/docs/twitter-\napi/tweets/search/api-reference/get-tweets-search-all)を見てみると、Rate\nlimit(利用制限)という項には次のように書かれています(\"15-minute window\"というのは、「過去15分間で」という意味です)。\n\n> App rate limit: 300 requests per 15-minute window \n> App rate limit: 1 request per second\n\n利用制限や、その回避方法については[ドキュメントで詳しく解説されています](https://developer.twitter.com/en/docs/twitter-\napi/rate-\nlimits)。この場合、検索結果を一定期間保存しておいて、以降の同じクエリに対してAPIを呼び出さない方法が考えられます。開発の場面では試行錯誤を繰り返す間に制限にひっかかることもよくありますが、その場合は大人しく待つことになります。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T02:24:45.980",
"id": "77557",
"last_activity_date": "2021-06-15T02:24:45.980",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "7500",
"parent_id": "77527",
"post_type": "answer",
"score": 3
}
] | 77527 | 77557 | 77557 |
{
"accepted_answer_id": null,
"answer_count": 2,
"body": "以下の正規表現を用いて文章から文字列を抽出したいです.\n\n```\n\n [\\w-]+(\\.[\\w-]+)*\n \n```\n\nこの正規表現が正しいかをweb上で確認したところ以下の図のように文字を抽出できました.\n\n * 例 \n[](https://i.stack.imgur.com/S50SQ.png)\n\nこれを用いてPythonでも同様のことを行うとしたのですがうまくいきませんでいた.\n\n```\n\n test_data = '検索したい文字列'\n result = re.findall(r'/*[\\w-]+(\\.[\\w-]+)*', test_data)\n \n```\n\nおそらくPythonコードの書き方に何か問題があるのだと思います. \nどこに問題があるのか教えていただきたいです. \nよろしくお願いします.",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T13:58:05.657",
"favorite_count": 0,
"id": "77530",
"last_activity_date": "2021-06-13T17:03:23.660",
"last_edit_date": "2021-06-13T16:45:37.300",
"last_editor_user_id": "3060",
"owner_user_id": "44214",
"post_type": "question",
"score": 0,
"tags": [
"python",
"正規表現"
],
"title": "web上ではうまく文字抽出できるのに,pythonで正規表現がうまくいかない",
"view_count": 195
} | [
{
"body": "うーん、抜き出したいのは、\n\n * 1文字以上で\n * 1文字目は英数字か - で\n * 2文字目以降は英数字と - に加えて . もあり\n\nなのではないですか? \nそれなら`r'[\\w-][\\w\\.-]*'`で良いかと。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T14:30:39.060",
"id": "77531",
"last_activity_date": "2021-06-13T14:30:39.060",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "45045",
"parent_id": "77530",
"post_type": "answer",
"score": 0
},
{
"body": "JavaScript の正規表現エンジンと同様の結果を得るには non-capturing match group を使います。\n\n[Regular Expression\nSyntax](https://docs.python.org/3.8/library/re.html#regular-expression-syntax)\n\n> `(?:...)`\n>\n> A non-capturing version of regular parentheses. Matches whatever regular\n> expression is inside the parentheses, but the substring matched by the group\n> cannot be retrieved after performing a match or referenced later in the\n> pattern.\n```\n\n import re\n \n test_data = '''\n ['Conflicting with version dependencies when running pip install',\n \"Hi everyone, Having issues with version dependencies when running `pip install` on docker.\n However, when installing on my mac without docker and just virtualenv, works perfectly fine.\n **Mac OS** - macOS Mojave v10.14. **Python Version** - v3.7.3 **Docker Compose Version** -\n version 1.27.4, build 40524192 Here's the first error I got when running the docker-compose\n up I tried to loosen the `six` package from `six==1.10.0` to `six>=1.2,<=1.15.0` And throws\n a different error for requests package this time. Here's the error\n '''\n \n result = re.findall(r'[\\w-]+(?:\\.[\\w-]+)*', test_data)\n print(result)\n \n ## 結果(適宜改行を入れています)\n ['Conflicting', 'with', 'version', 'dependencies', 'when', 'running', 'pip',\n 'install', 'Hi', 'everyone', 'Having', 'issues', 'with', 'version', 'dependencies',\n 'when', 'running', 'pip', 'install', 'on', 'docker', 'However', 'when', 'installing',\n 'on', 'my', 'mac', 'without', 'docker', 'and', 'just', 'virtualenv', 'works',\n 'perfectly', 'fine', 'Mac', 'OS', '-', 'macOS', 'Mojave', 'v10.14', 'Python',\n 'Version', '-', 'v3.7.3', 'Docker', 'Compose', 'Version', '-', 'version', '1.27.4',\n 'build', '40524192', 'Here', 's', 'the', 'first', 'error', 'I', 'got', 'when',\n 'running', 'the', 'docker-compose', 'up', 'I', 'tried', 'to', 'loosen', 'the',\n 'six', 'package', 'from', 'six', '1.10.0', 'to', 'six', '1.2', '1.15.0', 'And',\n 'throws', 'a', 'different', 'error', 'for', 'requests', 'package', 'this', 'time',\n 'Here', 's', 'the', 'error']\n \n```\n\nその他に [re.finditer](https://docs.python.org/3.8/library/re.html#re.finditer)\nを使う方法があります。\n\n```\n\n result = [m.group(0) for m in re.finditer(r'[\\w-]+(\\.[\\w-]+)*', test_data)]\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T16:37:57.007",
"id": "77533",
"last_activity_date": "2021-06-13T17:03:23.660",
"last_edit_date": "2021-06-13T17:03:23.660",
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77530",
"post_type": "answer",
"score": 0
}
] | 77530 | null | 77531 |
{
"accepted_answer_id": "77540",
"answer_count": 1,
"body": "Rustでrusqliteで与える引数の&の意味がわかりません。 \n以下のように conn.execute(\"INSERT INTO todo (text) VALUES (?)\", &[¶ms.text])?;\nとしている箇所がありますが、ここでの &[¶ms.text]の二つの&は何を意味しているのでしょうか? \n[params.text]というように&を両方削除してもコンパイルは通り、期待通りの動きをしていました。\n\n¶ms.text は文字列型を文字列型の参照にして、それを[](配列?)で囲ってそれをさらに&で参照?が何をしているのかがよく理解できません。 \n(ドキュメント( <https://docs.rs/rusqlite/0.13.0/rusqlite/struct.Connection.html>\n)でも&[&ToSql]という形で記載されており、必要なのだろうと思いますが、&を削除しても動いたのが疑問になってしまいました。)\n\n(以下のサイトのコード\n<https://github.com/forcia/rustbook/blob/master/ch05/5-4/src/main.rs> )\n\n```\n\n conn.execute(\"INSERT INTO todo (text) VALUES (?)\", &[¶ms.text])?;\n \n```\n\nわかる方いましたらよろしくお願いいたします。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-13T15:06:43.373",
"favorite_count": 0,
"id": "77532",
"last_activity_date": "2021-06-14T14:29:29.903",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "42136",
"post_type": "question",
"score": 1,
"tags": [
"rust"
],
"title": "Rustのrusqliteの引数の&の意味が理解できません",
"view_count": 283
} | [
{
"body": "> ここでの &[¶ms.text]の二つの&は何を意味しているのでしょうか?\n\n変数名の前に`&`を付けると参照ができます。また、`&[ ...\n]`はスライスを作ります。これらの実体はポインターの一種で、メモリーのどこか他の場所にある値を指しています。(なおRustには`Deref`としくみがあって、ある条件を満たすと、`&`を付けた参照からスライスを作ることができます。質問とは直接関係がないので説明は省略します)\n\nRustには所有権という概念があります。これにより、ある変数の値を他の変数に代入すると、(多くの型では)その値の所有権が元の変数から他の変数へムーブ(移動)し、元の変数からはアクセスできなくなります。\n\n```\n\n fn main() {\n let a = \"Hello\".to_string(); // aはString型\n \n // aの内容を表示する\n println!(\"{}\", a);\n \n // aの値をbに代入する。これにより文字列の所有権がaからbへムーブ(移動)する\n let b = a; // bはString型\n \n // aの内容を表示しようとすると、コンパイルエラーになる\n println!(\"{}\", a);\n // → error[E0382]: borrow of moved value: `a` (ムーブ済みの値 a の借用)\n \n```\n\n一方、参照やスライスを使うと、元の値をムーブせずに、その値にアクセスすることができます。\n\n```\n\n // 上のコードの続き\n \n let c = &b; // bは&String型(Stringの参照型)\n println!(\"{}\", b); // エラーにならずHelloと表示される\n println!(\"{}\", c); // エラーにならずHelloと表示される\n }\n \n```\n\n参照やスライスにはこのような特徴があり、値をムーブしたくないときに便利に使えます。\n\n所有権、参照、スライスについてはRustの公式ドキュメントの4章で丁寧に解説されていますので、そちらを参照してください。\n\nここに和訳があります。\n\n * <https://doc.rust-jp.rs/book-ja/ch04-00-understanding-ownership.html>\n\n* * *\n\n> [params.text]というように&を両方削除してもコンパイルは通り、期待通りの動きをしていました。\n\nなぜ`&`を両方削除しても動いたかというと、rusqliteではRustのジェネリクスという仕組みを使って、`execute`メソッドなどが色々な型の引数を取れるようになっているからです。rusqliteのドキュメントに\n[例が載っており](https://docs.rs/rusqlite/0.25.3/rusqlite/trait.Params.html#positional-\nparameters) 、そこには `[2i32, 3i32]` も `&[&2i32, &3i32]` を含むいくつかの受け付け可能な型があります。\n\n(ジェネリクスについても上の和訳ドキュメントで解説されています)\n\nでは`[params.text]`と書かずに`&[¶ms.text]`と書くと何が嬉しいのかというと、先ほどの所有権のムーブの話が関係しています。\n\n`[params.text]`では所有権のムーブが起こり、元の変数からは値にアクセスできなくなります。\n\n```\n\n // ジェネリックな関数f。どんな型の引数も取れる\n fn f<T>(param: T) {}\n \n fn main() {\n // aはString型\n let a = \"Hello\".to_string();\n \n // bは[String; 1]型(長さが固定の配列)\n // こう書くとaの持つ文字列の所有権が配列にムーブする\n let b = [a];\n \n // ムーブしたのでもうaにはアクセスできない。コンパイルエラー\n println!(\"{}\", a);\n \n // 関数fに引数としてbを渡す\n // bの持つ配列の所有権が、関数fにムーブする\n f(b);\n \n // ムーブしたのでもうbにはアクセスできない。コンパイルエラー\n println!(\"{:?}\", b);\n }\n \n```\n\n一方、`&[¶ms.text]`なら所有権がムーブしないので、元の変数から引き続きアクセスできます。\n\n```\n\n // ジェネリックな関数f。どんな型の引数も取れる\n fn f<T>(param: T) {}\n \n fn main() {\n // aはString型\n let a = \"Hello\".to_string();\n \n // bは&[&String]型(&Stringのスライス)\n // 参照なのでaの持つ文字列の所有権をムーブしないで済む\n let b = &[&a];\n \n // まだaにアクセスできる\n println!(\"{}\", a);\n \n // 関数fに引数としてbを渡す\n f(b);\n \n // まだbにアクセスできる\n println!(\"{:?}\", b);\n }\n \n```\n\n`[params.text]`と`&[¶ms.text]`にはこのような違いがあり、所有権をムーブさせたくないときには後者が使えます。\n\n* * *\n\n**追記**\n\nコメント欄で以下のご指摘と質問を受けましたので、それらに対する回答を追記します。\n\n 1. スライスの作り方について。(`let b = &[&a];` としている箇所ですが、スライスは&変数名[num..num]という形という理解だったのですが、&[&変数名]の記法があるんでしょうか?)\n 2. 例示のコードではスライス型になってないのでは?(IDEだと後者は&[&std::string::String; 1] ... と表示されており、型が違いました)\n 3. `&[&a]`はあくまでrusqliteの引数の型に合わせるため?(単に所有権をムーブしたくない場合は参照でさえあればよく、&[&a]、&aや[&a]のいずれでも問題ないという理解であっているでしょうか?)\n\n2はご指摘通りで、スライス型になってませんでした。例を作ったときの私のミスです。1の説明と合わせて、修正したコードを下に書きました。\n\n3はその理解で合っています。\n\n1について説明します。スライスを明示的に作るときは、ご指摘通り`&変数名[num..num]`という記法を使います。ただ、配列や`Vec`の全要素に対するスライスを作るときに毎回`&変数名[..]`と書くのは面倒なので、`&変数名`と書くだけで暗黙的に全要素を対象にしたスライスを作ることができます。この暗黙的なスライスの作成は`std::ops::Deref`というトレイトを使って実現されており、Deref\ncoercion(Derefによる型強制、参照外しによる型強制)と呼ばれます。\n\n```\n\n // ジェネリックなT型を要素とするスライスを引数に取る\n fn f2<T>(params: &[T]) {}\n \n fn main() {\n // aはString型\n let a = \"Hello\".to_string();\n \n // 配列を作成する\n // bは[&String; 1]型(長さ1の&Stringの配列)\n let b = [&a];\n \n // cは&[&String; 1]型(長さ1の&Stringの配列への参照)\n let c = &b;\n \n // bから明示的にスライスを作る。dは&[&String]型(スライス)\n let d = &b[..];\n \n // bをスライス型へ型強制することで暗黙的にスライスを作れる\n // (Deref coercion)\n let e: &[&String] = &b;\n \n // dとeはf2の引数paramsと型が合うので、当然引数として渡せる\n f2(d);\n f2(e);\n \n // cは型が直接合わないが、paramsがスライスを要求していることで\n // b → eと同じくDeref coercionが働き、引数として渡せる\n f2(c);\n \n // 配列の作成から、b → eまでの変換を一気に行う\n f2(&[&a]);\n \n // もちろんb → dのように明示的にスライスを作ることもできる。\n // が、結果は1つ上と同じなのでわざわざこう書く必要はない\n f2(&[&a][..]);\n }\n \n```\n\nコード内の`b`から`e`を作るところがDeref coercionによるスライスの作成になります。\n\nそして、下から2つ目の`f2(&[&a])`がrusqliteで出てきた配列の作成からDeref coercionまでを一気に行う記法となります。\n\nDerefトレイトのしくみや型強制について、詳しくは以下のドキュメントを参照してください。\n\n * TRPL — [Derefトレイトでスマートポインタを普通の参照のように扱う](https://doc.rust-jp.rs/book-ja/ch15-02-deref.html)\n * Rust裏本 — [型強制](https://doc.rust-jp.rs/rust-nomicon-ja/coercions.html)",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T06:23:08.707",
"id": "77540",
"last_activity_date": "2021-06-14T14:29:29.903",
"last_edit_date": "2021-06-14T14:29:29.903",
"last_editor_user_id": "14101",
"owner_user_id": "14101",
"parent_id": "77532",
"post_type": "answer",
"score": 2
}
] | 77532 | 77540 | 77540 |
{
"accepted_answer_id": "77565",
"answer_count": 1,
"body": "ダウンロードして立ち上げましたが、「データベース接続を設定」の画面で何を入力してよいのか分かりません。通常のワードプレスをローカルにインストールした経験は有りますが、その場合はphpmyadminにてデータベースを構築して、ユーザーネームはroot、パスワードはxxxxxxx等簡単に入力して次のステップに進めましたが、Kusanagiの場合はどうすれば良いのですか。 \n立ち上げた時点でのアウトプットは以下です\n\n```\n\n (base) nobu@nobu-IdeaPad-3-15IIL05:~/.kusanagi$ sudo docker-compose up\n [sudo] password for nobu: \n Starting kusanagi-data ... done\n Starting kusanagi-mariadb ... done\n Starting kusanagi-php5 ... done\n Starting kusanagi-php7 ... done\n Starting kusanagi-nginx ... done\n Attaching to kusanagi-data, kusanagi-mariadb, kusanagi-php5, kusanagi-php7, kusanagi-nginx\n kusanagi-mariadb | 210614 1:44:35 [Note] mysqld (mysqld 10.0.24-MariaDB-1~jessie) starting as process 1 ...\n kusanagi-php5 | [14-Jun-2021 01:44:36] NOTICE: fpm is running, pid 1\n kusanagi-php5 | [14-Jun-2021 01:44:36] NOTICE: ready to handle connections\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: Using mutexes to ref count buffer pool pages\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: The InnoDB memory heap is disabled\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: Memory barrier is not used\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: Compressed tables use zlib 1.2.8\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: Using Linux native AIO\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: Using CPU crc32 instructions\n kusanagi-php7 | Cannot load Zend OPcache - it was already loaded\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: Initializing buffer pool, size = 256.0M\n kusanagi-php7 | [14-Jun-2021 01:44:36] NOTICE: PHP message: PHP Warning: Module 'apc' already loaded in Unknown on line 0\n kusanagi-php7 | [14-Jun-2021 01:44:36] NOTICE: PHP message: PHP Warning: Module 'apcu' already loaded in Unknown on line 0\n kusanagi-php7 | [14-Jun-2021 01:44:36] NOTICE: fpm is running, pid 1\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: Completed initialization of buffer pool\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: Highest supported file format is Barracuda.\n kusanagi-php7 | [14-Jun-2021 01:44:36] NOTICE: ready to handle connections\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: 128 rollback segment(s) are active.\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: Waiting for purge to start\n kusanagi-mariadb | 210614 1:44:35 [Note] InnoDB: Percona XtraDB (http://www.percona.com) 5.6.28-76.1 started; log sequence number 1616737\n kusanagi-mariadb | 210614 1:44:35 [Note] Plugin 'FEEDBACK' is disabled.\n kusanagi-mariadb | 210614 1:44:35 [Note] Server socket created on IP: '::'.\n kusanagi-mariadb | 210614 1:44:35 [Warning] 'proxies_priv' entry '@% root@4f6314a820fe' ignored in --skip-name-resolve mode.\n kusanagi-mariadb | 210614 1:44:35 [Note] mysqld: ready for connections.\n kusanagi-mariadb | Version: '10.0.24-MariaDB-1~jessie' socket: '/var/run/mysqld/mysqld.sock' port: 3306 mariadb.org binary distribution\n kusanagi-nginx | nginx: [warn] \"ssl_stapling\" ignored, issuer certificate not found\n status \n kusanagi-php7 | 172.19.0.6 - 14/Jun/2021:01:45:09 +0000 \"POST /wp-admin/setup-config.php\" 500\n kusanagi-php7 | 172.19.0.6 - 14/Jun/2021:01:45:57 +0000 \"GET /index.php\" 302\n kusanagi-php7 | 172.19.0.6 - 14/Jun/2021:01:45:57 +0000 \"GET /wp-admin/setup-config.php\" 200\n kusanagi-php7 | 172.19.0.6 - 14/Jun/2021:01:48:42 +0000 \"GET /wp-admin/setup-config.php\" 200\n kusanagi-php7 | 172.19.0.6 - 14/Jun/2021:01:48:46 +0000 \"GET /wp-admin/setup-config.php\" 200\n \n```\n\n上記にて最初に気づいたのは`nginx: [warn] \"ssl_stapling\" ignored, issuer certificate not\nfound status`のエラーです。Google検索した結果Pleskにて直せるそうですが、それ以外の手法はありませんか。\n\n[KUSANGI Runs on Dockerの使い方](https://github.com/prime-strategy/kusanagi-\ndocker/blob/master/HowToUse_RoD.jp.md#kusangi-runs-on-\ndocker%E3%81%AE%E4%BD%BF%E3%81%84%E6%96%B9) にコマンドが載っていますが、 以下を入力しても駄目でした。\n\n```\n\n (base) nobu@nobu-IdeaPad-3-15IIL05:~/.kusanagi$ ls\n bin HowToUse_RoD.md LICENSE update_version.sh\n docker-compose.yml install.sh README.md\n HowToUse_RoD.jp.md lib RoD.png\n (base) nobu@nobu-IdeaPad-3-15IIL05:~/.kusanagi$ kusanagi-docker --dbname wordpress_test\n no such sub command --dbname\n Try kusanagi-docker -h\n INFO: Done.\n (base) nobu@nobu-IdeaPad-3-15IIL05:~/.kusanagi$ kusanagi-docker --dbuser nobu\n no such sub command --dbuser\n Try kusanagi-docker -h\n INFO: Done.\n (base) nobu@nobu-IdeaPad-3-15IIL05:~/.kusanagi$ kusanagi-docker --dbpass tennis33\n no such sub command --dbpass\n Try kusanagi-docker -h\n INFO: Done.\n \n```\n\n設定の経験のある方、教えてください。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T02:19:51.077",
"favorite_count": 0,
"id": "77536",
"last_activity_date": "2021-06-15T04:43:12.893",
"last_edit_date": "2021-06-14T02:56:59.553",
"last_editor_user_id": "3060",
"owner_user_id": "29239",
"post_type": "question",
"score": 0,
"tags": [
"php",
"wordpress",
"nginx",
"mariadb"
],
"title": "Kusanagi ワードプレスの初期設定の仕方を教えてください",
"view_count": 166
} | [
{
"body": "サブコマンド provision が抜けています。\n\nkusanagi-docker **provision** \\--dbname wordpress_test --dbuser nobu --dbpass\ntennis33",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T04:43:12.893",
"id": "77565",
"last_activity_date": "2021-06-15T04:43:12.893",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "46868",
"parent_id": "77536",
"post_type": "answer",
"score": 1
}
] | 77536 | 77565 | 77565 |
{
"accepted_answer_id": "77538",
"answer_count": 1,
"body": "pandasの `=` の動きを理解しないまま、推測でコードを書いています。\n\nまず、下記のように書くと動くことが確認できました。\n\n```\n\n import matplotlib.pyplot as plt\n import pandas as pd\n \n df = pd.DataFrame({\n 'date': ['01-01', '01-02', '01-03', '02-01', '02-01'],\n 'value': [10000, 5000, 1000, 500, 100]\n })\n \n df['group'] = df['date']\n \n g_df = df.groupby('group')\n g_df.head()\n \n```\n\n結果: \n[](https://i.stack.imgur.com/P2awF.png)\n\nまた下記のようにすると動くことも確認できました。\n\n```\n\n import matplotlib.pyplot as plt\n import pandas as pd\n \n df = pd.DataFrame({\n 'date': ['01-01', '01-02', '01-03', '02-01', '02-01'],\n 'value': [10000, 5000, 1000, 500, 100]\n })\n \n df['group'] = '01-01'.split('-')[0]\n \n g_df = df.groupby('group')\n g_df.head()\n \n```\n\n結果: \n[](https://i.stack.imgur.com/qt3x7.png)\n\nなるほど。であれば、\n\n```\n\n df['group'] = df['date'].split('-')[0]\n \n```\n\nとすればうまくいくのかと思ったのですが、これはエラーになりました。\n\n> AttributeError: 'Series' object has no attribute 'split'\n\nうーん。文字列とおもっていたのにどうやら私が操作していたのは、`Series`のようだと思い、\n\n[pandasで'DataFrame' object has no attribute\n'split'のエラーを解決したい](https://ja.stackoverflow.com/questions/66717/pandas%E3%81%A7dataframe-\nobject-has-no-attribute-\nsplit%E3%81%AE%E3%82%A8%E3%83%A9%E3%83%BC%E3%82%92%E8%A7%A3%E6%B1%BA%E3%81%97%E3%81%9F%E3%81%84)\n\nを見てみて `str` というのがあるのかと思って下記を試しました。\n\n```\n\n df['group'] = df['date'].str.split('-')[0]\n \n```\n\n今度は、\n\n> ValueError: Length of values (2) does not match length of index (5)\n\nというエラーでした。\n\n試しに、\n\n```\n\n df['group'] = df['date'].str\n \n g_df = df.groupby('group')\n g_df.head()\n \n```\n\nとしてみると\n\n結果: \n[](https://i.stack.imgur.com/N7IIo.png)\n\nとなっており、`pandas`の文字列関係のオブジェクトが入っているよです。\n\nどうすれば、各レコードごとのデータを文字列としてsplitで加工し、新しい列を追加できるのでしょうか?",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T03:50:23.933",
"favorite_count": 0,
"id": "77537",
"last_activity_date": "2021-06-14T04:38:18.047",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "9008",
"post_type": "question",
"score": 0,
"tags": [
"python",
"pandas"
],
"title": "ValueError: Length of values (2) does not match length of index (5) が起こる",
"view_count": 3325
} | [
{
"body": "例えばこちらの記事の回答に書いた最後の方法で出来ます。 \n[Excelの日付フォーマットを変換の回答](https://ja.stackoverflow.com/a/76083/26370)\n\nこんな風になります。\n\n```\n\n df['group'] = df['date'].apply(lambda _: _.split('-')[0])\n \n```\n\n* * *\n\n同様に@metroploisさんコメントの方法だとこちらになります。\n\n```\n\n df['group'] = df['date'].str.split('-', expand=True)[0]\n \n```\n\n* * *\n\n他に分割した両方とも使いたい場合は、上記@metroploisさんコメントの方法を使って、単純には代入できないので`pd.concat`で元のdfと結合するという方法があります。 \n[pandasの文字列を区切り文字や正規表現で複数の列に分割](https://note.nkmk.me/python-pandas-split-\nextract/)\n\nこんな風になります。\n\n```\n\n df = pd.concat([df,df['date'].str.split('-', expand=True)],axis=1)\n df.rename(columns={0: 'group', 1: 'subgroup'}, inplace=True)\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T04:04:39.483",
"id": "77538",
"last_activity_date": "2021-06-14T04:38:18.047",
"last_edit_date": "2021-06-14T04:38:18.047",
"last_editor_user_id": "26370",
"owner_user_id": "26370",
"parent_id": "77537",
"post_type": "answer",
"score": 1
}
] | 77537 | 77538 | 77538 |
{
"accepted_answer_id": "77546",
"answer_count": 1,
"body": "pandasで、うまく、最大の行数を変更できません。\n\n```\n\n pd.set_option('display.max_columns', 50)\n pd.set_option('display.max_rows', 500)\n df_list[0]\n \n```\n\nどうすれば、最大の行数を変更することが出来るのでしょうか? \n[](https://i.stack.imgur.com/oM5P2.png)",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T06:44:44.870",
"favorite_count": 0,
"id": "77542",
"last_activity_date": "2021-06-16T06:27:13.593",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "42741",
"post_type": "question",
"score": 1,
"tags": [
"python",
"pandas"
],
"title": "pandasで、うまく、最大の行数を変更できません。",
"view_count": 1618
} | [
{
"body": "`display.max_rows, 500` ですが, 件数が多いようなので\n\n先頭だけなら\n\n```\n\n df.head(500)\n \n```\n\n最後の方なら\n\n```\n\n df.tail(500)\n \n```\n\n適当なら\n\n```\n\n df.sample(500)\n \n```\n\n…を試してみてください \n全件ならばこういうのも\n\n```\n\n pd.set_option('display.max_rows', None)\n \n # あるいは少し意味違うけど\n # df.style\n \n```\n\n* * *\n\n#### 追記\n\nどのような表示か, 質問になかったので推測ですが, \n途中省略された形式のまま少し件数を増やしたいとかでしょうか? \n`min_rows`, `max_rows` と実際の行数との兼ね合いになるけど以下で可能\n\n```\n\n pd.set_option(\"display.max_rows\", 500)\n pd.set_option(\"display.min_rows\", 500)\n \n display(df)\n \n```\n\n参考: \n<https://pandas.pydata.org/pandas-\ndocs/stable/user_guide/options.html#frequently-used-options>",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T07:59:26.993",
"id": "77546",
"last_activity_date": "2021-06-16T06:27:13.593",
"last_edit_date": "2021-06-16T06:27:13.593",
"last_editor_user_id": "43025",
"owner_user_id": "43025",
"parent_id": "77542",
"post_type": "answer",
"score": 0
}
] | 77542 | 77546 | 77546 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "画面遷移を繰り返してもチェックした項目はチェックしたままにしたいのですが、チェックボックスだけうまく作動しません。わかる方いましたらご教示お願いします。\n\n```\n\n window.onload = function onLoad() {\n //コース選択済み表示\n const date = document.getElementsByName(\"a\");\n if(sessionStorage.getItem('A') ===\"true\"){\n date[0].checked=true;\n }\n if(sessionStorage.getItem('B') ===\"true\"){\n date[1].checked=true;\n }\n if(sessionStorage.getItem('C') ===\"true\"){\n date[2].checked=true;\n }\n if(sessionStorage.getItem('D') ===\"true\"){\n date[3].checked=true;\n }\n if(sessionStorage.getItem('E') ===\"true\"){\n date[4].checked=true;\n }\n \n //お支払方法選択済み表示\n var elements = document.getElementsByName(\"level\");\n var pay = sessionStorage.getItem(\"pay\")\n switch(pay){\n case \"代金引換\":\n elements[0].checked=true;\n break;\n case \"コンビニ支払い\":\n elements[1].checked=true;\n break;\n case \"クレジットカード\":\n elements[2].checked=true;\n break;\n default:\n break; \n }\n }\n \n function check(){\n //コースの値取得\n const course = [];\n const check = [];\n const a = document.getElementsByName(\"a\");\n for(var i = 0; i < a.length; i++){\n if(a[i].checked){\n course.push(a[i].value);\n }\n check.push(a[i].checked);\n }\n \n //お支払方法の値取得\n var elements = document.getElementsByName(\"level\");\n var len = elements.length;\n var pay = '';\n \n for (var i = 0; i < len; i++){\n if (elements.item(i).checked){\n pay = elements.item(i).value;\n }\n }\n \n sessionStorage.setItem('course', course);\n sessionStorage.setItem('pay', pay);\n sessionStorage.setItem('A',course[0]);\n sessionStorage.setItem('B',course[1]);\n sessionStorage.setItem('C',course[2]);\n sessionStorage.setItem('D',course[3]);\n sessionStorage.setItem('E',course[4]);\n }\n```\n\n```\n\n コース\n <input type=\"checkbox\" name=\"a\" id=\"a\" value=\"A\"> A\n <input type=\"checkbox\" name=\"a\" id=\"a\" value=\"B\"> B\n <input type=\"checkbox\" name=\"a\" id=\"a\" value=\"C\"> C\n <input type=\"checkbox\" name=\"a\" id=\"a\" value=\"D\"> D\n <input type=\"checkbox\" name=\"a\" id=\"a\" value=\"E\"> E\n \n お支払い方法\n <input type=\"radio\" name=\"level\" id=\"level\" value=\"代金引換\">代金引換\n <input type=\"radio\" name=\"level\" id=\"level\" value=\"コンビニ引き換え\">コンビニ支払い\n <input type=\"radio\" name=\"level\"id=\"level\" value=\"クレジットカード\">クレジットカード\n \n <input type=\"button\" class=\"button\"Value=\"次へ\" onclick=\"check()\" >\n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T07:45:14.487",
"favorite_count": 0,
"id": "77544",
"last_activity_date": "2022-04-24T01:02:55.460",
"last_edit_date": "2021-06-17T12:32:25.347",
"last_editor_user_id": "7500",
"owner_user_id": "46738",
"post_type": "question",
"score": 0,
"tags": [
"javascript"
],
"title": "チェックボックスの値を保持できない。",
"view_count": 1635
} | [
{
"body": "Session Storageに保存する部分では `sessionStorage.setItem('A',course[0]);`\nが並んでいるため、実際には次のような配列を作りたいのだと思います。\n\n```\n\n course == [\"false\", \"false\", \"false\", \"true\", \"true\"] // D, Eがチェックされている場合\n \n```\n\nしかし `course` の中身を`console.log(course)`で見てみると、`[\"D\",\n\"E\"]`など、チェックをつけた箇所の`value`の配列になってしまっています。したがって、ソースコード中の次に示す部分を修正する必要があります。\n\n```\n\n //コースの値取得\n const course = [];\n const check = [];\n const a = document.getElementsByName(\"a\");\n for(var i = 0; i < a.length; i++){\n if(a[i].checked){\n course.push(a[i].value);\n }\n }\n \n```\n\nまた、試行錯誤の痕跡でしょうか、`sessionStorage.setItem('course',\ncourse);`という行で`course`をそのまま保存しているのが見えます。私ならこの配列をループしてチェックボックスの値をセットするようにします。A,\nB, C, D, Eに続く新たなコースが追加された場合にも容易に対応できるからです。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T05:45:42.270",
"id": "77620",
"last_activity_date": "2021-06-17T05:45:42.270",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "7500",
"parent_id": "77544",
"post_type": "answer",
"score": 1
}
] | 77544 | null | 77620 |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "とある学習サイトで以下のような説明がありました。\n\n> Post型の変数を受け取る関数を作って、データ型が継承されることを説明していきます。\n>\n> 型の継承 型を継承するメリット\n\nクラスを継承すると親クラスのプロパティやメソッドが子クラスに継承されるというのは理解できています。\n\n”データ型が継承される”というのはここでは下記の2か所を指しているのでしょうか? \n`%s` と `%s by %s` で「文字列を出力する」とフォーマットが指定されています。\n\n```\n\n public function show(){\n printf('%s',$this->text);\n }\n \n```\n\nと\n\n```\n\n public function show(){\n printf('%s by %s', $this->text, $this->sponsor);\n }\n \n```\n\n要するにこのサイトのこの項目ではプロパティやメソッドだけでなく付随するデータ型( \n文字列型、整数型、浮動小数点数型、論理型、配列型、オブジェクト型、リソース型、NULL) \nも継承されるということなのでしょうか?\n\n初歩的な質問かと思いますが「Post型の変数を受け取る関数を作って、データ型が継承されることを説明していきます。」という文面に対して混乱しています。ウェブサイトや教材を眺めてもクラスの継承の際に”データ型”も継承されるというという点を見つけることが出来ませんでした。 \n初学者です。もし解釈が間違っているのならばご指摘願います。\n\n* * *\n\n### ソースコード\n\n```\n\n <?php\n \n class Post{\n \n protected $text;\n \n public function __construct($text){\n $this->text = $text;\n }\n public function show(){\n \n printf('%s',$this->text);\n }\n }\n //↑------classPost------↑\n \n //↓------classSponsoredPost------↓\n \n class SponsoredPost extends Post{\n \n private $sponsor;\n \n public function __construct($text, $sponsor){\n parent::__construct($text);\n $this->sponsor = $sponsor;\n }\n \n \n public function show(){\n printf('%s by %s', $this->text, $this->sponsor);\n }\n }\n //↑------classSponsoredPost------↑\n $posts = [];\n $posts[0] = new Post('hello');\n $posts[1] = new Post('hello again');\n $posts[2] = new SponsoredPost('iPhone','Apple');\n \n function processPost(Post $post){\n $post->show();\n }\n \n // 型の継承がされているでSponsoredPost型のインスタンスも\n // Post型として扱うことができうまくいく\n \n foreach($posts as $post){\n processPost($post);\n echo \"<br>\";\n \n```\n\n### 表示結果\n\n[](https://i.stack.imgur.com/lS7J9.png)",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T07:53:43.360",
"favorite_count": 0,
"id": "77545",
"last_activity_date": "2021-06-14T08:14:04.193",
"last_edit_date": "2021-06-14T08:14:04.193",
"last_editor_user_id": "3060",
"owner_user_id": "42150",
"post_type": "question",
"score": 0,
"tags": [
"php"
],
"title": "PHPで型の継承、データ型の継承について混乱しています。",
"view_count": 178
} | [] | 77545 | null | null |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "Python初学者です。 \nCSVファイルから情報を取得して、QListWidgetに表示させました。 \nそのQListWidgetから情報を取得して、Jsonファイルを作成するコードを書きました。 \nしかし、ファイルは作成したのですが、最後の1行しか入ってません。 \nQListWidgetを使うことが間違っているのでしょうか?\n\n**環境:** \nWindows 10 \nPython3 \nPySide2\n\nコードは以下のように書きました。\n\n```\n\n def callback_create_file_button_clicked(self):\n for row in range(self.listwgt.count()):\n item = self.listwgt.item(row)\n jsonlist = item.text()\n filename = \"C:/Users/User/Documents/Jymaker/json/sample.json\"\n with open(filename, \"w\", encoding=\"utf_8\") as f:\n json.dump(jsonlist, f)\n \n```\n\ncsvファイルを読み込む部分です。\n\n```\n\n def load_csv(self, file):\n json_list =[]\n with open(file, \"r\", encoding=\"utf_8\") as f:\n reader = csv.reader(f)\n for row in reader:\n json_list.append(\",\".join(row))\n \n return(json_list)\n \n```\n\n返り値を受け取る部分です。\n\n```\n\n def callback_file_dialog_button_clicked(self):\n file, filter_ = QtWidgets.QFileDialog.getOpenFileName(\n self, \"Open CSV\", \"C:/Users/User/Documents/Jymaker/csv\", \"CSV (*.csv)\"\n )\n \n if file:\n self.line_edit.setText(file)\n json_list = self.load_csv(file)\n self.listwgt.clear()\n self.listwgt.addItems(json_list)\n \n```",
"comment_count": 5,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T10:05:49.897",
"favorite_count": 0,
"id": "77551",
"last_activity_date": "2021-06-14T11:56:22.720",
"last_edit_date": "2021-06-14T11:56:22.720",
"last_editor_user_id": "3060",
"owner_user_id": "43098",
"post_type": "question",
"score": 0,
"tags": [
"python",
"python3",
"json",
"csv"
],
"title": "QListWidgetに表示されている文字の情報を取得してJSONファイルを作成したい",
"view_count": 298
} | [] | 77551 | null | null |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "### 前提・実現したいこと\n\n現在React.jsを用いて投稿型webアプリを制作しています。 \nメインのコードは書き終えたのですが1箇所だけwarningが解決しないため、是非皆さんの知恵を貸していただきたいです。 \nエラーは以下の通りです。\n\n### 発生している問題・エラーメッセージ\n\n```\n\n Aborted attempt to load Google Maps JS with @googlemaps/js-api-loader.This may result in undesirable behavior as script parameters may not match. \n \n```\n\n### 該当のソースコード\n\nMap.js\n\n```\n\n import GoogleMapReact from \"google-map-react\";\n ...\n //住所から地名を取得\n const Geocoding = useCallback(() => {\n Geocode.setApiKey(\"AIzaSyDUDTHfWX33hew2WbRittJIKhHfVWgz5dY\");\n Geocode.fromAddress(prop.address).then(\n (response) => {\n const { lat, lng } = response.results[0].geometry.location;\n setSpotLat(lat);\n setSpotLng(lng);\n console.log(lat, lng);\n },\n (error) => {\n console.error(error);\n }\n );\n }, [prop.address]);\n useEffect(() => {\n Geocoding();\n }, [Geocoding]);\n ...\n <GoogleMapReact\n bootstrapURLKeys={{ key: \"AIzaSyDUDTHfWX33hew2WbRittJIKhHfVWgz5dY\" }}\n center={{\n lat: spotLat,\n lng: spotLng,\n }}\n defaultZoom={16}\n yesIWantToUseGoogleMapApiInternals\n >\n \n```\n\nMap.js\n\n```\n\n import GooglePlacesAutocomplete from \"react-google-places-autocomplete\";\n ...\n <GooglePlacesAutocomplete\n apiKey=\"AIzaSyDUDTHfWX33hew2WbRittJIKhHfVWgz5dY\"\n selectProps={{\n value: courseSpotAddress,\n onChange: setcourseSpotAddress,\n placeholder: \"名前を打ち込んでください(例 神戸駅)\",\n }}\n apiOptions={{ language: \"jp\", region: \"jp\" }}\n menuContainerStyle={{ zIndex: 999 }}\n //style={styles.tweet_input}\n menuPortalTarget={document.body}\n menuPosition={\"fixed\"}\n />\n \n```\n\n### 他サイト様での質問\n\nteratailにて同様の質問をしています。 \n<https://teratail.com/questions/343951>",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T10:22:43.343",
"favorite_count": 0,
"id": "77553",
"last_activity_date": "2021-06-15T01:17:05.277",
"last_edit_date": "2021-06-15T01:17:05.277",
"last_editor_user_id": "45409",
"owner_user_id": "45409",
"post_type": "question",
"score": 0,
"tags": [
"reactjs",
"google-maps"
],
"title": "GooglePlacesAutocompleteとgoogle-map-reactを共存させる方法",
"view_count": 114
} | [] | 77553 | null | null |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "表題について、解決する方法があるかお聞きしたいです。 \n現在、Linux環境で、Xserverのサービスを作成し、起動している状態です。 \n方法は、以下の関連質問と少し重複しますが、記述させていただきます。\n\n関連質問:[linux(CentOS)上でのxhostコマンドをCUIモードでできないか、または、サービスの自動起動でxhostを設定できないか](https://ja.stackoverflow.com/questions/77462/linuxcentos%E4%B8%8A%E3%81%A7%E3%81%AExhost%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89%E3%82%92cui%E3%83%A2%E3%83%BC%E3%83%89%E3%81%A7%E3%81%A7%E3%81%8D%E3%81%AA%E3%81%84%E3%81%8B-%E3%81%BE%E3%81%9F%E3%81%AF-%E3%82%B5%E3%83%BC%E3%83%93%E3%82%B9%E3%81%AE%E8%87%AA%E5%8B%95%E8%B5%B7%E5%8B%95%E3%81%A7xhost%E3%82%92%E8%A8%AD%E5%AE%9A%E3%81%A7%E3%81%8D%E3%81%AA%E3%81%84%E3%81%8B)\n\nXServerサービスファイルを以下のように作成します。\n\n```\n\n [Unit]\n Description=X server\n After=network-online.target\n Wants=network-online.targetコードをここに入力\n \n [Service]\n Type=exec\n ExecStart=/usr/bin/Xorg -broadcast -keeptty -retro -listen tcp dpms vt7 v -allowMouseOpenFail -allowNonLocalXvidtune \n #Restart=always\n Restart=no\n \n [Install]\n WantedBy=multi-user.target\n \n```\n\n以下を参考に作成、起動しています。起動すると、Linuxの画面自体は縞模様の画面となり、何も押しても反応しない状態となります(ディスプレイマネージャが起動していないため?)。 \n表示としては問題ありません。またteratermでリモートで操作しています。\n\n[Systemdを使ってさくっと自作コマンドをサービス化してみる](https://qiita.com/DQNEO/items/0b5d0bc5d3cf407cb7ff)\n\n[ラズパイのX端末化【大幅改訂版](https://qiita.com/kakinaguru_zo/items/ce6e36765baa9b31d974)\n\n問題点として、現在、XServerサービスのステータスを確認すると(コマンド:systemctl status Xserver.service) \n表題のようなエラーが起動後しばらくしてから数分ごとに発生します。また、画面も更新され初期状態になります。 \n例えば、現在XClientとなるLinux機器からアプリをリモートで、XServer側に表示させようとしておりますが、XServerの画面が更新され、XClient側のアプリも落ちてしまう状況が発生します。\n\n今回、ディスプレイマネージャーを起動していないが、XServerがディスプレイマネージャーに接続しようとするため、このようなエラーが表示されるのではないかと考えております。 \nXServerがディスプレイマネージャーに接続しない方法を考えましたが、今のところ分かっていません。何か方法はあるでしょうか?また、その他解決できる方法はあるでしょうか?\n\nお手数ですがよろしくお願いします。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T10:39:26.620",
"favorite_count": 0,
"id": "77554",
"last_activity_date": "2021-06-14T10:39:26.620",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "43586",
"post_type": "question",
"score": 0,
"tags": [
"linux"
],
"title": "XServerのサービスのエラー「localhost.localdomain Xorg[8254]: XDM: too many retransmissions, declaring session dead」について",
"view_count": 131
} | [] | 77554 | null | null |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "AWSにてVPCとセキュリティグループ、EC2を作成しました。 \nサブネットを割り当て自分のターミナルにてSSH接続を試みましたがSSH接続ができない状況です。\n\n実行コマンド:\n\n```\n\n > ssh -i xxx.pem ec2-user@Elasticipアドレス\n \n```\n\nエラー結果は以下になります。\n\n```\n\n ec2-user@Elasticipアドレス: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).\n \n```\n\npemキーは自分のダウンロードフォルダ内に存在しており、権限は以下です\n\n```\n\n -rw-------@ xxx.pem\n \n```\n\nまた、エラーの詳細を知るために `ssh -vvv` を実行した結果は下記になります。\n\n```\n\n penSSH_8.1p1, LibreSSL 2.7.3\n debug1: Reading configuration data /Users/xxx/.ssh/config\n debug1: Reading configuration data /etc/ssh/ssh_config\n debug1: /etc/ssh/ssh_config line 47: Applying options for *\n debug1: Connecting to 1qaz2wsx.pem port 22.\n ssh: Could not resolve hostname xxx.pem: nodename nor servname provided, or not known\n \n```\n\n名前解決ができていないと思うのですが、具体的にどこを修正すればいいかわかりません。 \nどなたか教えていただけないでしょうか。",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T14:33:22.257",
"favorite_count": 0,
"id": "77555",
"last_activity_date": "2021-06-18T11:45:04.927",
"last_edit_date": "2021-06-14T16:37:25.460",
"last_editor_user_id": "3060",
"owner_user_id": "46866",
"post_type": "question",
"score": -1,
"tags": [
"linux",
"ssh",
"amazon-ec2"
],
"title": "EC2へのSSH接続ができない",
"view_count": 804
} | [
{
"body": "Elasticの`/etc/ssh/sshd_config`を編集して、sshdを再起動してみてください。\n\n```\n\n HostKey /etc/ssh/ssh_host_rsa_key\n HostKey /etc/ssh/ssh_host_dsa_key\n HostKey /etc/ssh/ssh_host_ecdsa_key\n HostKey /etc/ssh/ssh_host_ed25519_key\n PubkeyAuthentication yes\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-18T09:23:29.927",
"id": "77642",
"last_activity_date": "2021-06-18T11:45:04.927",
"last_edit_date": "2021-06-18T11:45:04.927",
"last_editor_user_id": "3060",
"owner_user_id": "46923",
"parent_id": "77555",
"post_type": "answer",
"score": -1
}
] | 77555 | null | 77642 |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "### やりたいこととできないこと\n\n[こちらのコード](https://github.com/kboy-\nsilvergym/coriander/tree/01ee584236784c5e75e8fe99a66e1cb038bf5eb3/lib)\nを参考にしてFlutterでボタンをクリックすると色が変わる機能を作ろうとしています。\n\nボタン1に関してはクリックするとchangeButtonColor1()メソッドが呼ばれ、ボタンの色が変わります。 \nその後、ボタンの数を増やすことになりました。 \nボタン2とボタン3に関しては状態管理の変数(buttonColor1,buttonColor2,buttonColor3)を増やし、changeButtonColor2(),changeButtonColor3()と作っていくとコードの肥大化が止まらず今後ボタン4、ボタン5と増やしていくつもりなので、changeButtonColorAddArgumentというメソッドの引数に状態管理の変数を入れるようにしました。しかし、そうするとクリックしてもボタン2、ボタン3の色が変わりません。\n\n[](https://i.stack.imgur.com/0nsKx.jpg)\n\n[](https://i.stack.imgur.com/Gg2Ce.jpg)\n\n### ソースコード\n\n```\n\n // main.dart\n \n import 'package:flutter/cupertino.dart';\n import 'package:flutter/material.dart';\n import 'package:provider/provider.dart';\n import 'main_model.dart';\n \n // ChangeNotifierを継承すると変更可能なデータを渡せる\n void main() => runApp(MyApp());\n \n class MyApp extends StatelessWidget {\n \n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n title: 'Flutter Demo',\n home: ChangeNotifierProvider<MainModel>(\n create: (_) => MainModel(),\n child: Scaffold(\n appBar: AppBar(\n title: Text('ボタンの色を変えたい。'),\n ),\n body: Consumer<MainModel>(builder: (context, model, child) {\n return Center(\n child: Column(\n children: [\n // ignore: deprecated_member_use\n RaisedButton(\n child: Text('ボタン1'),\n onPressed: () { \n model.changeButtonColor1();\n },\n color: model.buttonColor1,\n ),\n RaisedButton(\n child: Text('ボタン2'),\n onPressed: () { \n // クリックしても動かないmodel.changeButtonColorAddArgument(model.buttonColor2);\n },\n color: model.buttonColor2,\n ),\n RaisedButton(\n child: Text('ボタン3'),\n onPressed: () {\n // クリックしても動かないmodel.changeButtonColorAddArgument(model.buttonColor3);\n },\n color: model.buttonColor3,\n ),\n ],\n ),\n );\n }),\n ),\n ),\n );\n }\n }\n \n```\n\n```\n\n // main_model.dart\n import 'package:flutter/material.dart';\n \n class MainModel extends ChangeNotifier {\n Color buttonColor1 = Colors.red;\n Color buttonColor2 = Colors.red;\n Color buttonColor3 = Colors.red;\n void changeButtonColor1(){\n // buttonColor = Colors.blue;\n // canChange = true;\n if (buttonColor1 == Colors.blue){\n buttonColor1 = Colors.red;\n } else if(buttonColor1 == Colors.red){\n buttonColor1 = Colors.blue;\n }\n notifyListeners();\n }\n void changeButtonColorAddArgument(Color buttonColor){\n if (buttonColor == Colors.blue){ \n buttonColor = Colors.red;\n } else if(buttonColor == Colors.red){\n print(buttonColor);\n buttonColor = Colors.blue;\n print(buttonColor); \n }\n notifyListeners();\n }\n }\n \n```\n\n### 実施した手順とその結果\n\n**手順1**\n\nchangeButtonColorAddArgument()のbuttonColor =\nColors.blueの前後にprint(buttonColor)して状態管理用の変数がどうなっているのか調べました。 \nコンソールの結果は以下になります。\n\n```\n\n Performing hot reload...\n Syncing files to device iPhone 8...\n Reloaded 1 of 566 libraries in 522ms.\n flutter: MaterialColor(primary value: Color(0xfff44336))\n flutter: MaterialColor(primary value: Color(0xff2196f3))\n \n```\n\n[f44336](https://encycolorpedia.jp/f44336)は赤、[2196f3](https://encycolorpedia.jp/2196f3)は青だったので、状態管理(buttonColor2,3)の変数の色自体は変わっていますが、それがUIに反映されていないことがわかります。\n\n**手順2**\n\n次に手順1を参考にして以下のキーワードで検索しました。\n\n * flutter provider UIが更新されない\n * flutter provider UI is not updated.\n * flutter provider 引数 動かない\n * flutter provider argument not working\n\nしかし、これらの検索ワードからでは引数を追加することによって動作しなくなる理由を見つけることができませんでした。\n\nこの問題を解決するにあたって何かアドバイスがあればお願いします。\n\n### 環境\n\nflutter 2.30 \ndart 2.14.0 \nandroid studio 4.2.1 \nprovider ^5.0.0 \nMacBook Air (M1, 2020) 16GB \nBig Sur 11.4",
"comment_count": 5,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-14T16:24:05.810",
"favorite_count": 0,
"id": "77556",
"last_activity_date": "2021-06-15T00:22:18.907",
"last_edit_date": "2021-06-15T00:22:18.907",
"last_editor_user_id": "3060",
"owner_user_id": "36424",
"post_type": "question",
"score": 0,
"tags": [
"flutter",
"dart"
],
"title": "Flutter,Providerを使用してクリックするとボタンの背景色を変えたいが、状態管理用の変数を引数に入れて実行するとなぜか動作しない。",
"view_count": 621
} | [] | 77556 | null | null |
{
"accepted_answer_id": null,
"answer_count": 4,
"body": "PHPで以下の定数エラーが起きます。なぜでしょうか?\n\n**エラーメッセージ:**\n\n```\n\n Symfony\\Component\\Debug\\Exception\\FatalThrowableError\n syntax error, unexpected 'const' (T_CONST)\n \n```\n\n**該当のコード:**\n\n```\n\n const $ABBB = 300;\n \n```\n\n**実行環境:**\n\n```\n\n % php -version\n PHP 7.3.24-(to be removed in future macOS) (cli) (built: Dec 21 2020 21:33:22) ( NTS )\n \n```\n\n以下の関数の中でエラーが起きました。\n\n```\n\n public function getYourAnswer($stack)\n {\n $calcCost = 0;\n const INITIAL_COST = 300;\n \n $calcCost = calculate();\n \n $totalCost = $calcCost + INITIAL_COST;\n return $totalCost;\n }\n \n```",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T02:42:08.957",
"favorite_count": 0,
"id": "77558",
"last_activity_date": "2023-04-24T19:00:45.133",
"last_edit_date": "2021-06-15T10:52:38.283",
"last_editor_user_id": "44839",
"owner_user_id": "44839",
"post_type": "question",
"score": 0,
"tags": [
"php"
],
"title": "定数エラー 'const' (T_CONST)",
"view_count": 882
} | [
{
"body": "PHPでは定数には`$`を付けません。\n\n```\n\n const ABBB = 300;\n \n```\n\nしかし、それにしてはエラーメッセージはちょっと違うことを言っているようです。 \nおそらく問題はその行ではなく1つ前までのコードに何か問題があると思われます。 \nたぶん文末のセミコロン`;`が無いとか。 \n確認してみてください。",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T03:10:02.820",
"id": "77562",
"last_activity_date": "2021-06-15T04:10:14.540",
"last_edit_date": "2021-06-15T04:10:14.540",
"last_editor_user_id": "3060",
"owner_user_id": "45045",
"parent_id": "77558",
"post_type": "answer",
"score": 0
},
{
"body": "PHPでは、全ての変数宣言の位置で`const`による定数宣言が書けるわけではありません。\n\n(また、@ItagakiFumihiko さんの回答にあるように定数名には`$`は付けません。)\n\n例えば、以下のようにクラス定数を宣言することならできます。\n\n```\n\n class MyClass {\n private const INITIAL_COST = 300;\n \n public function getYourAnswer($stack)\n {\n $calcCost = 0;\n \n $calcCost = calculate();\n \n $totalCost = $calcCost + MyClass::INITIAL_COST;\n return $totalCost;\n }\n }\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T11:07:00.127",
"id": "77578",
"last_activity_date": "2021-06-15T11:07:00.127",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "13972",
"parent_id": "77558",
"post_type": "answer",
"score": 0
},
{
"body": "`public`が付いていることから想像するに、`getYourAnswer`はクラスのメソッドですか? \nいずれにしてもクラスのメソッドや通常の関数内でconstで定数を定義することはできません。 \n定義するなら外です。\n\n```\n\n class hogehoge {\n \n const INITIAL_COST = 300;\n \n public function getYourAnswer($stack)\n {\n $calcCost = 0;\n \n $calcCost = calculate();\n \n $totalCost = $calcCost + INITIAL_COST;\n return $totalCost;\n }\n }\n \n```\n\n`INITIAL_COST`を関数スコープ内に置きたいのなら、定数である必要があるかも検討してください。通常の変数でも良いのではないですか?\n\nそれから、質問とは関係ありませんが、提示されたコードには全角スペースが入っているため、そこでもエラーになります。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T11:17:17.653",
"id": "77579",
"last_activity_date": "2021-06-15T11:17:17.653",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "45045",
"parent_id": "77558",
"post_type": "answer",
"score": 0
},
{
"body": "`define()` での宣言と比較して `const` キーワードには以下の制限があります。\n\n[PHP: Constants\nSyntax](https://www.php.net/manual/en/language.constants.syntax.php)\n\n> **Note** : \n> As opposed to defining constants using define(), constants defined using\n> the **const keyword must be declared at the top-level scope because they are\n> defined at compile-time. This means that they cannot be declared inside\n> functions, loops, if statements or try/catch blocks**.",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T11:39:32.313",
"id": "77581",
"last_activity_date": "2021-06-15T11:39:32.313",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77558",
"post_type": "answer",
"score": 0
}
] | 77558 | null | 77562 |
{
"accepted_answer_id": "77569",
"answer_count": 1,
"body": "現状説明。\n\nmediawikiをインストール、ショートURLのためにnginxを設定中。\n\n初期状態では \n`http://example.com` \nにアクセスすると \n`http://example.com/index.php?title=メインページ` \nにリダイレクトされる。\n\nリダイレクト先を以下のようなものに変更したい \n`http://example.com/wiki/メインページ`\n\nmediawikiの公式サイトを元に設定、リダイレクト先の変更には成功。\n\n```\n\n server {\n # [...]\n \n # Location for wiki's entry points\n location ~ ^/w/(index|load|api|thumb|opensearch_desc|rest|img_auth)\\.php$ {\n include /etc/nginx/fastcgi_params;\n fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n fastcgi_pass 127.0.0.1:9000; # or whatever port your PHP-FPM listens on\n }\n \n # Images\n location /w/images {\n # Separate location for images/ so .php execution won't apply\n }\n location /w/images/deleted {\n # Deny access to deleted images folder\n deny all;\n }\n # MediaWiki assets (usually images)\n location ~ ^/w/resources/(assets|lib|src) {\n try_files $uri 404;\n add_header Cache-Control \"public\";\n expires 7d;\n }\n # Assets, scripts and styles from skins and extensions\n location ~ ^/w/(skins|extensions)/.+\\.(css|js|gif|jpg|jpeg|png|svg|wasm)$ {\n try_files $uri 404;\n add_header Cache-Control \"public\";\n expires 7d;\n }\n # Favicon\n location = /favicon.ico {\n alias /w/images/6/64/Favicon.ico;\n add_header Cache-Control \"public\";\n expires 7d;\n }\n \n # License and credits files\n location ~ ^/w/(COPYING|CREDITS) {\n default_type text/plain;\n }\n \n ## Uncomment the following code if you wish to use the installer/updater\n ## installer/updater\n #location /w/mw-config/ {\n # # Do this inside of a location so it can be negated\n # location ~ \\.php$ {\n # include /etc/nginx/fastcgi_params;\n # fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n # fastcgi_pass 127.0.0.1:9000; # or whatever port your PHP-FPM listens on\n # }\n #}\n \n # Handling for Mediawiki REST API, see [[mw:API:REST_API]]\n location /w/rest.php/ {\n try_files $uri $uri/ /w/rest.php?$query_string;\n }\n \n ## Uncomment the following code for handling image authentication\n ## Also add \"deny all;\" in the location for /w/images above\n #location /w/img_auth.php/ {\n # try_files $uri $uri/ /w/img_auth.php?$query_string;\n #}\n \n # Handling for the article path (pretty URLs)\n location /wiki/ {\n rewrite ^/wiki/(?<pagename>.*)$ /w/index.php;\n }\n \n # Allow robots.txt in case you have one\n location = /robots.txt {\n }\n # Explicit access to the root website, redirect to main page (adapt as needed)\n location = / {\n return 301 /wiki/Main_Page;\n }\n \n # Every other entry point will be disallowed.\n # Add specific rules for other entry points/images as needed above this\n location / {\n return 404;\n }\n }\n \n```\n\n<https://www.mediawiki.org/wiki/Manual:Short_URL/Nginx/ja>\n\nしかし、以下のどちらのURLからでもメインページが表示される。 \n`http://example.com/index.php?title=メインページ` \n`http://example.com/wiki/メインページ`\n\n`http://example.com/wiki/メインページ` \nへ1本化したい。\n\n公式のサンプルコードを意味も分からずコピペしたので内容を読解している最中。\n\nここからが質問です。\n\nmediawikiの公式サンプルに出てくる下記のコード\n\n```\n\n # Handling for the article path (pretty URLs)\n location /wiki/ {\n rewrite ^/wiki/(?<pagename>.*)$ /w/index.php;\n }\n \n```\n\n`(?<pagename>.*)`は名前付きキャプチャ、マッチする部分を`$pagename`という変数で再利用できる \nという風に理解しています。\n\nしかし、`$pagename`という変数はサンプルコードの中では使われていません。 \n`?<pagename>`のように名前付きキャプチャにする意味はあるのでしょうか?\n\nmediawiki用のnginxの設定は \n/etc/nginx/conf.d/mediawiki.conf \nというファイルを新規作成して記入しました。\n\nもしかすると`pagename`自体が予約語になっていて、mediawiki.conf以外の場所で `$pagename`を参照していたりするのでしょうか? \n(default.confやindex.phpなどに名前付きキャプチャの値を引き継ぐような仕様があるのか?)\n\nまた、 \n`rewrite ^/wiki/(?<pagename>.*)$ /w/index.php;` \nの部分は \nindex.php に内部でリダイレクトをしていると理解しています。\n\nキャプチャした値をリダイレクト先に引き継がせていないように見えるのですが \n`rewrite .* /w/index.php;` \nのように、全部リダイレクトという書き方ではだめなのでしょうか?\n\nまとめ \n・`(?<pagename>.*)`の名前付きキャプチャは、mediawiki.conf以外の場所から参照されている可能性はある? \n・名前付きキャプチャどころか、そもそもキャプチャせずに全部rewriteすればいいのでは?",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T03:02:27.797",
"favorite_count": 0,
"id": "77561",
"last_activity_date": "2021-06-15T06:30:40.083",
"last_edit_date": "2021-06-15T04:00:52.333",
"last_editor_user_id": "2238",
"owner_user_id": "45540",
"post_type": "question",
"score": 0,
"tags": [
"php",
"正規表現",
"nginx",
"url"
],
"title": "nginx、名前付きキャプチャの適用範囲は?",
"view_count": 118
} | [
{
"body": "`nginx.conf` の編集履歴から 2019/2/21 の時点でのスナップショットを参照してみます。\n\n[https://www.mediawiki.org/w/index.php?title=Manual:Short_URL/Nginx&oldid=3103792](https://www.mediawiki.org/w/index.php?title=Manual:Short_URL/Nginx&oldid=3103792)\n\n`$pagename` に関係する部分は以下の通りで `PATH_INFO` に割り当てられています。\n\n```\n\n # Handling for the article path (pretty URLs)\n location /wiki/ {\n rewrite ^/wiki/(?<pagename>.*)$ /w/index.php;\n include /etc/nginx/fastcgi_params;\n # article path should always be passed to index.php\n fastcgi_param SCRIPT_FILENAME $document_root/w/index.php;\n fastcgi_param PATH_INFO $pagename;\n fastcgi_param QUERY_STRING $query_string;\n fastcgi_pass 127.0.0.1:9000; # or whatever port your PHP-FPM listens on\n }\n \n```",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T06:30:40.083",
"id": "77569",
"last_activity_date": "2021-06-15T06:30:40.083",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77561",
"post_type": "answer",
"score": 1
}
] | 77561 | 77569 | 77569 |
{
"accepted_answer_id": "77564",
"answer_count": 1,
"body": "下記のように、`seaborn`でデフォルトで読み込める tips のデータで試してみました。\n\n`total_bill`や`tip`とそれに続くカラムは全て同じカウントの数を出しているだけなので不要です。 \n`count`というカラムだけあればいいと思うのですが、どのようにすれば実現できますか?\n\n**試したコード:**\n\n```\n\n import pandas as pd\n import pandas_profiling as pdp\n import matplotlib.pyplot as plt\n import seaborn as sns\n \n tips = sns.load_dataset('tips')\n tips.groupby('day').count()\n \n```\n\n**結果:**\n\n[](https://i.stack.imgur.com/UkC18.png)",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T04:06:59.817",
"favorite_count": 0,
"id": "77563",
"last_activity_date": "2021-06-15T04:53:37.307",
"last_edit_date": "2021-06-15T04:53:37.307",
"last_editor_user_id": "3060",
"owner_user_id": "9008",
"post_type": "question",
"score": 1,
"tags": [
"python",
"pandas",
"seaborn"
],
"title": "group_by 後に count した時、必要なカラムのみ表示したい",
"view_count": 353
} | [
{
"body": "本家SOでいくつか書き方を見つけました。\n\n`reset_index`[例](https://stackoverflow.com/a/48770057)\n\n```\n\n tips.groupby('day').day.count().to_frame('count').reset_index()\n \"\"\" \n day count\n 0 Thur 62\n 1 Fri 19\n 2 Sat 87\n 3 Sun 76\n \"\"\" \n \n```\n\n`agg`[例](https://stackoverflow.com/a/29836715)\n\n```\n\n tips.groupby('day').agg(count = pd.NamedAgg(column = 'day', aggfunc = 'count'))\n \"\"\" \n count\n day\n Thur 62\n Fri 19\n Sat 87\n Sun 76\n \"\"\" \n \n```\n\nカラムを絞る[例](https://stackoverflow.com/a/54417351)\n\n```\n\n tips.groupby('day')['total_bill'].count()\n \"\"\" \n day\n Thur 62\n Fri 19\n Sat 87\n Sun 76\n Name: total_bill, dtype: int64\n \"\"\" \n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T04:31:06.140",
"id": "77564",
"last_activity_date": "2021-06-15T04:31:06.140",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "9820",
"parent_id": "77563",
"post_type": "answer",
"score": 1
}
] | 77563 | 77564 | 77564 |
{
"accepted_answer_id": "77568",
"answer_count": 1,
"body": "アンチウイルスソフトなどで、マルウェアや、悪意のあるプロセスなどを特定することができると思いますが、これをOSSを使って、コマンドラインでやる方法はありますか?",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T05:34:06.793",
"favorite_count": 0,
"id": "77566",
"last_activity_date": "2021-06-15T06:16:15.100",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "5025",
"post_type": "question",
"score": 0,
"tags": [
"macos",
"security"
],
"title": "MacOSのコマンドラインで、悪意のあるプロセスを特定する方法",
"view_count": 98
} | [
{
"body": "[ClamAV](https://www.clamav.net/)というクロスプラットフォームのアンチウィルスソフトならコマンドラインからの操作もできます。mac版はbrewでも提供されていたと思います。 \n私も昔使ったことがあるだけで、現在どこまでお望みの機能が含まれているかは把握していません。Webで検索すると、いろいろ使い方のヒントになるサイトがヒットしましたので、調べてみてはいかがでしょうか。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T06:16:15.100",
"id": "77568",
"last_activity_date": "2021-06-15T06:16:15.100",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "9515",
"parent_id": "77566",
"post_type": "answer",
"score": 0
}
] | 77566 | 77568 | 77568 |
{
"accepted_answer_id": "77572",
"answer_count": 2,
"body": "**試したコード**\n\n```\n\n import pandas as pd\n import matplotlib.pyplot as plt\n import seaborn as sns\n \n tips = sns.load_dataset('tips')\n tips['total_bill'].plot.bar()\n \n```\n\n**結果**\n\n[](https://i.stack.imgur.com/yOkgH.png)\n\n下記のように行数を制限すると読めています。\n\n```\n\n tips['total_bill'][:10].plot.bar()\n \n```\n\n**結果** \n[](https://i.stack.imgur.com/9fEbO.png)\n\nなにか良い方法はありますでしょうか?",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T06:06:14.073",
"favorite_count": 0,
"id": "77567",
"last_activity_date": "2021-06-15T07:30:49.667",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "9008",
"post_type": "question",
"score": 0,
"tags": [
"python",
"pandas",
"matplotlib",
"seaborn"
],
"title": "プロットの横軸が詰まって読めない",
"view_count": 227
} | [
{
"body": "例えばこんな感じで元のX軸ラベルを取得して、同数の空文字列配列に10個おきに値をコピーして再設定すれば、間引いて表示されるので見易くなるでしょう。\n\n```\n\n ax = tips['total_bill'].plot.bar()\n xlabels = ax.get_xticklabels()\n \n newlabels = [''] * len(xlabels)\n for i in range(0,len(xlabels),10):\n newlabels[i] = xlabels[i]\n \n ax.set_xticklabels(newlabels)\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T07:17:47.287",
"id": "77571",
"last_activity_date": "2021-06-15T07:17:47.287",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "26370",
"parent_id": "77567",
"post_type": "answer",
"score": 1
},
{
"body": "`MaxNLocator` を使う方法です。\n\n```\n\n ax = tips['total_bill'].plot.bar()\n ax.xaxis.set_major_locator(plt.MaxNLocator(len(tips)//20+1))\n plt.show()\n \n```\n\n[](https://i.stack.imgur.com/43RwB.png)",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T07:30:49.667",
"id": "77572",
"last_activity_date": "2021-06-15T07:30:49.667",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77567",
"post_type": "answer",
"score": 1
}
] | 77567 | 77572 | 77571 |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "`rails db:migrate` を実行すると以下のエラーが発生します。\n\n```\n\n rails aborted!\n ActiveRecord::StatementInvalid: Mysql2::Error: The user specified as a definer ('mysql.infoschema'@'localhost') does not exist\n /Users/yuzuki/environment/yuzuki_app/bin/rails:5:in `<top (required)>'\n /Users/yuzuki/environment/yuzuki_app/bin/spring:10:in `require'\n /Users/yuzuki/environment/yuzuki_app/bin/spring:10:in `block in <top (required)>'\n /Users/yuzuki/environment/yuzuki_app/bin/spring:7:in `<top (required)>'\n \n Caused by:\n Mysql2::Error: The user specified as a definer ('mysql.infoschema'@'localhost') does not exist\n /Users/yuzuki/environment/yuzuki_app/bin/rails:5:in `<top (required)>'\n /Users/yuzuki/environment/yuzuki_app/bin/spring:10:in `require'\n /Users/yuzuki/environment/yuzuki_app/bin/spring:10:in `block in <top (required)>'\n /Users/yuzuki/environment/yuzuki_app/bin/spring:7:in `<top (required)>'\n Tasks: TOP => db:migrate\n (See full trace by running task with --trace)\n \n```\n\n以下はdatabase.ymlです\n\n```\n\n default: &default\n adapter: mysql2\n encoding: utf8mb4\n pool: <%= ENV.fetch(\"RAILS_MAX_THREADS\") { 5 } %>\n username: root\n password: Yuzuki_1201\n host: localhost\n \n development:\n <<: *default\n database: yuzuki_app_development\n \n test:\n <<: *default\n database: yuzuki_app_test\n \n production:\n <<: *default\n database: yuzuki_app_production\n username: <%= ENV['DB_USERNAME'] %>\n password: <%= ENV['DB_PASSWORD'] %>\n \n```\n\n以下言語のバージョンです。\n\n・Ruby (3.0.1) \n・Ruby on Rails (6.1.3.2) \n・MySQL (8.0.25)\n\nこのエラーの原因と解決策を教えてくださると助かります。 \nよろしくお願いします。",
"comment_count": 6,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T07:44:57.287",
"favorite_count": 0,
"id": "77573",
"last_activity_date": "2021-06-16T00:39:52.903",
"last_edit_date": "2021-06-16T00:39:52.903",
"last_editor_user_id": "3060",
"owner_user_id": "46861",
"post_type": "question",
"score": 0,
"tags": [
"ruby-on-rails",
"mysql"
],
"title": "rails db:migrate をすると「Mysql2::Error: The user specified as a definer」というエラー",
"view_count": 211
} | [] | 77573 | null | null |
{
"accepted_answer_id": "77575",
"answer_count": 1,
"body": "[早く知っておきたかったmatplotlibの基礎知識、あるいは見た目の調整が捗るArtistの話 -\nQiita](https://qiita.com/skotaro/items/08dc0b8c5704c94eafb9) \nを読んでいます。\n\n> print('ax.xaxis:', ax.xaxis)\n\nとなっており、私も実際に下記のコードを書いて動くことを確かめました。\n\n```\n\n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n print('ax.xaxis:', ax.xaxis)\n \n```\n\n結果:\n\n```\n\n ax.xaxis: XAxis(54.0,36.0)\n \n```\n\nより詳細なことを見に行こうと\n\n<https://matplotlib.org/stable/api/axes_api.html>\n\nを見たところ\n\n```\n\n Attributes: \n dataLimBbox:\n The bounding box enclosing all data displayed in the Axes.\n \n viewLimBbox:\n The view limits in data coordinates.\n \n```\n\nとなっており、てっきり Attributes に `XAxis` についての記述があるかと思ったのですが載っていません。\n\n親クラスは、`_AxesBase` のようですが、ソースコードが掲載されているページしか見つけられませんでした。 \n<https://matplotlib.org/stable/_modules/matplotlib/axes/_base.html>\n\nまた参考資料に下記のように`AxesSubplot`についての言及があります。\n\n> AxesSubplotはplt.subplotsで作った場合のAxesオブジェクトと思って問題ありません。\n\nこの`AxesSubplot`ドキュメントなら何か記載があるかと思ったのですが、ドキュメントどころかソースコードのページも見つかりません(もしかしたらGitHubをあされば見つかるのかも?)\n\nそもそも、実際に私も色々表示させてみると `AxesSubplot` というは見たことありますが、`Axes`と表示されているのは見たことがありません。\n\nオブジェクトが持っているインスタンス変数やメソッドの一覧が見れないと、ソースコードを書くのが結構きついです。 \nドキュメントにどこか記載されていないものでしょうか?\n\n質問タイトルについて: \nよく使われる変数名`ax`に本来は`AxesSubplot`が入っているのでしょうが、`AxesSubplot`と`Axes`の違いも理解があやふやなので、なんと書いていいかわからず、一般的に使われている変数名`ax`を使用しています。\n\n* * *\n\n追記: \n質問背景としては、x軸の設定方法が`ax`から直接する方法と、`ax`の`xaxis`を使う方法の2種類の方法がネットにあるようだからです。\n\n例1\n\n```\n\n import pandas as pd\n import matplotlib.pyplot as plt\n import seaborn as sns\n \n tips = sns.load_dataset('tips')\n count_df = tips.groupby('day').day.count().to_frame('count').reset_index()\n \n ax = count_df.plot.bar()\n ax.set_xticklabels(count_df.day) # <--- axから直接ティックラベル設定\n \n```\n\n例2\n\n```\n\n ...\n ax.xaxis.set_ticklabels(count_df.day) # <--- axのxaxisからティックラベル設定\n ...\n \n```\n\nさらにgetterでxaxisを取得して設定する 例3(この方法はネットで見かけたことがない気がする)\n\n```\n\n ...\n ax.get_xaxis().set_ticklabels(count_df.day) # <--- getterで取得してからティックラベル設定\n ...\n \n```\n\n`オブジェクト指向インタフェース`というからにはオブジェクトごとに役割が決まっているのかと思ったのですが、`ax`から直接X軸の設定ができたり混乱する要素が多いです(まあこれはこれでそこまで変な設計ではないと思いますが)。\n\n私にはプロパティでX軸にアクセスする `ax.xaxis.set_ticklabels(count_df.day)`\nの書き方が、1番自然と感じられたのですが、ドキュメントには\n`xaxis`プロパティの記載がなく、このように`xaxis`プロパティに直接アクセスしていいもののか?とすこし疑問に思ったからです(ドキュメントに記載がなくてもアクサスできちゃうのであればアクセスしても何の問題もないとは思いますが)。\n\nきっと、私がまだ`matplotlib`のドキュメントに慣れておらず、`AxesSubplot`のドキュメント(あるのであれば)や、`_AxesBase`といった親クラスに`xaxis`プロパティの存在が記載されているのではないかと推測していました。",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T07:55:41.757",
"favorite_count": 0,
"id": "77574",
"last_activity_date": "2021-06-15T09:39:05.550",
"last_edit_date": "2021-06-15T09:37:49.890",
"last_editor_user_id": "9008",
"owner_user_id": "9008",
"post_type": "question",
"score": 0,
"tags": [
"python",
"matplotlib"
],
"title": "axがxaxisを持っていることについてドキュメントに記載がない",
"view_count": 172
} | [
{
"body": "その参照している [matplotlib.axes](https://matplotlib.org/stable/api/axes_api.html)\nのページに色々と出てきていますが、それらのことでは不足なのでしょうか?\n\n* * *\n\n例えば最初の方の説明(太字化は回答者)\n\n> The Axes contains most of the figure elements: **Axis** , Tick, Line2D,\n> Text, Polygon, etc., and sets the coordinate system.\n\n> sharex, sharey : **Axes** , optional \n> The **x or y axis** is shared with the **x or y axis** in the input Axes.\n\nあるいは下の方の表?にいくつも`axis`が出てきます。\n\n> [Text and annotations](https://matplotlib.org/stable/api/axes_api.html#text-\n> and-annotations)\n\n> [Appearance](https://matplotlib.org/stable/api/axes_api.html#appearance)\n\n> [Axis / limits](https://matplotlib.org/stable/api/axes_api.html#axis-limits)\n\nここの最初に以下があり、AxesからXAxisが取得出来るようです。\n\n> Axes.get_xaxis Return the XAxis instance.\n\n以後の表にもいっぱいaxisが出てきています。\n\n* * *\n\n`X`とか`Y`の付かない`Axis`の説明はこちらのページで、これを継承して`XAxis`があるという図になっています。 \n[matplotlib.axis](https://matplotlib.org/stable/api/axis_api.html)\n\n* * *\n\nコメントに対して:\n\n最初に参照している\n[早く知っておきたかったmatplotlibの基礎知識、あるいは見た目の調整が捗るArtistの話](https://qiita.com/skotaro/items/08dc0b8c5704c94eafb9)\nの記事で、[Figure, Axes,\nAxisは階層構造になっている](https://qiita.com/skotaro/items/08dc0b8c5704c94eafb9#figure-\naxes-\naxis%E3%81%AF%E9%9A%8E%E5%B1%A4%E6%A7%8B%E9%80%A0%E3%81%AB%E3%81%AA%E3%81%A3%E3%81%A6%E3%81%84%E3%82%8B)\nの部分に、そうしたアクセスの例が記述されています。\n\n>\n```\n\n> fig = plt.figure()\n> ax = fig.add_subplot(1,1,1) # 何もプロットしていないAxesでもAxisは自動的に作られる\n> print('fig.axes:', fig.axes)\n> print('ax.figure:', ax.figure)\n> print('ax.xaxis:', ax.xaxis)\n> print('ax.yaxis:', ax.yaxis)\n> print('ax.xaxis.axes:', ax.xaxis.axes)\n> print('ax.yaxis.axes:', ax.yaxis.axes)\n> print('ax.xaxis.figure:', ax.xaxis.figure)\n> print('ax.yaxis.figure:', ax.yaxis.figure)\n> print('fig.xaxis:', fig.xaxis)\n> \n```\n\nその次の\n[グラフに表示されているものは全てArtist](https://qiita.com/skotaro/items/08dc0b8c5704c94eafb9#%E3%82%B0%E3%83%A9%E3%83%95%E3%81%AB%E8%A1%A8%E7%A4%BA%E3%81%95%E3%82%8C%E3%81%A6%E3%81%84%E3%82%8B%E3%82%82%E3%81%AE%E3%81%AF%E5%85%A8%E3%81%A6artist)\nのところで、データ構造の階層図の直後にこう書かれています。\n\n>\n> 前項のサンプルコードの結果を見るとわかりますが、Axisは実際にはXAxisとYAxisという名前です。Axisの下にはさらTickという目盛り関連の線や文字のためのcontainerがあります。containerはその名の通りprimitiveを入れる箱を持っています。このとき、containerの階層構造にあった「一つしか持てない」という制限はなく、いくつでもおなじprimitiveを持つことができます。\n\nそしてmatplotlibの\n[Appearance](https://matplotlib.org/stable/api/axes_api.html#appearance)\nの表にある以下が、「Axisは実際にはXAxisとYAxisという名前です。」を表しているのかもしれません。 \n(同じく太字化は回答者)\n\n> **Axes.axis Convenience method to get or set some axis properties.**\n\nそれだと、確かに公式ドキュメントでは端折りすぎていて説明不足な感じですね。 \n今のところ明確には書かれていない感じでしょうか。\n\n* * *\n\nちなみに他にこんな記事があります。 \n[matplotlibのめっちゃまとめ](https://qiita.com/nkay/items/d1eb91e33b9d6469ef51) \n[6\\.\n軸の設定](https://qiita.com/nkay/items/d1eb91e33b9d6469ef51#6-%E8%BB%B8%E3%81%AE%E8%A8%AD%E5%AE%9A)\n\n> グラフの軸は、横軸Axes.xaxisと縦軸Axes.yaxisと、グラフの枠Axes.spinesでできている。\n\n以後の説明で`ax.xaxis.xxxx`というのがいっぱい使われています。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T08:49:15.707",
"id": "77575",
"last_activity_date": "2021-06-15T09:39:05.550",
"last_edit_date": "2021-06-15T09:39:05.550",
"last_editor_user_id": "26370",
"owner_user_id": "26370",
"parent_id": "77574",
"post_type": "answer",
"score": 2
}
] | 77574 | 77575 | 77575 |
{
"accepted_answer_id": "77593",
"answer_count": 1,
"body": "### やりたいこと\n\ngmailに複数の未読メールがあっても一つだけを読み込みたいです。 \n現在は下記のコードだと全ての未読メールが読み込まれます。 \n一つだけを読み込みするため、どのように指定すればよろしいでしょうか。\n\n```\n\n import imaplib, re, email, six, dateutil.parser\n \n mail=imaplib.IMAP4_SSL('example.gmail.com',993) #SMTPは993,POPは995\n mail.login('example@jp','exam123')\n mail.select('example.jp') #メールボックスの選択\n \n #UNSEEN未読メールを読み込む\n type,data=mail.search(None,'UNSEEN') #メールボックス内にあるすべてのデータを取得ALL\n \n for i in data[0].split(): #data分繰り返す\n ok,x=mail.fetch(i,'RFC822') #メールの情報を取得\n ms=email.message_from_string(x[0][1].decode('iso-2022-jp')) #パースして取得\n \n #差出人を取得\n ad=email.header.decode_header(ms.get('From'))\n ms_code=ad[0][1]\n if(ms_code!=None):\n address=ad[0][0].decode(ms_code)\n address+=ad[1][0].decode(ms_code)\n else:\n address=ad[0][0]\n \n #タイトルを取得\n sb=email.header.decode_header(ms.get('Subject'))\n ms_code=sb[0][1]\n if(ms_code!=None):\n sbject=sb[0][0].decode(ms_code)\n else:\n ms_code=sb[1][1]\n sbject=sb[1][0].decode(ms_code)\n \n #本文を取得\n maintext=ms.get_payload()\n \n mail.store(i,'+FLAGS', '\\\\Seen')\n \n #メールの日時を取得\n time = dateutil.parser.parse(ms.get('Date')).strftime(\"%Y-%m-%d %H:%M\")[:-1]\n print(time)\n \n #出力\n print(sbject)\n print(address)\n print(maintext)\n \n mail.close()\n mail.logout()\n \n```",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T09:23:39.520",
"favorite_count": 0,
"id": "77576",
"last_activity_date": "2021-06-16T06:51:21.457",
"last_edit_date": "2021-06-16T06:51:21.457",
"last_editor_user_id": "3060",
"owner_user_id": "18859",
"post_type": "question",
"score": 0,
"tags": [
"python",
"python3",
"gmail"
],
"title": "imaplib モジュールで未読メールを指定件数のみ読み込みたい",
"view_count": 562
} | [
{
"body": "単純にfor文の末尾で`break`する方法で対応可能です。\n\nまたはfor文を使わずに`ok,x=mail.fetch(i,'RFC822')`を \n`ok,x=mail.fetch(data[0].split()[0], 'RFC822')`に書き換える方法もあります。\n\n本家SOの類似質問 \n[Python imaplib: get the first unread\nemail](https://stackoverflow.com/q/66401210)\n\n※[コメント](https://ja.stackoverflow.com/questions/77576/imaplib-%e3%83%a2%e3%82%b8%e3%83%a5%e3%83%bc%e3%83%ab%e3%81%a7%e6%9c%aa%e8%aa%ad%e3%83%a1%e3%83%bc%e3%83%ab%e3%82%92%e6%8c%87%e5%ae%9a%e4%bb%b6%e6%95%b0%e3%81%ae%e3%81%bf%e8%aa%ad%e3%81%bf%e8%be%bc%e3%81%bf%e3%81%9f%e3%81%84#comment87676_77576)を回答化しました。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T04:23:30.413",
"id": "77593",
"last_activity_date": "2021-06-16T06:50:54.483",
"last_edit_date": "2021-06-16T06:50:54.483",
"last_editor_user_id": "3060",
"owner_user_id": "9820",
"parent_id": "77576",
"post_type": "answer",
"score": 3
}
] | 77576 | 77593 | 77593 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "vscodeでpdbの挙動を調べるのに以下のようなコードをつかって、遊んでいました。 \n下から二行目のprint(\"start\")にブレークポイントをもってきてスタートさせ、 \nstep intoで進んでいきます。 \na=100のあと、print(a)にカーソルが来たときに、 \nGUI操作で、a=1000とすると、いったんは、数字が更新されますが、すぐに100に戻ってしまいます。(更新されていない?) \nそもそもDEBUG CONSOLEからだと、グローバル変数を更新できません。 \npdbにおいて、関数内において、DEBUG CONSOLEなどを使って、グローバル変数に値を入力したり、更新する方法はあるのでしょうか?\n\n```\n\n def main():\n global a\n a=100\n print(a)\n func1()\n \n \n def func1():\n b=200\n print(b)\n func2()\n \n def func2(): \n c=300\n print(c)\n func3()\n \n def func3():\n d=400\n print(d)\n \n print(\"start\")\n main()\n \n \n```",
"comment_count": 8,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T12:29:11.040",
"favorite_count": 0,
"id": "77582",
"last_activity_date": "2021-06-23T00:10:16.737",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "40961",
"post_type": "question",
"score": 0,
"tags": [
"python"
],
"title": "pythonのデバッガー(pdb)において、関数スコープ内でglobal変数をいじっても、維持されませんか?",
"view_count": 308
} | [
{
"body": "`main()` の中の `print` にさしかかったときに、デバッグコンソールから `global a;a=1000`\nとしても反映されませんし、単にVARIABLES枠で `a:100⇛1000` に修正しても、`print` 関数のアウトプットには反映されません。\n\nCALL\nSTACK枠で、対象となるスタックフレーム(今回のように関数の階層になっている場合どのレベルにいるか、グローバル変数なら一番外。)に変更してから上記を入力する必要があります。\n\n[](https://i.stack.imgur.com/HjevY.jpg)",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T11:08:09.530",
"id": "77629",
"last_activity_date": "2021-06-23T00:10:16.737",
"last_edit_date": "2021-06-23T00:10:16.737",
"last_editor_user_id": "3060",
"owner_user_id": "40961",
"parent_id": "77582",
"post_type": "answer",
"score": 0
}
] | 77582 | null | 77629 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "PHP初心者です。\n\nある変数TestPosition \nAの配列Arrayに含まれる数値なら A \n同様に Bの配列に含まれるなら B \nを返すような関数を作りたいと思っています。\n\n下記のように `in_array` で判定できるかとテストを行ったのですが、エラーが出ます。\n\n**エラーメッセージ:**\n\n```\n\n Use of undefined constant A_CERTAIN_AREA_A_ARRAY - assumed 'A_CERTAIN_AREA_A_ARRAY' (this will throw an Error in a future version of PHP)\n \n```\n\n宣言しているのに undefined constant と言われるのがよくわかりません\n\nまた将来のphpのバージョンでは定数はエラーとして扱われてしまうのでしょうか?\n\n```\n\n class TEST {\n const A_CERTAIN_AREA_A_ARRAY = [1,11,13];\n const A_CERTAIN_AREA_B_ARRAY = [2,22,23];\n const A_CERTAIN_AREA_C_ARRAY = [3,23,53];\n \n public function index(Request $request)\n {\n $testPosition = 3;\n Log::debug(\":\".\"テスト\",in_array($testPosition, A_CERTAIN_AREA_A_ARRAY, true));\n return view('index');\n }\n }\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T12:48:34.163",
"favorite_count": 0,
"id": "77583",
"last_activity_date": "2021-06-15T16:42:11.127",
"last_edit_date": "2021-06-15T16:42:11.127",
"last_editor_user_id": "3060",
"owner_user_id": "44839",
"post_type": "question",
"score": 0,
"tags": [
"php",
"laravel"
],
"title": "PHPで、ある数字が特定の配列の値に含まれるかの判定を行いたい",
"view_count": 99
} | [
{
"body": "クラス定数を参照するには定数名だけでは不十分です。 \n`self::A_CERTAIN_AREA_A_ARRAY` のようにしてクラスを特定してください。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T13:17:48.883",
"id": "77584",
"last_activity_date": "2021-06-15T13:17:48.883",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "9464",
"parent_id": "77583",
"post_type": "answer",
"score": 0
}
] | 77583 | null | 77584 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "大学の課題で、以下のような問題が出題されました。\n\n> 情報隠蔽を行うために メソッドpublic void setColor(java.awt.Color c)を追加した TurtleTrap4\n> クラスを作成せよ. \n> さらに,mainメソッドで TurtleTrap4 クラスのオブジェクトを作成して,\n> setColorメソッドを呼び出してペンの色を変えるように変更せよ.\n\nそこで、私は以下のようにプログラムしましたが、エラーが出力されてしまいました。\n\n```\n\n public class TurtleTrap4 {\n Turtle t;\n int x, y;\n int dx, dy;\n \n public void init(int xpos, int ypos, int xspeed, int yspeed) {\n this.x = xpos;\n this.y = ypos;\n this.dx = xspeed;\n this.dy = yspeed;\n this.t = new Turtle();\n this.t.move(xpos, ypos);\n this.t.penDown();\n }\n \n public void setColor(java.awt.Color c)\n \n public void step() {\n if (this.x < 20 || 340 < this.x)\n this.dx = -this.dx;\n if (this.y < 20 || 340 < this.y)\n this.dy = -this.dy;\n \n this.x += this.dx;\n this.y += this.dy;\n this.t.move(this.x, this.y);\n }\n \n public static void main(String[] args) {\n TurtleTrap4 trapA = new TurtleTrap4();\n trapA.init(100, 200, 10, 5);\n \n TurtleTrap4 trapB = new TurtleTrap4();\n trapB.init(150, 250, -10, 3);\n setColor(RED);\n \n \n \n while (true) {\n trapA.step();\n trapB.step();\n }\n }\n }\n \n```\n\nエラーメッセージ\n\n```\n\n TurtleTrap4.java:17: エラー: ';'がありません\n public void setColor(java.awt.Color c)\n ^\n エラー1個\n \n```\n\nこれはどういう意味なのでしょうか。\n\n私は、javaを先週から授業で始めたばかりの初心者で、文法など理解していない点は多々あると思いますが、どこを修正するべきか教えていただけるととても助かります。 \n(主に、 public void setColor(java.awt.Color\nc)をどのようにプログラムすればいいかをヒントでもいいので、教えていただけるととても助かります。)\n\nよろしくお願いします。",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T14:21:12.983",
"favorite_count": 0,
"id": "77585",
"last_activity_date": "2021-06-19T12:01:20.613",
"last_edit_date": "2021-06-15T16:29:23.720",
"last_editor_user_id": "3060",
"owner_user_id": "46879",
"post_type": "question",
"score": -3,
"tags": [
"java"
],
"title": "javaの情報隠蔽プログラム",
"view_count": 358
} | [
{
"body": "質問文中のコードにはメソッドのボディが無いためコンパイルエラーになっています。\n\nメソッドの宣言にはメソッドのボディ([8.4. Method\nDeclarations](https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-8.4))が必要で、メソッドのボディとは、セミコロン(`;`)かコードブロック(`{}`)のこと([8.4.7.\nMethod\nBody](https://docs.oracle.com/javase/specs/jls/se11/html/jls-8.html#jls-\nMethodBody))です。\n\n* * *\n\n`setColor`メソッドはこのクラスで実装する想定だと思いますので、(セミコロンでなく)コードブロックを追記します。\n\nつまり、次のような形になります:\n\n```\n\n public static void setColor(java.awt.Color c) {\n // ここにメソッドが呼ばれたときの処理を実装する\n }\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-19T12:01:20.613",
"id": "77653",
"last_activity_date": "2021-06-19T12:01:20.613",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "2808",
"parent_id": "77585",
"post_type": "answer",
"score": 1
}
] | 77585 | null | 77653 |
{
"accepted_answer_id": "77592",
"answer_count": 1,
"body": "[ブラウザで開いてるページの ajax 通信の内容をローカルファイルに残したい](https://ja.stackoverflow.com/q/76026)\n\n前回の質問でも同様の質問をしたんですが \nブラウジング中のパケットをキャプチャして \n特定の通信内容が現れたらアラートを鳴らしたりするようなツールを作りたいです\n\n* * *\n\n以前やってたゲームでこんな拡張機能があって\n\n<https://chrome.google.com/webstore/detail/chrome%E9%8E%AE%E5%AE%88%E5%BA%9C/hcjpbcmhppmlohedljpeagnjplpjonhc?hl=ja>\n\nディベロッパーツール自体にメニューを追加して \n通信パケット内容を覗き見て内容によって表示を変えるみたいになっています\n\nディベロッパーツールにメニューを追加したり \nパケット情報を取得したりするのってどういう技術でできるんでしょうか\n\nディベロッパーツールカスタマイズとかで調べてもでてこないので \n入門的な記事やドキュメント等を紹介をしていただけると助かります",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-15T16:39:56.650",
"favorite_count": 0,
"id": "77586",
"last_activity_date": "2021-06-16T03:58:01.113",
"last_edit_date": "2021-06-15T16:47:19.823",
"last_editor_user_id": "3060",
"owner_user_id": null,
"post_type": "question",
"score": 0,
"tags": [
"google-chrome-devtools"
],
"title": "chrome ディベロッパツールのカスタマイズ方法",
"view_count": 85
} | [
{
"body": "Chrome の拡張機能の中で開発者ツールの拡張が可能です。 \n<https://developer.chrome.com/docs/extensions/mv3/devtools/>",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T03:58:01.113",
"id": "77592",
"last_activity_date": "2021-06-16T03:58:01.113",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "3475",
"parent_id": "77586",
"post_type": "answer",
"score": 1
}
] | 77586 | 77592 | 77592 |
{
"accepted_answer_id": null,
"answer_count": 3,
"body": "mediawikiをインストール、ショートURLのためにnginxを設定中。\n\n<https://www.mediawiki.org/wiki/Manual:Short_URL/Nginx/ja> \n公式のサンプルコード(Manual:Short URL/Nginx/ja)を元に \n/etc/nginx/conf.d/mediawiki.confに以下のような設定。\n\n```\n\n server {\n server_name example.com;\n root /home/taro/mediawiki;\n \n # Location for wiki's entry points\n location ~ ^/(index|load|api|thumb|opensearch_desc|rest|img_auth)\\.php$ {\n include /etc/nginx/fastcgi_params;\n fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n fastcgi_pass 127.0.0.1:9000;\n }\n \n # Images\n location /w/images {\n # Separate location for images/ so .php execution won't apply\n }\n location /w/images/deleted {\n # Deny access to deleted images folder\n deny all;\n }\n # MediaWiki assets (usually images)\n location ~ ^/w/resources/(assets|lib|src) {\n try_files $uri 404;\n add_header Cache-Control \"public\";\n expires 7d;\n }\n # Assets, scripts and styles from skins and extensions\n location ~ ^/w/(skins|extensions)/.+\\.(css|js|gif|jpg|jpeg|png|svg|wasm)$ {\n try_files $uri 404;\n add_header Cache-Control \"public\";\n expires 7d;\n }\n # Favicon\n location = /favicon.ico {\n alias /w/images/6/64/Favicon.ico;\n add_header Cache-Control \"public\";\n expires 7d;\n }\n \n # License and credits files\n location ~ ^/w/(COPYING|CREDITS) {\n default_type text/plain;\n }\n \n \n # Handling for Mediawiki REST API, see [[mw:API:REST_API]]\n location /w/rest.php/ {\n try_files $uri $uri/ /w/rest.php?$query_string;\n }\n \n ## Uncomment the following code for handling image authentication\n ## Also add \"deny all;\" in the location for /w/images above\n #location /w/img_auth.php/ {\n # try_files $uri $uri/ /w/img_auth.php?$query_string;\n #}\n \n # Handling for the article path (pretty URLs)\n location /wiki/ {\n rewrite .* /index.php;\n }\n \n # Allow robots.txt in case you have one\n location = /robots.txt {\n }\n # Explicit access to the root website, redirect to main page (adapt as needed)\n location = / {\n return 301 /wiki/メインページ;\n }\n \n # Every other entry point will be disallowed.\n # Add specific rules for other entry points/images as needed above this\n location / {\n return 404;\n }\n }\n \n```\n\nブラウザで \n`http://example.com` \nにアクセスすると \n`http://example.com/wiki/メインページ` \nへリダイレクトされる。\n\n`http://example.com/index.php?title=メインページ` \nへアクセスしても全く同じページが表示される。\n\nmediawiki.confの設定を解読中なのですが、なぜそういう動きになるのか理解できず。 \n多段階で内部リダイレクトが発生していると思うのですが、自分の理解とnginxの動きが一致しているのか確認するため、どのlocationディレクティブが適用されているのかを知りたいです。\n\n現状の自分の理解は以下の通りです。\n\nブラウザで \n`http://example.com` \nにアクセスすると\n\n```\n\n # Explicit access to the root website, redirect to main page (adapt as needed)\n location = / {\n return 301 /wiki/メインページ;\n }\n \n```\n\nが適用され \n`http://example.com/wiki/メインページ` \nにリダイレクトされる。 \n(ブラウザ上でのURLも`http://example.com/wiki/メインページ`になる)\n\nさらに\n\n```\n\n # Handling for the article path (pretty URLs)\n location /wiki/ {\n rewrite .* /index.php;\n }\n \n```\n\nが適用され \n`http://example.com/index.php` \nに内部リダイレクトされる。 \n(`/メインページ`という情報が消えてしまう?)\n\nブラウザ上での表示は`http://example.com/wiki/メインページ`のまま。\n\nさらに\n\n```\n\n # Location for wiki's entry points\n location ~ ^/(index|load|api|thumb|opensearch_desc|rest|img_auth)\\.php$ {\n include /etc/nginx/fastcgi_params;\n fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n fastcgi_pass 127.0.0.1:9000; # or whatever port your PHP-FPM listens on\n }\n \n```\n\nが適用され \n`/home/taro/mediawiki/index.php` \nがcgiで実行される。 \n(`/メインページ`という情報はどうなった?)\n\n以下の2つのURLで同じページが表示されるので \n`http://example.com/wiki/メインページ` \n`http://example.com/index.php?title=メインページ`\n\n`/wiki/メインページ`というパスが \n`?title=メインページ`というクエリに変換されて \n`/home/taro/mediawiki/index.php`に引き渡されているのだと思うのですが、なぜそうなるのか分かりません。\n\n```\n\n # Handling for the article path (pretty URLs)\n location /wiki/ {\n rewrite .* /index.php;\n }\n \n```\n\nを経由すると`/メインページ`の情報が消えてしまうように感じるので、 \nそもそもこのlocationディレクティブを経由しているという認識が間違っているのかも?\n\nということで、nginxの内部リダイレクトでどのlocationディレクティブがどういう順序で適用されているのかを正確にトレースしたいです。\n\nnginxの.confの中にprintf()だとかconsole.log()だとか、echoだとかを書いて、ログにメッセージを残すみたいなことはできないのでしょうか?\n\n`/var/log/nginx/access.log` \nを確認したところ \n`/wiki/メインページ` \nへのアクセスのみが記録されているように思います。 \n(細かいログが他にも記録されているが、おそらくcssや画像などのロードが記録されているだけ)",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T00:38:57.457",
"favorite_count": 0,
"id": "77588",
"last_activity_date": "2021-06-17T01:42:58.927",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "45540",
"post_type": "question",
"score": 2,
"tags": [
"php",
"正規表現",
"nginx",
"url",
"cgi"
],
"title": "nginx、どのlocationディレクティブが適用されたかデバッグするには?",
"view_count": 931
} | [
{
"body": "> `/wiki/メインページ` というパスが `?title=メインページ` というクエリに変換されて\n> `/home/taro/mediawiki/index.php` に引き渡されているのだと思うのですが、なぜそうなるのか分かりません。\n\n実は `REQUEST_URI` から自動的に `PATH_INFO` に相当する部分(`メインページ`) を取り出しているのです。\n\n[リリースノート/1.20 -\nMediaWiki](https://www.mediawiki.org/wiki/Release_notes/1.20/ja#MediaWiki_1.20.0)\n\n**Configuration changes**\n\n> `$wgUsePathInfo = true;` is no longer needed to make `$wgArticlePath` work\n> on servers using like nginx, lighttpd, and apache over fastcgi. **MediaWiki\n> now always extracts path info from REQUEST_URI** if it's available.\n\n前回の質問に対する回答で言及した古い `nginx.conf` から `PATH_INFO` の設定が削除されていたのはこのためなのではないかと思います。\n\n[https://www.mediawiki.org/w/index.php?title=Manual:Short_URL/Nginx&oldid=3103792](https://www.mediawiki.org/w/index.php?title=Manual:Short_URL/Nginx&oldid=3103792)\n\n```\n\n location /wiki/ {\n rewrite ^/wiki/(?<pagename>.*)$ /w/index.php;\n include /etc/nginx/fastcgi_params;\n # article path should always be passed to index.php\n fastcgi_param SCRIPT_FILENAME $document_root/w/index.php;\n fastcgi_param PATH_INFO $pagename;\n fastcgi_param QUERY_STRING $query_string;\n fastcgi_pass 127.0.0.1:9000; # or whatever port your PHP-FPM listens on\n }\n \n```",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T03:01:21.647",
"id": "77591",
"last_activity_date": "2021-06-16T03:01:21.647",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77588",
"post_type": "answer",
"score": 4
},
{
"body": "以下の3つのlocationディレクティブ、1つずつコメントアウトして実験しました。\n\n```\n\n # Explicit access to the root website, redirect to main page (adapt as needed)\n location = / {\n return 301 /wiki/メインページ;\n }\n \n```\n\n```\n\n # Handling for the article path (pretty URLs)\n location /wiki/ {\n rewrite .* /index.php;\n }\n \n```\n\n```\n\n # Location for wiki's entry points\n location ~ ^/(index|load|api|thumb|opensearch_desc|rest|img_auth)\\.php$ {\n include /etc/nginx/fastcgi_params;\n fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n fastcgi_pass 127.0.0.1:9000; # or whatever port your PHP-FPM listens on\n }\n \n```\n\n`location = /`だけをコメントアウトした場合。\n\n`http://example.com`にアクセスるすると404 Not Found。 \n`http://example.com/wiki/メインページ`へのリダイレクトが発生しない。\n\n`http://example.com/wiki/メインページ`に直接アクセスするとメインページが正常に表示される。 \n`http://example.com/index.php?title=メインページ`に直接アクセスするとメインページが正常に表示される。\n\n* * *\n\n`location /wiki/`だけをコメントアウトした場合。\n\n`http://example.com`は \n`http://example.com/wiki/メインページ`へリダイレクトされた後、404 Not Found。\n\n`http://example.com/wiki/メインページ`に直接アクセスした場合も404 Not Found。\n\n`http://example.com/index.php?title=メインページ`はページが表示される。\n\n* * *\n\n`location ~\n^/(index|load|api|thumb|opensearch_desc|rest|img_auth)\\.php$`だけをコメントアウトした場合。\n\n`http://example.com` \n`http://example.com/wiki/メインページ` \n`http://example.com/index.php?title=メインページ` \n3つのURLですべて404 Not Found。\n\n* * *\n\nlocationディレクティブの適用順序は、\n\n 1. `location = /`\n 2. `location /wiki/`\n 3. `location ~ ^/(index|load|api|thumb|opensearch_desc|rest|img_auth)\\.php$`\n\nの順序で間違いなさそう。 \n(段階的に404 Not FoundになるURLが増えるから)\n\nコメントアウトしながら現象を観測する以外に、 \nどのディレクティブがどの順序で適用されたかを明確に把握する方法をご存知の方がいたら情報ください。\n\n* * *\n\nリダイレクトされるURLは、\n\n`http://example.com` \n↓ 外部リダイレクト \n`http://example.com/wiki/メインページ` \n↓ 内部リダイレクト \n`http://example.com/index.php?title=メインページ`\n\nという動きだと思っていたけど、\n\n`http://example.com` \n↓ 外部リダイレクト \n`http://example.com/wiki/メインページ` \n↓ 内部リダイレクト \n`http://example.com/index.php`\n\nという動きをしているっぽい。\n\n`REQUEST_URI`に`/wiki/メインページ`というテキストがセットされて、`index.php`の中で利用されているっぽい。 \n`index.php`のソース中には`$_SERVER['REQUEST_URI']`は使われていないが、`index.php`で`require`しているファイルの中のどれかで使っていると思われる。\n\n最終的に \n`http://example.com/index.php`に内部リダイレクトされるとしたら、 \n`REQUEST_URI`の値は`/index.php`になるんじゃないの? \nなぜ中間の`/wiki/メインページ`が採用されるの?\n\n多段的にリダイレクトされた場合、REQUEST_URIがどのように決定されるのか、誰か教えてください。 \nたぶん、外部リダイレクトと内部リダイレクトの違いだと思うけど、自力ではドキュメントを見つけられず。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T13:39:11.590",
"id": "77599",
"last_activity_date": "2021-06-16T13:39:11.590",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "45540",
"parent_id": "77588",
"post_type": "answer",
"score": 1
},
{
"body": "nginxに任意のログメッセージを出力する方法。\n\n`/etc/nginx/nginx.conf` \nに以下の1行を追加。\n\n`log_format mydebug \"[MYDEBUG][$time_local] $request_uri, dbg1:$dbg1\ndbg2:$dbg2 dbg3:$dbg3\";`\n\n(mydebug や $dbg1 は任意の文字列)\n\n`/etc/nginx/conf.d/mediawiki.conf` \nに下記の3か所で`set ~~`と`access_log ~~`を追加.\n\n```\n\n # Location for wiki's entry points\n location ~ ^/(index|load|api|thumb|opensearch_desc|rest|img_auth)\\.php$ {\n \n set $dbg1 $msec;\n access_log /var/log/nginx/mydebug.log mydebug;\n \n include /etc/nginx/fastcgi_params;\n fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;\n fastcgi_pass 127.0.0.1:9000; # or whatever port your PHP-FPM listens on\n }\n \n```\n\n```\n\n # Handling for the article path (pretty URLs)\n location /wiki/ {\n \n set $dbg2 $msec;\n access_log /var/log/nginx/mydebug.log mydebug;\n \n rewrite .* /index.php;\n }\n \n```\n\n```\n\n # Explicit access to the root website, redirect to main page (adapt as needed)\n location = / {\n \n set $dbg3 $msec;\n access_log /var/log/nginx/mydebug.log mydebug;\n \n return 301 /wiki/メインページ;\n }\n \n```\n\n`mydebug.log`を確認すると以下のようなログが確認できる。\n\n> [MYDEBUG][17/Jun/2021:09:51:09 +0900] /, dbg1: dbg2: dbg3:1623891069.090 \n> [MYDEBUG][17/Jun/2021:09:51:09 +0900]\n> /wiki/%E3%83%A1%E3%82%A4%E3%83%B3%E3%83%9A%E3%83%BC%E3%82%B8,\n> dbg1:1623891069.100 dbg2:1623891069.100 dbg3:\n\n`$request_uri`が`/`、 \n`dbg3`にタイムスタンプが入ったログがまず記録される。\n\n`location = /`のディレクティブが最初に適用されていることが確定。\n\n`$request_uri`が`/wiki/%E3%83%A1%E3%82%A4%E3%83%B3%E3%83%9A%E3%83%BC%E3%82%B8`(/wiki/メインページ),\n`dbg1`と`dbg2`にタイムスタンプが入ったログが次に記録される。\n\n`dbg1`と`dbg2`のタイムスタンプは同じ値。 \n`dbg1`と`dbg2`どちらが先かは分からないが、連続して処理されているっぽい。\n\nログが3行分記録されることを期待していたが、2行しかない。\n\n`dbg2`の方の`access_log ~~`はコメントアウトしても、ログの出力に影響なし。 \n`dbg1`側の`access_log ~~`だけ採用されて、`dbg2`側の`access_log ~~`は使われていないみたい。\n\n`rewrite`(内部リダイレクト)の場合、最終的にたどりついたlocationディレクティブで`access_log`が記録されると思われる。\n\n* * *\n\nREQUEST_URIの話。\n\n`http://example.com` \n↓ \n`http://example.com/wiki/メインページ` \n↓ \n`http://example.com/index.php`\n\nという1連の処理だと認識していたのが間違い。\n\nブラウザ: `http://example.com`へリクエスト \nサーバー: `http://example.com/wiki/メインページ`の方へアクセスしてくださいというレスポンス。\n\nここで1つ目のリクエストは終了。\n\nブラウザ: `http://example.com/wiki/メインページ`へリクエスト \nサーバー: なんやかんや処理してhtmlをレスポンス。\n\n2つ目のリクエストでは、`http://example.com/wiki/メインページ`へアクセスしているので、`REQUEST_URI`は`/wiki/メインページ`になる。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T01:42:58.927",
"id": "77614",
"last_activity_date": "2021-06-17T01:42:58.927",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "45540",
"parent_id": "77588",
"post_type": "answer",
"score": 0
}
] | 77588 | null | 77591 |
{
"accepted_answer_id": "77604",
"answer_count": 1,
"body": "AtCoder Beginner Contest 204 のE問題で以下のコードを提出するとWAになってしまいます。 \nサンプルコードはすべてACで、全体では23/36がACになるのに、なぜ一部でWAになるのかわかりません。 \n原因がわかる方是非教えていただきたいです。\n\n```\n\n import heapq\n from sys import stdin\n \n \n def calc_best_time(C, D):\n func = lambda x: x + C + D // (x+1)\n lower = int(pow(D, 0.5)-1)\n upper = lower + 1\n if lower < 0: return 0, func(0), func\n if func(lower) < func(upper): return lower, func(lower), func\n else: return upper, func(upper), func\n \n def dijkstra(root, adjacencies):\n min_time = {vertex: -1 for vertex in adjacencies}\n heap = [(0, root)]\n searched = set()\n while heap:\n time, vertex = heapq.heappop(heap)\n if vertex in searched: continue\n searched.add(vertex)\n min_time[vertex] = time\n for adj_vertex, (start, end, func) in adjacencies[vertex].items():\n if adj_vertex in searched: continue\n if time <= start: heapq.heappush(heap, (end, adj_vertex))\n else: heapq.heappush(heap, (func(time), adj_vertex))\n return min_time\n \n def main():\n input = lambda: stdin.readline().rstrip()\n N, M = map(int, input().split())\n adjacencies = {vertex: {} for vertex in range(1, N+1)}\n for _ in range(M):\n A, B, C, D = map(int, input().split())\n adjacencies[A][B] = calc_best_time(C, D)\n adjacencies[B][A] = calc_best_time(C, D)\n min_time = dijkstra(1, adjacencies)\n print(min_time[N])\n \n if __name__ == '__main__':\n main()\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T02:10:05.703",
"favorite_count": 0,
"id": "77589",
"last_activity_date": "2021-06-16T16:14:59.330",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "41730",
"post_type": "question",
"score": 0,
"tags": [
"python",
"python3"
],
"title": "AtCoder Beginner Contest 204 E問題でWAになる",
"view_count": 133
} | [
{
"body": "多重辺が考慮されてません \n入力例2のように同じ頂点を結ぶ辺が複数あった場合に最後のものしか使えないようになっています。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T16:14:59.330",
"id": "77604",
"last_activity_date": "2021-06-16T16:14:59.330",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "33033",
"parent_id": "77589",
"post_type": "answer",
"score": 1
}
] | 77589 | 77604 | 77604 |
{
"accepted_answer_id": null,
"answer_count": 2,
"body": "あるサービスで、商品(3種類)とエリアにより、価格を決定する方法を考えています。 \n以下のように、価格テーブルを作ることにより、みやすく、価格を返す関数作れるかなと思っています。\n\n商品コード 12,32,33 の三種類があり、エリアが以下のように分かれており、 \nこの二つから価格を決定する良い方法を考えているのですが・・・\n\n中々可読性を高くする良い方法が思い浮かびません 教えてください。\n\n//例えば、 \n配列の順番から、0=12 , 1 = 32, 2 = 33とした場合 \n対象の場所=2 商品12 \n対象の場所のエリアはCHUO \n1700が価格。\n\n対象の場所=8 商品32 \n対象の場所のエリアはMINAMIなので \n990が価格となるような感じです。\n\n```\n\n $targetPlace = 2\n \n class PRICE{\n const HIGSHI = [5,6,7];\n const CHUO = [1,2,4];\n const MINAMI = [8,9,10,11];\n \n const PRICES_TABLE = array(HIGSHI => [2200,3200,4400], CHUO => [1700,1900,4000] MINAMI=>[440,990,1000]);\n \n public static $tokyo_array = array(\n '1'=>'千代田区',\n '2'=>'港区',\n '3'=>'渋谷区',\n //...\n '23'=>'板橋区',\n }\n \n \n```\n\n```\n\n PRICE::PRICES_TABLE[[$targetPlace]][0];\n \n```",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T04:52:15.937",
"favorite_count": 0,
"id": "77594",
"last_activity_date": "2021-06-17T04:19:38.910",
"last_edit_date": "2021-06-16T08:25:12.117",
"last_editor_user_id": "44839",
"owner_user_id": "44839",
"post_type": "question",
"score": 0,
"tags": [
"php"
],
"title": "PHP Arrayに入れた値を取得する方法",
"view_count": 162
} | [
{
"body": "正規化を要する複雑なデータ構造ならばリレーショナルデータベース(RDB)を使用した方が良いように思います。\n\nRDBを使うほど大掛かりにしたくないけれど第三者がコードリーディングした時の可読性を上げたいのならば連想配列やメソッド、コメントを使ってコードに意味を持たせつつ整形する方法が保守や拡張しやすい正攻法ではないでしょうか。\n\n```\n\n <?php\n class Price {\n //エリアごとに23区の区コードを振り分ける\n const AREAS = array('東' => [5,6,7],\n '中央' => [1,2,4],\n '南' => [8,9,10,11]);\n //エリアと商品コードごとに一意の価格を振り分ける\n const PRICES = array('東' => array(12 => 2200, 32 => 3200, 33 => 4400),\n '中央' => array(12 => 1700, 32 => 1900, 33 => 4000),\n '南' => array(12 => 440, 32 => 990, 33 => 1000));\n //区コードと商品コードから価格を取得する\n public static function getPrice($ward, $item) {\n foreach(array_keys(self::AREAS) as $area) {\n if(in_array($ward, self::AREAS[$area]) && array_key_exists($item, self::PRICES[$area])) {\n //エリアの区コードに $ward を含む場合は商品コードに該当する価格を返す\n return self::PRICES[$area][$item];\n }\n }\n //todo 該当が存在しない場合のエラー処理を追記すること(この例では-1を返す)\n return -1;\n }\n }\n \n echo Price::getPrice(2, 12).\"\\n\"; // 1700\n echo Price::getPrice(8, 32).\"\\n\"; // 990\n echo Price::getPrice(5, 13); // -1 (存在しないキー)\n ?>\n \n```",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T15:14:59.813",
"id": "77602",
"last_activity_date": "2021-06-17T04:19:38.910",
"last_edit_date": "2021-06-17T04:19:38.910",
"last_editor_user_id": "9820",
"owner_user_id": "9820",
"parent_id": "77594",
"post_type": "answer",
"score": 1
},
{
"body": "以下では、価格テーブル(`PRICE::$priceTable`)を作成して memoize(メモ化) しています。\n\n```\n\n class PRICE {\n private const TOKYO_AREA = [\n [5, 6, 7], // EAST\n [1, 2, 4], // CENTRAL\n [8, 9, 10, 11], // SOUTH\n ];\n \n private const GOODS_CODE = [12, 32, 33];\n private const _PRICES_TABLE = [\n [2200, 3200, 4400], // EAST\n [1700, 1900, 4000], // CENTRAL\n [ 440, 990, 1000], // SOUTH\n ];\n \n private static $priceTable = null;\n public static function PRICES_TABLE() {\n if (self::$priceTable === null) {\n $i = 0;\n self::$priceTable = array_reduce(\n self::TOKYO_AREA,\n function ($result, $item) use(&$i) {\n array_map(function ($a) use(&$result, &$i) {\n $result[$a] = array_combine(\n self::GOODS_CODE, self::_PRICES_TABLE[$i]);\n }, $item);\n $i++;\n return $result;\n }, array());\n }\n \n return self::$priceTable;\n }\n }\n \n // Testing\n foreach([[2, 12], [8, 32], [5, 33]] as $v) {\n printf(\"PRICE::PRICES_TABLE()[{$v[0]}][{$v[1]}] = %4d\\n\",\n PRICE::PRICES_TABLE()[$v[0]][$v[1]]);\n }\n \n // 実行結果\n PRICE::PRICES_TABLE()[2][12] = 1700\n PRICE::PRICES_TABLE()[8][32] = 990\n PRICE::PRICES_TABLE()[5][33] = 4400\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T23:24:19.777",
"id": "77609",
"last_activity_date": "2021-06-16T23:24:19.777",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77594",
"post_type": "answer",
"score": 1
}
] | 77594 | null | 77602 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "Sony Spresenseを用いたGNSSトラッカーを作成しています。\n\nドキュメントには、GNSS取得周期が1Hzであると記載されていますが、10Hzまで周期を大きくすることはできないのでしょうか?\n\nまた、現時点では10Hzできない場合、今後将来的に10HzでGNSS測定できるように開発を進める予定はございますでしょうか? \nよろしくお願いいたします。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T06:37:00.403",
"favorite_count": 0,
"id": "77596",
"last_activity_date": "2021-07-06T00:04:15.843",
"last_edit_date": "2021-06-16T06:43:36.193",
"last_editor_user_id": "2238",
"owner_user_id": "46887",
"post_type": "question",
"score": 1,
"tags": [
"spresense",
"gps"
],
"title": "SpresenseのGNSS測定周期を変更することは可能ですか?",
"view_count": 217
} | [
{
"body": "ioctlのCXD56_GNSS_IOCTL_SET_OPE_MODEで測位周期を変更できます。\n\n```\n\n /* Set the GNSS operation interval. */\n \n set_opemode.mode = 1; /* Operation mode:Normal(default). */\n set_opemode.cycle = 1000; /* Position notify cycle(msec step). */\n \n ret = ioctl(fd, CXD56_GNSS_IOCTL_SET_OPE_MODE, (uint32_t)&set_opemode);\n \n```\n\nデフォルトはcycle=1000(1Hz)になっていますが、この値を変えると測位周期を変えられます。\n\n私もSpresenseでトラッカーを自作しましたが、ベストエフォートで動作しているようで、 \n500(2Hz), 250(4Hz), 200(5Hz) と指定すると、その周期で測位値を取得できました。 \n(4Hz, 5Hz を指定したときに、高速移動中だとややドリフト軌跡が目立つかも)\n\n試しに100(10Hz) を指定してみてその周期をみると200msec間隔になっているので、 \n結果的に5Hzが限界な気がします。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-07-06T00:04:15.843",
"id": "78001",
"last_activity_date": "2021-07-06T00:04:15.843",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "31378",
"parent_id": "77596",
"post_type": "answer",
"score": 1
}
] | 77596 | null | 78001 |
{
"accepted_answer_id": "77625",
"answer_count": 2,
"body": "C言語初心者です。コンパイラはgcc-11.0.1、環境はUbuntu21.0.4です。 \n表題のとおり、思い立って連結リスト(双方向リスト)を実装してみました。実装したのは、リストの要素を表す構造体、リストの生成、追加、削除を行う関数です。そのうち、要素の削除を行う関数でトラブルが起こりました。 \nトラブルが発生したコードは以下のとおりです。\n\n```\n\n struct L {\n int element;\n struct L* prev;\n struct L* next;\n };\n typedef struct L List;\n \n /* リストの生成 */\n List* init_list() {\n List* node = (List*)malloc(sizeof(List));\n node->element = 0;\n node->prev = NULL;\n node->next = NULL;\n return node;\n }\n \n void insert_list(List* list, int element, int pos) {/* 省略 */}\n void insert_last_list(List* list, int element) {/* 省略 */}\n void insert_head_list(List* list, int element) {/* 省略 */}\n \n /* リスト要素の削除 */\n void erase_list(List* list, int pos) {\n if(list == NULL) return;\n List* node = list;\n while(pos--) {\n node = node->next;\n if(!node) return;\n }\n if(node->prev) node->prev->next = node->next;\n if(node->next) node->next->prev = node->prev;\n free(node);\n node = NULL;\n }\n \n int main(int argc, char* argv[]) {\n List* list = init_list();\n list->element = 1;\n for(int i = 2; i <= 10; i++) { /* リストに1〜10の値を持つ要素が設定される */\n insert_last_list(list, i);\n }\n \n List* itr = list;\n do {\n printf(\"%d\\n\", itr->element); /* 1~10が改行区切りで表示された */\n } while(itr = itr->next);\n \n for(int i=9;i>=0;i--) erase_list(list, i); /* リスト要素をすべて削除 */\n \n if(!list) {\n printf(\"List is deleted.\\n\"); /* こちらが表示されると期待 */\n } else {\n itr = list;\n do{\n printf(\"%d\\n\", itr->element); /* 実際はこちらが実行され、おかしな値が表示 */\n } while(itr = itr->next);\n }\n return 0;\n }\n \n```\n\nmain関数内のlistには、erase_list内でNULLが代入されることを期待しましたが、printfで出力すると、明らかにNULLでないアドレス値が表示されました。 \n見返すと、erase_listの引数として、listをポインタ渡ししなければならないと気づき、以下のようにerase_listを変更しました。結果としては、期待通り1~10が改行区切りで表示された後、\"List\nis deleted.\"が表示されました。\n\n```\n\n void erase_list(List** list, int pos) {\n if(list == NULL) return;\n List* node = *list;\n while(pos--) {\n node = node->next;\n if(!node) return;\n }\n if(node->prev) node->prev->next = node->next;\n if(node->next) node->next->prev = node->prev;\n if(!node->prev && !node->next) { /* prevもnextもNULLなら要素は一つなので、引数で渡されたlistを解放 */\n free(*list);\n *list = NULL;\n } else { /* 二重解放しないよう、elseで実行する\n free(node);\n node = NULL;\n }\n }\n \n```\n\n質問は2点です。 \n1.この変更によって、一応は想定の動作をしているのですが、このコードではどこかでメモリリークはしていないのでしょうか?具体的には、free(node)とfree(*list)によって、リスト要素のために確保したメモリは解放されているのでしょうか? \n2.すべてのリスト要素が削除されたときに、先頭要素のアドレスが解放されてかつmain関数内のポインタlistがNULLに設定されることを想定して上記のコード変更をしましたが、これを実現するためのよりスマートな実装方法はありますでしょうか?",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T14:49:57.647",
"favorite_count": 0,
"id": "77600",
"last_activity_date": "2021-06-17T08:36:13.577",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "44216",
"post_type": "question",
"score": 0,
"tags": [
"c",
"アルゴリズム"
],
"title": "C言語で連結リストの作成をしましたが、要素削除の実装でメモリ解放でトラブルを連発しました。一応動くようにはなりましたが、このコードで問題はあるでしょうか?",
"view_count": 651
} | [
{
"body": "A1. コードを精査する時間が無いのでほかの方にお任せ \nA2. 「スマート」の定義次第だと思う。 \nオイラなら空のとき `NULL` になるような線形リスト **だけ**\nを保持してもあまりうれしくないと思うので、次のようなリスト管理クラス(構造体)を用意する、んではないかな・・・\n\n```\n\n struct list_manager_type {\n list* top; ///< 先頭要素\n list* bot; ///< 末尾要素\n size_t count; ///< 要素数\n };\n \n```\n\nこうしておくと\n\n * `list*` 以外に `list_manage_type` 分の微小なメモリオーバーヘッドが増える\n * 末尾追加に `O(n)` のコストがかからない\n * 個数把握に `O(n)` のコストがかからない\n * リストが空でも `list_manage_type` は空(`NULL`)にならないので実装の際に楽できる\n\nリストを使う側からすると、空のリストを特別扱いしたくはないので、その辺の泥臭いあたりを `list_manage_type` に押し付けることで\n**使う側は手を抜く** ことができるほうがスマート鴨。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T03:36:34.753",
"id": "77616",
"last_activity_date": "2021-06-17T03:36:34.753",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "8589",
"parent_id": "77600",
"post_type": "answer",
"score": 0
},
{
"body": "> 1.この変更によって、一応は想定の動作をしているのですが、このコードではどこかでメモリリークはしていないのでしょうか?\n> 具体的には、`free(node)` と `free(*list)` によって、リスト要素のために確保したメモリは解放されているのでしょうか?\n\ngcc には `-fsanitize=leak` というオプションがあります。\n\n**gcc(1)**\n\n> -fsanitize=leak\n>\n> Enable LeakSanitizer, a memory leak detector. This option only matters for\n> linking of executables and the executable is linked against a library that\n> overrides \"malloc\" and other allocator functions. See\n> <https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer>\n> for more details. The run-time behavior can be influenced using the\n> LSAN_OPTIONS environment variable.\n```\n\n $ lsb_release -d\n Description: Ubuntu 21.04\n $ gcc --version\n gcc (Ubuntu 10.3.0-1ubuntu1) 10.3.0\n \n $ gcc -fsanitize=leak -Wall -Wextra -g -o list list.c\n $ ./list\n 1\n :\n 10\n List is deleted.\n \n```\n\nここで、最後のノードは `free()` しない様にしてコンパイル・実行してみます。\n\n```\n\n for(int i=9;i>=0;i--) erase_list(&list, i); /* リスト要素をすべて削除 */\n // 変更\n for(int i=9;i>0;i--) erase_list(&list, i);\n \n```\n\n```\n\n $ gcc -fsanitize=leak -Wall -Wextra -g -o list list.c\n $ ./list\n :\n \n =================================================================\n ==695453==ERROR: LeakSanitizer: detected memory leaks\n \n Direct leak of 24 byte(s) in 1 object(s) allocated from:\n #0 0x7f2e0378b5d1 in __interceptor_malloc ../../../../src/libsanitizer/lsan/lsan_interceptors.cpp:56\n #1 0x55ee26c1521e in init_list list.c:14\n #2 0x55ee26c153cc in main list.c:61\n #3 0x7f2e035b7564 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x28564)\n \n SUMMARY: LeakSanitizer: 24 byte(s) leaked in 1 allocation(s).\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T08:36:13.577",
"id": "77625",
"last_activity_date": "2021-06-17T08:36:13.577",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77600",
"post_type": "answer",
"score": 2
}
] | 77600 | 77625 | 77625 |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "個人的な興味から、機械学習における基本的な多層パーセプトロンについて、入力や重み行列を行列データでなく(数学的な意味での)関数として表した表現を考えています。\n\n入力をバッチ次元xデータ次元yなf(x,y) \n重みをデータ次元yニューロン次元zなg(y,z) \nとしたとき、行列積に相当する計算は、おそらく\n\n∫f(x,y)*g(y,z)dy (でy=0〜nの定積分)\n\nのようになるだろうという所までは考えを進めました。\n\nそしてこの形がほぼシフト値0の相互相関関数に近いという事までは調べる事ができたのですが、相互相関関数は一般的に一変数のもので、多変数のものがあったとしてもx,y,zの3変数を用いてyを定積分で潰す形について説明している資料が見つけられませんでした。\n\n行列積を一般化しただけなので、この形はそれほど特殊ではなく一般的な名称があるのではないかと考えたのですが、そのようなものをご存知であれば教えていただきたいのです。\n\n* * *\n\n**追記1** \nコメントを受け、誤解を招きそうな部分を追記で補います。最終的な目的は、行列の全てのパラメータを連続化し、xy平面を成す関数として捉え直し、それをもってパーセプトロンを記述することです。\n\nまず行列を、2つのインデックス(i,j)を引数にとり一つの値を返す関数と見做します。このままでは(i,j)は行と列の要素を指す整数値しか取れないので、ここを一般化して中間の値を滑らかに指定できるようにすると、もはや行列はパラメータ(x,y)でxy平面を作る関数f(x,y)と見做せるであろう、という考え方をしています。\n\nそのような関数同士の、行列積に相当する関数(汎関数でしょうか)を考えた時に上記のような形が思い当たったという経緯です。\n\nそして、この関数の性質を更に掘り下げるため、既存の呼称やこれについて説明した資料を求めているという形になります。\n\n行列積の関数版(パラメータ連続版)が相互相関関数であると考えた根拠として、ベクトルの内積が相互相関関数の離散版であると指摘しているサイトを参考に挙げます。\n\n<http://hooktail.sub.jp/fourieralysis/RelationFnc/>\n\n* * *\n\n**追記2** \n蛇足かもしれませんが、上記の式が行列積に相当することをSympy(Python3)で確認したプログラムを貼りつけておきます。\n\n[](https://i.stack.imgur.com/ANQBI.png)\n\n```\n\n import sympy as sp\n import numpy as np\n import matplotlib.pyplot as plt\n \n x, y, z = sp.symbols(\"x, y, z\")\n \n \n def dot_for_functions(f, g, xs):\n h = sp.integrate(f * g, (xs, 0, 1))\n return h\n \n \n if __name__ == '__main__':\n f_xy = sp.sin(10*x) + y # xとyの適当な関数\n g_yz = sp.sin(4*y) + sp.cos(4*z) # yとzの適当な関数\n \n h_xz = dot_for_functions(f_xy, g_yz, y).simplify()\n \n # 値域 0to1 の 離散化した 32x32 行列として F, G, H を作成\n F = np.zeros((32, 32))\n G = np.zeros((32, 32))\n H = np.zeros((32, 32))\n \n for iy in range(0, 32):\n vy = iy / 31\n for ix in range(0, 32):\n vx = ix / 31\n vf = f_xy.subs(x, vx).subs(y, vy)\n F[ix, iy] = vf\n \n for iz in range(0, 32):\n vz = iz / 31\n for iy in range(0, 32):\n vy = iy / 31\n vg = g_yz.subs(y, vy).subs(z, vz)\n G[iy, iz] = vg\n for ix in range(0, 32):\n vx = ix / 31\n vh = h_xz.subs(x, vx).subs(z, vz)\n H[ix, iz] = vh\n \n # 行列の内積から生成したdot(F, G)が\n # 関数の内積的表現から生成したHにほぼ近いことを確認\n H_from_matrix = np.dot(F, G)\n \n plt.subplot(2, 2, 1)\n plt.imshow(F)\n plt.ylabel(\"F\")\n plt.subplot(2, 2, 2)\n plt.imshow(G)\n plt.ylabel(\"G\")\n plt.subplot(2, 2, 3)\n plt.imshow(H)\n plt.ylabel(\"H\")\n plt.subplot(2, 2, 4)\n plt.imshow(H_from_matrix)\n plt.ylabel(\"H raw\")\n plt.show()\n \n```\n\n* * *\n\n**追記3** \n頂いたコメントを読み直し、調べ直した所、関数同士の積の積分は単に関数同士の内積と呼ばれている事を理解しました。\n\nあとははじめに示したように、行列計算と同様のf(x,y)、g(y,z)を取る場合に特別な呼称が有れば良いのですが、無ければただのそういう内積であるものとして納得しようと思います。",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T19:40:28.697",
"favorite_count": 0,
"id": "77606",
"last_activity_date": "2021-06-17T14:27:26.263",
"last_edit_date": "2021-06-17T14:27:26.263",
"last_editor_user_id": "46896",
"owner_user_id": "46896",
"post_type": "question",
"score": 2,
"tags": [
"機械学習",
"数学"
],
"title": "行列を数学的な関数と見做した時の行列積計算に相当する関数に一般的な呼称はありますか?",
"view_count": 195
} | [] | 77606 | null | null |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "plotlyで、一回グラフのサイズを指定してグラフを作り、、そのあとに、自動でグラフのサイズを成形したいのですが、どうすればいいのでしょうか? \n目的としては、サイズを指定したグラフとサイズが自動で変わるグラフを作り、htmlで保存して、サイズを指定した方は、印刷用。サイズが自動で変わる方は、使うモニターの解像度に合わせて適切なサイズを表示させる用途で使いたいのです。\n\n```\n\n # imports\n import pandas as pd\n import plotly.graph_objs as go\n import numpy as np\n \n # data\n np.random.seed(4)\n x = np.linspace(0, 1, 50)\n y = np.cumsum(np.random.randn(50))\n \n # plotly line chart\n fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[-4,4])\n fig.update_layout(\n width=1000,\n height=1000 * 2 ** 0.5,\n ) \n fig.show()\n fig.update_layout(\n autosize=True\n ) \n fig.show()\n \n```\n\nhtmlを生成する場合、\n\n```\n\n # imports\n import pandas as pd\n import plotly.graph_objs as go\n import numpy as np\n \n # data\n np.random.seed(4)\n x = np.linspace(0, 1, 50)\n y = np.cumsum(np.random.randn(50))\n \n # plotly line chart\n fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[-4,4])\n fig.update_layout(\n width=1000,\n height=1000 * 2 ** 0.5,\n ) \n fig.write_html(\"a.html\")\n fig.update_layout(\n autosize=True\n ) \n fig.write_html(\"aa.html\")\n \n```\n\n異なるサイズのグラフを表示させたい(片方は、サイズが自動で変わるようにしたいです)",
"comment_count": 11,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-16T23:18:29.297",
"favorite_count": 0,
"id": "77608",
"last_activity_date": "2022-01-11T06:59:04.523",
"last_edit_date": "2022-01-11T06:59:04.523",
"last_editor_user_id": "3060",
"owner_user_id": "42741",
"post_type": "question",
"score": 1,
"tags": [
"python",
"plotly-python"
],
"title": "plotlyでグラフのサイズを自動にしたい。",
"view_count": 4103
} | [
{
"body": "何かヒントというか何が問題なのかが分かってきたかもしれません。 \n2つ目で`autosize=True`を指定しても、その前に指定した`width=1000,height=1000 * 2 **\n0.5,`は残ったままなので、それが影響しているのかもしれませんね。 \n最初の固定サイズの指定を消すか相対値化する機能があるか探してみては? 無ければ2つ目は最初から作り直すとか?\n\nとりあえず以下のように2つ目を最初から作り直すようにすると、出来ると思われます。\n\n```\n\n # plotly line chart\n fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[-4,4])\n fig.update_layout(\n width=1000,\n height=1000 * 2 ** 0.5,\n ) \n fig.show()\n #### 2つ目グラフもあらためて最初から作成する\n fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[-4,4]) ####\n fig.update_layout(\n autosize=True\n ) \n fig.show()\n \n```\n\n* * *\n\n@metropolis さんコメントの方法も同様の結果で有効と思われます。\n\n```\n\n fig.update_layout(\n width=None,\n height=None,\n autosize=True\n )\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T06:22:21.310",
"id": "77621",
"last_activity_date": "2021-06-17T07:12:50.973",
"last_edit_date": "2021-06-17T07:12:50.973",
"last_editor_user_id": "26370",
"owner_user_id": "26370",
"parent_id": "77608",
"post_type": "answer",
"score": 1
}
] | 77608 | null | 77621 |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "RTX A6000を使用しておりますが、下記の環境下(tensorflow-gpu 1.13.1)ではエラーが出てしまいます。 \n一方、tensorflow-gpuをバーション2.1にすると正常に動きます。 \ntensorflow-gpuバージョンを1.13.1で動かしたいのですが、RTX A6000では使用できないのでしょうか?\n\n### エラー内容、症状\n\n * エラーメッセージにはメモリオーバーフローと記載(たぶん)\n * エラーではないがGPUメモリのロードが異常に遅い\n\n### 確認内容\n\n * 下記サイトのコードを動かして正常に動いているかの確認をしました。\n\n * tensorflow-gpu 1.13.1ではエラーメッセージでて止まります。\n * tensorflow-gpu 2.1ではエラーメッセージでずに正常に稼働。\n\n[TensorFlowのチュートリアルがディープラーニングの勉強のスタートに良かったのでオススメしたい](https://qiita.com/Kuma_T/items/4449f008cad18fbb7f1a)\n\n * GPUやCUDAを認識しているかの動作確認は下記サイトを参考にしました。\n\n[NVIDIA CUDA toolkit on\nWindows](https://qiita.com/n-yamanaka/items/b00a94eec7eac4d2e76a) \n[TensorFlowでGPU学習させるためにCUDA周りではまったときの対処法](https://qiita.com/karaage0703/items/5d46b249f6be68186210)\n\n### エラーメッセージ\n\n```\n\n 2021-06-17 13:47:01.520738: E tensorflow/stream_executor/cuda/cuda_blas.cc:698] failed to run cuBLAS routine cublasSgemm_v2: CUBLAS_STATUS_EXECUTION_FAILED\n Traceback (most recent call last):\n File \"shibata-test.py\", line 24, in <module>\n model.fit(x_train, y_train, epochs=5)\n File \"C:\\Users\\ixs-quadro05\\anaconda3\\envs\\deeplabv3plus\\lib\\site-packages\\tensorflow\\python\\keras\\engine\\training.py\", line 880, in fit\n validation_steps=validation_steps)\n File \"C:\\Users\\ixs-quadro05\\anaconda3\\envs\\deeplabv3plus\\lib\\site-packages\\tensorflow\\python\\keras\\engine\\training_arrays.py\", line 329, in model_iteration\n batch_outs = f(ins_batch)\n File \"C:\\Users\\ixs-quadro05\\anaconda3\\envs\\deeplabv3plus\\lib\\site-packages\\tensorflow\\python\\keras\\backend.py\", line 3076, in __call__\n run_metadata=self.run_metadata)\n File \"C:\\Users\\ixs-quadro05\\anaconda3\\envs\\deeplabv3plus\\lib\\site-packages\\tensorflow\\python\\client\\session.py\", line 1439, in __call__\n run_metadata_ptr)\n File \"C:\\Users\\ixs-quadro05\\anaconda3\\envs\\deeplabv3plus\\lib\\site-packages\\tensorflow\\python\\framework\\errors_impl.py\", line 528, in __exit__\n c_api.TF_GetCode(self.status.status))\n tensorflow.python.framework.errors_impl.InternalError: Blas GEMM launch failed : a.shape=(32, 512), b.shape=(512, 10), m=32, n=10, k=512\n [[{{node dense_1/MatMul}}]]\n [[{{node loss/mul}}]]\n \n```\n\n### 環境\n\nWindows : Windows 10 Pro, バージョン20H2 \nプロセッサ : Intel(R) Core(TM) i9-10980XE CPU @ 3.00GHz 3.00 GHz \nNVIDIAドライバー : R460 U6 (462.31) \nファイル名:462.31-quadro-rtx-desktop-notebook-win10-64bit-international-dch-\nwhql.exe \nNVIDIA CUDA Toolkit :10.0 \nファイル名::cuda_10.0.130_411.31_win10.exe \nNVIDIA cuDNN:7.4 \nファイル名:cudnn-10.0-windows10-x64-v7.4.1.5.zip \nAnaconda仮想環境内 \n・python : 3.6.8 \n・tensorflow-gpu : 1.13.1 \n*tensorflow-gpuをcondaでインストールするとcudnnなどが自動インストールされるためpipでインストール \n(上記でtensorflow-gpu 2.1に変更すると動く!!)\n\n**補足**\n\n * tensorflow-gpuバージョンを下記に変更しても動きませんでした \n1.13.1、1.14.0、1.15.0、2.0.0\n\n * CUDAなどバージョンを下記に変更しても動きません。ただ、tensorflow-gpu 2.1は動きます。 \nCUDA Toolkit :10.1、cuDNN:7.6\n\n * NVIDIAに問い合わせましたが「tensorflowはオープンソースソフトウェアのため回答できません」とのことです",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T00:48:16.873",
"favorite_count": 0,
"id": "77610",
"last_activity_date": "2021-06-17T06:11:58.400",
"last_edit_date": "2021-06-17T06:11:58.400",
"last_editor_user_id": "3060",
"owner_user_id": "46897",
"post_type": "question",
"score": 0,
"tags": [
"python",
"tensorflow",
"gpu"
],
"title": "NVIDIA RTX A6000でtensorflow-gpu 1.13.1が使えない",
"view_count": 433
} | [] | 77610 | null | null |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "クロールして取得したデータ(1行分)をスプレッドシートの最下行に反映したいのですが、下記エラーが表示されうまく反映されません。 \n解決方法はありますでしょうか。\n\n**コード**\n\n```\n\n JSON_KEYFILE = 'APIのJSONファイル'\n SPREADSHEET = 'TEST'\n WORKSHEET = 'Sheet1'\n \n scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']\n \n #認証情報設定\n serviceAccountCredentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEYFILE, scope)\n gspreadClient = gspread.authorize(serviceAccountCredentials)\n worksheet = gspreadClient.open(SPREADSHEET).worksheet(WORKSHEET)\n \n df = pd.read_csv('test.csv', encoding=\"shift_jis\")\n ls = df.loc[0:0]\n \n ls = ls.to_json()\n \n spread = client.open(SPREADSHEET) \n sheet = spread.worksheet(WORKSHEET)\n worksheet.append_row(ls)\n \n```\n\n**エラーコード**\n\n`worksheet.append_row(ls)` の部分でAPIエラーが発生してしまいます。\n\n```\n\n gspread.exceptions.APIError: {'code': 400, 'message': 'Invalid value at \\'data.values[0]\\' (type.googleapis.com/google.protobuf.ListValue), \"{\"\\\\u58f2\\\\u4e0a\\\\u65e5\":{\"0\":\"2021\\\\/06\\\\/14\"},\"\\\\u30a4\\\\u30f3\\\\u30d7\\\\u30ec\\\\u30c3\\\\u30b7\\\\u30e7\\\\u30f3(I)\":{\"0\":19},\"\\\\u30af\\\\u30ea\\\\u30c3\\\\u30af(C)\":{\"0\":36},\"\\\\u30aa\\\\u30fc\\\\u30c0\\\\u30fc\\\\u767a\\\\u751f\\\\u4ef6\\\\u6570\":{\"0\":0},\"\\\\u30aa\\\\u30fc\\\\u30c0\\\\u30fc\\\\u767a\\\\u751f\\\\u500b\\\\u6570\":{\"0\":0},\"\\\\u30aa\\\\u30fc\\\\u30c0\\\\u30fc\\\\u30ad\\\\u30e3\\\\u30f3\\\\u30bb\\\\u30eb\\\\u500b\\\\u6570\":{\"0\":0},\"\\\\u30aa\\\\u30fc\\\\u30c0\\\\u30fc\\\\u58f2\\\\u4e0a\\\\u984d\":{\"0\":0},\"\\\\u30ad\\\\u30e3\\\\u30f3\\\\u30bb\\\\u30eb\\\\u76f8\\\\u5f53\\\\u984d\":{\"0\":0},\"\\\\u5831\\\\u916c\\\\u5bfe\\\\u8c61\\\\u7d14\\\\u58f2\\\\u4e0a\\\\u984d\":{\"0\":0},\"\\\\u5831\\\\u916c\\\\u5bfe\\\\u8c61\\\\u30af\\\\u30ea\\\\u30c3\\\\u30af\\\\u6570\":{\"0\":0},\"\\\\u5831\\\\u916c\\\\u5bfe\\\\u8c61\\\\u30ea\\\\u30fc\\\\u30c9(\\\\u63d0\\\\u643a\\\\u8ab2\\\\u91d1)\\\\u6570\":{\"0\":0},\"\\\\u6210\\\\u679c\\\\u5831\\\\u916c\\\\u984d\":{\"0\":0},\"\\\\u78ba\\\\u5b9a\\\\u60c5\\\\u5831\":{\"0\":\"\\\\u78ba\\\\u5b9a\"}}\"', 'status': 'INVALID_ARGUMENT', 'details': [{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'data.values[0]', 'description': 'Invalid value at \\'data.values[0]\\' (type.googleapis.com/google.protobuf.ListValue), \"{\"\\\\u58f2\\\\u4e0a\\\\u65e5\":{\"0\":\"2021\\\\/06\\\\/14\"},\"\\\\u30a4\\\\u30f3\\\\u30d7\\\\u30ec\\\\u30c3\\\\u30b7\\\\u30e7\\\\u30f3(I)\":{\"0\":19},\"\\\\u30af\\\\u30ea\\\\u30c3\\\\u30af(C)\":{\"0\":36},\"\\\\u30aa\\\\u30fc\\\\u30c0\\\\u30fc\\\\u767a\\\\u751f\\\\u4ef6\\\\u6570\":{\"0\":0},\"\\\\u30aa\\\\u30fc\\\\u30c0\\\\u30fc\\\\u767a\\\\u751f\\\\u500b\\\\u6570\":{\"0\":0},\"\\\\u30aa\\\\u30fc\\\\u30c0\\\\u30fc\\\\u30ad\\\\u30e3\\\\u30f3\\\\u30bb\\\\u30eb\\\\u500b\\\\u6570\":{\"0\":0},\"\\\\u30aa\\\\u30fc\\\\u30c0\\\\u30fc\\\\u58f2\\\\u4e0a\\\\u984d\":{\"0\":0},\"\\\\u30ad\\\\u30e3\\\\u30f3\\\\u30bb\\\\u30eb\\\\u76f8\\\\u5f53\\\\u984d\":{\"0\":0},\"\\\\u5831\\\\u916c\\\\u5bfe\\\\u8c61\\\\u7d14\\\\u58f2\\\\u4e0a\\\\u984d\":{\"0\":0},\"\\\\u5831\\\\u916c\\\\u5bfe\\\\u8c61\\\\u30af\\\\u30ea\\\\u30c3\\\\u30af\\\\u6570\":{\"0\":0},\"\\\\u5831\\\\u916c\\\\u5bfe\\\\u8c61\\\\u30ea\\\\u30fc\\\\u30c9(\\\\u63d0\\\\u643a\\\\u8ab2\\\\u91d1)\\\\u6570\":{\"0\":0},\"\\\\u6210\\\\u679c\\\\u5831\\\\u916c\\\\u984d\":{\"0\":0},\"\\\\u78ba\\\\u5b9a\\\\u60c5\\\\u5831\":{\"0\":\"\\\\u78ba\\\\u5b9a\"}}\"'}]}]}\n \n```",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T01:56:10.700",
"favorite_count": 0,
"id": "77615",
"last_activity_date": "2022-12-08T09:08:26.053",
"last_edit_date": "2021-06-17T06:56:57.830",
"last_editor_user_id": "3060",
"owner_user_id": "45216",
"post_type": "question",
"score": 0,
"tags": [
"python",
"python3",
"google-spreadsheet"
],
"title": "Google スプレッドシートへのデータフレーム追加時にエラー: type.googleapis.com/google.protobuf.ListValue",
"view_count": 693
} | [
{
"body": "[metropolis氏のコメント](https://ja.stackoverflow.com/questions/77615/%e3%82%b9%e3%83%97%e3%83%ac%e3%83%83%e3%83%89%e3%82%b7%e3%83%bc%e3%83%88%e3%81%b8%e3%81%ae%e3%83%87%e3%83%bc%e3%82%bf%e3%83%95%e3%83%ac%e3%83%bc%e3%83%a0%e3%81%ae%e8%bf%bd%e5%8a%a0#comment87737_77615)でもあるように、Sheets\nAPIを使用して値をSpreadsheetへ挿入する場合は、セルに入るデータ部分はリストである必要があります。そこで、次のような修正はいかがでしょうか。\n\n## Pattern 1:\n\nこのパターンでは、dataframeはリストに変換されて`values_update`メソッドを使ってセルへ挿入します。\n\n### From:\n\n```\n\n ls = df.loc[0:0]\n ls = ls.to_json()\n \n spread = client.open(SPREADSHEET) \n sheet = spread.worksheet(WORKSHEET)\n worksheet.append_row(ls)\n \n```\n\n### To:\n\n```\n\n ls = df.loc[0:0]\n \n values = [ls.columns.values.tolist()]\n values.extend(ls.values.tolist())\n \n spread = client.open(SPREADSHEET)\n spread.values_update(WORKSHEET, params={'valueInputOption': 'USER_ENTERED'}, body={'values': values})\n \n```\n\n## Pattern 2:\n\nこのパターンでは、[gspread-dataframe](https://github.com/robin900/gspread-\ndataframe)のライブラリを使用します。\n\n### From:\n\n```\n\n ls = df.loc[0:0]\n ls = ls.to_json()\n \n spread = client.open(SPREADSHEET) \n sheet = spread.worksheet(WORKSHEET)\n worksheet.append_row(ls)\n \n```\n\n### To:\n\n```\n\n ls = df.loc[0:0]\n \n spread = client.open(SPREADSHEET) \n sheet = spread.worksheet(WORKSHEET)\n gd.set_with_dataframe(sheet, ls)\n \n```\n\nこの場合、`import gspread_dataframe as gd`を使用します。\n\n### References:\n\n * [values_update(range, params=None, body=None)](https://docs.gspread.org/en/latest/api.html?highlight=values_update#gspread.models.Spreadsheet.values_update)\n * [gspread-dataframe](https://github.com/robin900/gspread-dataframe)",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T06:44:44.090",
"id": "77622",
"last_activity_date": "2021-06-17T06:44:44.090",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "19460",
"parent_id": "77615",
"post_type": "answer",
"score": 1
}
] | 77615 | null | 77622 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "非常に初歩的な質問で大変恐縮です。\n\nやりたいことは、\n\n 1. ユーザー自身にアプリをダウンロードしてもらい、ダブルクリック実行してもらう。\n 2. バックグラウンドにて任意のターミナルコマンド(sw_vers)を実行し実行結果からProductVersionの値をファイル名として任意のパスにファイルを作成。\n 3. ユーザーに完了のポップアップ表示。\n\nということをさせたいと考えています。\n\nこのような動作をさせるアプリケーションをXcodeで作成することは可能でしょうか。\n\nまた、任意のMac利用者へ配布して実行してもらうことを想定していますが、 \n開発環境以外のMac環境上で実行する場合、気を付けるべきことは有りますでしょうか。\n\n内容が類似しているアプリのサンプルコードなどをご存じでしたらご教示頂けませんでしょうか。\n\n宜しくお願いいたします。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T04:21:03.887",
"favorite_count": 0,
"id": "77617",
"last_activity_date": "2021-06-17T07:01:06.260",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "45392",
"post_type": "question",
"score": 0,
"tags": [
"xcode",
"macos"
],
"title": "ターミナルコマンドの実行結果から任意のファイル名のファイルを書き出すアプリをXcodeで作成出来るでしょうか",
"view_count": 96
} | [
{
"body": "> このような動作をさせるアプリケーションをXcodeで作成することは可能でしょうか。\n\n可能ですよ",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T07:01:06.260",
"id": "77623",
"last_activity_date": "2021-06-17T07:01:06.260",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "27481",
"parent_id": "77617",
"post_type": "answer",
"score": 0
}
] | 77617 | null | 77623 |
{
"accepted_answer_id": "77845",
"answer_count": 1,
"body": "AUTOCADからの移行作業を行っております \nAUTOCADでは動作していたのですがIJCADでは下記のエラーが出ます\n\n```\n\n 実行時エラー '-2147467259(8004005)':\n 'AddMInsertBlock'メソッドは失敗しました:'IGcadModelSpeace'オブジェクト\n \n```\n\n作業はブロックを1定の幅で並べるという物です(枠を作る) \n素人のプログラムで見づらい所も多いですがご了承ください\n\n```\n\n Type Point\n Point(2) As Double\n End Type\n \n Dim PropertyIns As Point\n PropertyIns.Point(0) = 100 * DwgScale\n PropertyIns.Point(1) = 50 * DwgScale\n PropertyIns.Point(2) = 0#\n \n Dim InsertPoint As Variant\n InsertPoint = PropertyIns.Point\n \n Dim Blockobj As GcadObject\n Set Blockobj = ThisDrawing.ModelSpace.AddMInsertBlock(InsertPoint, Block_FileName, XScale, YScale, ZScale, Rotate, Rows, 1, FrameHeight, 0)\n Blockobj.Layer = \"0\"\n \n```\n\nヘルプを読んでも構文に問題はないと思っております\n\n皆様にご教示いただきたく \nよろしくお願いいたします",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T08:45:14.337",
"favorite_count": 0,
"id": "77626",
"last_activity_date": "2021-06-29T04:34:52.907",
"last_edit_date": "2021-06-17T08:56:03.550",
"last_editor_user_id": "3060",
"owner_user_id": "46906",
"post_type": "question",
"score": 0,
"tags": [
"vba",
"ijcad"
],
"title": "配列ブロック(AddMInsertBlock)の書き方",
"view_count": 150
} | [
{
"body": "IJCADでAddMInsertBlock()メソッドを実行した所、質問で書かれたのと同じエラーが出ました。 \nIJCADの不具合っぽいですね。\n\n> 作業はブロックを1定の幅で並べるという物です(枠を作る)\n\nブロックを1定の幅で並べるのなら、AcadEntityのArrayRectangular()メソッドが \n代用できるのではないでしょうか。 \nArrayRectangular()メソッドは下記のように使います。\n\n```\n\n Type Point\n Point(2) As Double\n End Type\n \n Sub InsertBlockUsingArrayRectangular()\n Dim Blockobj As GcadBlockReference\n Dim Block_FileName As String\n Dim XScale, YScale, ZScale, Rotate, RowSpace, ColSpace As Double\n Dim XMin, YMin As Double\n Dim NumRows, NumColumns As Long\n Dim PropertyIns As Point\n \n XMin = 0\n YMin = 0\n '配列にしたい任意の図面ファイルを指定する。\n Block_FileName = \"~.dwg\"\n XScale = 1\n YScale = 1\n ZScale = 1\n Rotate = 0\n \n PropertyIns.Point(0) = XMin\n PropertyIns.Point(1) = YMin\n PropertyIns.Point(2) = 0#\n NumRows = 2\n NumColumns = 3\n ColSpace = 100\n RowSpace = 50\n Set Blockobj = ThisDrawing.ModelSpace.InsertBlock(PropertyIns.Point, Block_FileName, XScale, YScale, ZScale, Rotate)\n Call Blockobj.ArrayRectangular(NumRows, NumColumns, 1, RowSpace, ColSpace, 0)\n End Sub\n \n```",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-29T04:34:52.907",
"id": "77845",
"last_activity_date": "2021-06-29T04:34:52.907",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "39778",
"parent_id": "77626",
"post_type": "answer",
"score": 0
}
] | 77626 | 77845 | 77845 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "(Windows、Java1.8.0) \nJAX-RS(Jersey)を使うAPIとして現在、下記のようなコードを書いています。\n\n```\n\n @Path(\"API_01\") // API呼出し時のURL\n \n @POST\n @Produces(MediaType.APPLICATION_JSON)\n public ResponseObj execute(RequestObj request) {\n \n ResponseObj reponse = new ResponseObj();\n reponse.status = \"00\";\n reponse.message = \"\";\n \n return reponse;\n }\n \n```\n\n```\n\n ※POSTリクエストを送信すると上記のexecuteメソッドがJerseyから自動的に呼び出されます。\n ※JSON形式のリクエスト内容がJerseyによって RequestObj に変換されます。\n ※RequestObj、ResponseObjはスカラーのメンバ変数を持つ単純なVOです。\n \n```\n\n上記について、以下のようにしたいと考えています。 \n①API処理を記述するクラスの基底クラス作り、基底クラスのexecuteメソッド内で \n共通処理を記述したい \n(実際に作成するAPIは複数個あるので、それらの共通処理を基底クラスに記述したい) \n(共通処理の記述後に、executeSub(...) といった抽象メソッドを呼び出しておく \n形にする想定) \n \n②API処理を記述するクラスは上記のexecuteSub()をover rideし個別の処理はそちらに記述させたい \n \n③リクエストオブジェクト、レスポンスオブジェクトにはそれぞれ、複数のAPIに跨る共通の変数を持っているので、リクエストオブジェクトの基底クラス、レスポンスオブジェクトの基底クラスを持たせる形にしたい \n例 リクエストオブジェクトの基底クラス:RequestObjBase \nレスポンスオブジェクトの基底クラス:ResponseObjBase \n \nAPI1用 リクエストオブジェクト Request1 extends RequestObjBase \nレスポンスオブジェクト Response1 extends ResponseObjBase \n \nここで、下記の記述方法が分かっていません。 \n・基底クラスの executeメソッドの引数と戻り値の型をどのように記述すればよいか \n(今回実装するすべてのAPIのリクエスト、レスポンスの型を総称的に扱える記述にしたい) \n \n・リクエスト、レスポンスの型を総称的に扱えるメソッド定義となった時、それをOver ride \nした具象クラスのメソッド内で、どのように記述すれば Request1型のオブジェクトが受け取れるか \n \n上記の記述方法や、あるいは実装の構成案自体についてどうするべきかなど、ご教示頂けると大変助かります。\n\n※試みに、基底クラスのメソッド引数と戻り値を、リクエスト・レスポンス用のオブジェクト基底クラスで指定してみましたがリクエストの内容のダウンキャストができず、また戻り値の型も不一致のコンパイルエラーとなるため断念しました。 \n※クラス型を抽象的/相称的に扱うための Class<? extends\nRequestObjBase>やジェネリクスを使えば実装できそうな気がして調べてみましたが知見が乏しく、今回の目的のためにどのように記述すべきか分かりませんでした。 \n※メソッド引数と戻り値を Object\nにし、強制的にHashMapにキャストすることはできましたが、記述が煩雑となるため、できれば実装は上述のRequest1、Response1などの型を使って記述したいと考えています。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T09:10:27.670",
"favorite_count": 0,
"id": "77627",
"last_activity_date": "2021-06-18T21:02:43.477",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "42710",
"post_type": "question",
"score": 0,
"tags": [
"java",
"api",
"ジェネリクス"
],
"title": "APIのメソッドの引数、戻り値を抽象的に定義したい",
"view_count": 428
} | [
{
"body": "`<RESP extends ResponseObjBase>`\nのような[境界型パラメータ](https://docs.oracle.com/javase/tutorial/java/generics/bounded.html)で、利用できる型を制限できます。\n\n基底クラス:\n\n```\n\n public abstract class MyAbstractResource<RESP extends ResponseObjBase, REQ extends RequestObjBase> {\n \n @POST\n @Produces(MediaType.APPLICATION_JSON)\n public RESP execute(final REQ request) {\n \n // ...\n // 共通処理実行\n \n return executeSub(request);\n }\n \n protected abstract RESP executeSub(REQ request);\n \n }\n \n```\n\n具象リソースクラス:\n\n```\n\n @Path(\"/example1\")\n public class MyConcreteResource extends MyAbstractResource<Response1, Request1> {\n \n @Override\n protected Response1 executeSub(final Request1 request) {\n \n final Response1 reponse = new Response1();\n reponse.status = \"00\";\n reponse.message = \"\";\n \n return reponse;\n }\n }\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-18T21:02:43.477",
"id": "77647",
"last_activity_date": "2021-06-18T21:02:43.477",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "2808",
"parent_id": "77627",
"post_type": "answer",
"score": 0
}
] | 77627 | null | 77647 |
{
"accepted_answer_id": "77634",
"answer_count": 1,
"body": "例えば以下のような表があったとき、飛び飛びについている0の個数を検出したいです。\n\n```\n\n 実績A 1 1 1 1 1 1 1 1 1\n 実績B 1 1 0 1 0 1 1 1 1\n 実績C 1 1 0 0 0 0 1 1 1\n 実績D 0 0 0 1 1 1 0 0 0\n 実績E 1 1 1 1 1 0 0 0 0\n \n```\n\n例の場合、実績B、Cのように、0が1に挟まれている状態がNGです。実績Bは2個、Cは4個です。 \n実績DとEは、0は存在しますが、最初から連続している、または最後まで連続していて、1に挟まれていないのでOKです。\n\nいいアイデアがあればアドバイスいただけると嬉しいです。",
"comment_count": 4,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T10:14:39.613",
"favorite_count": 0,
"id": "77628",
"last_activity_date": "2021-06-17T21:27:02.930",
"last_edit_date": "2021-06-17T11:07:10.100",
"last_editor_user_id": "3060",
"owner_user_id": "46909",
"post_type": "question",
"score": -1,
"tags": [
"vba",
"excel"
],
"title": "Excelで、虫食い状になっている実績を検出したい",
"view_count": 202
} | [
{
"body": "* 先頭から連続する`0`をスキップ、つまり最初に出現する`1`を探す\n * 同様に末尾に連続する`0`をスキップ、つまり最後に出現する`1`を探す\n * これによって縮小された範囲の中で`0`をカウント\n\nで得られるのではありませんか?\n\n仮に検索範囲を`$B1:$J1`としたら\n\n```\n\n =LET(\n DATA, $B1:$J1,\n START, XMATCH(1, DATA, 0, 1),\n END, XMATCH(1, DATA, 0, -1),\n COUNTIF(OFFSET(DATA, 0, START-1, 1, END-START+1), 0)\n )\n \n```\n\nでできるかと。例示されている通り横並びで計算しましたが縦並びの場合は[`OFFSET`関数](https://support.microsoft.com/ja-\njp/office/offset-%E9%96%A2%E6%95%B0-c8de19ae-\ndd79-4b9b-a14e-b4d906d11b66)に与える引数を変えてください。",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T21:27:02.930",
"id": "77634",
"last_activity_date": "2021-06-17T21:27:02.930",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "4236",
"parent_id": "77628",
"post_type": "answer",
"score": 1
}
] | 77628 | 77634 | 77634 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "**実行環境:** \nWindows、Java1.8.0\n\nJAX-RS(Jersey)を使うAPIのエラー時の処理として現在、後述のようなコードを書いています。\n\nここで、特定の場合にレスポンスに任意のエンティティを格納つつ、BAD_REQUESTなどのHTTPステータスを返したいのですが、方法が分かりません。 \n(下記のコードでは、単にHttpServletResponseをimplementした「ResponseObj」にsetStatus()しているだけのため、機能しないようです(正常200で返ります)。\n\n```\n\n @Path(\"API_01\") // API呼出し時のURL\n \n @POST\n @Produces(MediaType.APPLICATION_JSON)\n public ResponseObj execute(RequestObj request) throws Exception {\n \n ResponseObj response = new ResponseObj();\n response.status = \"999\";\n response.message = \"エラー\";\n \n response.setStatus(Status.BAD_REQUEST.getStatusCode());\n \n return response;\n }\n \n```\n\n * POSTリクエストを送信すると上記のexecuteメソッドがJerseyから自動的に呼び出されます。\n * JSON形式のリクエスト内容がJerseyによって RequestObj に変換されます。\n * ResponseObjはスカラーのメンバ変数を持つ単純なVOですが、上記では試みに、 \nResponseObjはHttpServletResponseの実装としてHttpServletResponseを \nimplementし、setStatus()でHTTPステータスをセットしてみたものです。 \n(実行した結果、正常の200となりました)\n\n * 別途、 \n`return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();` \nを試したところ、想定通り400のHTTPステータスで返りましたが、レスポンスのBODY部 \nにResponseObjを格納する方法が分かりませんでした。 \n(HTTPレスポンスのBODY部にはResponseObjの内容のみ格納したいと考えています)\n\n上記のリクエスト受信のHttpServletResponseを取得し、それにsetStatus()することでHTTPステータスが設定できそうだと思いますが、上記のコンテキスト中?でHttpServletResponseを取得して任意のHTTPステータスをセットする方法が分からないため、ご教示頂けますでしょうか。\n\nもしくは、Responseビルダを使って生成するResponseのBODY部に任意のエンティティを格納する方法をご教示頂けますでしょうか。\n\nまた行おうとしといる処理内容と実装構成自体に問題があれば、ご指摘いただけますと大変助かります。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-17T13:07:21.097",
"favorite_count": 0,
"id": "77630",
"last_activity_date": "2023-08-08T03:09:26.183",
"last_edit_date": "2021-06-18T00:19:16.763",
"last_editor_user_id": "3060",
"owner_user_id": "42710",
"post_type": "question",
"score": 1,
"tags": [
"java",
"api"
],
"title": "APIのレスポンスで、BODYに任意のエンティティを格納してHTTPステータス200以外を返したい",
"view_count": 705
} | [
{
"body": "`Response` 型(`javax.ws.rs.core.Response` または\n`jakarta.ws.rs.core.Response`)を返すことで実現できます。\n\n * [3\\. Resources > 3.3.3. Return Type](https://jakarta.ee/specifications/restful-ws/3.0/jakarta-restful-ws-spec-3.0.html#resource_method_return)\n\n```\n\n @Path(\"API_01\")\n public class MyResource {\n \n @POST\n @Produces(MediaType.APPLICATION_JSON)\n public Response execute(final RequestObj request) throws Exception {\n \n final ResponseObj response = new ResponseObj();\n response.status = \"999\";\n response.message = \"エラー\";\n \n return Response.status(Status.BAD_GATEWAY).entity(response).build();\n }\n }\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-18T16:53:41.360",
"id": "77646",
"last_activity_date": "2021-06-18T16:53:41.360",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "2808",
"parent_id": "77630",
"post_type": "answer",
"score": 1
}
] | 77630 | null | 77646 |
{
"accepted_answer_id": "77636",
"answer_count": 1,
"body": "[local PC] ↔ [踏み台Server] ↔ [WebServer] \n※[WebServer]は閉ざされた環境\n\n踏み台Serverから以下のポートフォワーディングし、 \nlistened host … localhost:10100 \nconnect host … xxx.xxx.xxx.xxx:80\n\nブラウザから http://localhost:10100/ アクセスでapacheのdefault rootが表示される状態です。\n\nで、今回、WebServerにWebApplicationを導入したのですが、xxx.xxx.xxx.xxx:8888を指定してアクセスする仕組みとなっており、接続できずに行き詰ってしまいました。\n\nこのような場合、対処する方法はありますでしょうか?",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-18T00:47:14.223",
"favorite_count": 0,
"id": "77635",
"last_activity_date": "2021-06-18T01:24:56.470",
"last_edit_date": "2021-06-18T01:24:56.470",
"last_editor_user_id": "3060",
"owner_user_id": "46916",
"post_type": "question",
"score": 1,
"tags": [
"centos",
"network"
],
"title": "ポートフォワードしたWEBサーバへのポート指定によるブラウザ接続",
"view_count": 299
} | [
{
"body": "PCからWebサーバにアクセスすると、xxx.xxx.xxx.xxx:80にあるApacheのデフォルトのページを閲覧できるということですね。これを:8888につながるようにしたいので、「踏み台Server」の「connect\nhost」を xxx.xxx.xxx.xxx:8888 にすれば、Webアプリケーションにつながるはずです。",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-18T01:23:33.930",
"id": "77636",
"last_activity_date": "2021-06-18T01:23:33.930",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "7500",
"parent_id": "77635",
"post_type": "answer",
"score": 0
}
] | 77635 | 77636 | 77636 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "このエラーの意味と改善の仕方を教えてもらえないでしょうか\n\n[](https://i.stack.imgur.com/Jktcg.png)",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-18T06:28:51.703",
"favorite_count": 0,
"id": "77638",
"last_activity_date": "2021-06-18T07:39:27.500",
"last_edit_date": "2021-06-18T06:53:18.683",
"last_editor_user_id": "3060",
"owner_user_id": "46917",
"post_type": "question",
"score": -1,
"tags": [
"python"
],
"title": "エラーの原因を教えてください SyntaxError: invalid character in identifier",
"view_count": 6992
} | [
{
"body": "おそらく、`print(\"「{}」\" .format(s))`の後ろに全角空白文字あたりが付いているのでしょう。 \n閉じ括弧`)`の後ろに文字があるようでしたら、削除してみてください。\n\nそれから、それを直しても、その行のインデントが無いように見えたりするので、意図通りにソースコードが入力されているか、よく確かめてみてください。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-18T07:39:27.500",
"id": "77641",
"last_activity_date": "2021-06-18T07:39:27.500",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "26370",
"parent_id": "77638",
"post_type": "answer",
"score": 2
}
] | 77638 | null | 77641 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "javascriptを使って端末のカメラを起動するwebアプリを作成しています。 \n現在、getUserMediaを使って、起動したカメラの設定をいじっているおりまして、端末の画面にはリアカメラの映像を映し出すことが出来ています。 \nですが、シャッタースピードを変更する方法が分かっていない状態です。\n\n参考サイト \n[Web でカメラを使おう – WebRTC (getUserMedia) on WebView](https://houwa-\njs.co.jp/2019/06/20190604/)\n\ngetUserMediaでは、シャッタースピードの変更はできないのでしょうか。 \nまた、それ以外にシャッタースピードを設定する方法をご存知の方がいらっしゃいましたら、教えていただきたいです。 \nよろしくお願いいたします。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-18T09:41:17.770",
"favorite_count": 0,
"id": "77643",
"last_activity_date": "2021-06-19T04:49:30.267",
"last_edit_date": "2021-06-18T09:47:29.307",
"last_editor_user_id": "3060",
"owner_user_id": "46924",
"post_type": "question",
"score": 1,
"tags": [
"javascript",
"camera",
"webapi"
],
"title": "javascriptで端末のカメラを起動してシャッタースピードを変更したいです。",
"view_count": 517
} | [
{
"body": "こちらの記事とそこからのリンク先が類似の話題を扱っているようですが、おそらくChromeでしか動作しない実験的なAPIを使えば出来るのかもしれません。 \n[getUserMedia lock\nfocus/exposure](https://stackoverflow.com/q/29324556/9014308)\n\n> What I would like to do is, once the page starts taking snapshots, lock the\n> getUserMedia camera's focus/exposure, so that in between snapshot intervals\n> the environment can change without the light balance changing or the camera\n> refocusing. \n>\n> 私がやりたいのは、ページがスナップショットの撮影を開始したら、getUserMediaカメラのフォーカス/露出をロックして、スナップショットの間隔の間に、ライトバランスを変更したりカメラの焦点を合わせ直したりせずに環境を変更できるようにすることです。\n\n> Not yet. Unfortunately, WebRTC does not allow photo-level access to cameras,\n> but a new Image Capture spec is being worked on to solve this. None of the\n> browsers implement it yet though. >未だに。\n> 残念ながら、WebRTCはカメラへの写真レベルのアクセスを許可していませんが、これを解決するために新しいImageCapture仕様に取り組んでいます。\n> ただし、どのブラウザもまだ実装していません。\n\n[Take photo when the camera is automatically\nfocused](https://stackoverflow.com/q/47637708/9014308) \n[Why the difference in native camera resolution -vs- getUserMedia on iPad /\niOS?](https://stackoverflow.com/q/52900311/9014308)\n\n* * *\n\nこの辺の記事を読むと、`exposure`とか`iso`に関連する情報を操作することで、間接的にシャッタースピードを操作出来るように見えます。\n\n[シャッター速度 -\nWikipedia](https://ja.wikipedia.org/wiki/%E3%82%B7%E3%83%A3%E3%83%83%E3%82%BF%E3%83%BC%E9%80%9F%E5%BA%A6)\n/ [Shutter speed - Wikipedia](https://en.wikipedia.org/wiki/Shutter_speed)\n\n> シャッター速度(シャッターそくど、英: Shutter speed\n> )は、カメラによる写真撮影の際、シャッターが開放され、フィルムまたは撮像素子がレンズを通した光にさらされる(露出する)時間(露光時間、シャッタースピード、「SS」とも略される)をいう。\n\n[CAMERA EXPOSURE](https://www.cambridgeincolour.com/tutorials/camera-\nexposure.htm)\n\n[MediaStream Image Capture](https://www.w3.org/TR/image-capture/)\n\n> W3C Working Draft, 6 April 2021 \n> [9.4. MediaTrackSettings dictionary](https://www.w3.org/TR/image-\n> capture/#mediatracksettings-section) \n> DOMString exposureMode; \n> double exposureCompensation; \n> double exposureTime; \n> double iso;\n\n[MediaStream Image Capture\nAPI](https://developer.mozilla.org/ja/docs/Web/API/MediaStream_Image_Capture_API)\n\n> Experimental \n> これは実験的な機能です。 \n> 本番で使用する前にブラウザー互換性一覧表をチェックしてください。\n\n[Web でカメラを使おう – WebRTC (getUserMedia) on WebView](https://houwa-\njs.co.jp/2019/06/20190604/)\n\n> 細かい制御 \n> 参考までに各ブラウザでの実行結果を載せておきます。 \n> Google Chrome\n>\n> \"exposureCompensation\": true, \n> \"exposureMode\": true, \n> \"exposureTime\": true, \n> \"iso\": true,\n\n* * *\n\n何かキーワードで関連しそうなもの \n[Q.\nUSBカメラの露出値と露光時間(シャッタースピード)の関係](http://faq.hozan.co.jp/support/faq/detail?site=ZAWBTM42&id=239) \n[LinuxでUVC(USB Video\nClass)タイプのUSBカメラを使う](https://qiita.com/nonbiri15/items/9593d61a2be81f2b31a9) \n[ガイドカメラ](http://norikyu.blogspot.com/p/blog-page_11.html) \n[Pythonでカメラを制御する【研究用】](https://qiita.com/opto-line/items/7ade854c26a50a485159)",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-19T04:49:30.267",
"id": "77649",
"last_activity_date": "2021-06-19T04:49:30.267",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "26370",
"parent_id": "77643",
"post_type": "answer",
"score": 1
}
] | 77643 | null | 77649 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "昔はファイルサーバー+アップデート担当者、それから次の時代はCVS、今はSubversionを使っています. \nSubversion以前は、ほぼプログラムの置き場程度の使い方、作り方だったのですが、さすがに今ではそんな管理ではとても開発の現場の動きについてゆけません.このため、\n\n * 基本的には受託の顧客単位のリポジトリがあり\n * リポジトリには`/trunk`、`/branches`、`/tags` があります.\n\nおよその使い方のルールは以下のようなものです.\n\n * 顧客からの依頼/開発コンポーネント毎にブランチを切って、開発はそこで集中的に行います.開発が終わってメンテナンスフェーズに入れば、`/trunk`にマージします.\n * しかし、現在運用しているプログラムで不具合報告が上がれば、`/trunk`からブランチを切って、そこで障害対応を行い、修正完了できれば`/trunk`にマージします.\n * あとプログラム開発の単位をバージョンNNというように切り分けるのがなかなか難しいのですが、さすがに年度単位で発注/納品は完了しますので、その際は`/tags`に`/trunk`から移します.(ブランチを切ります)\n\n聞きたいことはこのようにバージョン管理に馴染むものと、そうでないものの使い分けです.顧客単位のプロジェクトなので、リポジトリ割り当ては1つなんですが、以下のようなものも管理しなければなりません.\n\n * ドキュメント類(これは大きな量にならないのでそんなには問題にはならない)\n * 顧客から渡されるテストデータ(どうしても開発メンバー間で共有して取っておかねばならないのですが、たまに膨大なサイズになります)\n * フォントなど(最近はNotoフォントなんかを使うお客様がいるので、環境を一気に作れるようSubversionに入れています.大きいですね)\n * 直接顧客にリリースするプログラムではありませんが、データをコンバージョンしたり、検証を行うために開発/使用するユーティリティ的なプログラム\n\nこのようなものも`/trunk`に入れるとします.そうすると上記のファイル類を入れたタイミングと`/trunk`から開発/障害対応ブランチを切ったタイミングに依りますが、\n**開発作業でブランチ間を`switch`で行き来する際に、ファイルの作成/削除でやたらオーバーヘッドがかかる場合が発生します.**\nこれにはちょっとついてゆけないと感じることがしばしばです.\n\n上記のようにあまりバージョン管理に馴染まないものは、どのようにリポジトリを組み立てるのがベストプラクティスなのでしょうか?\n\n 1. `/trunk`、`/branches`、`/tags`と並列のフォルダで`/docs`、`/test-data`、`/resources`、`/tools`のようなものを作って管理する.\n 2. そもそもこのようなものは別のリポジトリを作って管理する.\n\n※ 1. は`/trunk`、`/branches`、`/tags`と`/docs`、`/test-\ndata`、`/resources`でフォルダ構成が異なるでしょう.\n\nお知恵がありましたらよろしくお願いいたします.\n\n以上",
"comment_count": 4,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-19T02:16:32.943",
"favorite_count": 0,
"id": "77648",
"last_activity_date": "2021-06-20T21:07:51.623",
"last_edit_date": "2021-06-20T21:07:51.623",
"last_editor_user_id": "9503",
"owner_user_id": "9503",
"post_type": "question",
"score": 0,
"tags": [
"svn"
],
"title": "Subversionのリポジトリの持ち方について",
"view_count": 466
} | [
{
"body": "※あくまで私が考える配置方法で、最適解ではありません。そのうえでお読みいただければ。\n\nコメントにも同じく記載されていますが、「対象のデータはバージョン管理に必要か」を基準としてsvnのリポジトリに含めるかどうか決めるのがベターなのではないかと思います。\n\n * ドキュメントはバージョンによって変わっていくのでリポジトリに含めます。ただし既存の`/trunk` `/branches` `/tags`と並列には作らず、コードと同列の扱いで保管します。ただ、ドキュメント量が多くなってくると質問に書かれている通りチェックアウト時の待ち時間が膨大になります(実際そんな管理方法をしていたことがありました...)。システム規模に依るのでドキュメントのデータ量が膨大になるのであればドキュメント専用のリポジトリを作ってもらうのも選択肢として考えてみてください。\n * 顧客から渡されるテストデータはそのバージョン限り、または当該バージョン以降で使用する不変のデータと考えられます。よって、リポジトリには含めません。データサイズが大きいのがネックなので別ストレージに保管し、その保管先を書いたメモを当該バージョンに含めるのは問題ないと思います。\n * フォントファイルなどのリソースファイルはシステムの一部ですし、バージョンアップによって変わっていく可能性のあるものなのでリポジトリに入れる対象でしょうか。基本的に不変のものであれば別ストレージに保存しておき、リポジトリには保管先のメモを置いたりストレージからコピーしてくるバッチファイルを書いたりすると良いかもしません。ただ、フォントくらいならCDN化を検討できないかなと思います(インターネットに接続できない環境であれば仕方ありませんが)\n * 開発の補助プログラムやユーティリティは、その顧客のプロダクト専用のものであればソースコードと同様にバージョン管理しても差し支えないのかなと思います。複数のプロジェクトで共通して使うユーティリティ等は別リポジトリでバージョン管理するのが適切であると思います。\n\nドキュメントに関してもう一つ。私が以前の勤務先で管理していたリポジトリは以下の用になっていました。\n\n```\n\n /部門名\n /A-system-src\n /trunk\n /branches\n /tags\n /A-system-doc\n /trunk\n /branches\n /tags\n /B-system-src\n /trunk\n /branches\n /tags\n /B-system-doc\n /trunk\n /branches\n /tags\n \n```\n\nソースコードとドキュメントを別々のサブディレクトリにしてあるのでドキュメント側のデータが膨大になってもソース側に影響しません。ただしこの構成ではIDEに付属するバージョン管理機能はほぼ使用できなくなるので不便さはありました。 \nドキュメント等はIDEで管理しないので、質問者さんの案通り`/docs`ディレクトリ等を作ってソースコード側とは別サブディレクトリにしてしまうのも良い手だとは思います。ただしバージョン管理すべきかどうかを勘案して決めたほうが良いと思います(結局ソース側とは連動しない別管理になってしまうので)",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-19T15:03:44.243",
"id": "77659",
"last_activity_date": "2021-06-19T15:03:44.243",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "46944",
"parent_id": "77648",
"post_type": "answer",
"score": 1
}
] | 77648 | null | 77659 |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "glibcを `make install` しようとすると `aarch64-linux-gnu-gcc: Command not found` \nとエラーが出てしまいます。 \nコマンド `aarch64-linux-gnu-gcc` 自体はパスが通っており、ターミナルで `aarch64-linux-gnu-gcc`\nの実行は可能です。\n\nmakeがパスをうまく認識してくれないのですが対処法を教えて頂きたいです。",
"comment_count": 4,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-19T04:57:11.523",
"favorite_count": 0,
"id": "77650",
"last_activity_date": "2021-06-19T05:08:39.357",
"last_edit_date": "2021-06-19T05:08:39.357",
"last_editor_user_id": "3060",
"owner_user_id": "46934",
"post_type": "question",
"score": 0,
"tags": [
"linux",
"makefile"
],
"title": "glibcのビルド時のCommand not foundエラー",
"view_count": 53
} | [] | 77650 | null | null |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "material-uiの下記リンクスナックバーのようなものを作成しようとしています。 \n<https://material-ui.com/ja/components/snackbars/#complementary-projects>\n\nその際のアニメーションで、要素が削除されたときに縦に移動するアニメーションの実装方法がわからず困っています。\n\n理想↓↓\n\n[](https://i.stack.imgur.com/swPw8.gif)\n\n現実↓↓ このように削除されたときにガタッと要素が詰められてしまう\n\n[](https://i.stack.imgur.com/bGHml.gif)\n\n横のアニメーションは `transform: translateX(-250px);` -> `transform: translateX(0);`\nのように行っています。\n\nどのような実装の方法があるでしょうか?思いつかず悩んでおります... \n教えていただける方いらっしゃればよろしくお願いします",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-19T10:47:24.127",
"favorite_count": 0,
"id": "77652",
"last_activity_date": "2021-06-19T16:46:48.853",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "46940",
"post_type": "question",
"score": 1,
"tags": [
"html",
"css",
"reactjs"
],
"title": "縦に積み上がる要素の削除したときに、下にガタっと落ちてしまうのを滑らかにアニメーションしたい",
"view_count": 400
} | [
{
"body": "左右にスライドするアニメーションが期待通りの動きであるならば、縦方向の動きも横方向と同様、 `transitionY`\nに適切な値を投入すれば上下方向のアニメーションができるはずです。 \nまた、画面外に消えたスナックバーをDOMからremoveするのであれば、アニメーションが終わったタイミングを見計らう必要もあるでしょう。\n\n質問文にコードが載っていないので実際どのように実装されているか定かではありませんが、比較的簡単に実現できる方法としては、\n\n * スナックバーのpositionを `fixed`にする\n * 位置関係は`left` `bottom`で調整する\n * `setTimeout` を使って、スライドするアニメーションと画面に残ったスナックバーを下に下げるアニメーションの実行にディレイをかける\n\nという方針になるかと思います。\n\n[codepenでサンプル](https://codepen.io/haruyan-\nhopemucci/pen/abJxzqv)を作成したので、参考にしてください。おそらく現状のあなたの実装とは異なる部分が多いと思いますが、実装例の一つとして参考になるはずです。\n\n```\n\n var snackbar_stack = []; // 画面上に出ているスナックバーを入れておく配列\n var SNACKBAR_MAX = 3; //画面上に配置できるsnackbarの最大数\n var SNACKBAR_HEIGHT = 50; // スナックバーのheight値\n var snackbar_area = document.querySelector('div.snackbar-area');\n \n function add_snackbar(){\n let sb = document.querySelector('#snackbar-template').content.cloneNode(true);\n let outer = sb.querySelector('.snackbar-outer');\n // console.log(outer);\n let shiftbar = null; // もし最大数を超えるスナックバーを追加する際、追い出されるスナックバーのNode\n let idx = snackbar_stack.push(outer) -1; // idxはスナックバー挿入位置\n if(snackbar_stack.length > SNACKBAR_MAX){\n // 最大数を超えるスナックバーがpushされている場合は、先頭を取り出しておく。\n shiftbar = snackbar_stack.shift();\n }\n // console.log(shiftbar);\n // スナックバーをDOMに追加\n snackbar_area.appendChild(sb);\n // 追加するスナックバーの初期Y位置。\n outer.style.bottom = `${idx * SNACKBAR_HEIGHT}px`;\n // 追加するスナックバーと追い出されるスナックバーのX位置をsetTimeoutで指定。\n // こうすることでtransitionが有効になる。(ディレイ0でもOK)\n setTimeout(() => {\n // スライドアウトするほう\n if(shiftbar){\n shiftbar.style.left = '-500px';\n }\n // スライドインしてくる方\n outer.style.left = `0px`;\n },0);\n \n // スナックバーのスライドイン、スライドアウトアニメが終了した後に残りのスナックバーを\n // 下方向にスライドさせる。ディレイ値にtransitionで指定したtransition-durationと同じ秒数を設定。\n // 同じくtransitionが有効。\n setTimeout( () => {\n // スライドアウトしたスナックバーはこのタイミングでDOMから削除すれば表示に影響はない。\n if(shiftbar){\n shiftbar.remove();\n }\n // 各スナックバーのY方向を再設定。\n snackbar_stack.forEach((e,i) => e.style.bottom = `${i * SNACKBAR_HEIGHT}px` );\n }, 300);\n }\n```\n\n```\n\n .snackbar-outer{\n /* positionは画面ベースで固定 */\n position: fixed;\n display: flex;\n justify-content: center;\n align-items: center;\n margin: 5px;\n /* width, heightは具体的に指定しておく */\n width: 200px;\n height: 40px;\n /* 挿入時の初期位置(X方向) */\n left: -300px;\n /* Y方向の初期位置は状況により変わるので初期値は適当で良い */\n bottom: 0;\n background-color: #333;\n color: #ddd;\n border-radius: 5px;\n box-shadow: 2px 2px 5px 1px #00000080;\n /* 比較的早目で、functionをease-inにすると軽く重力で落下するようなエフェクトになる */\n transition: all .3s ease-in; \n .snackbar-inner{\n width: 100%;\n text-align: center;\n }\n }\n```\n\n```\n\n <button id=\"add-snackbar\" onclick=\"add_snackbar()\">add snackbar</button>\n \n <!-- snackbarを配置する要素はどこにあっても良い。中身だけがfixedになるので。 -->\n <div class=\"snackbar-area\"></div>\n \n <template id=\"snackbar-template\">\n <div class=\"snackbar-outer\">\n <div class=\"snackbar-inner\">notification.</div>\n </div>\n </template>\n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-19T14:13:52.003",
"id": "77658",
"last_activity_date": "2021-06-19T16:46:48.853",
"last_edit_date": "2021-06-19T16:46:48.853",
"last_editor_user_id": "3068",
"owner_user_id": "46944",
"parent_id": "77652",
"post_type": "answer",
"score": 3
}
] | 77652 | null | 77658 |
{
"accepted_answer_id": "77660",
"answer_count": 2,
"body": "親プロセスが子プロセスを起動し、子プロセスは親プロセスがコマンドを打つたびに結果を返す。 \nコマンドと結果のやり取りは標準入出力で一行ずつやり取りする。 \nということを考えています。\n\n次のような実験を行ったのですが、下のようなエラーが出てうまくいきません。どのようにすればよいでしょうか。\n\nメイン:\n\n```\n\n import subprocess\n import sys\n \n with subprocess.Popen(\n [sys.executable, \"sub.py\"],\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n encoding=\"utf-8\"\n ) as p:\n print(\"hoge\", file=p.stdin)\n # TODO: 受け取り処理\n \n```\n\nsub.py:\n\n```\n\n from sys import stderr, stdin, stdout\n \n for line in stdin:\n # 通る 正常にファイルができる\n with open(\"out.txt\", \"a\") as f:\n print(line, file=f)\n \n # 通る 正常にコンソールに表示される\n print(line, file=stderr)\n \n # 通らない\n print(line)\n \n```\n\nエラー:\n\n```\n\n Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='cp932'> \n OSError: [Errno 22] Invalid argument\n \n```\n\n環境: \nwindows10 \npython 3.9.5",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-19T13:06:03.620",
"favorite_count": 0,
"id": "77654",
"last_activity_date": "2021-06-19T17:34:57.930",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "20885",
"post_type": "question",
"score": 0,
"tags": [
"python"
],
"title": "サブプロセスの標準出力を取得したい",
"view_count": 1194
} | [
{
"body": "`PIPE`を使っていて, 子プロセスから文字列出力しているのに, 親プロセスで受け取っていないから例外が出てるようですね\n\n`# TODO: 受け取り処理` 辺りに処理を追加するとよいかも \n(追記: この処理は, まとめて送信・受信, をおこなうもので「交互にやり取り」は **できません** )\n\n```\n\n stdout = p.communicate()[0]\n print(f'{stdout=}')\n p.stdin.close()\n \n```\n\n* * *\n\nあと, `stdin`に `print`するのも 考えてみれば奇妙に映るかもなので, コメントに記す, それっぽいコードにする?など対策あってもよいかも\n\n```\n\n # print 使わないで書き込むとか\n p.stdin.write('hello world\\n')\n p.stdin.write('this is a pen\\n')\n \n```\n\n```\n\n # print 使うにしてもそれっぽいこと示すとか\n from contextlib import redirect_stdout\n with redirect_stdout(p.stdin):\n print('hello world\\n')\n print('this is a pen\\n')\n \n```\n\n* * *\n\n#### (コメントにより)追記\n\n親プロセスと子プロセスで「 **交互** 」にやりとり行うのですね?\n\nその場合, Python同士なら [multiprocessing ---\nプロセスベースの並列処理](https://docs.python.org/ja/3/library/multiprocessing.html)\nが利用可能でプロセス間通信機能もそれなり豊富です\n\n`subprocess.Popen` 使用する場合, そのままだと標準入力待ちで制御が奪われます(戻ってこない) \nなので, スレッドあるいは(プロセス, あるいは)非同期処理を併用することになるでしょう\n\n * 非同期処理 (stackoverflow.com) [python asyncio how to read StdIn and write to StdOut? \n](https://stackoverflow.com/questions/64303607/python-asyncio-how-to-read-\nstdin-and-write-to-stdout)\n\n* * *\n\n#### さらに追記\n\ngenerator使う方法があるようです\n\n(元記事からの抜粋)\n\n```\n\n def get_lines():\n \n while True:\n line = proc.stdout.readline()\n if line:\n yield line\n \n if not line and proc.poll() is not None:\n break\n \n```\n\n組み合わせが問題ですが, 例えばこんなふうに (記事に合わせ `p` => `proc` として記述)\n\n```\n\n gen = get_lines()\n \n proc.stdin.write('hello world\\n')\n proc.stdin.flush()\n print(next(gen))\n \n proc.stdin.write('this is a pen\\n')\n proc.stdin.flush()\n print(next(gen))\n \n```\n\n参考:\n[Pythonのsubprocessで標準出力をリアルタイムに取得する](https://qiita.com/megmogmog1965/items/5f95b35539ed6b3cfa17)",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-19T14:00:07.007",
"id": "77655",
"last_activity_date": "2021-06-19T17:34:57.930",
"last_edit_date": "2021-06-19T17:34:57.930",
"last_editor_user_id": "43025",
"owner_user_id": "43025",
"parent_id": "77654",
"post_type": "answer",
"score": 0
},
{
"body": "pipe を `flush` するという方法もあるかと思います。\n\n**main.py**\n\n```\n\n import subprocess\n import sys\n \n with subprocess.Popen(\n [sys.executable, \"sub.py\"],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE,\n encoding=\"utf-8\",\n ) as p:\n for msg in ['hoge', 'fuga', 'piyo']:\n print(msg, file=p.stdin, flush=True)\n line = p.stdout.readline()\n print(line.strip())\n \n```\n\n**sub.py**\n\n```\n\n from sys import stderr, stdin, stdout\n \n for line in stdin:\n print(f'OK: {line.strip()}', flush=True)\n \n```\n\n**実行**\n\n```\n\n $ python3 --version\n Python 3.9.5\n $ python3 main.py\n OK: hoge\n OK: fuga\n OK: piyo\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-19T17:32:54.133",
"id": "77660",
"last_activity_date": "2021-06-19T17:32:54.133",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77654",
"post_type": "answer",
"score": 1
}
] | 77654 | 77660 | 77660 |
{
"accepted_answer_id": "77665",
"answer_count": 1,
"body": "長文大変失礼いたします.\n\n## 背景\n\nXMLで書かれたドキュメント群を変換してHTMLにし、CSSや画像ファイルとセットでパブリッシングするのをやっています.日本語だけでなく多言語をやっております.今般お客様の意向で、従来CSSで`@font-\nface`で指定していたフォントファイルを、今はやりのWeb Fontに置き換えることになりました.\n\n主な狙いは日本語フォントなんだろうと思います.サーバー側に置いたTrueTypeやOpenTypeのフォントを直接`@font-\nface`でアサインしてしまうと、フォントファイルの大きさはそれなりにありますので、ダウンロードやハンドリングに時間がかかります.Web\nFontを使うと、HTMLに忍び込ませたJavaScriptで、そのWebページで使っている文字を調べて、動的にサーバー側から`.woff`でサブセット化して送ってくれるそうです.それならブラウザの負担も減るでしょう.(早いかどうかはいろいろ議論があるようです)\n\nさて、Web Fontにすると、今までCSSの中で自分で`@font-face`を指定したものが、Web\nFontのサービスが自動的に生成してくれるCSSの`.woff`への`@font-face`を使うようになります.Web\nFontのサービスは、CSSの`font-family:~;`指定から、自動的に`@font-face`を自動生成してくれるようです.\n\nここまではいいことづくめだったのですが、問題が持ち上がりました.実はCSSの中には、`font-weight:\nbold;`が当たり前に書かれています.ところがWeb\nFontの`.woff`を使用するようになると、ブラウザは自動的にボールドフェースをシミュレートしてくれなくなるのです.それまでTrueTypeのフォントファイルを`@font-\nface`でアサインしていた時は、ブラウザがボールドフェースをシミュレート表示してくれていました.\n\nこの結果、`font-weight:\nbold;`はすべて無視されちゃって、Webページはノーマルフェースだけで文字の表示という、実にのっぺらぽうなものになってしまいます.これはとても見ていられません.\n\nこれを解決するにはWeb Fontを使う限り、以下のようにしなければなりません.(英文フォントの例になります.ファミリー名は正確ではありません)\n\n * 大元を取り仕切るCSSで`font-family: FuturaPro-Light;`とやっていたら\n * ボールドにしたいときは、あちこちのCSSに存在する`font-weight: bold;`はダメで、例えば`font-family: FuturaPro-Book;`と書かねばならない.(これで太字に見えてくれます)\n\nでもですね、フロントエンドのデザイナーさんが作ったCSSは、言語にほぼ全部共通で同じもを使っているのです.なので、運用側の都合で、ある言語ではWeb\nFontを使用、でもある言語ではクライアントにあるsans-serifでいいやというのは非常に困るのです.`font-weight:\nbold;`くらいは、どのフォントを使用しようが、それを意識することなしに自由に記述したいものです.\n\nちなみに多言語ですが、`font-\nfamily`の指定は大本のCSSの一ヶ所でやっているだけです.もちろんアラビア語なんかのためのLTR/RTLには対応しています.(以下で少々触れますSassで吸収しています.)\n\n## 考えた方法\n\n仕方がないのでWeb Fontを使用する言語のビルドでは、最終盤のステップでCSSの中の`font-weight:\nbold;`があったら、そのメディアやセレクタを覚えておいて、最後に`font-family: FuturaPro-\nBook;`と追記してやろうか??と考えました.\n\nではこれをどうやってやるかを考えたのですが、パブリッシングのためのビルドで、プログラムでCSSを書き換えるってそう簡単ではないですよね.システムがJavaベースなのでJavaのCSSのパーサーを探しました、パーサーでCSSを読んで、それをXML(!)に変換してしまう、そのXMLを読んで上記の書き換え処理をXSLTで実装して、結果をまたCSSに書き戻すというものです.Webで良く出てくる\n[CSS Parser](https://sourceforge.net/projects/cssparser/)\nを試してみたんですが、次のようなCSSを食わせるとお亡くなりになってしまいました.\n\n```\n\n @charset \"UTF-8\";\n body { direction: ltr; }\n body { font-family: \"メイリオ\",Meiryo,\"ヒラギノ角ゴ Pro W3\",\"Hiragino Kaku Gothic Pro\",HiraKakuPro-W3,\"MS Pゴシック\",\"MS PGothic\",Osaka,Verdana,sans-serif; color: #000; line-height: 1.5; background-color: #fff; overflow: hidden; }\n \n```\n\n以下は試してみたプログラムの一部:\n\n```\n\n public class Css2XmlImpl {\n private String mInputCssPath;\n private String mOutputXmlPath;\n \n /**\n * Constructor\n * @param inputCssPath\n * @param outputXmlPath\n * @throws IOException \n */\n public Css2XmlImpl(String inputCssPath, String outputXmlPath) throws IOException {\n mInputCssPath = inputCssPath;\n mOutputXmlPath = outputXmlPath;\n }\n public void parse() throws IOException {\n InputStream cssStream = null;\n XmlWriter xmlOutput = null;\n try {\n xmlOutput = new XmlWriter(mOutputXmlPath);\n cssStream = new FileInputStream(mInputCssPath);\n InputSource source = new InputSource();\n source.setByteStream(cssStream);\n source.setEncoding(\"UTF-8\");\n SACParserCSS3 parser = new SACParserCSS3();\n parser.setDocumentHandler(new Css2XMLHandler(xmlOutput));\n parser.parseStyleSheet(source);\n }\n catch (IOException ioe)\n {\n System.err.println (\"IO Error: \" + ioe);\n }\n catch (Exception e)\n {\n System.err.println (\"Error: \" + e);\n \n }\n finally\n {\n xmlOutput.close(); \n }\n }\n }\n \n class Css2XMLHandler implements DocumentHandlerExt {\n // ここでSaxのようにCSSパーサーのいろんなイベントを拾ってXMLに書く.\n }\n \n```\n\nこけたときの途中結果のXMLはこんな感じです.\n\n```\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <css>\n <charset arg=\"UTF-8\"/>\n <selector>\n <selector-item>body</selector-item>\n <property name=\"direction\" LexicalUnit=\"ltr\" important=\"false\"/>\n </selector>\n <selector>\n <selector-item>body</selector-item>\n <property name=\"font-family\" LexicalUnit=\"メイリオ\" important=\"false\"/>\n </selector>\n </css>\n \n```\n\nどうも\n\n```\n\n font-family: \"メイリオ\",Meiryo,\"ヒラギノ角ゴ Pro W3\",\"Hiragino Kaku Gothic Pro\",HiraKakuPro-W3,\"MS Pゴシック\",\"MS PGothic\",Osaka,Verdana,sans-serif;\n \n```\n\nの`font-family`の記述がパージングできずに、その先おかしくなってしまうようです.結果は以下のように出ます.\n\n```\n\n Error: org.w3c.css.sac.CSSException: unknown error\n \n```\n\n確かにちょっと変則的な書き方ですが、これくらいのCSSがパージングできないようでは全然ダメですね.\n\n## お伺いしたいこと\n\n私が直面している問題は、Web\nFontを使用するなら、フォントには依存しますが、どのような方でも共通じゃないか?と思うのですが、いかがでしょう?実際どのように解決しておられるでしょうか?\n\n## 追記\n\n実は、パブリッシングのためのビルドで、Sassを使用しています.なので、`.scss`ファイルの`font-weight:\nbold;`を、`@include bold-font`のようなmixinに置き換えて、そのmixinのbold-\nfontをSassのコンパイル毎に動的に生成しようかという案もありました.\n\n[動的に生成するmixin:Web Fontの場合]\n\n```\n\n @mixin bold-font {\n font-family: FuturaPro-Book;\n }\n \n```\n\n[動的に生成するmixin:Web Fontでない場合]\n\n```\n\n @mixin bold-font {\n font-weight: bold;\n }\n \n```\n\nでもよく考えるとCSSというフロントデザインを、Web\nFontを使うか/使わないか?という運用の問題でmixinに書き換えるというのも何か変な気がします.フロントエンド側はそこまで考えずに、デザインするのが筋ではないかと?なので、できたら、最終版でCSSを一気に書き換える方法をとりたいと考えております.\n\n以上 よろしくお願いいたします.",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-19T18:21:22.527",
"favorite_count": 0,
"id": "77661",
"last_activity_date": "2021-06-21T10:32:54.023",
"last_edit_date": "2021-06-20T02:43:21.940",
"last_editor_user_id": "9503",
"owner_user_id": "9503",
"post_type": "question",
"score": 0,
"tags": [
"java",
"css",
"sass"
],
"title": "ビルドでCSSを書き換えるには?",
"view_count": 123
} | [
{
"body": "`@font-face`は同名の`font-family`でweightの異なるフォントファイルを複数登録できます。 \n例えば、weightの違う複数のwoff2ファイルを持つフォント \"Foo Sans\"があったとします。\n\n```\n\n @font-face {\n font-family: 'Foo Sans';\n src: url('./assets/fonts/fooSans-Regular.woff2') format(\"woff2\");\n font-weight: normal;\n font-style: normal; \n }\n @font-face {\n font-family: 'Foo Sans';\n src: url('./assets/fonts/fooSans-Bold.woff2') format(\"woff2\");\n font-weight: bold;\n font-style: normal; \n }\n \n```\n\n上記の様にフォントファイルを配置し、\n\n```\n\n .foo{\n font-family: 'Foo Sans';\n font-size: 24pt;\n font-weight: normal;\n }\n .bold{\n font-weight: bold;\n }\n \n```\n\nというスタイルを用意すれば、html側で\n\n```\n\n <div>これは通常のフォントです。</div>\n <div class=\"foo\">これは Foo Sans フォントです。</div>\n <div class=\"foo bold\">これは Foo Sans フォントの bold です。</div>\n \n```\n\nと記載すれば、3行目のdivは期待通り Foo Sans の太字で表示されます。\n\n自前でwoffファイルを配信するのであれば上記の方法で問題なくfont-weightの指定ができる(しかも当該font-\nweightの指定がないドキュメントであれば当該のフォントファイルはロードされない)と思われますが、例えばfontplusなどのサービスを使用している場合はscriptでフォントファイルとcssを生成しているので標準的な方法では難しいかもしれません。(エンタープライズプランであればこのようなカスタマイズに応じてもらえるかもしれません) \nあるいは、これもfontplus限定の話ですがwebフォントのロードが完了したらコールバック関数を仕掛けることができるようなので、そのコールバック関数でcssの中身を解析して回答本文のような`@font-\nface`を生成する、という方法も考えられます。\n\n### 追記\n\nコメントと、私が投稿時に考えていたアイデアを具体的にご紹介します。\n\nfontplusのフォントは仰る通りjavascriptでドキュメントの中身を走査し、実際に使用されているフォントをDOMツリーに組み込んでいるようです(その際組み込んだstyleタグには特定のidが付与されているようです)\n\n```\n\n @font-face {\n font-family: 'FuturaPro-Light';\n font-weight: bold;\n src: url(FuturaPro-LightのURL);\n }\n \n @font-face {\n font-family: 'FuturaPro-Book';\n font-weight: bold;\n src: url(FuturaPro-BookのURL);\n }\n \n```\n\njavascriptのAPIで公開されている、フォントがロード完了したら実行できるコールバック関数内で、上記style要素を探し、以下のようなcssを追加します。\n\n```\n\n @font-face {\n font-family: 'FuturaPro';\n font-weight: normal;\n src: url(FuturaPro-LightのURL);\n }\n \n @font-face {\n font-family: 'FuturaPro';\n font-weight: bold;\n src: url(FuturaPro-Book);\n }\n \n```\n\nfont-familyは同名にし、weightを変え、src内のurlはスクリプトで追加されたurlを抽出して同じ値をセットします。 \nこのcssを追加すれば、ドキュメント内でベースのfont-familyを `font-family: 'FuturaPro'; font-weight:\nnormal;`とし、要所で`font-weight: bold;`が使えるのではないか、ということです。\n\nただし、javascriptでドキュメント内のfont-familyを走査しているのであれば実際に`FuturaPro-\nLight`などのフォント指定が出てこなければなりません。そこで、ドキュメントベースのfont-familyを\n\n```\n\n font-family: 'FuturaPro', 'FuturaPro-Light', 'FuturaPro-Book';\n \n```\n\nというように指定すし(抽出対象が全文字になってしまいますが)、javascript側で代替フォント部分までフォローしてくれるのであれば指定したフォントを取得してないだろうか、ということろまでが私のアイデアです。\n\nまた、javascfriptのAPIには [フォント指定](https://fontplus.jp/usage/javascript-\napi/method#api-8)というものがあり、これを使用すれば上記のfont-family指定に関係なく指定のフォントが取得できるのかもしれません。",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-20T13:26:25.573",
"id": "77665",
"last_activity_date": "2021-06-21T10:32:54.023",
"last_edit_date": "2021-06-21T10:32:54.023",
"last_editor_user_id": "46944",
"owner_user_id": "46944",
"parent_id": "77661",
"post_type": "answer",
"score": 1
}
] | 77661 | 77665 | 77665 |
{
"accepted_answer_id": "77667",
"answer_count": 2,
"body": "提示コードのvoid\nWait();関数部ですがwaitTime変数の値を表示させたのですが常にマイナスの値が出力されてしまい待機してくれません。なぜ待機してくれなのでしょか?待機できな程の負荷がかかってるとは到底思えないコードのため必ずこの数字はプラスの値が来ると思われるのですがなぜなのでしょうか?\n\n確認したこと \n変数はすべてコンストラクタ部で初期化0の値\n\n```\n\n #define FRAME_RATE 60\n \n```\n\n参考サイト: <https://dixq.net/g/03_14.html> \n※ clock();関数はミリ秒を返す関数です。\n\n追記clock()関数はCPU時間を返すの間違えていますよって以下のうにglfwGetTime()関数を使って秒をdouble型で取得してそれに1000掛けることによってミリ秒を取得しています。よって下の提示コードのclock();関数部は以下の関数に書き換えましたが \n矩形を描画して移動させていましたがなんか突っかかる感じがするのでまだ間違えています。\n\n```\n\n int getTime()\n {\n return (int)(glfwGetTime() * 1000.0f);\n }\n \n```\n\n利用ライブラリ \nglew \nglfw \nopengl \nstb 関係ありません \nglm 関係ありません \nfreeType 関係ありません\n\n[](https://i.stack.imgur.com/ua15T.png)\n\n```\n\n // ##################################### 待機フレームを計算 ##################################### \n void FrameWork::Window::FrameUpdate(glm::vec4 color)\n {\n float c = 1.0f / 255.0f;\n glClearColor(color.x * c, color.y * c, color.z * c, color.w * c); //カラーバッファのクリア色\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_ACCUM_BUFFER_BIT); //フレームバッファを初期化\n \n glEnable(GL_BLEND); //アルファブレンド有効\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //ブレンドタイプ\n \n //フレームレートを制御する\n \n if (count == 0)\n {\n startCount = (int)clock();\n }\n \n if (count == FRAME_RATE)\n {\n startCount = (int)clock();\n count = 0;\n }\n \n count++;\n }\n \n // ##################################### フレームを取得 ##################################### \n int FrameWork::Window::getFrame()\n {\n return count;\n }\n \n // ##################################### フレームレート 待機 ##################################### \n void FrameWork::Window::Wait()\n {\n int tookTime = clock() - startCount;\n int waitTime = (count * 1000 / FRAME_RATE) - tookTime;\n \n \n std::cout << waitTime << std::endl;\n \n if (waitTime > 0)\n {\n //std::cout << waitTime << std::endl;\n \n std::this_thread::sleep_for(std::chrono::milliseconds(waitTime));\n }\n }\n \n```",
"comment_count": 8,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-20T04:50:21.680",
"favorite_count": 0,
"id": "77662",
"last_activity_date": "2021-06-20T18:57:00.557",
"last_edit_date": "2021-06-20T10:59:20.333",
"last_editor_user_id": null,
"owner_user_id": null,
"post_type": "question",
"score": -1,
"tags": [
"c++",
"opengl"
],
"title": "clock();関数を使ってミリ秒を利用したフレームレートを制御の仕方が知りたい。待機するミリ秒を得たい。",
"view_count": 482
} | [
{
"body": "何が何でも`clock()`を使う必要があるのでしょうか?\n既に`<chrono>`を使われているようですので、[`std::chrono::steady_clock::now()`](https://ja.cppreference.com/w/cpp/chrono/steady_clock/now)に切り替えることをお勧めします。 \nあわせて期間を指定する`sleep_for()`ではなく時刻を指定する[`std::this_thread::sleep_until()`](https://ja.cppreference.com/w/cpp/thread/sleep_until)に切り替えると更に簡単になります。\n\n```\n\n std::chrono::steady_clock::time_point startTime;\n constexpr auto FrameInterval = 10ms;\n \n```\n\nとしておけば\n\n```\n\n void FrameWork::Window::Wait() {\n std::this_thread::sleep_until(startTime + FrameInterval);\n }\n \n```\n\nで済みませんか?",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-20T05:25:11.773",
"id": "77663",
"last_activity_date": "2021-06-20T05:25:11.773",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "4236",
"parent_id": "77662",
"post_type": "answer",
"score": 2
},
{
"body": "> 矩形を描画して移動させていましたがなんか突っかかる感じがするのでまだ間違えています。\n\n回答ではないのですが、以下の環境で適当にプログラムを作成してみました(`FrameUpdate()` と `Wait()`\nメソッドと同等の関数を含みます)。\n\n```\n\n $ lsb_release -d\n Description: Ubuntu 21.04\n \n $ apt-show-versions libglu1-mesa\n libglu1-mesa:amd64/hirsute 9.0.1-1build1 uptodate\n \n $ apt-show-versions libglfw3\n libglfw3:amd64/hirsute 3.3.2-1 uptodate\n \n $ apt-show-versions libglew-dev\n libglew-dev:amd64/hirsute 2.1.0-4 uptodate\n \n $ glmark2 --fullscreen --show-all-options\n =======================================================\n glmark2 2021.02\n =======================================================\n OpenGL Information\n GL_VENDOR: Intel\n GL_RENDERER: Mesa Intel(R) UHD Graphics 630 (CFL GT2)\n GL_VERSION: 4.6 (Compatibility Profile) Mesa 21.0.1\n =======================================================\n [build] duration=10.0:fps-pos=-1.0,-1.0:fps-size=0.03:fragment-precision=default,default,default,default:\n interleave=false:model=horse:nframes=:show-fps=false:title=:title-pos=-0.7,-1.0:title-size=0.03:\n use-vbo=false:vertex-precision=default,default,default,default: FPS: 1334 FrameTime: 0.750 ms\n [build] duration=10.0:fps-pos=-1.0,-1.0:fps-size=0.03:fragment-precision=default,default,default,default:\n interleave=false:model=horse:nframes=:show-fps=false:title=:title-pos=-0.7,-1.0:title-size=0.03:\n use-vbo=true:vertex-precision=default,default,default,default: FPS: 1380 FrameTime: 0.725 ms\n =======================================================\n glmark2 Score: 1357 \n =======================================================\n \n```\n\n60 FPS では以下の様になります。こちらの環境では突っかかる感じは見受けられません。\n\n[](https://i.stack.imgur.com/Yl61U.gif)\n\n`WaitTime` は 15ms 〜 17ms でした。また、参考までに 30 FPS, 70 FPS での結果も載せておきます。\n\n```\n\n $ ./moving_rectangle > record.dat\n \n # 60 FPS\n $ datamash --header-out min 1 max 1 mean 1 sstdev 1 < record.dat\n min max mean sstdev\n 15 17 16.317 0.636\n \n # 30 FPS\n $ datamash --header-out min 1 max 1 mean 1 sstdev 1 < record.dat\n min max mean sstdev\n 32 34 32.957 0.693\n \n # 70 FPS\n $ datamash --header-out min 1 max 1 mean 1 sstdev 1 < record.dat\n min max mean sstdev\n -150 14 -62.016 48.470\n \n```",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-20T18:57:00.557",
"id": "77667",
"last_activity_date": "2021-06-20T18:57:00.557",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77662",
"post_type": "answer",
"score": 1
}
] | 77662 | 77667 | 77663 |
{
"accepted_answer_id": "77668",
"answer_count": 1,
"body": "pygameを主に用いてシューティングゲームを作っています.弾の数が多くなると動作が非常に遅くなります. \n原因はfor文を多用していることではないかと考えています. \n下にコードを載せました.処理が早くなる方法を教えていただけると幸いです.\n\n<https://github.com/bobubobusuwawa/Nozaki_Ryo/tree/images>",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-20T07:51:07.777",
"favorite_count": 0,
"id": "77664",
"last_activity_date": "2021-06-22T05:55:24.990",
"last_edit_date": "2021-06-20T09:55:34.697",
"last_editor_user_id": "45588",
"owner_user_id": "45588",
"post_type": "question",
"score": -1,
"tags": [
"python",
"pygame"
],
"title": "pygameで作ったシューティングゲームで弾の数が多くなると動作が非常に遅くなる.",
"view_count": 627
} | [
{
"body": "弾の座標などを管理するリストの元の数を必要以上に大きくしていたことが原因でした. \n小さくすると動作しました.",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-21T00:31:05.543",
"id": "77668",
"last_activity_date": "2021-06-22T05:55:24.990",
"last_edit_date": "2021-06-22T05:55:24.990",
"last_editor_user_id": "45588",
"owner_user_id": "45588",
"parent_id": "77664",
"post_type": "answer",
"score": 1
}
] | 77664 | 77668 | 77668 |
{
"accepted_answer_id": null,
"answer_count": 2,
"body": "SPRESENSE BLE-EVK-701 を SPRESENSE SDKで動作確認が出来ませんでした。\n\n■環境 \nubuntu 18.04 \nVSCode V1.57.0 \nSPRESENSE SDK v2.2.0 \nブートローダ v2.2.0\n\n■状況 \nArduino SDK 環境では、動作確認が出来ており、 \nAndroidのBLEスキャナーアプリ(BLE Scanner)から、 \nペリフェラルアドバタイズパケットを確認、コネクション確立、送受信のサンプル動作確認済みです。\n\nしかしながら、SPRESENSE環境下では動作の確認が出来ません。 \nそのため、ハードウェア起因では無いと考えております。\n\nSPRESENSE環境下で試したことは下記です。\n\n * SPRESNSE SDKのExampleの実行 \n以下手順\n\n 1. SDKコンフィグ ー> 新規作成\n 2. Feature の bluetoothを選択\n 3. Example の ble_central, ble_peripheralを選択\n 4. ビルドー>書き込み\n 5. ble_peripheralを実行し、上記スキャナーアプリで確認 \nBLUETOOTH_LE_NAMEに記述されている\"SONY-BLE-CLASSIC\"というデバイス名で \nスキャナーアプリから確認できるかと思いましたが、デバイスを検出出来ませんでした。\n\n * [rohmのExample](https://github.com/RohmSemiconductor/NuttX/tree/master/examples/bluetooth)の実行 \nSPRESNSE SDKのExampleの実行手順に加え、 \n上記リンクのbluetooth.cを、新しいアプリケーションでコピーして実行。 \nSPRESNSE SDKのExampleの実行と同様、デバイス名を確認できませんでした。\n\n手順の誤りや、 \nどのような手順で実行すればよいか等ご教授願えますでしょうか。 \nよろしくお願いいたします。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-21T01:15:23.220",
"favorite_count": 0,
"id": "77669",
"last_activity_date": "2021-09-13T03:44:34.563",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "40647",
"post_type": "question",
"score": 0,
"tags": [
"spresense",
"bluetooth",
"bluetooth-lowenergy"
],
"title": "SPRESENSE BLE-EVK-701 が SPRESENSE SDKで動作確認ができない",
"view_count": 380
} | [
{
"body": "Spresense SDKにある Bluetooth のドライバは、bluetooth\\hal\\bcm20706 を見る限り、\n\n<https://github.com/sonydevworld/spresense/tree/master/sdk/modules/bluetooth/hal/bcm20706>\n\nCypress 社の BCM20706 のみ対応に見えますね。\n\n<https://www.digikey.jp/catalog/ja/partgroup/bcm20706/62903>\n\nなので、feature/bluetooth のコンフィグでは、SPRESENSE BLE-EVK-701 の MK71251-02A は動かないみたいです。\n\nRohmさんのページに NuttXのドライバもあるみたいです。\n\n<https://www.rohm.co.jp/support/spresense-add-on-board>",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-09-04T00:09:54.757",
"id": "82222",
"last_activity_date": "2021-09-04T00:09:54.757",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "32281",
"parent_id": "77669",
"post_type": "answer",
"score": 0
},
{
"body": "下記GitHubリンクにアップしているSPRESENSE BLE-EVK-701向けNuttXサンプルドライバの開発者の一人です。\n\n[Driver and sample app, GitHub, Rohm\nSemiconductor](https://github.com/RohmSemiconductor/NuttX)\n\n・上記手順を確認しましたが特に問題と思えることは見つかりませんでした。\n\n・ハードウェアの構成について確認させてください。SPRESENSEメインボード[CXD5602PWBMAIN1]とBLEボード[SPRESENSE BLE-\nEVK-701]は直接コネクタ接続されているでしょうか?それとも中間にSPRESENSE拡張ボード[CXD5602PWBEXT1]を介して接続されているでしょうか?後者の場合、メインボード上でUART2をEnableするためにコネクタJP10のP1とP2をショートする必要があります。(下記Readmeに記載)こちらはいかがでしょうか?\n\n[Readme for BT sample, GitHub, Rohm\nSemiconductor](https://github.com/RohmSemiconductor/NuttX/blob/master/examples/bluetooth/README.txt)",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-09-06T08:41:33.113",
"id": "82288",
"last_activity_date": "2021-09-13T03:44:34.563",
"last_edit_date": "2021-09-13T03:44:34.563",
"last_editor_user_id": "48088",
"owner_user_id": "48088",
"parent_id": "77669",
"post_type": "answer",
"score": 0
}
] | 77669 | null | 82222 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "この前から色々検索しながらnode.jsとjavascriptを使用してサイトを作ろうとしています。 \n複数のクエリの結果をejsに送るというコードを書こうとしているのですが、エラーになってしまいます。 \nres.renderの前でresults[0].length、results[1].length、results[2].lengthをすると正しいサイズが表示されるので、多分取得は出来ていると思います。 \n<https://stackoverflow.com/questions/42974598/unexpected-token-return-in-\nwhile-compiling-ejs> \n<https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Errors/Malformed_formal_parameter> \n上記の質問などがヒットしましたが、includeは使っていません。 \nejs-lintも使用してみました。\n\n```\n\n /home/ubuntu/views/results.ejs\n 1:1 error Parsing error: Unexpected token <\n \n ✖ 1 problem (1 error, 0 warnings)\n \n```\n\nしかし、1行目の1文字目の<はhtmlタグなので、そこでエラーが出るとは考えにくいです。 \n初歩的な質問で申し訳ございません。皆様の知恵をお借りしたいです。 \nよろしくお願い致します。\n\n```\n\n //server.js\n const express = require('express');\n const app = express();\n const bodyParser = require('body-parser');\n app.use(bodyParser.urlencoded({ extended: true }));\n \n let http = require('http');\n let fs = require('fs');\n let mysql = require('mysql');\n \n const connection = mysql.createConnection({\n multipleStatements:true,\n host: 'localhost',\n user: 'ユーザー名',\n password: 'パスワード',\n database: 'データベース名'\n });\n \n connection.connect(function(err) {\n if (err) throw err;\n console.log('Connected');\n });\n \n app.use(express.static('public'));\n app.get('/', (req, res) => {\n res.render('index.ejs');\n \n });\n \n app.post(\"/result\", (req, res) => {\n let selected = req.body.selected_series;\n let series;\n let human_series, item_series, quotation_series;\n //クエリを変数に入れる\n if(selected === \"one\"){\n series = \"SELECT * FROM human where series = \" + 1 + \"; SELECT * FROM item WHERE series = \" + 1 + \";\"; \n }else if(selected === \"two\"){\n series = \"SELECT * FROM human where series = \" + 2 + \"; SELECT * FROM item WHERE series = \" + 2 + \"; SELECT * FROM quotation WHERE series\" + \";\";\n \n }else if(selected === \"nt\"){\n series = \"SELECT * FROM human where series = \" + 3 + \"; SELECT * FROM item WHERE series = \" + 3 + \"; SELECT * FROM quotation series = \" + 3 + \";\";\n }else{\n human_series = Math.floor( Math.random() * 4 );\n item_series = Math.floor( Math.random() * 4 );\n quotation_series = Math.floor( Math.random() * 4 );\n series = \"SELECT * FROM human where series = \" + human_series + \"; SELECT * from item where series = \" + item_series + \"; SELECT * from quotation where series = \" + quotation_series +\";\";\n }\n connection.query(\n series,\n (error, results) => {\n res.render('results.ejs', {humans: results[0], items:results[1], quotations: results[2]});\n } \n );\n });\n \n \n app.listen(3000, () => {\n console.log(\"My app listening on port 3000!\");\n });\n \n```\n\n表示するためのreults.ejs\n\n```\n\n <html>\n <head>\n <title>結果</title>\n </head>\n <body>\n <% Object.values(humans); %>\n <% Object.values(items); %>\n <% Object.values(quotations); %>\n <p>-----登場人物-----</p>\n <% humans.forEach(human) => { %>\n <%= human %>\n <% } %>\n <p>-----アイテム-----</p>\n <% items.forEach(item) => { %>\n <%= item %>\n <% } %>\n <p>-----一言-----</p>\n <% quotations.forEach(quotation) => { %>\n <%= quotation %>\n <% } %>\n <a href=\"/\">もう一度占う</a>\n </body>\n </html>\n \n```\n\nエラー内容\n\n```\n\n SyntaxError: Malformed arrow function parameter list in /home/ubuntu/views/results.ejs while compiling ejs\n \n If the above error is not helpful, you may want to try EJS-Lint:\n https://github.com/RyanZim/EJS-Lint\n Or, if you meant to create an async function, pass `async: true` as an option.\n at new Function (<anonymous>)\n at Template.compile (/home/ubuntu/node_modules/ejs/lib/ejs.js:662:12)\n at Object.compile (/home/ubuntu/node_modules/ejs/lib/ejs.js:396:16)\n at handleCache (/home/ubuntu/node_modules/ejs/lib/ejs.js:233:18)\n at tryHandleCache (/home/ubuntu/node_modules/ejs/lib/ejs.js:272:16)\n at View.exports.renderFile [as engine] (/home/ubuntu/node_modules/ejs/lib/ejs.js:489:10)\n at View.render (/home/ubuntu/node_modules/express/lib/view.js:135:8)\n at tryRender (/home/ubuntu/node_modules/express/lib/application.js:640:10)\n at Function.render (/home/ubuntu/node_modules/express/lib/application.js:592:3)\n at ServerResponse.render (/home/ubuntu/node_modules/express/lib/response.js:1012:7)\n \n```\n\n追記 \nserver.jsに値を渡しているので一応index.ejsも貼ります。\n\n```\n\n <html>\n <head>\n <meta charset=\"utf8\">\n <script src=\"https://code.jquery.com/jquery-3.5.1.min.js\"></script>\n <script type=\"text/javascript\" src=\"siren.js\"></script>\n <link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\">\n <title>たいとる</title>\n </head>\n <body>\n <p>シリーズを選択してください</p>\n <form action=\"/result\" method=\"POST\">\n <select id=\"select_series\" name=\"selected_series\">\n <option value=\"none\" name=\"series\">--選択してください--</option>\n <option value=\"one\" name=\"series\">SIREN</option>\n <option value=\"two\" name=\"series\">SIREN2</option>\n <option value=\"nt\" name=\"series\">SIREN:NT</option>\n <option value=\"all\" name=\"series\">全シリーズ</option>\n </select>\n <button type=\"submit\" id=\"select\">決定</button>\n </form>\n <div id=\"result\"></div>\n </body>\n </html>\n \n```",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-21T02:31:00.640",
"favorite_count": 0,
"id": "77670",
"last_activity_date": "2022-09-07T09:07:05.660",
"last_edit_date": "2021-06-21T02:36:15.673",
"last_editor_user_id": "46953",
"owner_user_id": "46953",
"post_type": "question",
"score": 0,
"tags": [
"mysql",
"node.js"
],
"title": "node.jsとmysqlで複数のqueryを実行したい",
"view_count": 835
} | [
{
"body": "ありがとうございます。 \nforEachの書き方が違うという初歩的なミスでした。\n\n```\n\n <html>\n <head>\n <title>結果</title>\n </head>\n <body>\n <% Object.values(humans); %>\n <% Object.values(items); %>\n <% Object.values(quotations); %>\n <p>-----登場人物-----</p>\n <% humans.forEach(human => { %>\n <%= human %>\n <% }); %>\n <p>-----アイテム-----</p>\n <% items.forEach(item => { %>\n <%= item %>\n <% }); %>\n <p>-----一言-----</p>\n <% quotations.forEach(quotation => { %>\n <%= quotation %>\n <% }); %>\n <a href=\"/\">もう一度占う</a>\n </body>\n </html>\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-21T02:48:15.150",
"id": "77671",
"last_activity_date": "2021-06-21T02:48:15.150",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "46953",
"parent_id": "77670",
"post_type": "answer",
"score": 1
}
] | 77670 | null | 77671 |
{
"accepted_answer_id": null,
"answer_count": 2,
"body": "Linuxで下記のような事象に遭遇しました。ご存じの方は教えて欲しいです。\n\n### 事象\n\n`df -h` コマンドでマウントしているボリュームが50GBのサイズを有している\n\n`du -h` コマンドでマウントしているディレクトリの総サイズを調べてみたら、59GBでした。\n\n### 質問1\n\n何故duで計算した結果はボリュームのサイズを超えたか?\n\n### 質問2\n\nこの二つのコマンドの計算が違うか?\n\n### 試したこと\n\n * duのハードリンク、シンボルリンクと辿らないようなオプションを付ける\n * findコマンドでtypeがfの全部を探して、duで個々のサイズを計算し、総量を出す\n\n### 想像した原因\n\n 1. ハードリンク、シンボルリンクが数回duによって計算された \n→ findでファイルだけ出して計算しても同じなので、関係なさそう\n\n 2. 該当ディレクトリのしたにまたは別のボリュームがマウントしている \n→ なかった\n\n 3. Windowsのような、ファイルを圧縮して保存という機能が有効 \n→ 不明",
"comment_count": 5,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-21T02:52:30.057",
"favorite_count": 0,
"id": "77672",
"last_activity_date": "2021-06-24T07:01:09.160",
"last_edit_date": "2021-06-21T05:57:43.540",
"last_editor_user_id": "3060",
"owner_user_id": "46960",
"post_type": "question",
"score": 3,
"tags": [
"linux",
"filesystems"
],
"title": "dfコマンドで出力したサイズを超えたduの計算結果の原因を求める",
"view_count": 407
} | [
{
"body": "ボリュームのマウントポイント(=計測ポイント)のディレクトリのサブディレクトリに別のボリュームをマウントしている場合、「`du`」の結果が「`df`」の結果を超える(ボリュームサイズを超える)ことがあると思います。\n\n例えば、次のような場合、`du`の結果が`df`の結果を超えます。\n\n```\n\n Filesystem Size Used Avail Use% Mounted on\n /dev/sda3 50G 40G 10G 80% /var\n /dev/sda4 20G 18G 2G 90% /var/log\n \n```\n\n * `df -h /var`は`50G`となる。(50GBのSize)\n * `du -sh /var`は`58G`となる。(Usedの`40G`と`18G`の合計値)",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T10:35:02.697",
"id": "77740",
"last_activity_date": "2021-06-23T10:35:02.697",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "20098",
"parent_id": "77672",
"post_type": "answer",
"score": -1
},
{
"body": "思いつくのはこれくらいですね。\n\n 1. オープンしたまま削除されたファイルが存在している。 \n`lsof /path/to/mount/point |grep '(deleted)$`\n\n 2. 拡張属性 (SELinux ラベルも含む) が大量に付与されているファイルが多数存在する。\n\n`getfattr --recursive --no-dereference --dump /path/to/mount/point`\n\n 3. ACL が大量に付与されているファイルが多数存在する。\n\n`getfacl --recursive /path/to/mount/point`\n\n 4. ファイルシステムが壊れている。\n\n多くの場合は 1、稀に 4 はあるかと思いますが、2 と 3 は見たことありません。 \nちなみに拡張属性と ACL は、少ない数とサイズであれば、inode 内に保存されます。(ファイルシステムの種類と inode サイズに依る。Linux\nなら XFS や ext4)",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-24T07:01:09.160",
"id": "77755",
"last_activity_date": "2021-06-24T07:01:09.160",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "3061",
"parent_id": "77672",
"post_type": "answer",
"score": 0
}
] | 77672 | null | 77755 |
{
"accepted_answer_id": "80507",
"answer_count": 1,
"body": "#### やりたいこと\n\nPythonでメール内の処理でエラーが発生したら、特定のサイトにエラー通知を飛ばしたいです。 \n下記のコードのようにtryのブロック内にエラー通知を検知したいです。\n\n * if でメールが無い場合: 正常終了\n * エラーがある場合: exceptに飛ばしたい\n\nメールの有無を判定する分岐\n\n```\n\n if not time: \n return d[\"NULL\"]\n else:\n print('DL OK メールがあるので処理続く')\n \n```\n\n現状だとtryのブロック内でエラーが発生してもexceptに飛ばないです。 \n定義した関数で return を利用しているからでしょうか。\n\n```\n\n import imaplib, re, email, six, dateutil.parser\n import json\n import requests\n \n def a(d): \n try:\n mail=imaplib.IMAP4_SSL('imap.gmail.com',993) #SMTPは993,POPは995\n mail.login('[email protected]','12345')\n mail.select('testlabel') #メールボックスの選択\n \n #UNSEEN未読メールを読み込む\n type,data=mail.search(None,'UNSEEN') #メールボックス内にあるすべてのデータを取得ALL\n \n for i in data[0].split(): #data分繰り返す\n ok,x=mail.fetch(i,'RFC822') #メールの情報を取得\n ms=email.message_from_string(x[0][1].decode('iso-2022-jp')) #パースして取得\n \n #差出人を取得\n ad=email.header.decode_header(ms.get('From'))\n ms_code=ad[0][1]\n if(ms_code!=None):\n address=ad[0][0].decode(ms_code)\n address+=ad[1][0].decode(ms_code)\n else:\n address=ad[0][0]\n \n #タイトルを取得\n sb=email.header.decode_header(ms.get('Subject'))\n ms_code=sb[0][1]\n if(ms_code!=None):\n sbject=sb[0][0].decode(ms_code)\n else:\n ms_code=sb[1][1]\n sbject=sb[1][0].decode(ms_code)\n \n #本文を取得\n maintext=ms.get_payload()\n \n #メールの日時を取得\n time = dateutil.parser.parse(ms.get('Date')).strftime(\"%Y-%m-%d %H:%M\")[:-1]\n print(time)\n \n #出力\n print(sbject)\n print(address)\n print(maintext)\n \n \n #Data confirm null確認\n if not time:\n return d[\"NULL\"]\n #print('NULL')\n else:\n print('DL OK メールがあるので処理続く')\n \n mail.close()\n mail.logout() \n \n except :\n # エラー発生時ここにくる\n example_url =\"https://wh.example.com/connect-api/webhook/12234/abcd\"\n example_header ={ \n \n \"Accept\": \"application/vnd.tosslab.example-v2+json\",\n \"Content-Type\": \"application/json\"\n }\n example_payload ={\n \n \"body\": \"Error\",\n \"connectColor\": \"#FF0000\",\n \"connectInfo\": [{\n \n \"title\":\"正常に実行できませんでしたので、\\nご確認お願い致します。\"\n }\n ]\n }\n # post to example\n requests.post(url=example_url, data=json.dumps(example_payload), headers=example_header, timeout=10)\n \n print('正常終了')\n \n```",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-21T03:19:09.323",
"favorite_count": 0,
"id": "77673",
"last_activity_date": "2022-05-18T11:40:16.150",
"last_edit_date": "2022-05-18T11:40:16.150",
"last_editor_user_id": "3060",
"owner_user_id": "18859",
"post_type": "question",
"score": 0,
"tags": [
"python",
"python3",
"exception"
],
"title": "try ブロックでエラーが発生しても、意図した通り except に飛ばない",
"view_count": 407
} | [
{
"body": "さらに良いことに、あなたは例外を投げることができます\n\n```\n\n #...\n if not time:\n raise ValueError(\"Value null\")\n #return d[\"NULL\"]\n #print('NULL')\n else:\n #...\n \n```\n\nこれにより、このブロックは `except` ブロックに渡されます。",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-07-31T19:02:32.677",
"id": "80507",
"last_activity_date": "2021-07-31T19:02:32.677",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "47532",
"parent_id": "77673",
"post_type": "answer",
"score": 1
}
] | 77673 | 80507 | 80507 |
{
"accepted_answer_id": "77888",
"answer_count": 1,
"body": "現在リアルタイムにサーマルカメラで撮影し取得した画像に対し,keras-\nyolo3というpythonの物体検出ライブラリを用いて物体検出を行うことを考えています.\n\nサーマルカメラで撮影し,画像を取得したらその画像を保存するというプログラムを実行したところ,1秒に約10~11枚の画像が出力されました(FPS平均は約10).\n\nここに取得した画像をkeras-\nyolo3で読み込み,検出結果を出力するようにプログラムを書き換えて実行したところ,1枚の画像に対して物体検出に約10秒かかってしまいました(FPS平均は約0.1).\n\n目標としては,10枚の画像に対して1秒で物体検出を行えるようにしたいのですが,処理速度を上げるにはどうすればいいでしょうか.\n\n### 環境\n\nWindows10 \nAnaconda 64bit \nPython 3.6.6 \nGPU: GeForce RTX 2060 (Computer Capability : 7.5) \nCUDA 10.0 \ncuDNN 7.4 \ntensorflow-gpu 1.13.1 \nkeras 2.2.4 \nnumpy 1.16.4\n\n### 参考\n\n * [keras-yolo3 GitHub](https://github.com/qqwweee/keras-yolo3)\n * [keras-yolo3を使ってリアルタイム物体検出を簡単に試してみる](https://arakan-pgm-ai.hatenablog.com/entry/2019/03/20/090000)\n * [keras-yolo3で独自データセットの学習方法](https://sleepless-se.net/2019/06/21/how-to-train-keras%E2%88%92yolo3/)\n\n### ソースコード\n\n物体検出のプログラム(といってもyolo.pyの中身を少し修正したもの)\n\n```\n\n import colorsys\n import os\n import numpy as np\n import cv2\n from timeit import default_timer as timer\n from keras import backend as K\n from keras.models import load_model\n from keras.layers import Input\n from PIL import Image, ImageFont, ImageDraw\n from yolo3.model import yolo_eval, yolo_body, tiny_yolo_body\n from yolo3.utils import letterbox_image\n from keras.utils import multi_gpu_model\n \n from time import time\n \n class YOLO(object):\n _defaults = {\n \"model_path\": 'model_data/trained_nose.h5',\n \"anchors_path\": 'model_data/yolo_anchors.txt',\n \"classes_path\": 'model_data/my_classes_nose.txt',\n \"score\" : 0.3,\n \"iou\" : 0.45,\n \"model_image_size\" : (416, 416),\n \"gpu_num\" : 1,\n }\n \n @classmethod\n \n def get_defaults(cls, n):\n if n in cls._defaults:\n return cls._defaults[n]\n else:\n return \"Unrecognized attribute name '\" + n + \"'\"\n \n \n def __init__(self, **kwargs):\n self.__dict__.update(self._defaults)\n self.__dict__.update(kwargs)\n self.class_names = self._get_class()\n self.anchors = self._get_anchors()\n self.sess = K.get_session()\n self.boxes, self.scores, self.classes = self.generate()\n \n \n def _get_class(self):\n classes_path = os.path.expanduser(self.classes_path)\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n \n \n def _get_anchors(self):\n anchors_path = os.path.expanduser(self.anchors_path)\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return np.array(anchors).reshape(-1, 2)\n \n \n def generate(self):\n model_path = os.path.expanduser(self.model_path)\n assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.'\n num_anchors = len(self.anchors)\n num_classes = len(self.class_names)\n is_tiny_version = num_anchors==6\n try:\n self.yolo_model = load_model(model_path, compile=False)\n except:\n self.yolo_model = tiny_yolo_body(Input(shape=(None,None,3)), num_anchors//2, num_classes) \\\n if is_tiny_version else yolo_body(Input(shape=(None,None,3)), num_anchors//3, num_classes)\n self.yolo_model.load_weights(self.model_path) # make sure model, anchors and classes match\n else:\n assert self.yolo_model.layers[-1].output_shape[-1] == \\\n num_anchors/len(self.yolo_model.output) * (num_classes + 5), \\\n 'Mismatch between model and given anchor and class sizes'\n #print('{} model, anchors, and classes loaded.'.format(model_path))\n \n hsv_tuples = [(x / len(self.class_names), 1., 1.)\n for x in range(len(self.class_names))]\n self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\n self.colors = list(\n map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),\n self.colors))\n np.random.seed(10101)\n np.random.shuffle(self.colors)\n np.random.seed(None)\n \n self.input_image_shape = K.placeholder(shape=(2, ))\n if self.gpu_num>=2:\n self.yolo_model = multi_gpu_model(self.yolo_model, gpus=self.gpu_num)\n boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors,\n len(self.class_names), self.input_image_shape,\n score_threshold=self.score, iou_threshold=self.iou)\n return boxes, scores, classes\n \n \n def detect_image(self, image, t_start, num):\n \n image = image.convert('RGB')\n \n t = time()\n pass_time = t - t_start\n print(\"yolo_time_3: \",pass_time)\n \n if self.model_image_size != (None, None):\n assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required'\n assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required'\n boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size)))\n else:\n new_image_size = (image.width - (image.width % 32),\n image.height - (image.height % 32))\n boxed_image = letterbox_image(image, new_image_size)\n \n t = time()\n pass_time = t - t_start\n print(\"yolo_time_4: \",pass_time)\n \n image_data = np.array(boxed_image, dtype='float32')\n image_data /= 255.\n image_data = np.expand_dims(image_data, 0)\n out_boxes, out_scores, out_classes = self.sess.run(\n [self.boxes, self.scores, self.classes],\n feed_dict={\n self.yolo_model.input: image_data,\n self.input_image_shape: [image.size[1], image.size[0]],\n K.learning_phase(): 0\n })\n \n font = ImageFont.truetype(font='font/FiraMono-Medium.otf',\n size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))\n thickness = (image.size[0] + image.size[1]) // 300\n \n t_l_b_r = []\n \n t = time()\n pass_time = t - t_start\n print(\"yolo_time_5: \",pass_time)\n \n for i, c in reversed(list(enumerate(out_classes))):\n predicted_class = self.class_names[c]\n box = out_boxes[i]\n score = out_scores[i]\n \n label = '{} {:.2f}'.format(predicted_class, score)\n draw = ImageDraw.Draw(image)\n label_size = draw.textsize(label, font)\n \n top, left, bottom, right = box\n top = max(0, np.floor(top + 0.5).astype('int32'))\n left = max(0, np.floor(left + 0.5).astype('int32'))\n bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))\n right = min(image.size[0], np.floor(right + 0.5).astype('int32'))\n t_l_b_r.append(top)\n t_l_b_r.append(left)\n t_l_b_r.append(bottom)\n t_l_b_r.append(right)\n #print(t_l_b_r)\n print(label, (left, top), (right, bottom))\n \n if top - label_size[1] >= 0:\n text_origin = np.array([left, top - label_size[1]])\n else:\n text_origin = np.array([left, top + 1])\n \n for i in range(thickness):\n draw.rectangle([left + i, top + i, right - i, bottom - i],outline=self.colors[c])\n \n draw.rectangle([tuple(text_origin), tuple(text_origin + label_size)],fill=self.colors[c])\n draw.text(text_origin, label, fill=(0, 0, 0), font=font)\n del draw\n \n t = time()\n pass_time = t - t_start\n print(\"yolo_time_6: \",pass_time)\n \n result = np.asarray(image)\n result = cv2.cvtColor(result, cv2.COLOR_RGB2BGR)\n \n <検出結果を表示,保存します>\n \n cv2.namedWindow(\"result\", cv2.WINDOW_NORMAL)\n cv2.imshow(\"result\", result) \n cv2.imwrite(\"d:/study_data/image_'+format(num)+'.bmp\",result)\n \n return t_l_b_r\n \n def close_session(self):\n self.sess.close()\n \n \n```\n\nメインのプログラム\n\n```\n\n import usb.core\n import usb.util\n import numpy as np\n import os\n from PIL import Image\n from yolo_ex import YOLO\n \n import sys\n import argparse\n \n ~~~~~\n \n 関係ない箇所については省略させていただきます\n \n ~~~~~\n \n <yolo.video.py から拾ってきました>\n \n FLAGS = None\n parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)\n parser.add_argument('--model_path', type=str,help='path to model weight file, default ' + YOLO.get_defaults(\"model_path\"))\n parser.add_argument('--anchors_path', type=str,help='path to anchor definitions, default ' + YOLO.get_defaults(\"anchors_path\"))\n parser.add_argument('--classes_path', type=str,help='path to class definitions, default ' + YOLO.get_defaults(\"classes_path\"))\n parser.add_argument('--gpu_num', type=int,help='Number of GPU to use, default ' + str(YOLO.get_defaults(\"gpu_num\")))\n parser.add_argument('--image', default=False, action=\"store_true\",help='Image detection mode, will ignore all positional arguments')\n parser.add_argument(\"--input\", nargs='?', type=str,required=False,default='./path2your_video',help = \"Video input path\")\n parser.add_argument(\"--output\", nargs='?', type=str, default=\"\",help = \"[Optional] Video output path\")\n FLAGS = parser.parse_args()\n \n <main関数です>\n \n if __name__ == '__main__':\n import cv2\n from time import time\n \n num = 0\n \n <カメラからデータを取得します>\n \n t0 = time()\n \n time_np = np.empty(0)\n \n while True:\n \n t = time()\n if num == 0:\n t_start = time()\n pass_time = t - t_start\n print(\"\\n\\nyolo_time_1: \",pass_time)\n \n time_np = np.append(time_np, pass_time)\n t0 = time()\n \n <熱カメラからデータを取得し,輝度値に変換します> \n \n image = cam.get_image()\n image = rescale(image)\n image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)\n \n <得られた画像にサイズ変換を施します>\n \n image = add_margin(image,SIZE)\n \n image = Image.fromarray(image)\n tt = time()\n pass_time2 = tt - t_start\n print(\"yolo_time_2: \",pass_time2)\n \n <検出プログラムに画像を渡します>\n \n image_yolo = YOLO.detect_image(YOLO(**vars(FLAGS)), image, t_start, num)\n \n num += 1\n \n if cv2.waitKey(1) & 0xFF == ord('q'):\n cv2.destroyAllWindows()\n break\n \n \n```\n\n### どこで時間がかかっているのか\n\n上記のプログラムを動かし,各過程における時間を出力したところ,結果は画像のようになりました.\n\n[](https://i.stack.imgur.com/KsR1I.png)\n\n画像を検出プログラム内の関数\"detect_image()\"に渡す直前から,渡した直後のところで10秒ほどかかっていたので,この部分をどうにかするしかなさそうに見えますが...",
"comment_count": 6,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-21T05:20:41.463",
"favorite_count": 0,
"id": "77677",
"last_activity_date": "2021-07-02T06:11:46.533",
"last_edit_date": "2021-07-02T06:11:46.533",
"last_editor_user_id": "41740",
"owner_user_id": "41740",
"post_type": "question",
"score": 1,
"tags": [
"python",
"keras"
],
"title": "プログラムの実行速度をあげたい",
"view_count": 822
} | [
{
"body": "そのライブラリを知らないので一般論ですが、\n\n現在のコードだと一枚画像を処理するたびにモデルを作成してウェイトをロードして... とやっているように見えます。 \nこのモデルの初期化処理はかなり時間がかかります。\n\n特別に内部状態を持っていないモデルは何度でも推論(=物体検出)を行うことができます。 \nなので、起動時に一度だけモデルを作成し、以後の無限ループ部分ではそのモデルを使いまわすことができるはずです。\n\nモデルが状態を持っていた場合でも、状態だけをリセットする方法がないか探してみてはどうでしょうか。\n\n* * *\n\n追記\n\n[detect_video](https://github.com/qqwweee/keras-\nyolo3/blob/e6598d13c703029b2686bc2eb8d5c09badf42992/yolo.py#L172)\n関数が、やろうとしていることに非常に近いと思います。 \nこの関数は動画ファイルを入力としていますが、ファイル190行目で動画から1枚画像を取り出して、それを192行目で `yolo.detect_image`\nに渡しています。 \nこの `yolo` インスタンスは無限ループの中で再作成されていません。 \n190行目の処理を `cam.get_image()` に入れ替えて、画像形式の変換も適切に行えば期待通りの動きをすると思います。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-30T14:49:14.693",
"id": "77888",
"last_activity_date": "2021-07-01T11:09:02.123",
"last_edit_date": "2021-07-01T11:09:02.123",
"last_editor_user_id": "20885",
"owner_user_id": "20885",
"parent_id": "77677",
"post_type": "answer",
"score": 1
}
] | 77677 | 77888 | 77888 |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "```\n\n {=INDEX(result!N:Q,MATCH(B13&CE13,result!A:A&result!Q:Q,0),1)}\n \n```\n\n上記、index\nmatchの複数条件の式で、B13、CE13にある値を検索値に、「result」シートから値を取り出すという関数を組みました。この時点ではエラーは出ず、式は期待通りの値を拾ってきます。\n\n上記の式を、マクロにて、ローデータが存在する行分コピーするという処理を行います。\n\n```\n\n =INDEX(result!N:Q,MATCH(B13&CE13,@result!A:A&@result!Q:Q,0),1)\n \n```\n\nしかし、関数をコピーするマクロを回すと、 \nすべての行で上記の「@」がついた式に変換され、エラーになってしまいます。\n\n原因の見当は付きますでしょうか。 \nまた、index matchを複数条件で行うほかの方法などあればアドバイスいただきたいです。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-21T07:34:36.817",
"favorite_count": 0,
"id": "77680",
"last_activity_date": "2021-06-21T08:11:50.543",
"last_edit_date": "2021-06-21T08:11:50.543",
"last_editor_user_id": "3060",
"owner_user_id": "46909",
"post_type": "question",
"score": 0,
"tags": [
"excel"
],
"title": "マクロを使うと、数式に@がついて、エラーになる。",
"view_count": 93
} | [] | 77680 | null | null |
{
"accepted_answer_id": "77824",
"answer_count": 1,
"body": "spring-bootで複数のファイルを一括してアップロードする際に、個別で進捗を取得する方法はありますか? \n総量の進捗も取得します。\n\n※フォームを分割してアップロードするという方式は取りません。\n\n```\n\n <html>\n <form action=\"...\" method=\"POST\" enctype=\"multipart/form-data\">\n <input type=\"file\" name=\"files[]\"> or <input type=\"file\" name=\"files\" multiple>\n ...\n \n```\n\n * tips \n 1. spring-boot: 2.4.x\n 2. java: >= 11",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-21T08:56:59.360",
"favorite_count": 0,
"id": "77682",
"last_activity_date": "2021-06-27T17:01:13.377",
"last_edit_date": "2021-06-21T09:02:18.047",
"last_editor_user_id": "3060",
"owner_user_id": "46773",
"post_type": "question",
"score": 0,
"tags": [
"java",
"spring-boot"
],
"title": "spring-bootでの複数ファイルアップロードの進捗表示",
"view_count": 656
} | [
{
"body": "アップロード済みファイルサイズの総量から、個別のファイルアップロード状況を逆算することで求められるかと思います。\n\n```\n\n <html>\n <body>\n <div>\n <form\n id=\"form\"\n method=\"POST\"\n enctype=\"multipart/form-data\"\n action=\"/upload\"\n >\n <table>\n <tr>\n <td>File to upload:</td>\n <td><input id=\"input\" type=\"file\" name=\"files\" multiple /></td>\n </tr>\n <tr>\n <td></td>\n <td><input id=\"submit\" type=\"submit\" value=\"Upload\" /></td>\n </tr>\n </table>\n </form>\n </div>\n <script>\n const form = document.getElementById(\"form\");\n form.addEventListener(\"submit\", (ev) => {\n ev.preventDefault();\n const data = new FormData(form);\n const files = data.getAll(\"files\");\n /* console.log(files); */\n \n const request = new XMLHttpRequest();\n request.upload.addEventListener(\"progress\", (e) => {\n console.log(\n \"TOTAL: \" + ((100 * e.loaded) / e.total).toFixed(2) + \"%\"\n );\n \n /* アップロード済みサイズから各ファイルのアップロード状況を逆算 */\n let remain = e.loaded;\n for (const file of files) {\n if (file.size <= remain) {\n console.log(file.name + \": 100.00%\");\n remain = remain - file.size;\n } else {\n console.log(\n file.name + \": \" + ((100 * remain) / file.size).toFixed(2) + \"%\"\n );\n remain = 0;\n }\n }\n });\n request.open(\"POST\", \"/upload\");\n request.send(data);\n });\n </script>\n </body>\n </html>\n```",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-27T17:01:13.377",
"id": "77824",
"last_activity_date": "2021-06-27T17:01:13.377",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "2808",
"parent_id": "77682",
"post_type": "answer",
"score": 0
}
] | 77682 | 77824 | 77824 |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "表題の通り、Instagram Graph APIを使って、メディアIDからユーザー情報を取得したいと思っております。\n\n流れとしては、以下の通りを考えております。\n\n 1. ハッシュタグ検索で、ハッシュタグIDを取得する。\n 2. ハッシュタグIDを使って、投稿メディアリストを取得する。\n 3. メディアIDからユーザー情報(userID,username,follower_coumtなど)を取得する\n\n1・2は、APIを使って実現ができましたが、3に関しては、調べても出てきませんでした。\n\n※自身のユーザー情報ではなく、他人のユーザー情報を取得したいです。\n\nこちらの件、ご教授いただけますと幸いです。 \nご回答のほど、よろしくお願いいたします。\n\n使ったツール \n<https://developers.facebook.com/tools/explorer/>",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-21T09:59:12.377",
"favorite_count": 0,
"id": "77684",
"last_activity_date": "2023-05-10T01:29:08.270",
"last_edit_date": "2023-05-10T01:29:08.270",
"last_editor_user_id": "19769",
"owner_user_id": "46965",
"post_type": "question",
"score": 0,
"tags": [
"instagram"
],
"title": "Instagram Graph API にて、メディアIDからユーザー情報を取得する方法はありますか?",
"view_count": 521
} | [] | 77684 | null | null |
{
"accepted_answer_id": "77688",
"answer_count": 1,
"body": "### 環境\n\nruby 2.6.5 \nrails 6 \nMySQL \nM1チップ搭載macOS\n\n### 解決したいこと\n\nDockerコンテナで既存アプリを起動しましたが投稿がうまくいかず、画像が表示できません。 \nAWS_ACCESS_KEY_ID \nAWS_SECRET_ACCESS_KEY \nAWS_REGION \nをdocker-compose.ymlに記述しましたが、エラーになりました。\n\nsecret_access_key: AWS_SECRET_ACCESS_KEY \nsecret_access_key=AWS_SECRET_ACCESS_KEY \nsecret_access_key='AWS_SECRET_ACCESS_KEY' \nsecret_access_key : ${AWS_SECRET_ACCESS_KEY} \n色々書き方を試しましたが未だにうまくいきません。 \nわかる方がいらしたら教えてください! \nよろしくお願いします。\n\n### 発生している問題・エラー\n\n```\n\n Aws::Sigv4::Errors::MissingCredentialsError in Items#index\n \n Showing /fridge_app/app/views/items/_item.html.erb where line #5 raised:\n \n Cannot load `Rails.config.active_storage.service`: \n missing credentials, provide credentials with one of the following options:\n - :access_key_id and :secret_access_key\n - :credentials\n - :credentials_provider\n \n```\n\n[](https://i.stack.imgur.com/21nUP.png)\n\n### 該当するソースコード\n\n**Dockerfile**\n\n```\n\n FROM ruby:2.6.5\n \n RUN apt-get update && apt-get install -y curl apt-transport-https wget && \\\n curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \\\n echo \"deb https://dl.yarnpkg.com/debian/ stable main\" | tee /etc/apt/sources.list.d/yarn.list && \\\n apt-get update && apt-get install -y yarn\n \n RUN apt-get update -qq && apt-get install -y nodejs yarn\n RUN mkdir /fridge_app\n WORKDIR /fridge_app\n COPY Gemfile Gemfile.lock /fridge_app/\n ENV BUNDLER_VERSION 2.1.4\n RUN gem update --system \\\n && gem install bundler -v $BUNDLER_VERSION \\\n && bundle install -j 4\n COPY . /fridge_app\n \n RUN yarn install --check-files\n RUN bundle exec rails webpacker:install\n \n ENV PATH $PATH:/usr/local/src/bin\n \n COPY entrypoint.sh /usr/bin/\n RUN chmod +x /usr/bin/entrypoint.sh\n ENTRYPOINT [\"entrypoint.sh\"]\n EXPOSE 3000\n \n CMD [\"rails\", \"server\", \"-b\", \"0.0.0.0\"]\n \n```\n\n**docker-compose.yml**\n\n```\n\n version: '3'\n services:\n db:\n image: mysql:5.6\n platform: linux/x86_64\n environment:\n MYSQL_ROOT_PASSWORD: password\n MYSQL_DATABASE: root\n ports:\n - \"3306:3306\"\n volumes:\n - ./tmp/db:/var/lib/mysql\n \n web:\n build: .\n environment:\n region: ap-northeast-1\n access_key_id: AWS_ACCESS_KEY_ID\n secret_access_key: AWS_SECRET_ACCESS_KEY\n command: bash -c \"rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'\"\n volumes:\n - .:/fridge_app\n ports:\n - \"3000:3000\"\n depends_on:\n - db\n \n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-21T14:50:53.530",
"favorite_count": 0,
"id": "77687",
"last_activity_date": "2021-06-22T04:01:23.953",
"last_edit_date": "2021-06-22T04:01:23.953",
"last_editor_user_id": "3068",
"owner_user_id": "44865",
"post_type": "question",
"score": 0,
"tags": [
"docker",
"amazon-s3"
],
"title": "Dockerコンテナで既存アプリを起動しましたが投稿がうまくいかず、画像が表示できません。",
"view_count": 625
} | [
{
"body": "`Aws::Sigv4::Errors::MissingCredentialsError` は環境変数などで AWS\nのクレデンシャルが与えられていないときに出るエラーです。\n\nおそらくローカルで動かす際は環境変数もしくは `~/.aws/credentials`\nに設定がされており動いていたものが、コンテナの上で動かす際は一切設定されていないのでエラーとなったのではないでしょうか。\n\n`AWS_ACCESS_KEY_ID` と `AWS_SECRET_ACCESS_KEY` を適切に取得し、`AWS_REGION`\nと共に設定するようにしてみてください。この際 `AWS_SECRET_ACCESS_KEY` は秘匿値であることにご注意ください。\n\n更に、もしこの後このアプリを AWS 上で動かすのであれば、IAM Role をアタッチしてクレデンシャルを生の値では扱わないのがお勧めです。\n\n公式ドキュメントはこちらです: <https://docs.aws.amazon.com/ja_jp/sdk-for-ruby/v3/developer-\nguide/setup-config.html>",
"comment_count": 6,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-21T15:09:12.413",
"id": "77688",
"last_activity_date": "2021-06-21T15:09:12.413",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "19110",
"parent_id": "77687",
"post_type": "answer",
"score": 2
}
] | 77687 | 77688 | 77688 |
{
"accepted_answer_id": "77720",
"answer_count": 1,
"body": "Javaのプログラムで質問です。\n\n以下に、長方形の面積と円の面積を半径を表示するプログラム「Shape.java」「Circle.java」「Rectangle.java」「ShapeTester.java」の4つを示します。\n\nShape.java\n\n```\n\n public interface Shape {\n /** 図形を表示する */\n void print();\n \n /** 面積を返す */\n double getArea();\n }\n \n```\n\nCircle.java\n\n```\n\n public class Circle implements Shape {\n /** 円周率 */\n public static final double PI = 3.14;\n \n private double r;\n \n public Circle(double r) {\n this.r = r;\n }\n \n /** 図形を表示する */\n public void print() {\n System.out.println(\"半径 \" + r + \"の円です.\");\n }\n \n /** 面積を返す */\n public double getArea() {\n return PI * r * r;\n }\n \n /** 円周を返す */\n public double getLength() {\n return 2 * PI * r;\n }\n }\n \n```\n\nRectangle.java\n\n```\n\n public class Rectangle implements Shape {\n private double a, b;\n \n public Rectangle(double a, double b) {\n this.a = a;\n this.b = b;\n }\n \n /** 図形を表示する */\n public void print() {\n System.out.println(a + \" x \" + b + \"の長方形です.\");\n }\n \n /** 面積を返す */\n public double getArea() {\n return a * b;\n }\n }\n \n```\n\nShapeTester.java\n\n```\n\n public class ShapeTester {\n public static void info(Shape s) {\n s.print();\n System.out.println(\"面積 = \" + s.getArea());\n }\n \n public static void main(String args[]) {\n Shape s1 = new Rectangle(2.5, 4.0);\n info(s1);\n \n Circle c = new Circle(1.0);\n info(c);\n System.out.println(\"cの円周 = \" + c.getLength());\n \n Shape s2 = c;\n info(s2);\n System.out.println(\"s2の円周 = \" + s2.getLength());\n }\n }\n \n```\n\nしかし、このままコンパイルするとエラーメッセージが以下のように出てきてしまうので\n\n```\n\n ~/java$ javac Shape.java\n ~/java$ javac Rectangle.java\n ~/java$ javac Circle.java\n ~/java$ javac ShapeTester.java\n ShapeTester.java:17: エラー: シンボルを見つけられません\n System.out.println(\"s2の円周 = \" + s2.getLength());\n ^\n シンボル: メソッド getLength()\n 場所: タイプShapeの変数 s2\n エラー1個\n \n```\n\n一応、`System.out.println(\"s2の円周 = \" + s2.getLength());` を削除したら、きちんとコンパイルが通りました。 \nしかし、なぜ `System.out.println(\"s2の円周 = \" + s2.getLength());`\nが必要ないのかが、エラーメッセージを読んでもよくわからなかったので、教えていただきたい次第です。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T01:09:10.760",
"favorite_count": 0,
"id": "77690",
"last_activity_date": "2021-06-23T02:07:57.943",
"last_edit_date": "2021-06-22T01:56:06.267",
"last_editor_user_id": "3060",
"owner_user_id": "46879",
"post_type": "question",
"score": 0,
"tags": [
"java"
],
"title": "エラーになる意味がよくわからない",
"view_count": 264
} | [
{
"body": "そのエラーメッセージは、getLengthがない、といっています \nShapeにはそういうメソッドがないですよね",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T02:07:57.943",
"id": "77720",
"last_activity_date": "2021-06-23T02:07:57.943",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "27481",
"parent_id": "77690",
"post_type": "answer",
"score": 2
}
] | 77690 | 77720 | 77720 |
{
"accepted_answer_id": null,
"answer_count": 2,
"body": "Swiftでは以下のようなコードで、Float型の変数を文字列に変換できるようです。\n\n```\n\n let testArray:[Float] = [0.1,0.2,0.3]\n var message = \"\"\n message.append(\"test-----\\(testArray[0]),\\(testArray[1]),\\(testArray[2])|\")\n \n print(message)\n \n```\n\nしかし、このコードがどういう文法で動作しているのかよくわかりません。 \nなぜバックスラッシュとカッコを使うことで数値を文字列に変換できるのでしょうか?\n\nまた、このコードだと、一部のデバイスでは不具合が起きたりしますでしょうか? \n今、自分の使っているコードが、一部の環境で動かないと報告を受けており \nどこに原因があるのかを探っています。 \nこういった文法を使うと一部環境で動かなくなったりすることはあると思いますか?",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T03:11:44.233",
"favorite_count": 0,
"id": "77692",
"last_activity_date": "2021-06-22T09:27:52.553",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "36446",
"post_type": "question",
"score": 0,
"tags": [
"swift"
],
"title": "Swiftでバックスラッシュを使って数値を文字列に変換する文法について",
"view_count": 279
} | [
{
"body": "> しかし、このコードがどういう文法で動作しているのかよくわかりません。\n\nすでにコメントにリンクだけが記載されていますが、Swift本にも明記されているString Interpolation(文字列補間)と言う機能になります。\n\nなお、まともな日本語訳が無いのは大変ハードルが高いとは思いますが、Swiftでのプログラミングをされるのであれば[Swift本](https://docs.swift.org/swift-\nbook/)は最低一度は目を通しておくべきでしょう。Web版の他にiBooks版もあります。\n\n> なぜバックスラッシュとカッコを使うことで数値を文字列に変換できるのでしょうか?\n\nそのようにSwiftコンパイラ、およびSwiftの`String`型が構成されているためです。もっと厳密に言うと、Swiftコンパイラが`\"...\\(...)...\"`と言う文字列補間のリテラル表記を見つけると、部分ごとに分解した上で、`ExpressibleByStringInterpolation`で定義されたメソッドを呼び出す、と言う動作をするように\n**Swiftコンパイラが作られています** 。\n\n`String`型の場合、数値以外のどんな型の式を`\\(...)`内に書いても、文字列に変換できたりします。(ドキュメントに明記されていない変換結果に頼るべきでは無いですが。)\n\n> また、このコードだと、一部のデバイスでは不具合が起きたりしますでしょうか?\n\n> こういった文法を使うと一部環境で動かなくなったりすることはあると思いますか?\n\n上記のようにちゃんとした動作を解説すると、一冊本が書けるくらい内部的には複雑な動作をしているので、絶対に可能性が無いとは言えませんが、文字列補間自体はすべてのSwift処理系に共通な部分で処理されているため、「こういった文法を使うと一部環境で動かなくなったりする」コードをたまたま書いてしまうなんてことは、まず考えられません。\n\nご質問に記載された単純なケースではこれ以上何とも言えません。まずは、どう言った条件で再現する事象なのかをきちんと把握された上で、十分な情報を含めた上で再度ご質問された方が良いでしょう。私なら「こういった文法を使う」ことに直接関係しない部分で、環境依存になるようなコードを書かれていると考えて原因を探します。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T04:39:07.753",
"id": "77693",
"last_activity_date": "2021-06-22T04:39:07.753",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "13972",
"parent_id": "77692",
"post_type": "answer",
"score": 3
},
{
"body": "`\\()`の中の変数が、どのように文字列(String型)に変換されるかは、プロトコル`CustomStringConvertible`のプロパティ`description`で定義されます。\n\n[CustomStringConvertible](https://developer.apple.com/documentation/swift/customstringconvertible)\n\n```\n\n struct Hello: CustomStringConvertible {\n var name: String\n \n var description: String {\n return \"Hello, \" + name\n }\n }\n \n print(\"Say \\(Hello(name: \"World\"))\") // Say Hello, World\n \n```\n\n> 今、自分の使っているコードが、一部の環境で動かないと報告を受けており どこに原因があるのかを探っています。\n\n問題となっている変数の型が、`CustomStringConvertible`に準拠しているか、プロパティ`description`を適切に定義しているかを調べる必要があると思います。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T09:27:52.553",
"id": "77704",
"last_activity_date": "2021-06-22T09:27:52.553",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "18540",
"parent_id": "77692",
"post_type": "answer",
"score": 1
}
] | 77692 | null | 77693 |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "会社のファイルサーバーにVPN接続をし、ファイルサーバー上からemeditorでファイルを開こうとすると開けなくなりました。(6/18時点では問題なし)。 \n同じファイルを、ローカルにコピーするとemeditorで問題なく開けます。 \nまたサーバー上のファイルを、別のアプリ(メモ帳や秀丸など)で開いても問題なく開けます。 \n解決策がありましたらご教示ください。\n\n補足:開けない→該当ファイルがないとアラートが出ます。 \nファイル形式は .txtです。",
"comment_count": 4,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T04:45:37.793",
"favorite_count": 0,
"id": "77694",
"last_activity_date": "2021-06-22T04:56:24.343",
"last_edit_date": "2021-06-22T04:56:24.343",
"last_editor_user_id": "46972",
"owner_user_id": "46972",
"post_type": "question",
"score": 0,
"tags": [
"emeditor"
],
"title": "サーバー上のファイルが開けない",
"view_count": 104
} | [] | 77694 | null | null |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "method object is not iterable と出てしまうのですが、どうすれば良いのでしょうか。\n\n[](https://i.stack.imgur.com/mwprk.jpg)",
"comment_count": 4,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T06:31:53.320",
"favorite_count": 0,
"id": "77695",
"last_activity_date": "2022-12-18T10:08:31.020",
"last_edit_date": "2021-06-22T10:55:32.997",
"last_editor_user_id": "3060",
"owner_user_id": "46974",
"post_type": "question",
"score": 1,
"tags": [
"python"
],
"title": "method objectのエラーが出てしまいます",
"view_count": 775
} | [
{
"body": "`()` が足りないのが原因だと思われます。具体的には `df_good['index'].tolist` と\n`df_bad['index].tolist` です。単に `tolist` としてしまうと **メソッドの名前** になります。\n\n`tolist()` とすることでメソッドが実行されてリストが返ります。\n\n* * *\n\n_この投稿は @user39889 さんのコメント の内容を元に コミュニティwiki として投稿しました。_",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-07-09T04:08:55.537",
"id": "78067",
"last_activity_date": "2021-07-09T04:08:55.537",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "3060",
"parent_id": "77695",
"post_type": "answer",
"score": 1
}
] | 77695 | null | 78067 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "現在、パスワード管理アプリを制作しています。 \n入力された値をfirestoreに追加して、TableViewに表示するところまでできました。 \n次に、選択されたTableViewのセルを削除する機能を製作中なのですが、その時にfirestoreのデータ(ドキュメント)も削除したいです。\n\n[公式ドキュメント](https://firebase.google.com/docs/firestore/manage-data/delete-\ndata?authuser=0) の通りにドキュメントを削除するコードを書いてみたのですが、ドキュメントIDの取得方法がわかりません。\n\n```\n\n import UIKit\n import Firebase\n \n class MypageViewController: UIViewController, UITableViewDelegate {\n \n \n var displayData: [Data] = []\n \n let db = Firestore.firestore()\n \n @IBOutlet weak var tableView: UITableView!\n @IBOutlet weak var emailLabel: UILabel!\n override func viewDidLoad() {\n super.viewDidLoad()\n \n tableView.delegate = self\n tableView.dataSource = self\n self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: \"Cell\")\n emailLabel.text = Auth.auth().currentUser?.email\n db.collection(\"passwordData\").getDocuments() { (querySnapshot, err) in\n if let err = err {\n print(\"Error getting documents: \\(err)\")\n } else {\n for doc in querySnapshot!.documents {\n let data = doc.data()\n if let recorder = data[\"recorder\"] as? String, let service = data[\"service\"] as? String, let password = data[\"password\"] as? String {\n if recorder == Auth.auth().currentUser?.email {\n let cellData = Data(title: service, password: password, recorder: recorder)\n self.displayData.append(cellData)\n print(self.displayData)\n DispatchQueue.main.async {\n self.tableView.reloadData()\n let indexPath = IndexPath(row: self.displayData.count - 1, section: 0)\n self.tableView.scrollToRow(at: indexPath, at: .top, animated: true)\n }\n }\n }\n \n }\n }\n }\n }\n \n func selectRow(at indexPath: IndexPath?, animated: Bool, scrollPosition: UITableView.ScrollPosition) {\n print(indexPath)\n print(\"選択されました\")\n }\n \n }\n \n extension MypageViewController: UITableViewDataSource {\n func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {\n return self.displayData.count\n }\n \n func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {\n let passwords = displayData[indexPath.row]\n \n // let cell = tableView.dequeueReusableCell(withIdentifier: \"Cell\", for: indexPath)\n let cell = UITableViewCell(style: .subtitle, reuseIdentifier: \"Cell\")\n cell.textLabel?.text = passwords.password\n cell.detailTextLabel?.text = passwords.title\n return cell\n }\n \n func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool\n {\n return true\n }\n func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {\n \n let id: Data = self.displayData[indexPath.row]\n \n \n if editingStyle == UITableViewCell.EditingStyle.delete {\n displayData.remove(at: indexPath.row)\n tableView.deleteRows(at: [indexPath as IndexPath], with: UITableView.RowAnimation.automatic)\n db.collection(\"displayData\").document(\"ここのIDの取得方法を教えていただけませんか?\").delete() { err in\n if let err = err {\n print(\"Error removing document: \\(err)\")\n } else {\n print(\"Document successfully removed!\")\n }\n print(id)\n }\n \n }\n } \n }\n \n```\n\n入力されたデータは、以下のコードでfirestoreに追加しています。\n\n```\n\n struct Data {\n var title: String\n var password: String\n var recorder: String\n }\n \n if let title = titleText.text, let password = diaryText.text, let account = Auth.auth().currentUser?.email {\n var ref: DocumentReference? = nil\n ref = db.collection(\"passwordData\").addDocument(data: [\n \"recorder\": account,\n \"service\": title,\n \"password\": password,\n ]) { err in\n if let err = err {\n print(\"Error adding document: \\(err)\")\n } else {\n print(\"succesfully!\")\n }\n }\n }\n \n```",
"comment_count": 7,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T06:55:19.750",
"favorite_count": 0,
"id": "77696",
"last_activity_date": "2021-06-22T23:09:30.677",
"last_edit_date": "2021-06-22T15:26:52.077",
"last_editor_user_id": "3060",
"owner_user_id": "46975",
"post_type": "question",
"score": 0,
"tags": [
"swift",
"xcode",
"firebase"
],
"title": "tableViewのセルを削除する際にfirestoreのドキュメントも削除したいのですが、ドキュメントIDの取得方法がわかりません。",
"view_count": 251
} | [
{
"body": "各ドキュメントを表すデータ型(あなたの場合`Data`、Swiftの標準ライブラリにある型名と全く同じ型名の定義があるとつまらないことで引っかかる可能性があるので、以下では`PasswordData`に変更してあります)に`documentID`を表すプロパティを追加するのが確実で簡単だと思います。\n\nあなたのコードでは`FirebaseFirestoreSwift`モジュールをimportすると使えるようになる「カスタムオブジェクト」の機能は使っていないようなので、素直に`documentID`を取得して、所定のプロパティに設定してやるだけです。\n\n```\n\n struct PasswordData {\n var documentID: String\n var title: String\n var password: String\n var recorder: String\n }\n \n```\n\n```\n\n db.collection(\"passwordData\").getDocuments() { (querySnapshot, err) in\n if let err = err {\n print(\"Error getting documents: \\(err)\")\n } else {\n for doc in querySnapshot!.documents {\n let documentID = doc.documentID //<-\n let data = doc.data()\n if let recorder = data[\"recorder\"] as? String,\n let service = data[\"service\"] as? String,\n let password = data[\"password\"] as? String\n {\n if recorder == Auth.auth().currentUser?.email {\n let cellData = PasswordData(\n documentID: documentID, //<-\n title: service,\n password: password,\n recorder: recorder)\n //...\n }\n }\n }\n }\n }\n \n```\n\nこのようにしておけば、削除の時には削除される要素から`documentID`を取り出すだけです。\n\n```\n\n let removed = displayData.remove(at: indexPath.row)\n let documentID = removed.documentID\n //... `documentID`を使った削除処理\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T23:09:30.677",
"id": "77719",
"last_activity_date": "2021-06-22T23:09:30.677",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "13972",
"parent_id": "77696",
"post_type": "answer",
"score": 0
}
] | 77696 | null | 77719 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "heroku環境にて rails app を作成したのですが、searchkick経由でreindexをかけるとtimed\noutになったためその質問をさせてください。\n\n### 起きている事象\n\nheroku環境にて searchkick経由で `eroku run rails searchkick:reindex:all`\nをかけると、以下のエラーが発生する。 \nこちらのエラーについて調べても情報が出てきませんでした。\n\n```\n\n Error: timed out\n at TLSSocket.<anonymous> (/usr/local/Cellar/heroku/7.47.12/lib/client/7.54.1/node_modules/@heroku-cli/plugin-run/lib/lib/dyno.js:139:29)\n \n```\n\n**環境:**\n\nheroku (hobby) \nrails 6.0 \nsearchkickを利用 \naws elasticsearch (t3.small.elasticsearch)\n\nちなみに、indexしたいドキュメントの数は16000ほどです。\n\nこれは、おそらくherokuのdynoのメモリー不足が起因しているんでしょうか? \nよろしくお願いします。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T07:05:00.707",
"favorite_count": 0,
"id": "77697",
"last_activity_date": "2021-07-12T04:19:35.223",
"last_edit_date": "2021-06-22T11:04:48.617",
"last_editor_user_id": "3060",
"owner_user_id": "46976",
"post_type": "question",
"score": 0,
"tags": [
"ruby-on-rails",
"elasticsearch"
],
"title": "heroku環境で rails appを作成し、awsES にむけて searchkick経由でreindexをかけたが、timeoutになる",
"view_count": 100
} | [
{
"body": "自己解決しました。\n\n```\n\n rails runner \"Movie.reindex(resume: true)\"\n \n```\n\n上記のコマンドでいけました。 \n停止した場合、再開するという `resume true` が必要だったみたいです。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-07-12T02:55:07.843",
"id": "78118",
"last_activity_date": "2021-07-12T04:19:35.223",
"last_edit_date": "2021-07-12T04:19:35.223",
"last_editor_user_id": "3060",
"owner_user_id": "46976",
"parent_id": "77697",
"post_type": "answer",
"score": 1
}
] | 77697 | null | 78118 |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "ログイン画面のレイアウトは完成しています。aspnetでは、あまりコードを書くようなことはせず、Identityなどをつかって作成することができるなどの情報は入手したのですが、実際にどのように手順を踏んでやればよいかわからないので質問させていただきました。環境はvs2017\nwebforms framework 4.6.1 です。 \nイメージは、未入力時に未入力アラートを出す、IDかPWのどちらかか及び両方が間違っていたら、アラートを出すフォームを作りたいと思っています。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T07:21:59.907",
"favorite_count": 0,
"id": "77698",
"last_activity_date": "2021-06-22T07:21:59.907",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "46738",
"post_type": "question",
"score": 0,
"tags": [
"c#",
"asp.net"
],
"title": "asp.net でログイン画面を作りたい",
"view_count": 272
} | [] | 77698 | null | null |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "### 環境\n\nruby 2.6.5 \nrails 6 \nMySQL \nM1チップ搭載macOS\n\n### 解決したいこと\n\nプラットフォームがサポートされていないエラー、travis.ymlがうまく走りません。 \nまた、sudoは非推奨、効果がないとエラーが出てます。代替はroot権限の記述が必要でしょうか?よくわかりません \nわかる方がいらしたら教えてください! \nよろしくお願いします。\n\n### 発生している問題・エラー\n\n[](https://i.stack.imgur.com/UwYBr.png) \n[](https://i.stack.imgur.com/AFfeD.png)\n\n### 該当するソースコード\n\n**.Travis.yml**\n\n```\n\n language: ruby\n os: linux\n dist: xenial\n sudo: true\n services: docker\n \n before_install:\n - docker-compose up --build -d\n \n script:\n - docker-compose exec --env 'RAILS_ENV=test' web rails db:create\n - docker-compose exec --env 'RAILS_ENV=test' web rails db:migrate\n - docker-compose exec --env 'RAILS_ENV=test' web rails db:seed\n - docker-compose exec --env 'RAILS_ENV=test' web rails test\n \n```\n\n**Dockerfile**\n\n```\n\n FROM ruby:2.6.5\n \n RUN apt-get update && apt-get install -y curl apt-transport-https wget && \\\n curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \\\n echo \"deb https://dl.yarnpkg.com/debian/ stable main\" | tee /etc/apt/sources.list.d/yarn.list && \\\n apt-get update && apt-get install -y yarn\n \n RUN apt-get update -qq && apt-get install -y nodejs yarn\n RUN mkdir /fridge_app\n WORKDIR /fridge_app\n COPY Gemfile Gemfile.lock /fridge_app/\n ENV BUNDLER_VERSION 2.1.4\n RUN gem update --system \\\n && gem install bundler -v $BUNDLER_VERSION \\\n && bundle install -j 4\n COPY . /fridge_app\n \n RUN yarn install --check-files\n RUN bundle exec rails webpacker:install\n \n ENV PATH $PATH:/usr/local/src/bin\n \n COPY entrypoint.sh /usr/bin/\n RUN chmod +x /usr/bin/entrypoint.sh\n ENTRYPOINT [\"entrypoint.sh\"]\n EXPOSE 3000\n \n CMD [\"rails\", \"server\", \"-b\", \"0.0.0.0\"]\n \n```\n\n**docker-compose.yml**\n\n```\n\n version: '3'\n services:\n db:\n image: mysql:5.6\n platform: linux/amd64\n environment:\n MYSQL_ROOT_PASSWORD: password\n MYSQL_DATABASE: root\n ports:\n - \"3306:3306\"\n volumes:\n - ./tmp/db:/var/lib/mysql\n \n web:\n build: .\n environment:\n region: ap-northeast-1\n AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID\n AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY\n command: bash -c \"rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'\"\n volumes:\n - .:/fridge_app\n ports:\n - \"3000:3000\"\n depends_on:\n - db\n \n \n```",
"comment_count": 4,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T08:35:24.533",
"favorite_count": 0,
"id": "77699",
"last_activity_date": "2021-06-22T13:19:55.623",
"last_edit_date": "2021-06-22T13:19:55.623",
"last_editor_user_id": "44865",
"owner_user_id": "44865",
"post_type": "question",
"score": 0,
"tags": [
"docker",
"travis-ci"
],
"title": "プラットフォームがサポートされていないエラー、TravisCIがうまくいきません",
"view_count": 237
} | [
{
"body": "`x86_64` ではなく `amd64` と記載してみてください。\n\n[https://hub.docker.com/_/mysql?tab=description&page=1&ordering=last_updated](https://hub.docker.com/_/mysql?tab=description&page=1&ordering=last_updated)\n\n```\n\n platform: linux/amd64\n \n```",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T09:17:04.137",
"id": "77701",
"last_activity_date": "2021-06-22T09:17:04.137",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "3060",
"parent_id": "77699",
"post_type": "answer",
"score": 0
}
] | 77699 | null | 77701 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "グーグルフォームから入力されたパラメータを指定のスプレッドシートに転記するGASを作成しています。 \nそのスプレッドシートには、編集保護をかけて特定のユーザー権限のみ書き込めるようにしています。\n\nアプリケーションのオーナー権限は統一しています。 \nこのとき、GASを実行したところ以下のエラーでアプリケーションがストップしました。\n\n```\n\n 2021/06/22 19:57:43 エラー 保護されているセルやオブジェクトを編集しようとしています。編集する必要がある場合は、スプレッドシートのオーナーに連絡して保護を解除してもらってください。\n \n```\n\nとなります。そこで、try catchで次のように文章を囲みました。\n\n```\n\n try {\n // your script code here\n sheetdetail.getRange(lineNumberDetail, 1).setValue(applicationNumber);\n sheetdetail.getRange(lineNumberDetail, 2).setValue(detailsOfOrder);\n sheetdetail.getRange(lineNumberDetail, 3).setValue(appropriatenessOfTheApplicationAmount);\n sheetdetail.getRange(lineNumberDetail, 4).setValue(orderPeriod);\n sheetdetail.getRange(lineNumberDetail, 5).setValue(deliveryTime);\n sheetdetail.getRange(lineNumberDetail, 6).setValue(remarks);\n sheet.getRange(lineNumber, 33).setValue('未申請');\n } catch (e) {\n MailApp.sendEmail(\"********\", \"Error report\", e.message);\n }\n \n```\n\nこれでメールが送信されると思ったのですが、どうやらtryの中でアプリケーションが止まってしまっているように見えます。 \nこちらどういった原因が考えられますでしょうか? \n詳しい方おられましたらご教示いただけますと幸いです。 \n現時点では\n\nパーミッション系のエラーの場合try catchは無視されて実行できないと推察しております。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T11:06:44.387",
"favorite_count": 0,
"id": "77708",
"last_activity_date": "2021-06-22T16:30:03.323",
"last_edit_date": "2021-06-22T16:30:03.323",
"last_editor_user_id": "29826",
"owner_user_id": "46983",
"post_type": "question",
"score": 0,
"tags": [
"google-apps-script"
],
"title": "Google Apps Scriptのtry catchハンドリング",
"view_count": 195
} | [
{
"body": "GAS\nについては詳しくないので少し調べた程度ですが、いきなり書き込もうとしてエラーハンドリングするより、まずは編集権限の有無を確認してから書き込む方が良さそうです。\n\n例えば `canEdit()` で指定範囲の編集権限を確認できるようです。\n\n**参考:** \n[指定範囲に編集権限があるかどうか調べる:canEdit()](https://arukayies.com/gas/canedit)\n\n> 指定範囲に編集権限がある場合にはtrue、権限がない場合はfalseを返します。\n```\n\n> function myFunction() {\n> const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];\n> const range = sheet.getRange('B2:D10');\n> range.canEdit()\n> }\n> \n```",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T12:12:45.880",
"id": "77710",
"last_activity_date": "2021-06-22T12:12:45.880",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "3060",
"parent_id": "77708",
"post_type": "answer",
"score": 0
}
] | 77708 | null | 77710 |
{
"accepted_answer_id": "77712",
"answer_count": 1,
"body": "**環境**\n\nruby 2.7.2 \nrails 6.1 \nmacOS\n\n**前提**\n\n下記の記事を参考に、非同期でのコメント投稿機能を実装いたしました。\n\n[[Rails]\nAjaxを用いて非同期でコメント機能の実装](https://qiita.com/yuto_1014/items/c7d6213139a48833e21a)\n\n**解決したいこと**\n\nコメント投稿機能を非同期で実装させたいです!\n\n**試したこと**\n\nrenderで問題が発生しているため、`render :index`を仮で`redirect_to\nroot_path`と変更した所、rootページへ遷移しました。 \nまた、削除機能でも`render :index`を使用しているのですが、削除は正常に動作しています。\n\nエラー文をググり、下記の参考記事を試してみたのですが、同じエラーが表示されてしまいました。\n\n[Rails\nresponseにrenderでjsファイルを返すには](https://qiita.com/hmuronaka/items/d7b6afa3cd62dfe207b4)\n\nどのようにすればいいのか検討がついていない状態です。 \nわかる方がいましたらアドバイスいただけると幸いです。 \n何卒よろしくお願いします。\n\n**発生している問題・エラー**\n\nコメント投稿後、下記のエラー文が表示されてしまい、正常に動作していない状況です。\n\n[](https://i.stack.imgur.com/7zamW.png)\n\n**該当するソースコード** \n`travel_records_controller.rb`\n\n```\n\n def show\n @travel_record = TravelRecord.find(params[:id])\n @user = @travel_record.user\n # コメントの作成\n @comment = Comment.new\n # 新着順で表示\n @comments = @travel_record.comments.order(created_at: :desc)\n end\n \n```\n\n`comments_controller.rb`\n\n```\n\n class CommentsController < ApplicationController\n def create\n @travel_record = TravelRecord.find(params[:travel_record_id])\n #投稿に紐づいたコメントを作成\n @comment = @travel_record.comments.build(comment_params)\n @comment.user_id = current_user.id\n @comment.save\n render :index\n end\n \n def destroy\n @comment = Comment.find(params[:id])\n @comment.destroy\n render :index\n end\n \n private\n def comment_params\n params.require(:comment).permit(:comment, :user_id, :travel_record_id)\n end\n end\n \n```\n\n`index.js.erb`\n\n```\n\n $(\"#comments_area\").html(\"<%= j(render 'index', { comments: @comment.travel_record.comments }) %>\");\n $(\"textarea\").val('');\n \n```\n\n`travel_records/show.html.slim`\n\n```\n\n = render 'layouts/flash_messages'\n #comments_area\n = render 'comments/index', comments: @comments\n \n```\n\n`comments/_index.html.slim`\n\n```\n\n = comments.count\n | 件のコメント\n h6.more[data-toggle=\"collapse\" data-target=\"#collapseExample\" aria-expanded=\"false\" aria-controls=\"collapseExample\"]\n | もっと見る....\n - comments.first(2).each do |comment|\n - unless comment.id.nil?\n p = link_to \"@#{comment.user.name}\", user_path(comment.user.id)\n p\n | コメント:\n = comment.comment\n - if comment.user == current_user\n = link_to travel_record_comment_path(comment.travel_record_id, comment.id), method: :delete, remote: true do\n i.fas.fa-trash[style=\"color: black;\"]\n span = comment.created_at.strftime('%Y/%m/%d %H:%M:%S')\n #collapseExample.collapse\n - comments.offset(2).each do |comment|\n - unless comment.id.nil?\n p = link_to \"@#{comment.user.name}\", user_path(comment.user.id)\n p\n | コメント:\n = comment.comment\n - if comment.user == current_user\n = link_to travel_record_comment_path(comment.travel_record_id, comment.id), method: :delete, remote: true do\n i.fas.fa-trash[style=\"color: black;\"]\n span = comment.created_at.strftime('%Y/%m/%d %H:%M:%S')\n \n \n```\n\n`comments/_form.html.slim`\n\n```\n\n = form_with model: [travel_record, comment], url: travel_record_comments_path(travel_record) do |f|\n = f.text_area :comment\n = f.submit \"コメントする\", class: 'btn btn-primary btn-block'\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T11:12:15.217",
"favorite_count": 0,
"id": "77709",
"last_activity_date": "2021-06-23T01:29:59.313",
"last_edit_date": "2021-06-23T01:28:07.387",
"last_editor_user_id": "3060",
"owner_user_id": "46968",
"post_type": "question",
"score": 0,
"tags": [
"javascript",
"ruby-on-rails",
"ruby",
"jquery"
],
"title": "Ajaxを用いて非同期でコメント機能を実装したのですが、コメント投稿後、render処理でTemplate is missingエラーが表示されてしまう",
"view_count": 921
} | [
{
"body": "下記の参考記事をもとに自己解決できたので情報共有します。\n\n[【Rails\n6】(初心者向け)Ajax版最小構成CRUDアプリ(ページ移動をゼロに!)](https://qiita.com/take18k_tech/items/7d4917e30d4c879701ef)\n\n結論:Rails 6.1 から仕様が変わり, `local: true`がデフォルトになったため、`js.erb`を呼び出すには\n`form_with`に`local: false`の記述が必要。\n\n上記通り、コードを変更したことで、正常に動作させることができました!",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T13:18:25.577",
"id": "77712",
"last_activity_date": "2021-06-23T01:29:59.313",
"last_edit_date": "2021-06-23T01:29:59.313",
"last_editor_user_id": "3060",
"owner_user_id": "46968",
"parent_id": "77709",
"post_type": "answer",
"score": 0
}
] | 77709 | 77712 | 77712 |
{
"accepted_answer_id": "77717",
"answer_count": 1,
"body": "VSCode で JavaFX を import しようとすると 'The import javafx cant be resolved'\nと表示されて使うことができません。JavaFX に必要な 'jaavafx-sdk-1.0.2' というフォルダに入っている jar\nファイルは全てライブラリに追加したのですがだめでした。\n\nまた、JavaFX は最新の JDK では対応していないらしいので adoptopenjdk8 を使おうと思ったのですが、VSCode の\nsettings.json の java.home に adoptopenjdk8 のディレクトリを書き込んだら 'The java.home\nvariable defined in visual studio code settings does not point to a jdk'\nと表示されて使うことができませんでした。\n\nJavaFX を VSCode でインポートできるようにするにはどうすればいいでしょうか。 \nご教示お願いします。",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T12:51:12.457",
"favorite_count": 0,
"id": "77711",
"last_activity_date": "2021-06-23T01:24:49.113",
"last_edit_date": "2021-06-23T01:24:49.113",
"last_editor_user_id": "3060",
"owner_user_id": "44537",
"post_type": "question",
"score": 0,
"tags": [
"java",
"vscode",
"javafx"
],
"title": "VSCode で JavaFX をインポートできない",
"view_count": 1420
} | [
{
"body": "vscodeにjava extension pack\nが導入されているのであれば、MavenプロジェクトからJavaFXのアーキタイプを選択する方法が手っ取り早くJavaFXを実行する方法であると思います。\n\n次の手順で実行します。\n\n 1. コマンドパレット`Ctrl`+`shift`+`P`から、`Maven: Create Maven Project` を選択。\n 2. アーキタイプの選択を促されるが、一番上の`More`をクリック\n 3. テキストボックスに`openjfx`と入力し、出てきた候補から`javafx-archetype-simple`を選択(もしfamlを使いたかったら`javafx-archetype-faml`を選択してください)\n 4. バージョンを聞かれるので、一番最新のバージョンを選択。\n 5. GroupIDとArtifactIDを入力する。デフォルトの名前でも任意に入力しても良いです。\n 6. フォルダ選択ダイアログが表示されるので、プロジェクトを作成するフォルダを選択します。\n 7. ターミナルにプロジェクト作成の進捗ログが表示されていきます。途中何度か入力を促されます。とりあえず動作させることが目的であれば全て`Enter`入力で良いと思います。\n 8. ターミナルに`BUILD SUCCESS`と表示されればプロジェクト作成完了です。同時に新しいウィンドウでプロジェクトを開くかどうかのダイアログが表示されます。新しくウィンドウを開いた方が作業しやすいので`Open`を選択しましょう。\n 9. この方法で作成したプロジェクトには、\"Hello JavaFX\"を表示する簡単なフレームを表示するクラス`App.java`が予め実装されています。`App.java`を開き、`F5`キーやメニューで実行またはデバッグを選択し、無事ウィンドウが表示されればひとまず完了です。\n\nJDKは8が推奨だと思いますが、11でも動作しました(Pleiades All in oneに付属のAdopt openjdkです)\n\nあとはこのプロジェクトをベースに目的のアプリケーションを作っていきましょう。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T16:59:44.933",
"id": "77717",
"last_activity_date": "2021-06-22T16:59:44.933",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "46944",
"parent_id": "77711",
"post_type": "answer",
"score": 1
}
] | 77711 | 77717 | 77717 |
{
"accepted_answer_id": "77715",
"answer_count": 1,
"body": "引数arrayが0以外の場合意図する動作が実現できないようです。誰か問題点を指摘できますか ?\n\n```\n\n const spreadsheets = [];\n let spreadsheet = SpreadsheetApp.openById(\"X\");\n spreadsheets.push(spreadsheet);\n \n function problem(array,index){\n const things =[];\n const sheets = spreadsheets[0].getSheets();\n const values =sheets[index].getRange(1,array+1,1000,1).getValues();\n Logger.log(values);\n //problem(0,1):[[a1],[a2],[],[],[],[],.....]\n //problem(1,1):[[b1],[b2],[b3],[],[],[],.....]\n for(let i=0;i<1000;i=i+1){\n if(values[i][array]==\"\"){break;}\n things.push(values[i][array]);\n }\n Logger.log(things);\n //problem(0,1):[a1,a2]\n //problem(1,1):[null,null,null,......]\n return things;\n }\n \n```\n\nspreadsheets[0].getSheets()[1] | A | B \n---|---|--- \n1 | a1 | b1 \n2 | a2 | b2 \n3 | | b3",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T15:13:28.653",
"favorite_count": 0,
"id": "77714",
"last_activity_date": "2021-06-22T16:04:07.860",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "46987",
"post_type": "question",
"score": 0,
"tags": [
"google-apps-script"
],
"title": "各列の値を持つセルの値を取得したい",
"view_count": 55
} | [
{
"body": "二次元配列へのアクセスが誤っているのが原因です。\n\n```\n\n Logger.log(values);\n //problem(0,1):[[a1],[a2],[],[],[],[],.....]\n //problem(1,1):[[b1],[b2],[b3],[],[],[],.....]\n \n```\n\n`values` には、「「1つだけ要素のある配列(=セル、より正確には1行から幅が1つ分)」の配列( =`getValues()`\nで取得した範囲)」が入っています。\n\nなので、例えば `a1` の部分を取得するには `values[0][0]` 、 `a2` の部分を取得するには `values[0][1]` 、同様に\n`problem(1, 1)` で `b1` の部分を取得するには `values[0][0]` 、……とアクセスする必要があります。\n\nというところで続きのコードですが、\n\n```\n\n for(let i=0;i<1000;i=i+1){\n if(values[i][array]==\"\"){break;}\n things.push(values[i][array]);\n }\n Logger.log(things);\n //problem(0,1):[a1,a2]\n //problem(1,1):[null,null,null,......]\n \n```\n\n…… `values[i][array]` というアクセスをしています。これは、\n\n * `problem(0, 1)` の時:`values[0][1]`(a1) 、`values[1][1]` (a2)にアクセスする\n * `problem(1, 1)` の時:`values[1][1]` ( `null`) 、`values[1][1]` ( `null`)、……にアクセスする \n(無限に `null` がかえるので、終了しない)\n\nという結果を起こします。 \nですので、 `values` へのアクセス方法を修正すれば解決するでしょう。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-22T16:04:07.860",
"id": "77715",
"last_activity_date": "2021-06-22T16:04:07.860",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "29826",
"parent_id": "77714",
"post_type": "answer",
"score": 0
}
] | 77714 | 77715 | 77715 |
{
"accepted_answer_id": null,
"answer_count": 0,
"body": "### 環境\n\nruby 2.6.5 \nrails 6 \nMySQL \nM1チップ搭載macOS\n\n### 解決したいこと\n\nHerokuでDockerを導入していたらError: Exec format errorでアプリが表示できなくなりました \n表示させるにはどうした良いでしょうか?\n\n### 発生までの流れ\n\nheroku container:push web -a <アプリ名> \nheroku container:release web <アプリ名>\n\nheroku run rails db:migrate\n\nここで下記エラーが起こりました。\n\n### 発生している問題・エラー\n\n**ターミナル**\n\n```\n\n Error: Exec format error\n \n```\n\n### その他のエラー\n\nその後、heroku run rails c \nでも上記エラー \ngit push heroku masterを実行したらerror: failed to push some refs toのエラーが発生しております\n\n### heroku logs\n\n[](https://i.stack.imgur.com/Ed9T4.jpg)\n\n### 該当するソースコード\n\n**Dockerfile**\n\n```\n\n FROM ruby:2.6.5\n \n RUN apt-get update && apt-get install -y curl apt-transport-https wget && \\\n curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \\\n echo \"deb https://dl.yarnpkg.com/debian/ stable main\" | tee /etc/apt/sources.list.d/yarn.list && \\\n apt-get update && apt-get install -y yarn\n \n RUN apt-get update -qq && apt-get install -y nodejs yarn\n RUN mkdir /fridge_app\n WORKDIR /fridge_app\n COPY Gemfile Gemfile.lock /fridge_app/\n ENV BUNDLER_VERSION 2.1.4\n RUN gem update --system \\\n && gem install bundler -v $BUNDLER_VERSION \\\n && bundle install -j 4\n COPY . /fridge_app\n \n RUN yarn install --check-files\n RUN bundle exec rails webpacker:install\n \n ENV PATH $PATH:/usr/local/src/bin\n \n COPY entrypoint.sh /usr/bin/\n RUN chmod +x /usr/bin/entrypoint.sh\n ENTRYPOINT [\"entrypoint.sh\"]\n EXPOSE 3000\n \n CMD [\"rails\", \"server\", \"-b\", \"0.0.0.0\"]\n \n```\n\n**docker-compose.yml**\n\n```\n\n version: '3'\n services:\n db:\n image: mysql:5.6\n platform: linux/amd64\n environment:\n MYSQL_ROOT_PASSWORD: password\n MYSQL_DATABASE: root\n ports:\n - \"3306:3306\"\n volumes:\n - ./tmp/db:/var/lib/mysql\n \n web:\n build: .\n environment:\n region: ap-northeast-1\n AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID\n AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY\n command: bash -c \"rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'\"\n volumes:\n - .:/fridge_app\n ports:\n - \"3000:3000\"\n depends_on:\n - db\n \n \n```",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T02:14:50.703",
"favorite_count": 0,
"id": "77721",
"last_activity_date": "2021-06-23T02:33:22.110",
"last_edit_date": "2021-06-23T02:33:22.110",
"last_editor_user_id": "44865",
"owner_user_id": "44865",
"post_type": "question",
"score": 0,
"tags": [
"docker",
"heroku"
],
"title": "HerokuでDockerを導入していたらError: Exec format errorでアプリが表示できなくなりました",
"view_count": 653
} | [] | 77721 | null | null |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "一つのフォームで複数のモデルのレコードを更新できるように実装したいのですが、labelの表記がうまく反映されません。 \n`time_tables`テーブルのレコードと`artistsテーブル`のレコードを同時に保存したいため、モデルとコントローラーは以下のコードにしています。\n\n```\n\n class TimeTable < ApplicationRecord\n has_many :schedules # 複数のScheduleを持っている(中間テーブル)\n has_many :artists, through: :schedules # 複数のArtistを持っていて、中間モデルにSchedulesがある\n belongs_to :user # Userモデルに属している\n \n validates_associated :artists # Artistモデルのバリデーションを実行\n accepts_nested_attributes_for :artists, allow_destroy: true # Artistモデルを更新、削除刷ることができる\n end\n \n```\n\n```\n\n def new\n @time_table = TimeTable.new\n 10.times do\n @time_table.artists.build\n end\n end\n \n```\n\n一括登録の仕方がわからなかったのでtimes.doを使い、 **artistテーブル** のモデルを10回作成しようとしています。 \nerbファイルは以下のように記載しているのですが、ループ文が使われているため、フォーム欄は複数できるのですが、ラベルの表記が全部同じになってしまいます。\n\n```\n\n # 抜粋\n <div class=\"form-row\">\n <%= f.fields_for :artists do |a| %>\n <div class='form-group'>\n <%= a.label :name, '10:00' %>\n <%= a.text_field :name, class:'form-control' %>\n </div>\n <% end %>\n \n```\n\nラベルだけループさせずに、それぞれのフォームに合わせたラベルを作成したいのですが、どのように実装したらよいかわからないので、教えていただきたいです。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T02:28:54.143",
"favorite_count": 0,
"id": "77722",
"last_activity_date": "2021-06-23T09:50:00.960",
"last_edit_date": "2021-06-23T03:44:32.440",
"last_editor_user_id": "3060",
"owner_user_id": "43351",
"post_type": "question",
"score": 0,
"tags": [
"ruby-on-rails",
"ruby"
],
"title": "Rails 6.0 で label の表記が変わらない",
"view_count": 175
} | [
{
"body": "まず、accepts_nested_attributes_for は Rails\nによって提供されている機能ではありますが、非常に嫌われている半ば非推奨な機能です \n<https://github.com/rails/rails/pull/26976#discussion_r87855694>\n\n> I'd actually like to kill accepts_nested_attributes_for in due time.\n\nなので\n\n 1. formでやり取りするデータに対応する Form Object クラスを作成\n 2. コントローラーでフォームから送信された値を使って Form Object を new\n 3. Form Object 経由でデータベースに保存\n\nとするのが望ましいと思います\n\n仮に accepts_nested_attributes_for を使って実現するとしたら\n\nまず accepts_nested_attributes_for は Rails\nによって提供されている機能ではありますが、非常に嫌われている半ば非推奨な機能です\n\n * formでやり取りするデータに対応する Form Object クラスを作成\n * コントローラーでフォームから送信された値を使って Form Object を new\n * Form Object 経由でデータベースに保存\n\nとするのが望ましいと思います\n\n仮に accepts_nested_attributes_for を使って実現するとしたら\n\n```\n\n # config/routes.rb\n Rails.application.routes.draw do\n resources 'foos'\n end\n \n # app/models/foo.rb\n class Foo < ApplicationRecord\n has_many :bar,\n dependent: :destroy\n accepts_nested_attributes_for :bar,\n allow_destroy: true\n \n # fields_for に accepts_nested_attributes_for + has_many \n # 組み合わせであることを伝えるために必要\n def bars_attributes=(attributes)\n end\n end\n \n # app/models/bar.rb\n class Bar < ApplicationRecord\n belongs_to :foo,\n optional: true\n end\n \n # app/controllers/foos_controller.rb\n class FoosController < ApplicationController\n def new\n @foo = Foo.new\n # 3コ子要素を作る\n @foo.bar.build\n @foo.bar.build\n @foo.bar.build\n end\n \n def create\n params.permit!\n @foo = Foo.new(params[:foo])\n @foo.save!\n end\n end\n \n```\n\n```\n\n <%# app/views/foos/new.html.erb %>\n <%= form_with(model: @foo) do |f| %>\n <ul>\n <%= f.fields_for(:bar, :bar) { |f_bar| %>\n <li>index: <%= f_bar.index %></li>\n <li>name: <%= f_bar.text_field :name %></li>\n <% } %>\n </ul>\n <%= submit_tag %>\n <% end %>\n \n \n <%# app/views/foos/create.html.erb %>\n <% @foo.bar.each { |bar| %>\n <p><%= bar.name %></p>\n <% } %>\n \n```\n\nのような感じになると思います\n\n正直、このコードも fields_for のソースコードを読みながら書いたので、今後どのバージョンアップで壊れてもおかしくありません \naccepts_nested_attributes_for の利用は止めたほうが無難です",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T09:50:00.960",
"id": "77739",
"last_activity_date": "2021-06-23T09:50:00.960",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "9796",
"parent_id": "77722",
"post_type": "answer",
"score": 0
}
] | 77722 | null | 77739 |
{
"accepted_answer_id": "78150",
"answer_count": 1,
"body": "forの多重ループを用いて複数の .xlsx ファイルを順に読み込ませ、 \nBV、T1、T2、T3の4パターンを目的変数として選択し、 \nそれ以外のcolumnsを消して \n機械学習モデルのプログラムを作成していました。\n\n```\n\n for a in range(0,4,1):\n l1=['AP','ES','ET','FP']\n b=l1.pop(a)\n c=\".xlsx\"\n for d in range(0,4,1):\n df = pd.read_excel(b+c)\n l2=['BV','T1','T2','T3']\n del l2[d] \n df.drop(l2, axis=1,inplace=True)\n df.isnull().sum()\n df.dropna(inplace = True)\n df.isnull().sum()\n l3=['BV','T1','T2','T3']\n X = df.drop(l3[d], axis=1)\n Y = df[l3[d]]\n X=X.astype('str')\n Y=Y.astype('str')\n X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.3, random_state=0)\n model = RandomForestClassifier()\n model.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n with open('file.txt', 'a') as f:\n print(b,file=f)\n print(l2[d],file=f)\n print(\"RFtrain score:\",model.score(X_train,y_train),file=f)\n print(\"RFtest score:\",model.score(X_test,y_test),file=f)\n print(classification_report(y_test, y_pred),file=f)\n \n```\n\nしかし、以下のようにエラーが発生しました。\n\n```\n\n Traceback (most recent call last):\n File \"<stdin>\", line 24, in <module>\n IndexError: list index out of range\n \n```\n\nrangeがミスであると思われますが、構文のミスがわからなかったので教えていただけると幸いです。 \n※一周目の内側のループは出力できていました。",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T03:20:55.080",
"favorite_count": 0,
"id": "77725",
"last_activity_date": "2021-07-13T11:04:29.437",
"last_edit_date": "2021-06-23T03:50:40.250",
"last_editor_user_id": "3060",
"owner_user_id": "42526",
"post_type": "question",
"score": 0,
"tags": [
"python"
],
"title": "For ループの処理中に IndexError: list index out of range",
"view_count": 1558
} | [
{
"body": "コメント欄でのアドバイス通り、以下の記述を `l3[d]` に直したところ直りました。\n\n```\n\n print(l2[d],file=f)\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-07-13T09:19:08.760",
"id": "78150",
"last_activity_date": "2021-07-13T11:04:29.437",
"last_edit_date": "2021-07-13T11:04:29.437",
"last_editor_user_id": "3060",
"owner_user_id": "42526",
"parent_id": "77725",
"post_type": "answer",
"score": 0
}
] | 77725 | 78150 | 78150 |
{
"accepted_answer_id": "77730",
"answer_count": 1,
"body": "こちらのQiita記事を参考にSeleniumの勉強をしています。 \nUbuntu、Python3、Chromeを使っています。 \n以下のサンプルコードについて質門です。\n\n```\n\n import time\n from selenium import webdriver\n \n driver = webdriver.Chrome()\n driver.get('https://www.google.com/')\n time.sleep(5)\n search_box = driver.find_element_by_name(\"q\")\n search_box.send_keys('ChromeDriver')\n search_box.submit()\n time.sleep(5)\n driver.quit()\n \n```\n\n上のコードは正常に動作し、Googleで検索が行われた画面をスクリーンショットしました。\n\nこの、\n\n```\n\n search_box = driver.find_element_by_name(\"q\")\n \n```\n\nという部分は、Googleの検索ボックスを`<input\nname=\"q\">`という手がかりで特定していると思いますが、この\"q\"というnameの探し方が分かりません。\n\nwww.google.comにおいて検索ボックスを右クリックしてInspectを選択すると、以下の図のように要素が選択されます。\n\n[![Googleの検索ボックスをインスペクトした][1]][1] \n[1]: https://i.stack.imgur.com/vzZOv.png\n\n```\n\n <input id=\"input\" type=\"search\" autocomplete=\"off\" spellcheck=\"false\" role=\"combobox\" placeholder=\"Search Google or type a URL\" aria-live=\"polite\">\n \n```\n\nここにはnameアトリビュートがありません。 \nこの前後の表示をnameや\"q\"で検索したのですが、この要素に該当するものはなかったと思います。\n\nまた、`id=\"input\"`で引っかけようと思って\n\n```\n\n #search_box = driver.find_element_by_name(\"q\")\n search_box = driver.find_element_by_id(\"input\")\n \n```\n\nとコードを書き換えてみると\n\n```\n\n selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {\"method\":\"css selector\",\"selector\":\"[id=\"input\"]\"}\n \n```\n\nとエラーが出て止まってしまいました。\n\nということで、このGoogleの検索ボックスを特定する\"q\"というnameの割り出し方について、ご教示くださるようお願いいたします。",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T03:21:45.687",
"favorite_count": 0,
"id": "77726",
"last_activity_date": "2021-06-23T06:06:24.803",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "26673",
"post_type": "question",
"score": 0,
"tags": [
"python",
"html",
"selenium",
"selenium-webdriver"
],
"title": "Seleniumの要素を特定しているnameの取得方法が分からない?",
"view_count": 1083
} | [
{
"body": "コメントをいただきました。\n\n * Chromeの場合、lazy loadingが働いているのではないか。chrome://new-tab-page/lazy_load.js を見ますと、URLSearchParams;searchParams.append(\"q\",this.finalResult_);と書かれている\n * FirefoxでInspectすると<input class=\"gLFyf gsfi\" ... name=\"q\" ... title=\"検索\" ...> と表示される\n\n確かにFirefoxでInspectされるとname=\"q\"が確認できたので、私としてはこれで問題解決とします。ありがとうございました。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T06:06:24.803",
"id": "77730",
"last_activity_date": "2021-06-23T06:06:24.803",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "26673",
"parent_id": "77726",
"post_type": "answer",
"score": 1
}
] | 77726 | 77730 | 77730 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "クリックしてアクティブにしたリンクの背景にだけ、ふわふわと動く背景画像を出現させたいです。 \ncssだけでできないかと調べてlabelを試して失敗し、jqueryでクラスを付け替えることを試しましたがうまくいきません。\n\nコードは以下\n\n```\n\n <!DOCTYPE html>\n <html lang=\"ja\">\n <head>\n <meta charset=\"utf-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <title>タイトル</title>\n <link rel=\"stylesheet\" href=\"style.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>\n </head>\n <body>\n <nav>\n <ul class=\"flex_\" id=\"nav_\">\n <li><a href=\"#\">top</a></li>\n <li><a href=\"#one\">関連記事</a></li>\n <li><a href=\"#two\">みなさんのメッセージ</a></li>\n </ul>\n </nav>\n <section id=\"one\">\n <p>ここはoneだよ</p>\n </section>\n <section id=\"two\">\n <p>ここはtwoだよ</p>\n </section>\n <script>\n var linkList = $('#nav li');\n //リストをクリックした時の処理\n linkList.on('click', function () {\n //リンクのclass設定をリセット\n linkList.removeClass('huwahuwa');\n //クリックしたリストにcurrentのclassを追加\n $(this).addClass('huwahuwa');\n });\n </script>\n </body>\n </html>\n \n @charset \"utf-8\";\n \n html{\n scroll-behavior: smooth;\n }\n body{\n width:960px;\n margin:0 auto;\n font-size: 16px;\n position: relative ;\n }\n \n a {\n -webkit-transition: 0.3s;\n -moz-transition: 0.3s;\n -o-transition: 0.3s;\n -ms-transition: 0.3s;\n transition: 0.3s;\n }\n \n nav{\n height:90px;\n width:95%;\n margin:0 auto;\n position: fixed;\n top:0;\n left:0;\n }\n \n .flex_{\n max-width: 1200px;\n width:40%;\n margin:0 0 0 60%;\n height:80px;\n line-height:80px;\n display: flex;\n justify-content: space-between;\n text-decoration: none;\n list-style: none;\n }\n \n @media(max-width: 959px){\n body{\n width:100%;\n }\n .flex_{\n width:95%;\n margin:0 auto;\n }\n }\n \n .flex_ a{\n display: block;\n font-size:1.2rem;\n padding:0;\n margin-left:15px;\n color:#000;\n text-decoration: none;\n }\n \n .huwahuwa{\n animation:huwahuwa 3s infinite ease-in-out .8s alternate;\n background:url(icon.png) no-repeat center center / 60px auto;\n display:inline-block;\n transition:1.5s ease-in-out;\n width:100px;\n height:100px;\n margin-left:-100px;\n z-index:-99;\n }\n \n @keyframes huwahuwa {\n 0%{\n transform:translate(0,0) rotate(-7deg);\n }\n 50%{\n transform:translate(0,-7px) rotate(0deg);\n }\n 100%{\n transform:translate(0,0) rotate(7deg);\n }\n }\n \n .huwahuwa2{\n animation:huwahuwa 2.7s infinite ease-in-out .65s alternate;\n background:url(icon.png) no-repeat center center / 60px auto;\n display:inline-block;\n transition:1.5s ease-in-out;\n width:100px;\n height:100px;\n margin-left:-100px;\n z-index:-99;\n }\n \n @keyframes huwahuwa2 {\n 0%{\n transform:translate(0,0) rotate(-7deg);\n }\n 50%{\n transform:translate(0,-7px) rotate(0deg);\n }\n 100%{\n transform:translate(0,0) rotate(7deg);\n }\n }\n \n .flex_ a:hover{\n opacity:0.6;\n transition: .6s;\n }\n \n #one,#two,#three{\n width:100%;\n height:600px;\n }\n #one{\n margin-top:80px;\n background:pink;\n z-index:-100;\n }\n #two{\n background:skyblue;\n z-index:-100;\n }\n #three{\n background:green;\n z-index:-100;\n }\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T05:09:42.713",
"favorite_count": 0,
"id": "77727",
"last_activity_date": "2021-06-23T07:20:53.200",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "46994",
"post_type": "question",
"score": 0,
"tags": [
"html",
"jquery",
"css"
],
"title": "動く背景がクリックすると表示され、別のものをクリックするとそちらに動く背景が移るメニューを作りたい",
"view_count": 76
} | [
{
"body": "「ふわふわと動く背景画像」とは一体どういうものか \n出来上がりのイメージがあいまいでよくわかりませんでした。\n\nただjQueryが動かないのは\"nav_\"になっているからかなと思います。 \nnavにすれば正しく動くと思います。\n\n```\n\n var linkList = $('#nav li');\n //リストをクリックした時の処理\n linkList.on('click', function () {\n //リンクのclass設定をリセット\n $(\"section\").removeClass('huwahuwa');\n $(this).addClass('huwahuwa');\n });\n```\n\n```\n\n @charset \"utf-8\";\n \n html{\n scroll-behavior: smooth;\n }\n body{\n width:960px;\n margin:0 auto;\n font-size: 16px;\n position: relative ;\n }\n \n a {\n -webkit-transition: 0.3s;\n -moz-transition: 0.3s;\n -o-transition: 0.3s;\n -ms-transition: 0.3s;\n transition: 0.3s;\n }\n \n nav{\n height:90px;\n width:95%;\n margin:0 auto;\n position: fixed;\n top:0;\n left:0;\n }\n \n .flex_{\n max-width: 1200px;\n width:40%;\n margin:0 0 0 60%;\n height:80px;\n line-height:80px;\n display: flex;\n justify-content: space-between;\n text-decoration: none;\n list-style: none;\n }\n \n @media(max-width: 959px){\n body{\n width:100%;\n }\n .flex_{\n width:95%;\n margin:0 auto;\n }\n }\n \n .flex_ a{\n display: block;\n font-size:1.2rem;\n padding:0;\n margin-left:15px;\n color:#000;\n text-decoration: none;\n }\n \n .huwahuwa{\n animation:huwahuwa 3s infinite ease-in-out .8s alternate;\n background:url(icon.png) no-repeat center center / 60px auto;\n display:inline-block;\n transition:1.5s ease-in-out;\n width:100px;\n height:100px;\n margin-left:-100px;\n z-index:-99;\n }\n \n @keyframes huwahuwa {\n 0%{\n transform:translate(0,0) rotate(-7deg);\n }\n 50%{\n transform:translate(0,-7px) rotate(0deg);\n }\n 100%{\n transform:translate(0,0) rotate(7deg);\n }\n }\n \n .huwahuwa2{\n animation:huwahuwa 2.7s infinite ease-in-out .65s alternate;\n background:url(icon.png) no-repeat center center / 60px auto;\n display:inline-block;\n transition:1.5s ease-in-out;\n width:100px;\n height:100px;\n margin-left:-100px;\n z-index:-99;\n }\n \n @keyframes huwahuwa2 {\n 0%{\n transform:translate(0,0) rotate(-7deg);\n }\n 50%{\n transform:translate(0,-7px) rotate(0deg);\n }\n 100%{\n transform:translate(0,0) rotate(7deg);\n }\n }\n \n .flex_ a:hover{\n opacity:0.6;\n transition: .6s;\n }\n \n #one,#two,#three{\n width:100%;\n height:600px;\n }\n #one{\n margin-top:80px;\n background:pink;\n z-index:-100;\n }\n #two{\n background:skyblue;\n z-index:-100;\n }\n #three{\n background:green;\n z-index:-100;\n }\n```\n\n```\n\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <nav>\n <ul class=\"flex_\" id=\"nav\">\n <li><a href=\"#\">top</a></li>\n <li><a href=\"#one\">関連記事</a></li>\n <li><a href=\"#two\">みなさんのメッセージ</a></li>\n </ul>\n </nav>\n <section id=\"one\">\n <p>ここはoneだよ</p>\n </section>\n <section id=\"two\">\n <p>ここはtwoだよ</p>\n </section>\n```",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T05:27:05.223",
"id": "77729",
"last_activity_date": "2021-06-23T07:20:53.200",
"last_edit_date": "2021-06-23T07:20:53.200",
"last_editor_user_id": "22665",
"owner_user_id": "22665",
"parent_id": "77727",
"post_type": "answer",
"score": 0
}
] | 77727 | null | 77729 |
{
"accepted_answer_id": "77751",
"answer_count": 3,
"body": "あるPHPの入門書にデストラクタについての解説があります。\n\n> *デストラクタ \n> コンストラクタとは反対に、オブジェクトが破棄されるタイミングで実行されるのがデストラクタです。名前は __destructに固定されている。 \n> デストラクタには、クラスの中で使用したリソースを破棄するなど、主に終了するときの処理を記述するのが一般的です。\n\n以下のような記述をしました。(person.php)\n\n```\n\n <?php\n \n class Person{\n \n public $lastName;\n public $firstName;\n \n public function __construct($lastName, $firstName){\n $this->firstName = $firstName;\n $this->lastName = $lastName;\n }\n \n public function show(){\n print \"<p>私の名前は {$this->lastName} {$this->firstName}です。</p>\";\n }\n \n public function __destruct(){\n print \"<p>インスタンスが破棄されました。<p>\";\n }\n }\n ?>\n \n```\n\n上の記述をインスタンス化する記述です。(instancne.php)\n\n```\n\n <?php\n require_once('person.php');\n \n $p = new Person('田中', '幸太郎');\n $p->show();\n ?>\n \n```\n\n<表示結果>\n\n```\n\n 私の名前は 田中 幸太郎です。\n \n インスタンスが破棄されました。\n \n```\n\nとなります。試しにもうひとつインスタンスを追加します。\n\n```\n\n <?php\n require_once('person.php');\n \n $p = new Person('田中', '幸太郎');\n $p->show();\n $p1 = new Person('鈴木', '京子');\n $p1->show();\n ?>\n \n```\n\n<表示結果>\n\n```\n\n 私の名前は 田中 幸太郎です。\n \n 私の名前は 鈴木 京子です。\n \n インスタンスが破棄されました。\n \n インスタンスが破棄されました。\n \n```\n\n説明にある、 \n「オブジェクトが破棄されるタイミングで実行されるのがデストラクタです。」 \n「デストラクタには、クラスの中で使用したリソースを破棄するなど、主に終了するときの処理を記述するのが一般的です。」\n\nこれらの意味がわかりません。\n\nコンストラクタの \n「new 演算子によってインスタンス化されるタイミングで実行される」 \n「プロパティの初期化」 \nなどの意味は理解できているつもりです。\n\nデストラクタを使うと「オブジェクトが破棄される」、「クラスの中で使用したリソースを破棄する」とありますが、『一度インスタンスを作るとクラス内のリソースが破棄されるのかな?』と思い、試しにもう一つインスタンスを作成しました。上記の通り問題なく使えています。 \n膨大な記述になると、クラス、この場合は 「class Person」」は再利用出来なくすると言った意味になるのでしょうか?\n\n他の教材やネットで検索してみたりしたのですが、イメージがつかめません。 \n以下のPHP公式のサイトから考えてみると、クラス内で参照できるものがなければ、コールされるという風に解釈できるかもしれませんが、意味がわかりません。\n\nデストラクタ(__destruct)はコンストラクタ(__construct)の反対というように記述されているものもありますが余計に意味が分かりません。\n\n初学者にもわかるようにデストラクタについて教えてもらえないでしょうか? \nまたどういうケースで利用するのかもよく分かりません。 \nそのあたりも併せて教えて下さい。 \n宜しくお願いいたいます。\n\n**参考:**\n\n[デストラクタ | PHP Manual](https://www.php.net/manual/ja/language.oop5.decon.php)\n\n>\n```\n\n> __destruct(): void\n> \n```\n\n>\n> PHP には、C++ のような他のオブジェクト指向言語に似たデストラクタの概念があります。 デストラクタメソッドは、\n> 特定のオブジェクトを参照するリファレンスがひとつもなくなったときにコールされます。 あるいは、スクリプトの終了時にも順不同でコールされます。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T06:38:08.013",
"favorite_count": 0,
"id": "77731",
"last_activity_date": "2021-06-24T00:54:19.370",
"last_edit_date": "2021-06-23T08:33:53.350",
"last_editor_user_id": "3060",
"owner_user_id": "42150",
"post_type": "question",
"score": 1,
"tags": [
"php"
],
"title": "デストラクタ __destruct はどのような時に使うのですか?",
"view_count": 1483
} | [
{
"body": "ここで示しているリソースとは、外部と連携して利用しているリンクや[リソース](https://www.php.net/manual/ja/language.types.resource.php)を指します。\n\n一番有名なところですとMySQLなどのDBのリソースでしょう。\n\nDBを例にとると \nクラスの中でDBとコネクションを実施してリソースを確保して、処理を行います。 \nもしリソースを明示的に破棄しないと、OS側ではつながったままです。 \nOSのコネクション数にも限界がありますし余分にコストをかける必要性はないので一旦破棄しようとなったときにデストラクタで処理すると一括で処理できてわかりやすくなります。\n\n他にもいろいろな外部と連携する用の[リソース](https://www.php.net/manual/ja/resource.php)が存在します。 \nそもそも破棄するのも必要がないものもあったりしますが、一般的にはつないで必要がなくなったら切っておくが理想的なプログラムでしょう",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T07:08:53.683",
"id": "77734",
"last_activity_date": "2021-06-23T07:08:53.683",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "22665",
"parent_id": "77731",
"post_type": "answer",
"score": 2
},
{
"body": ">\n> 他の教材やネットで検索してみたりしたのですが、イメージがつかめません。以下のPHP公式のサイトから考えてみると、クラス内で参照できるものがなければ、コールされるという風に解釈できるかもしれませんが、意味がわかりません。\n\n#### 原文(英語)\n\n[PHP: Constructors and\nDestructors](https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.destructor)\n\n> **Destructor**\n>\n> PHP possesses a destructor concept similar to that of other object-oriented\n> languages, such as C++. The destructor method will be called as soon as\n> there are no other references to a particular object, or in any order during\n> the shutdown sequence.\n\n例えば関数内のローカル変数を考えてみると良いかもしれません。以下にサンプルコードを示しますが、`NewPerson()` 関数の実行が完了した時点で\ndestructor が実行されている事が判ります。\n\n```\n\n <?php\n \n require_once('person.php');\n \n function NewPerson() {\n $p = new Person('田中', '幸太郎');\n $p->show();\n }\n \n NewPerson();\n echo \"<p>Done.<p>\";\n \n $p = new Person('山田', '太郎');\n $p->show();\n \n echo \"<p>Exit.<p>\";\n \n```\n\n#### 実行結果\n\n```\n\n 私の名前は 田中 幸太郎です。\n \n インスタンスが破棄されました。\n \n Done.\n \n 私の名前は 山田 太郎です。\n \n Exit.\n \n インスタンスが破棄されました。\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T11:00:12.597",
"id": "77742",
"last_activity_date": "2021-06-23T11:00:12.597",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77731",
"post_type": "answer",
"score": 1
},
{
"body": "質問本文を拝見するに「インスタンスに所属するもの」「クラスに所属するもの」「クラス自体」の区別がついていないような気がします。提示例 `Person`\nにおいて `firstName` と `lastName` はインスタンスに所属するものです。なので **インスタンス`p1` が破棄**されるとき\n`p1->firstName` も一緒に破棄されるわけです。 `p1` の破棄(デストラクト)の際にクラス `Person`\nが破棄されることはありません。実際 @metropolis 氏のサンプルでそのように挙動しています。\n\n提示例は `php` 自体が提供している文字列のみを利用しているので破棄の際に必要な処理は `php` 自体が勝手に行っているというか `php`\nだけで完結しているというか。だから「デストラクタ」で特別な処理を行う必要が無いので余計に必要性がわからないというか。オイラ `php`\nはメインに使っている言語でない関係でサンプルを出せるとしたら [c++](/questions/tagged/c%2b%2b \"'c++'\nのタグが付いた質問を表示\") (それも better C としてのサンプル)\n\n```\n\n struct filetest_type {\n FILE* f;\n filetest_type() : f(NULL) { }\n ~filetest_type() {\n if (f!=NULL) fclose(f);\n }\n void open(const char* fn) {\n f=fopen(fn, \"r\");\n }\n };\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-24T00:54:19.370",
"id": "77751",
"last_activity_date": "2021-06-24T00:54:19.370",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "8589",
"parent_id": "77731",
"post_type": "answer",
"score": 1
}
] | 77731 | 77751 | 77734 |
{
"accepted_answer_id": null,
"answer_count": 2,
"body": "以下画像のようなcsvファイルからDendrite Length列とFilamentID列のデータを取り出すための関数を書いたのですが、 \n[](https://i.stack.imgur.com/9E2fp.png)\n\n```\n\n DataandIdExtractionfromCSV <- function(path,sectionid,dataname) {\n \n df = read.csv(path, \n fileEncoding = \"UTF-8-BOM\",\n stringsAsFactors=F,\n na.strings=\"NULL\",\n )\n \n df <- na.omit(df)\n # 0,1,2行目を削除\n df2<-df[c(-0,-1,-2),]\n \n \n # 最左列とFilamentIDのdatatypeを変換\n \n df2$dataname <- as.numeric(df2$dataname)\n df2$X.5 <- as.integer(df2$X.5)\n \n \n # Dendrite LengthとFilamentIDをtibble列として再定義、Header(名前)もつける\n tibbledataid = tibble(tibbledataid = df2$dataname)\n tibbledata = tibble(tibbledata = df2$X.5)\n \n # 2列を一つのtibble(行列)に統合\n df_tidy = bind_cols(tibbledataid,tibbledata)\n # 長さと対応するidだけ抽出した行列\n head(df_tidy)\n tidieddfname = paste(sectionid,\"_tidy.csv\", sep = \"\", collapse = NULL)\n write.csv(df_tidy, tidieddfname)\n \n }\n \n```\n\nこれを以下の様に実行すると\n\n```\n\n DataandIdExtractionfromCSV(\"WT1 x20 ROI1 S ctx 06212021_Statistics/Dendrite_Length.csv\",\"tesuto\",Dendrite.Length)\n \n```\n\n```\n\n Error during wrapup: 置換は 0 列ですが、データは 133 列です \n Error: no more error handlers available (recursive errors?); invoking 'abort' restart\n \n```\n\n以上のようなエラーが出てしまいます。 \nbrowse()関数でエラー箇所を調べてみたところ、まず\n\n```\n\n df2$dataname <- as.numeric(df2$dataname)\n \n```\n\n以上の箇所で引っかかっていることが分かりましたが、それ以上何が原因でどうすればよいのか分かりませんでした。\n\n有識者の方々、何卒ご教示いただけますと幸いです。\n\n追記:[](https://i.stack.imgur.com/Hxlvs.png) \nコード中のX.5という列名?は以下のように自動で付与されていました。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T06:39:23.667",
"favorite_count": 0,
"id": "77732",
"last_activity_date": "2023-08-01T02:00:30.057",
"last_edit_date": "2021-06-23T11:00:56.130",
"last_editor_user_id": "36869",
"owner_user_id": "36869",
"post_type": "question",
"score": 0,
"tags": [
"r"
],
"title": "Error during wrapup: 置換は 0 列ですが、データは 133 列です というエラーが解決できない",
"view_count": 1813
} | [
{
"body": "問題点は `df2$dataname` という表記にあります。この場合、データフレーム `df2` の `dataname`\nカラムという意味になってしまいます。なので、indirect access な表記に変更します。\n\n```\n\n ## df2$dataname -> df2[, dataname] へ変更\n \n df2$dataname <- as.numeric(df2$dataname)\n =>\n df2[, dataname] <- as.numeric(df2[, dataname])\n \n tibbledataid = tibble(tibbledataid = df2$dataname)\n =>\n tibbledataid = tibble(tibbledataid = df2[, dataname])\n \n```\n\nまた、DataandIdExtractionfromCSV 関数呼び出しの際に指定する第3引数を文字列に変更します。\n\n```\n\n ## Dendrite.Length -> \"Dendrite.Length\" へ変更\n \n DataandIdExtractionfromCSV(\"...\", \"tesuto\", Dendrite.Length)\n =>\n DataandIdExtractionfromCSV(\"...\", \"tesuto\", \"Dendrite.Length\")\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T11:52:02.697",
"id": "77744",
"last_activity_date": "2021-06-23T11:52:02.697",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77732",
"post_type": "answer",
"score": 0
},
{
"body": "質問からかなり時間も経過していますので御参考です。 \n「CSV ファイルから `Dendrite Length` 列と `FilamentID` 列を取り出して,別の CSV\nファイルに書き出す」処理について,`tidyverse` パッケージを用いた記述例を下記に示します。\n\n```\n\n library(tidyverse)\n options(pillar.sigfig = 6)\n \n path <- \"Dendrite_Length.csv\"\n sectionid <- \"tesuto\"\n dataname <- \"Dendrite Length\"\n \n df <- read_csv(path, skip = 2, show_col_types = FALSE)\n df\n ## # A tibble: 7 × 8\n ## `Dendrite Length` Unit Category Depth Level Time FilamentID ID\n ## <dbl> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl>\n ## 1 71.1878 um Dendrite NA NA 1 100000373 510000000000\n ## 2 3.84491 um Dendrite NA NA 1 100000378 510000000000\n ## 3 2.72817 um Dendrite NA NA 1 100000378 510000000000\n ## 4 29.3313 um Dendrite 2 2 1 100000369 510000000000\n ## 5 34.1316 um Dendrite NA NA 1 100000378 510000000000\n ## 6 16.0978 um Dendrite 2 1 1 100000369 510000000000\n ## 7 28.5015 um Dendrite 1 1 1 100000369 510000000000\n \n df2 <- df |>\n select(all_of(dataname), FilamentID)\n df2\n ## # A tibble: 7 × 2\n ## `Dendrite Length` FilamentID\n ## <dbl> <dbl>\n ## 1 71.1878 100000373\n ## 2 3.84491 100000378\n ## 3 2.72817 100000378\n ## 4 29.3313 100000369\n ## 5 34.1316 100000378\n ## 6 16.0978 100000369\n ## 7 28.5015 100000369\n \n path2 <- paste0(sectionid, \"_tidy.csv\")\n write_csv(df2, path2)\n \n```\n\n次に,これを基に関数で記述すると下記になります。\n\n```\n\n library(tidyverse)\n options(pillar.sigfig = 6)\n \n DataandIdExtractionfromCSV <- function(path, sectionid, dataname) {\n df <- read_csv(path, skip = 2, show_col_types = FALSE)\n df2 <- df |>\n select(all_of(dataname), FilamentID)\n \n path2 <- paste0(sectionid, \"_tidy.csv\")\n write_csv(df2, path2)\n }\n DataandIdExtractionfromCSV(\"Dendrite_Length.csv\", \"tesuto\", \"Dendrite Length\")\n \n (read_csv(\"tesuto_tidy.csv\", show_col_types = FALSE))\n ## # A tibble: 7 × 2\n ## `Dendrite Length` FilamentID\n ## <dbl> <dbl>\n ## 1 71.1878 100000373\n ## 2 3.84491 100000378\n ## 3 2.72817 100000378\n ## 4 29.3313 100000369\n ## 5 34.1316 100000378\n ## 6 16.0978 100000369\n ## 7 28.5015 100000369\n \n```\n\nなお,入力ファイルは下記になります。 \nDendrite_Length.csv:\n\n```\n\n Dendrite Length\n ===============\n Dendrite Length,Unit,Category,Depth,Level,Time,FilamentID,ID\n 71.1878,um,Dendrite,,,1,100000373,5.10E+11\n 3.84491,um,Dendrite,,,1,100000378,5.10E+11\n 2.72817,um,Dendrite,,,1,100000378,5.10E+11\n 29.3313,um,Dendrite,2,2,1,100000369,5.10E+11\n 34.1316,um,Dendrite,,,1,100000378,5.10E+11\n 16.0978,um,Dendrite,2,1,1,100000369,5.10E+11\n 28.5015,um,Dendrite,1,1,1,100000369,5.10E+11\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2023-06-05T06:36:35.887",
"id": "95102",
"last_activity_date": "2023-06-05T06:36:35.887",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "54588",
"parent_id": "77732",
"post_type": "answer",
"score": 0
}
] | 77732 | null | 77744 |
{
"accepted_answer_id": null,
"answer_count": 2,
"body": "# 環境\n\nOS: Windows 10 Home 64ビット \nRのバージョン: 4.0.3 \nRStudioのバージョン: 1.4.1106 \nディレクトリ:C:\\Users\\xxx\\rmarkdownfile\\test.Rmd (xxxには自分のユーザー名が入ります)\n\n# 問題\n\n初めてこちらで質問させて頂きます。 \n表題の通り、RStudioでRmarkdownファイルを作成しているのですが、メッセージが文字化けして表示されます。 \n例えばパッケージ\"socviz\"を読み込むため、次のようなチャンクを実行します。\n\n```\n\n library(socviz)\n \n```\n\nすると次のようなメッセージが表示されます。\n\n> �p�b�P�[�W �esocviz�f �̓o�[�W���� 4.0.5 �� R �̉��ő����܂���\n\nおそらくメッセージ内容としては \n「警告メッセージ: パッケージ ‘socviz’ はバージョン 4.0.5 の R の下で造られました」 \nという内容だと思われ、load自体は出来ているようなのですが、メッセージが読めないと不便なため解決したいと考えています。 \nsocvizに限らず、MASSやtidyverseなどのライブラリでも同様の文字化けが起こります。 \nパスにも文書内にも日本語含む2バイト文字は含まれていません。 \nコンソールから直接実行したり、R Scriptsから入力した場合には問題なく日本語が表示されます。\n\n# 対処したこと\n\nGoogle\nDriveやOneDrive管理下のフォルダをワーキングディレクトリにしていると文字化けが起こると聞いたので、ワーキングディレクトリをローカルな場所に置き念の為同期を停止した上で実行しているのですが変わりません。 \nTools>Global Options>code>saving>Default text encodingはUTF-8に設定しています。 \nFile>Reopen with EncodingからUTF-9、cp932、SHIFT-JISを試しましたが、いずれでも同じ現象が起きています。",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T07:36:41.487",
"favorite_count": 0,
"id": "77735",
"last_activity_date": "2021-06-26T02:39:22.067",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "45442",
"post_type": "question",
"score": 1,
"tags": [
"r",
"markdown",
"rstudio"
],
"title": "RStudioでRmarkdownファイルを作成中、日本語メッセージが文字化けする",
"view_count": 1012
} | [
{
"body": "自己解決致しました。 \nSet.locale(\"LC_ALL\",\n\"C\")とすることでエラーメッセージが正常に表示されるようになりました。ただし、ロケールを\"C\"とすることで2バイト文字を扱えなくなる?ようなので、どうしても日本語を含む必要がある場合にはまた違う方法を考える必要があるかもしれません......。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T08:24:38.783",
"id": "77737",
"last_activity_date": "2021-06-23T08:24:38.783",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "45442",
"parent_id": "77735",
"post_type": "answer",
"score": 0
},
{
"body": "現時点では Windows でメッセージの日本語化とそれ以外を両立するのは不可能です. UTF-8 が前提となっているからですが, Windows\nの日本語ロケールでは UTF-8 を使用していないためこうなります. WSL や Docker などで Linux系の仮想環境を作るか,\nクラウド上の環境で作業するしかありません (UTF-8対応版Rの開発も進んでいますがまだリリースされていません). Windows 環境では,\n\n```\n\n Sys.setlocale(\"LC_ALL\", 'Japanese_Japan.932')\n \n```\n\nとして, OSと同じCP932エンコーディングにして, メッセージは英語表示にするパターンが一番不具合が起こりにくいと思います.\n\n> ロケールを\"C\"とすることで2バイト文字を扱えなくなる?ようなので\n\nこれはそのとおりです. \"C\" はマルチバイト文字の扱いをやめるという意味です (正確な定義は違いますが). よってそれ以外の場面での不便が増します.\n\n> Tools>Global Options>code>saving>Default text encodingはUTF-8に設定しています。 \n> File>Reopen with EncodingからUTF-9、cp932、SHIFT-JISを試しましたが、いずれでも同じ現象が起きています。\n\nこれは読み込むテキストファイル (CSV, R ファイル等) のエンコーディングなので, 今回の問題とは直接関係ありません.\n関係しているのはシステムのエンコーディングの変更です.\n\n> Google DriveやOneDrive管理下のフォルダをワーキングディレクトリにしていると文字化けが起こる \n> 日本語環境ではそれらのフォルダを指すパスに日本語が含まれていることが多いため不具合が起こりやすいですが,\n> 文字化けそのものを引き起こすケースはあまりないと思います.",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-26T02:39:22.067",
"id": "77795",
"last_activity_date": "2021-06-26T02:39:22.067",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "40575",
"parent_id": "77735",
"post_type": "answer",
"score": 1
}
] | 77735 | null | 77795 |
{
"accepted_answer_id": "77747",
"answer_count": 2,
"body": "gatsby.jsで製作中のサイトにTwitterのツイートを埋め込もうとしています。\n\nhtmlの`<head>`で \n`<script async src=\"https://platform.twitter.com/widgets.js\"\ncharset=\"utf-8\"></script>` \nを読み込んでいてるのですが、どうすればこれの読み込み完了をjavascriptで検知できるでしょうか?\n\n```\n\n const [tweetId, setTweetId] = useState()\n \n useEffect(() => {\n const container = document.getElementById(\"container\")\n window.twttr.widgets.createTweet(tweetId, container)\n }, [tweetId])\n \n setTweetId(12345)\n \n```\n\n上記のようなコードで、ページにツイートを埋め込んでいるのですが、「`window.twttr`が存在しません」みたいなエラーになります。\n\n`window.twttr`というのは`widgets.js`がロード完了すると使えるようになる何かです。 \n(DOMなのか何なのか理解していません。誰か知っていたら教えてください。)\n\n 1. トップページ(ツイートを埋め込んでいない)にアクセスして、`widgets.js`を読み込ませる。\n 2. サブページ(ツイートを埋め込んでいる)に移動。 \nのような手順ならエラーになりません。ツイートが画面に表示されます。\n\nwidgets.jsさえ読み込めればツイートを表示できているので、`window.twttr.widgets.createTweet()`の部分のコード自体が間違っている訳ではないです。\n\nいまのところ、`setInterval`で1秒ごとに`window.twttr`の存在確認をしているのですが、効率が悪いと感じています。\n\n`addEventListener`などで`window.twttr`が利用可能になるまで待ち、`window.twttr.widgets.createTweet()`を実行させるにはどうすればいいでしょうか?",
"comment_count": 8,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T08:38:07.520",
"favorite_count": 0,
"id": "77738",
"last_activity_date": "2021-06-23T16:29:36.273",
"last_edit_date": "2021-06-23T12:25:19.910",
"last_editor_user_id": "45540",
"owner_user_id": "45540",
"post_type": "question",
"score": 0,
"tags": [
"javascript",
"reactjs",
"ajax",
"twitter",
"gatsby"
],
"title": "javascriptでwidgets.js(外部の.jsファイル)読み込み完了を検知するには?",
"view_count": 1086
} | [
{
"body": "ごく素直に、対象の`script`要素の`load`イベントで検知できるはずです。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T13:18:22.667",
"id": "77745",
"last_activity_date": "2021-06-23T13:18:22.667",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "3475",
"parent_id": "77738",
"post_type": "answer",
"score": 0
},
{
"body": "Twitter Developer Platformでは、「最も信頼できる方法」としてwidgets.jsロード用のサンプルコードが紹介されています。 \n<https://developer.twitter.com/en/docs/twitter-for-websites/javascript-\napi/guides/set-up-twitter-for-websites>\n\n```\n\n <script>window.twttr = (function(d, s, id) {\n var js, fjs = d.getElementsByTagName(s)[0],\n t = window.twttr || {};\n if (d.getElementById(id)) return t;\n js = d.createElement(s);\n js.id = id;\n js.src = \"https://platform.twitter.com/widgets.js\";\n fjs.parentNode.insertBefore(js, fjs);\n \n t._e = [];\n t.ready = function(f) {\n t._e.push(f);\n };\n \n return t;\n }(document, \"script\", \"twitter-wjs\"));</script>\n \n```\n\nこのように`widgets.js`をロードした後、`twttr.ready`関数の引数にロード完了後実行したいコールバック関数またはアロー関数を投入すればツイートが表示されます。\n\n```\n\n twttr.ready( () => twttr.widgets.createTweet(\"20\",document.querySelector('div.container'))) ;\n \n```\n\nここまでがリンク先のドキュメントに記載されいてる内容です。\n\n質問のようなコードの場面で使用するのであれば、`twttr.ready`関数の引数に`setTweetId`を実行するコールバック関数を設定すれば表示できるのではないかと思います。",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T16:07:49.123",
"id": "77747",
"last_activity_date": "2021-06-23T16:29:36.273",
"last_edit_date": "2021-06-23T16:29:36.273",
"last_editor_user_id": "3060",
"owner_user_id": "46944",
"parent_id": "77738",
"post_type": "answer",
"score": 2
}
] | 77738 | 77747 | 77747 |
{
"accepted_answer_id": null,
"answer_count": 1,
"body": "レジストラでドメインを取得して、オンプレミスの権威DNSサーバに取得したドメインを委譲(管理)するメリットはありますでしょうか?\n\nそのままレジストラのネームサーバで管理していた方が、セキュリティ・可用性の面で良い気がしますが、「xxxのためにはオンプレミスの権威DNSサーバで管理した方が便利」などあればご教授いただきたいと思います。\n\nなお、現在考えている構成は、オンプレミスにインターネットからアクセス可能なWebサーバが1台あり、そのWebサーバーに紐づくドメインの管理について設計しております。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-23T14:25:47.403",
"favorite_count": 0,
"id": "77749",
"last_activity_date": "2021-06-27T12:57:32.923",
"last_edit_date": "2021-06-23T16:26:01.150",
"last_editor_user_id": "3060",
"owner_user_id": "47004",
"post_type": "question",
"score": 0,
"tags": [
"dns"
],
"title": "権威DNSサーバをオンプレミスに設置するメリットについて",
"view_count": 265
} | [
{
"body": "DNSサーバの設計運用に精通しているのであれば自前のDNSサーバの「自由にコントロールできる」点はメリットになりますが、知識がないのであればメリットどころかデメリットになります。\n\n上記は一例で、一般的に前提条件なしでメリットを探すのは意味がないので、まず要件に適合しているのかどうかで考えてください。",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-27T12:57:32.923",
"id": "77818",
"last_activity_date": "2021-06-27T12:57:32.923",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "5793",
"parent_id": "77749",
"post_type": "answer",
"score": 0
}
] | 77749 | null | 77818 |
{
"accepted_answer_id": "77768",
"answer_count": 1,
"body": "rails_same_site_cookie を staging, production だけでいれて \nhttp://localhost:3000 でアクセスする development にはいれたくないです\n\n```\n\n gem \"rails_same_site_cookie\", group: [:staging, :production]\n \n```\n\nとかいてもローカルで bundle install すると普通に入ってしまいます \ndevelopment 以外でのみインストールしたい場合どのようにかけばいいのでしょうか",
"comment_count": 3,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-24T06:18:31.073",
"favorite_count": 0,
"id": "77753",
"last_activity_date": "2021-06-25T01:02:48.837",
"last_edit_date": "2021-06-24T10:58:03.637",
"last_editor_user_id": "3060",
"owner_user_id": null,
"post_type": "question",
"score": 0,
"tags": [
"ruby-on-rails",
"gemfile"
],
"title": "development 以外にだけインストールしたい Gemfile の書き方",
"view_count": 126
} | [
{
"body": "bundle install時に\n\n```\n\n bundle install --without production staging\n \n```\n\nとしてみて下さい。\n\nbundle\ninstall時にはどのenvironmentで使うか分からないので、すべてのenvironmentのgemがインストールされるという事だと思います。\n\n一度`--without`を指定すればその情報は`.bundle/config`に記録されて、以降は`bundle\ninstall`でも大丈夫になるようです。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-25T01:02:48.837",
"id": "77768",
"last_activity_date": "2021-06-25T01:02:48.837",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "12203",
"parent_id": "77753",
"post_type": "answer",
"score": 1
}
] | 77753 | 77768 | 77768 |
{
"accepted_answer_id": "77784",
"answer_count": 2,
"body": "SNS等でサインアップをして\n\n次回からログインすると自分のページに入れますが\n\nそれはデータベースを生成しているのですか?\n\nまた テーブルの生成とのメリットのちがいは何ですか?",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-24T07:09:21.020",
"favorite_count": 0,
"id": "77756",
"last_activity_date": "2021-06-25T07:22:45.377",
"last_edit_date": "2021-06-25T06:54:31.787",
"last_editor_user_id": "39481",
"owner_user_id": "39481",
"post_type": "question",
"score": 0,
"tags": [
"mysql"
],
"title": "ログインとデータベース生成",
"view_count": 164
} | [
{
"body": "あなたが言う「データベース」が、何を指しているかで、回答が変わってきます。 \n[データベース -\nウィクショナリー](https://ja.wiktionary.org/wiki/%E3%83%87%E3%83%BC%E3%82%BF%E3%83%99%E3%83%BC%E3%82%B9)\n\n広義的な意味で、「様々な情報を、電子計算機(コンピューター)を用いて検索することができるように体系的に構成したもの」という意味でしたら、答えは「Yes」です。 \n少なくとも、ログインに使う認証情報などが、ログインしたサービスを動かしているコンピューターのどこかに記録されます。\n\n「[データベース管理システム\n(DBMS)](https://ja.wikipedia.org/wiki/%E3%83%87%E3%83%BC%E3%82%BF%E3%83%99%E3%83%BC%E3%82%B9%E7%AE%A1%E7%90%86%E3%82%B7%E3%82%B9%E3%83%86%E3%83%A0)」を指しているのでしたら、ログインするサービスによるでしょう。 \n一般的に、ログインを必要とする大半のサービスは、 MySQL, MariaDB, PostgreSQL, SQLite, Microsoft SQL\nServer, MongoDB, Redis 等々... と言った、 DBMS に情報を記録しているでしょう。 \nしかし、理論上はどこかに情報が記録さえされていれば良いので、極端な話 DBMS を使わずに XML のテキストファイルに記録してもサービスは作れます。 \nこのため、世の中には DBMS を使っていないサービスも、探せばあると思われます。\n\nちなみに、一般的に DBMS が利用されるのは、 記録や検索を高速に効率よく行えたり、\n複数のユーザーが同時にサービスにアクセスするような対応を、サポートしやすいからですね。",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-24T13:16:18.107",
"id": "77764",
"last_activity_date": "2021-06-24T13:16:18.107",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "8237",
"parent_id": "77756",
"post_type": "answer",
"score": 1
},
{
"body": "回答としては \n「サービスによります」 \nが第一になります。がそれだと面白くないと思いますので一般的な話をしておきます。\n\nアカウントを作るたびにデータベースやテーブルを生成することはあまりなく、 \nアカウントテーブルにデータをINSERTして、投稿テーブルに対してはアカウントのキーを割り当てることでテーブルにINSERTします。\n\n例えば以下のアカウントテーブルがあったとします。\n\ncustomerId | customerName \n---|--- \n1 | Taro \n2 | Hanako \n \n新しくアカウントを増やす場合はINSERTでIDが3のレコードが増えます。\n\nさらに投稿テーブルがあったとします。 \n投稿テーブルには投稿したアカウントのIDを入れておくことで誰の投稿かわかるようにします。\n\npostId | postCustomerId | postText \n---|---|--- \n1 | 1 | はじめまして太郎といいます \n2 | 1 | SNSを始めてみました \n3 | 2 | 私が来た! \n \nアカウントの数に限らず投稿の数は複数持てるので、一対多であるといえます。 \nこういったデータ間の関係性を表すのを「関係モデル」といいその関係モデルと実現したデータ構造がMySQLをはじめとするリレーショナルテータベースです。\n\nSQLで取得するさいはきちんと自分のIDのデータだけ取ってくるようにすることで \nそれ以外のデータが混じらないようにアプリで制御しています。",
"comment_count": 11,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-25T07:22:45.377",
"id": "77784",
"last_activity_date": "2021-06-25T07:22:45.377",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "22665",
"parent_id": "77756",
"post_type": "answer",
"score": 2
}
] | 77756 | 77784 | 77784 |
{
"accepted_answer_id": "77759",
"answer_count": 1,
"body": "画像のように、沢山のデータフレームから任意の列を抜き出して右へと結合していき新たなデータフレームを作りたいと思いgoogle\ncolaboratoryでコードを書いています。沢山の列を結合させようとfor文を使用してコードを書いているのですが、取り出した列を結合させる段階でエラーが起きたり、最後に取り出した列しか表示されなかったりします。検索しても同じようなエラーが起きるので詰まっております。どのように改善すれば良いのでしょうか。株価のデータで練習していたので、コードもそのまま載せております。\n\n[](https://i.stack.imgur.com/fIuqn.jpg)\n\n```\n\n %matplotlib inline\n import pandas as pd\n import matplotlib.pyplot as plt\n import seaborn as sns\n from pandas_datareader.stooq import StooqDailyReader\n from datetime import datetime\n import numpy as np\n import sys\n import matplotlib.dates as mdate\n \n codes =[1301,1332,1333]\n start = datetime(2021, 6, 1)\n end = datetime(2021, 6, 22)\n \n for n in codes:\n \n brand = str(n) + '.JP'\n stooq = StooqDailyReader(brand, start, end) #stooqから株価情報を取得\n data = stooq.read() \n df = pd.DataFrame(data) #データフレーム化\n df = df.iloc[::-1]\n df = df[\"Close\"] #終値だけ取り出す\n df = df.drop(columns ='Date') \n df = df.rename({'Close':'brand'})\n \n print(df,type(df))\n dfc=pd.concat([dfc,df], axis=1)\n \n```\n\n以下、エラー内容\n\n```\n\n ---------------------------------------------------------------------------\n TypeError Traceback (most recent call last)\n <ipython-input-45-49461954e53c> in <module>()\n 27 \n 28 print(df,type(df))\n ---> 29 dfc=pd.concat([dfc,df], axis=1)\n 30 \n 31 \n \n 1 frames\n /usr/local/lib/python3.7/dist-packages/pandas/core/reshape/concat.py in __init__(self, objs, axis, join, keys, levels, names, ignore_index, verify_integrity, copy, sort)\n 357 \"only Series and DataFrame objs are valid\"\n 358 )\n --> 359 raise TypeError(msg)\n 360 \n 361 # consolidate\n \n TypeError: cannot concatenate object of type '<class 'list'>'; only Series and DataFrame objs are valid\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-24T08:12:21.413",
"favorite_count": 0,
"id": "77757",
"last_activity_date": "2021-06-24T11:48:06.930",
"last_edit_date": "2021-06-24T11:48:06.930",
"last_editor_user_id": "3060",
"owner_user_id": "47011",
"post_type": "question",
"score": 0,
"tags": [
"python",
"pandas"
],
"title": "pandas.DataFrameの結合を自動化したいです。",
"view_count": 347
} | [
{
"body": "以下では list comprehension(リスト内包表記)で `dfc` を作成しています。\n\n※ 元のコードでは日付(index)を削除して銘柄コードを全て `brand` という文字列に置き換えてしまっていますが、少し判りづらい様に見えます。\n\n```\n\n dfc = pd.concat([\n StooqDailyReader(f'{n}.JP', start, end).read()\n .iloc[::-1].reset_index(drop=True).Close\n .rename('brand')\n for n in codes\n ], axis=1)\n \n print(dfc)\n \n # 結果\n brand brand brand\n 0 2974 514 2435\n 1 2918 516 2435\n 2 2936 534 2465\n 3 2935 540 2455\n 4 2942 548 2448\n 5 2924 561 2494\n 6 2950 560 2513\n 7 2947 547 2477\n 8 2924 543 2431\n 9 2931 542 2425\n 10 2949 546 2457\n 11 2940 546 2431\n 12 2934 543 2419\n 13 2915 535 2391\n 14 2900 521 2328\n 15 2901 539 2427\n \n```\n\n#### 追記\n\n[pandas_datareader.stooq.StooqDailyReader](https://pandas-\ndatareader.readthedocs.io/en/latest/readers/stooq.html#module-\npandas_datareader.stooq) の場合、複数の銘柄をリストにして指定できますので、以下の様に書く事もできます。\n\n```\n\n dfc = (\n StooqDailyReader([f'{n}.JP' for n in codes], start, end).read()\n .Close.iloc[::-1].reset_index(drop=True)\n .set_axis(['brand']*len(codes), axis=1)\n )\n \n```",
"comment_count": 1,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-24T09:02:38.663",
"id": "77759",
"last_activity_date": "2021-06-24T09:34:50.413",
"last_edit_date": "2021-06-24T09:34:50.413",
"last_editor_user_id": null,
"owner_user_id": null,
"parent_id": "77757",
"post_type": "answer",
"score": 0
}
] | 77757 | 77759 | 77759 |
{
"accepted_answer_id": null,
"answer_count": 2,
"body": "Ubuntu+Python+SeleniumでChromeを自動化し、Saveボタンをクリックしてファイルをローカルに保存するところまで出来ましたが、このファイル名が手動で制御出来ず、取得元のサイトが検索ワードに基づいて付けた適当な名前になります。 \nこの、たった今保存されたファイルのファイル名をPythonで取得する場合、どの方法が賢いでしょうか。 \nディレクトリを検索し、正規表現でファイル名に合致したリストを得て、最も新しいものがそれだ、というのを考えましたが、たぶんあるあるの事例だと思いますので、より良い方法がありましたらご教示くだされば幸いです。",
"comment_count": 4,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-24T09:33:01.397",
"favorite_count": 0,
"id": "77760",
"last_activity_date": "2021-06-25T11:55:53.573",
"last_edit_date": null,
"last_editor_user_id": null,
"owner_user_id": "26673",
"post_type": "question",
"score": 0,
"tags": [
"python",
"ubuntu",
"google-chrome",
"selenium",
"selenium-webdriver"
],
"title": "Seleniumで取得保存したファイル名の特定",
"view_count": 3268
} | [
{
"body": "> Ubuntu+Python+Selenium\n\nご質問の前提条件から外れてしまいますが、 Selenium ではなく [Puppeteer](https://pptr.dev/)\nであれば、直接ダウンロードするパスとファイル名を指定する方法があります。 \n→ [puppeteer でファイルをダウンロードするときに、任意のパスと名前で保存する | Aqua Ware\nつぶやきブログ](https://aquasoftware.net/blog/?p=1583)\n\n上記の記事は、 node.js + Puppeteer の例ですが、\n[pyppeteer](https://github.com/pyppeteer/pyppeteer) を使うことで、以下のように Python\nでも同様の結果が得られます。\n\n```\n\n import os\n import asyncio\n \n # Fetch.enable に対応している Chromeimum リビジョンを指定\n os.environ['PYPPETEER_CHROMIUM_REVISION'] = '884014'\n import pyppeteer\n \n event_loop = asyncio.get_event_loop()\n \n async def main(file_name, headless=True, wait_time=5.0):\n b = await pyppeteer.launch({'headless': headless})\n p = await b.newPage()\n await p.goto('https://github.com/pyppeteer/pyppeteer')\n e = await p.querySelector('get-repo')\n await e.click()\n \n client = await p.target.createCDPSession()\n await client.send('Page.setDownloadBehavior', { 'behavior': 'allow', 'downloadPath': os.getcwd() })\n await client.send('Fetch.enable', { 'patterns': [ { 'urlPattern': '*', 'requestStage': 'Response' }] })\n \n async def onRequestPaused(requestEvent):\n responseHeaders = [v for v in requestEvent['responseHeaders'] if v['name'] != 'content-disposition']\n requestId = requestEvent['requestId']\n if requestEvent['responseStatusCode'] == 200:\n responseHeaders.append({ 'name': 'content-disposition', 'value': f'attachment; filename=\"{file_name}\"'})\n response = await client.send('Fetch.getResponseBody', { 'requestId': requestId })\n await client.send('Fetch.fulfillRequest', { 'requestId': requestId, 'responseCode': 200, 'responseHeaders': responseHeaders, 'body': response['body'] })\n else:\n await client.send('Fetch.continueRequest', { 'requestId': requestId }); \n client.on('Fetch.requestPaused', lambda e: asyncio.ensure_future(onRequestPaused(e), loop=event_loop))\n \n # Github の \"Download ZIP\" のボタンをクリック\n e = await p.querySelector('a[href$=\".zip\"]')\n await e.click()\n await asyncio.sleep(wait_time)\n await client.send('Fetch.disable')\n await b.close()\n \n event_loop.run_until_complete(main(file_name='specified_name.zip', headless=False))\n \n```\n\nWindows および WSL 上の Ubuntu で動作確認済みです。\n\npyppeteer のオリジナルが node.js であることから、基本非同期な API となっているため、 Selenium の同期的な API\nに慣れていると、扱いづらいとは思います。 \n参考になれば。",
"comment_count": 2,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-24T19:37:32.033",
"id": "77766",
"last_activity_date": "2021-06-24T19:42:55.383",
"last_edit_date": "2021-06-24T19:42:55.383",
"last_editor_user_id": "8237",
"owner_user_id": "8237",
"parent_id": "77760",
"post_type": "answer",
"score": 1
},
{
"body": "コメントでお示しいただいた、以下の記事を参考に解決しました。\n\n[Python Selenium\n動的なダウンロード完了待機](https://qiita.com/hajimejimejime/items/58949dc18b52ae926b1b)\n\n実は表題の問題の他に、ダウンロードの終了を関知できないという問題もあったのですが、同時に解決してハッピーです。 \n拙ソースを掲げます。\n\n守秘義務の関係でぼかしていますが、以下の条件とします。\n\n * `https://foo.example.com/` というサイトを検索する\n * barbarbar、bazbazbazというワードで検索する\n * 検索結果はfoo_search_*.txtという名前で保存される(*の部分はbarbarb~1のような、検索ワードを元にした短縮した名前になるようだ?)\n\nプログラムの要点は以下の通りです。\n\n * glob.glob関数を使って、foo_search_*.txt.crdownloadというファイルがあるかぎり、1秒待ちながらループする\n * ループの中で、foo_search_*.txt.crdownloadから.crdownloadを削除してファイル名を得る\n * ループを脱出した場合は、ダウンロードが終わったか、そもそもダウンロードが行えなかったかであるので、適当に処理する\n\n```\n\n #! /usr/bin/python3\n import glob \n import time\n from selenium import webdriver\n from selenium.webdriver.common.by import By # for find_element_by_ID\n from selenium.webdriver.support.ui import WebDriverWait\n from selenium.webdriver.support import expected_conditions\n from selenium.webdriver.common.keys import Keys\n \n options = webdriver.ChromeOptions()\n options.add_argument('--headless')\n options.add_argument('--disable-gpu')\n driver = webdriver.Chrome(options=options) \n wait = WebDriverWait(driver, 10) # wait.untilの秒数の上限\n driver.get('https://foo.example.com/') # 検索サイト\n print(driver.title)\n \n def search_and_save(search_term):\n element = \n wait.until(expected_conditions.visibility_of_element_located((By.ID, \"search_term_id\"))) # 検索ボックスが表示されるのを待つ\n element.send_keys(Keys.CONTROL + \"a\")\n element.send_keys(Keys.DELETE)\n element.send_keys(search_term) # 検索ワードを入力してサブミット\n element.submit()\n driver.find_element_by_class_name(\"search-submit\").click()\n new_file = 'ERROR' + search_term # ダウンロードするファイル名、最初はエラー名にしておく\n for i in range(30): # MAX30秒待つ\n download_fileName = glob.glob(f'foo_search_*.txt.crdownload') # crdownloadを探す\n if download_fileName: # crdownloadがあれば\n new_file = download_fileName[0].replace('.crdownload', '') # crdownloadを削除したものでnew_fileを置き換える\n time.sleep(1) # 1秒待つ\n else: # crdownloadがない。downloadが終わったかそもそも始まってなかった\n break\n print('new_file:' + new_file) # ダウンロードが正常に終わっていればそのファイル名が、ダウンロードされていなければファイル名が入る\n \n search_and_save('barbarbar')\n search_and_save('bazbazbaz')\n driver.quit()\n \n```",
"comment_count": 0,
"content_license": "CC BY-SA 4.0",
"creation_date": "2021-06-25T03:09:51.990",
"id": "77775",
"last_activity_date": "2021-06-25T11:55:53.573",
"last_edit_date": "2021-06-25T11:55:53.573",
"last_editor_user_id": "3060",
"owner_user_id": "26673",
"parent_id": "77760",
"post_type": "answer",
"score": 0
}
] | 77760 | null | 77766 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.