はてなキーワード:Lenとは
気が付くと朝4時になっていた。
なんか動くところまで出来たので貼っておく。
importpdfplumberimport re#クリーンアップdef cleanuptext(text): #決算書の合計値を太字にしたことでpdfplumberが暴走するケースへの対処 #例流動資産 -> 流流流流流動動動動動資資資資資産産産産産 #誤爆が怖いので、これが起きている時だけ補正します if "流流流流流動動動動動資資資資資産産産産産" intext:text = re.sub(r'(.)92;1{4,}', r'92;1',text) #△をマイナスに。数字中のカンマを消して結合するtext = re.sub(r'△([0-9])', r'-92;1',text)text = re.sub(r'▲([0-9])', r'-92;1',text)text = re.sub(r'([0-9]),([0-9])', r'92;192;2',text) #たまに、煽り屋みたいに文字の後にスペースが入る嫌がらせを修正する #例: 投 資 有 価 証 券 ->投資有価証券text = re.sub(r'(?<=[92;u4E00-92;u9FFF92;u3040-92;u30FF])92;s(?=[92;u4E00-92;u9FFF92;u3040-92;u30FF])', '',text) returntext#今期の勘定科目の数字を取得def get_AccountName(text,need): pattern =rf'^{need} -?[0-9]+ (-?[0-9]+)' r = re.search(pattern,text, re.MULTILINE) if ris not None: return float(r[1]) return 0#清原ネットキャッシュを計算する。def calc_KiyoharaNetCash(text): total_current_assets = get_AccountName(text,'流動資産合計') if total_current_assets == 0: #要約財政状態計算書しか公開していない、楽天のような素敵な会社様への対処 total_assets = get_AccountName(text,'資産合計') if total_assets != 0: #とりあえず、資産の部の6割を流動資産とみなす total_current_assets = total_assets * 0.6 else: #流動資産合計ではなく、流動資産という単語を使っている我が道を行く東北電力への対処 total_current_assets = get_AccountName(text,'流動資産') if total_current_assets == 0: raise Exception("流動資産合計の勘定科目が見つかりませんでした。"+text) total_liabilities = get_AccountName(text,'負債合計') if total_liabilities == 0: #負債合計ではなく、負債の部合計に拘るオムロンの嬉しい決算書への対策。なんでや・・・ total_liabilities = get_AccountName(text,'負債の部合計') if total_liabilities == 0: raise Exception("負債合計の勘定科目が見つかりませんでした。"+text) #負債をご丁寧にマイナス表記で書いてくれる中外製薬の親切な決算書への対策。いい加減にしろよ・・・ if total_liabilities < 0: total_liabilities = total_liabilities * -1 #投資有価証券はないこともあるので、0を容認する marketable_securities = get_AccountName(text,'投資有価証券') #print(total_current_assets,marketable_securities,total_liabilities) netcash = total_current_assets + (marketable_securities*0.7) - total_liabilities #たまに単位を1000円にしている銘柄があるので補正する ifis_tanni_senyen(text): netcash = netcash / 1000 return netcash# "流動資産合計" と "負債合計" の間に "単位:千円" があるかをチェックdefis_tanni_senyen(text): if "単位:千円" intext: returnTrue if "単位: 千円" intext: returnTrue if "単位 : 千円" intext: returnTrue if "単位 :千円" intext: returnTrue returnFalsedefpdf_to_kiyohara_netcash(pdfpath): withpdfplumber.open(pdfpath)aspdf:text = ''.join(page.extract_text() for page inpdf.pages)text = cleanuptext(text) #print(text) kiyohara_netcash = calc_KiyoharaNetCash(text) #print(kiyohara_netcash) return kiyohara_netcashdef mymain(): import sys args = sys.argv argc =len(args) if argc <= 1:print('''これは、清原達郎氏のネットキャッシュ比率(以下、清原ネットキャッシュ比率)を決算短信のpdfから求めるソフトです。清原ネットキャッシュ=流動資産合計+(投資有価証券*0.7)-負債合計清原ネットキャッシュ比率=清原ネットキャッシュ/時価総額*100遊び方1.決算短信pdfから清原ネットキャッシュを求めるpython calc_kiyohara_netcash.py 140120240514594985.pdf結果: 30757.0決算書には、100万円単位で数字が書かれているはずなので、この数字の単位は100万円です。つまり、3075700万円。2.時価総額を億円単位で追加することで、清原ネットキャッシュ比率を求める時価総額が146億円なら146と書いてください。python calc_kiyohara_netcash.py 140120240514594985.pdf 146結果: 210.66%このコードはNYSLライセンスです。無保証、自己責任ですが、ご自由に。かぶ探とかとつなげるといいかもね。 ''') return if argc <= 2: kiyohara_netcash =pdf_to_kiyohara_netcash(args[1])print(kiyohara_netcash) return if argc <= 3: market_cap=float(args[2])*100 #億円から百万円表記に kiyohara_netcash =pdf_to_kiyohara_netcash(args[1]) ratio = round(kiyohara_netcash/market_cap*100,2)print(f"{ratio}%") returnif __name__ == '__main__': mymain()
import requestsimportjsonfromurllib.parse import quotedef fetch_bookmarks(url):try: #URLをエスケープ escaped_url = quote(url, safe="") api_url = f"https://b.hatena.ne.jp/entry/json/?url={escaped_url}"response = requests.get(api_url)response.raise_for_status()try: returnresponse.json() exceptjson.decoder.JSONDecodeErroras e:print(f"Error decodingJSON from {api_url}: {e}")print("Response content:",response.text) return [] except requests.exceptions.RequestExceptionas e:print(f"Error fetching bookmarks from {api_url}: {e}") return []def find_common_bookmarks(bookmarks1, bookmarks2,url1,url2): common_users =set(bm["user"] for bm in bookmarks1 if bm["comment"]) &set(bm["user"] for bm in bookmarks2 if bm["comment"]) common_bookmarks = [] foruser in common_users: comments = [] for bm in bookmarks1: if bm["user"] ==user and bm["comment"]: comments.append({"url":url1, "comment": bm["comment"], "timestamp": bm["timestamp"]})break for bm in bookmarks2: if bm["user"] ==user and bm["comment"]: comments.append({"url":url2, "comment": bm["comment"], "timestamp": bm["timestamp"]})break iflen(comments) == 2: common_bookmarks.append({"user":user, "comments": comments}) return common_bookmarksif __name__ == "__main__":url1 = "https://news.yahoo.co.jp/articles/f9966c4ccc374fc88babbb50175a9ea844c99638"url2 = "https://www.asahi.com/articles/ASN6K7F64N6KUJHB00L.html" data1 = fetch_bookmarks(url1) data2 = fetch_bookmarks(url2) common_bookmarks = find_common_bookmarks(data1["bookmarks"], data2["bookmarks"],url1,url2)print(json.dumps(common_bookmarks, indent=2, ensure_ascii=False))
url1,url2のところを対象としたいものに変えれば使えるよ
バグあったら直して使ってね
importjsonimporturllib.request#True にするとユーザー名を隠すhide_user =False# 以下を書き換える。sys.argv 使ってもいいんだけどurl1 = "https://www.cygames.co.jp/news/id-23172/"url2 = "https://mtg60.com/archives/palworlddoujinsi.html"def get_bookmarks(url:str): req =urllib.request.Request(f"https://b.hatena.ne.jp/entry/json/{url}") withurllib.request.urlopen(req)as res: dict =json.loads(res.read())user_comments = {} forbookmark in dict["bookmarks"]: ifbookmark["comment"]:user_comments[bookmark["user"]] =bookmark["comment"] returnuser_commentsb1 = get_bookmarks(url1)b2 = get_bookmarks(url2)common =set(b1.keys()).intersection(b2.keys())print(f"[1] {url1}")print(f"[2] {url2}")print()foruser in sorted(common): if hide_user:print(user[0] + "*" * (len(user) - 1)) else:print(user)print(f"[1] {b1[user]}")print(f"[2] {b2[user]}")print()
こんます~
2023年も残すところわずかとなりましたが、皆様方におかれましてはいかがお過ごしでしょうか。
一年間の振り返りなどはされましたでしょうか。
2423件の日記を綴っており、
頂いた総ブクマ数は1893、総トラバ数は1060となりました。
本年も大変お世話になりました。
最期に、ポンコツの私がChatGPTの手となり足となり作成した増田集計コードを掲載します。
各日記のURL、タイトル、投稿日時、文字数、被ブクマ数、被トラバ数を取得しCSVファイルに出力するものです。
お暇な方はお使いください。
それではよいお年をお迎えください。
import requestsfrom bs4 import BeautifulSoupimporttimeimportcsvimportosimport re#ログインURLlogin_url = 'https://hatelabo.jp/login'#ログイン情報login_data = { 'key': 'あなたのユーザ名またはメールアドレス', 'password': 'あなたのパスワード', 'mode': 'enter'}user_name = 'あなたのユーザ名'#User-Agent ヘッダー(例:Google Chrome)headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT10.0;Win64;x64) AppleWebKit/537.36 (KHTML,likeGecko)Chrome/58.0.3029.110Safari/537.3'}#セッションを開始session = requests.Session()#ログインresponse = session.post(login_url, data=login_data, headers=headers)print('login',response.status_code)# 集計データitem = { 'url': '', #URL 'title': '', #タイトル 'datetime': '', #投稿日時 'characters': '', #文字数 'bookmark': '', # 被ブクマ数 'trackback': '', # 被トラバ数}#CSVファイル名output_file = 'masuda_output.csv'#CSVファイルが存在しない場合はヘッダーを書き込むif notos.path.exists(output_file): withopen(output_file, 'w', newline='', encoding='utf-8')as file:writer =csv.DictWriter(file, fieldnames=item.keys())writer.writeheader()# 集計page_start = 1page_end = 3for i in range(page_start, page_end+1): # 待機time.sleep(3) #増田一覧取得 page = session.get(f'https://anond.hatelabo.jp/{user_name}/?page={i}')print(page.url) # 応答のHTMLをBeautifulSoupで解析 soup = BeautifulSoup(page.content, 'html.parser') entries = soup.find_all('div', class_='section') for entry in entries: header = entry.find('h3')timestamp = header.find('a').get('href')[1:] item['url'] = 'https://anond.hatelabo.jp/'+timestamp item['title'] = header.get_text()[:-1] item['datetime'] = f"{timestamp[0:4]}/{timestamp[4:6]}/{timestamp[6:8]} {timestamp[8:10]}:{timestamp[10:12]}" footersection_text = entry.find_all('p')[-2].get_text() item['characters'] =len(entry.find('p').get_text().strip(footersection_text)) item['trackback'] = int(re.search(r'92;((.*?)92;)', footersection_text).group(1) if re.search(r'92;((.*?)92;)', footersection_text) else '') if item['title'] == '■': item['title'] = entry.find('p').get_text().strip(footersection_text)[:35] # 待機time.sleep(3)bookmark_page = session.get(f'https://b.hatena.ne.jp/entry/button/?url=https%3A%2F%2Fanond.hatelabo.jp%2F{timestamp}&amp;layout=basic-label-counter&amp;lang=ja') soup_b = BeautifulSoup(bookmark_page.content, 'html.parser') item['bookmark'] = int(soup_b.find('a', class_='count').get_text()) #CSVファイルに追記 withopen(output_file, 'a', newline='', encoding='utf-8')as file:writer =csv.DictWriter(file, fieldnames=item.keys())writer.writerow(item)
(追記)
わー。ごめんなさい。文字が何か所か変わっていました。
92; → \
僕はプログラミング歴2週間の初心者です。キーと値を入力できるデータベースを作っています。
以下のコードを実行してデータを追加し続けると、一定のサイズを超えるとエラーが出てしまうみたいです。
理想は、データが追加された後にサイズが足りなくなったら動的に自動拡大されることです。
もし詳しい人がいたらご教示お願い致します。
import sysimportosimportmmapimport hashlibdef h(x): return int(hashlib.sha512(x.encode()).hexdigest(), 16)def create_db(filename): withopen(filename, 'wb')as f: f.write(b'\0' * 1024 * 1024) # 1MBの空ファイルを作成defset_key(filename,key,value): withopen(filename, 'r+b')as f:mm =mmap.mmap(f.fileno(), 0)pos = h(key) %mm.size() whilemm[pos:pos+1] != b'\0':pos = (pos + 1) %mm.size() ifpos == h(key) %mm.size():f.seek(0,os.SEEK_END) f.write(b'\0' *mm.size()) #ファイルサイズを2倍にするmm =mmap.mmap(f.fileno(), f.tell()) #ファイルサイズを反映させるpos = h(key) %mm.size() #ハッシュ値を再計算する data =key + '\0' +value + '\0' data = data.encode()mm[pos:pos+len(data)] = datamm.close() #mmapオブジェクトを閉じるdefget_key(filename,key): withopen(filename, 'r+b')as f:mm =mmap.mmap(f.fileno(), 0)pos = h(key) %mm.size() whilemm[pos:pos+1] != b'\0': end =mm.find(b'\0',pos,mm.size()) # 第2引数と第3引数を指定する if end == -1: end =mm.size() ifmm[pos:end].decode() ==key:pos = end + 1 end =mm.find(b'\0',pos,mm.size()) # 第2引数と第3引数を指定する if end == -1: end =mm.size()value =mm[pos:end].decode()mm.close() #mmapオブジェクトを閉じる returnvaluepos = (pos + 1) %mm.size() ifpos == h(key) %mm.size(): breakmm.close() #mmapオブジェクトを閉じる return Nonedefmain(): cmd = sys.argv[1] if cmd == 'create': create_db(sys.argv[2]) elif cmd == 'set':set_key(sys.argv[2], sys.argv[3], sys.argv[4]) elif cmd == 'get':print(get_key(sys.argv[2], sys.argv[3]))if __name__ == '__main__':main()
https://chat.openai.com/share/c80d83ea-752b-4561-a162-7ea0bd116d56
Option Explicit
Dim objExcel, objWorkbook, objWorksheet
Dim strFolderPath, strSourceFile, strTargetFile, strSearchString, strReplaceString
Dim intLastRow, intRow, intColumn
Set objExcel = CreateObject("Excel.Application")
strFolderPath = ".\" 'スクリプトと同じフォルダにあることを仮定
strSourceFile = "変更一覧.xlsx"
strTargetFile = "変更一覧.xlsx"
Set objWorkbook = objExcel.Workbooks.Open(strFolderPath & strSourceFile)
objWorkbook.Sheets("1月").Copy , objWorkbook.Sheets("1月").Index
objWorkbook.Sheets("1月 (2)").Name = "2月"
'セルの値の置換
Set objWorksheet = objWorkbook.Sheets("2月")
objWorksheet.Cells(1, 1).Value = Replace(objWorksheet.Cells(1, 1).Value, "1月", "2月")
objWorksheet.Cells(2, 7).Value = Replace(objWorksheet.Cells(2, 7).Value, "2023/2/14", "2023/3/14")
' 最終行の取得
intLastRow = objWorksheet.Cells(objWorksheet.Rows.Count, 1).End(-4162).Row ' xlUp
' 値のクリア
For intRow = 8 To intLastRow
For intColumn = 1 To 6
objWorksheet.Cells(intRow, intColumn).ClearContents
Dim objFSO, objTextFile, strContents, arrLines, arrFields, strNewContents
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(strFolderPath & "変更一覧.txt", 1)
strContents = objTextFile.ReadAll
objTextFile.Close
arrLines = Split(strContents, vbNewLine)
For Each strContents In arrLines
arrFields = Split(strContents, ",")
For Each strContents In arrFields
If IsNumeric(strContents) Then
strNewContents = strNewContents & "'" & strContents & ","
Else
strNewContents = strNewContents & strContents & ","
End If
strNewContents = Left(strNewContents,Len(strNewContents) - 1) & vbNewLine
'データをシートに貼り付け
Set objWorksheet = objWorkbook.Sheets("2月")
objWorksheet.Cells(1, 8).Value = strNewContents
'セルの値の置換
objWorksheet.Cells(123, 1).Value = Replace(objWorksheet.Cells(123, 1).Value, "F", "FH")
objWorkbook.Save
objWorkbook.Close
objExcel.Quit
Sub CheckForGarbledCharacters()
Dim rngAs Range
Dim iAs Integer
Dim garbledFoundAs Boolean
Dim unicodeValAs Long
garbledFound =False
' すべてのワークシートをチェックします。
For Eachws In ThisWorkbook.Worksheets
For Eachcell In rng
If Not ((32 <= unicodeVal And unicodeVal <= 126) Or (12353 <= unicodeVal And unicodeVal <= 12447) Or (12448 <= unicodeVal And unicodeVal <= 12543) Or (65382 <= unicodeVal And unicodeVal <= 65439) Or (19968 <= unicodeVal And unicodeVal <= 40959)) Then
MsgBox "文字化けが見つかりました: " & vbCrLf & _
"ワークシート: " &ws.Name & vbCrLf & _
"セル: " &cell.Address & vbCrLf & _
"セルの値: " &cell.Value & vbCrLf & _
"文字化けしている文字: " &char, vbExclamation
garbledFound =True
Exit For
End If
Next i
If garbledFound ThenExit For
If garbledFound ThenExit For
If Not garbledFound Then
MsgBox "文字化けが見つかりませんでした。", vbInformation
End If
EndSub
1ろくでなしBLUES巻頭カラー VOL.191SHE SMILED SWEETLY
2電影少女 VIDEO-GIRL-LEN 新連載カラー CHAPTER1(青天のへきれき)
3DRAGON BALL 其之三百六十九人造人間対セル
4SLAM DUNK #77 ROOKIESENSATION
5DRAGON QUESTダイの大冒険 第123話 閃光の大逆襲!!!の巻
6幽☆遊☆白書 呪氷使い・凍矢!!の巻
8 新ジャングルの王者ターちゃん♡ No.204ダン王国の正体!?の巻
10 爆発!宇宙クマさん タータ・ベア&菊千代くん 第3話宿命のライバルと減点パパの巻
12ペナントレース やまだたいちの奇蹟 第44回スワローズ戦⑤・ただいま三冠王!
13 超機動暴発蹴球野郎リベロの武田 その55サッカー成金になりたい!!の巻
14まじかる☆タルるートくん タルるート人生最良の日!?の巻
15こちら葛飾区亀有公園前派出所暴走!一寸法師の巻
17魔神冒険譚-アラビアン-ランプ・ランプ 第18夜 捨て去った感情
これ優秀やね。元増田のやつよりお手軽。
あとせっかくだからサムネイルを並べて表示するコードを紹介しとこう。
import matplotlib.pyplotas pltnum_inference_steps =10 #Number of denoising stepsguidance_scale = 7.5 #Scale for classifier-free guidancebatch_size = 1def show_images(images, figsize=(20,10), columns = 5): plt.figure(figsize=figsize) for i,image in enumerate(images): plt.subplot(len(images) / columns + 1, columns, i + 1) plt.imshow(image)#入力文字 ここに好きな禁則文字をいれてくださいprompt = ["hatenaanonymous diary"]#画像のサイズheight = 512 #default height of Stable Diffusionwidth = 512 #default width of Stable Diffusion#SEED値、ここをかえると 同じ入力文字でも別の画像がでますseedId = 1images = []for i in range(5): generator = torch.manual_seed(seedId + i)print(seedId + i)image =run(prompt,generator,height,width,num_inference_steps,guidance_scale,batch_size)images.append(image)show_images(images)
もう対抗馬さんは出てこなくなっちゃったのかね。
さみしいので俺が書いとくわ。
2021/07/20(火) の予測値 1,084 (95%予測区間 902 ~ 1,258)2021/07/21(水) の予測値 1,350 (95%予測区間 1,177 ~ 1,534)2021/07/22(木) の予測値 1,611 (95%予測区間 1,437 ~ 1,782)2021/07/23(金) の予測値 1,555 (95%予測区間 1,384 ~ 1,757)2021/07/24(土) の予測値 1,612 (95%予測区間 1,436 ~ 1,796)2021/07/25(日) の予測値 1,273 (95%予測区間 1,088 ~ 1,452)2021/07/26(月) の予測値966 (95%予測区間 783 ~ 1,145)2021/07/27(火) の予測値 1,332 (95%予測区間 1,134 ~ 1,519)2021/07/28(水) の予測値 1,649 (95%予測区間 1,429 ~ 1,854)2021/07/29(木) の予測値 1,957 (95%予測区間 1,722 ~ 2,205)2021/07/30(金) の予測値 1,879 (95%予測区間 1,617 ~ 2,128)2021/07/31(土) の予測値 1,938 (95%予測区間 1,675 ~ 2,220)2021/08/01(日) の予測値 1,523 (95%予測区間 1,290 ~ 1,771)2021/08/02(月) の予測値 1,151 (95%予測区間 949 ~ 1,378)2021/08/03(火) の予測値 1,579 (95%予測区間 1,296 ~ 1,852)2021/08/04(水) の予測値 1,948 (95%予測区間 1,615 ~ 2,267)2021/08/05(木) の予測値 2,302 (95%予測区間 1,959 ~ 2,715)2021/08/06(金) の予測値 2,203 (95%予測区間 1,768 ~ 2,611)2021/08/07(土) の予測値 2,264 (95%予測区間 1,851 ~ 2,739)2021/08/08(日) の予測値 1,773 (95%予測区間 1,391 ~ 2,155)2021/08/09(月) の予測値 1,336 (95%予測区間 1,035 ~ 1,668)2021/08/10(火) の予測値 1,827 (95%予測区間 1,425 ~ 2,258)2021/08/11(水) の予測値 2,247 (95%予測区間 1,728 ~ 2,794)2021/08/12(木) の予測値 2,648 (95%予測区間 2,054 ~ 3,296)2021/08/13(金) の予測値 2,526 (95%予測区間 1,876 ~ 3,184)2021/08/14(土) の予測値 2,590 (95%予測区間 1,918 ~ 3,317)2021/08/15(日) の予測値 2,023 (95%予測区間 1,482 ~ 2,618)2021/08/16(月) の予測値 1,520 (95%予測区間 1,060 ~ 1,983)2021/08/17(火) の予測値 2,075 (95%予測区間 1,440 ~ 2,719)2021/08/18(水) の予測値 2,545 (95%予測区間 1,766 ~ 3,377)2021/08/19(木) の予測値 2,994 (95%予測区間 2,065 ~ 4,002)2021/08/20(金) の予測値 2,850 (95%予測区間 1,946 ~ 3,818)2021/08/21(土) の予測値 2,916 (95%予測区間 2,006 ~ 3,900)2021/08/22(日) の予測値 2,273 (95%予測区間 1,443 ~ 3,069)
ついでにソースも公開しとくわ。Google Colaboratory に貼ればそのまま動く。
見ての通り、単に過去の感染者数をFacebook Prophet に放り込んだだけの単純なモノ。人流も変異株もワクチンも全く考慮ナシ。
適当に改良よろ。
!pip install -q fbprophetfrom fbprophet import Prophetimport pandasaspd!wget --no-check-certificate --output-document=covid19_tokyo.json 'https://raw.githubusercontent.com/tokyo-metropolitan-gov/covid19/development/data/data.json'data =pd.read_json('covid19_tokyo.json')date_data = []posi_data = []for i in range(len(data['patients_summary']['data'])): date_data.append(data['patients_summary']['data'][i]['日付']) posi_data.append(data['patients_summary']['data'][i]['小計'])data=pd.DataFrame({'ds': date_data, 'y': posi_data})data['ds'] = data['ds'].astype('datetime64')model = Prophet(interval_width=0.95, changepoint_range=1.0, changepoint_prior_scale=0.5, seasonality_prior_scale=10.0, seasonality_mode='multiplicative', n_changepoints=50)model.fit(data)future =model.make_future_dataframe(periods=35, freq='D')forecast =model.predict(future)model.plot(forecast);
% poetrycache clear --helpUSAGE poetrycache clear [--all] <cache>ARGUMENTS <cache> Thename of thecache to clear.OPTIONS --all Clearall entries in thecache.GLOBAL OPTIONS -h (--help) Display this helpmessage -q (--quiet) Do not outputanymessage -v (--verbose) Increase the verbosity ofmessages: "-v" fornormal output, "-vv" formore verbose output and "-vvv" for debug -V (--version) Display thisapplicationversion --ansi ForceANSI output --no-ansi DisableANSI output -n (--no-interaction) Do notaskany interactive question
これ見ると
poetrycache clearpypi
で動きそうじゃん?
% poetrycache clearpypi RuntimeErrorAdd the --all option ifyou want to clearallpypicachesat /usr/local/lib/python3.8/site-packages/poetry/console/commands/cache/clear.py:44 in handle 40│ ) 41│ 42│ iflen(parts) == 1: 43│ if not self.option("all"): → 44│ raise RuntimeError( 45│ "Add the --all option ifyou want to clearall " 46│ "{}caches".format(parts[0]) 47│ ) 48│
ブブー
動きません
正しくはこう
poetrycache clearpypi --all
直感的には--allをついてたら全てのキャッシュを消すべきだと思うが
% poetrycache clear --all Not enough arguments (missing: "cache").
ブブー
動きません
意味不明に思ったのは俺だけではないらしくIssueが出ている
https://github.com/python-poetry/poetry/issues/521
opened this issueon 19 Oct 2018 · 18 comments
2年前ですよ2年前!
Issue700個も溜まってますよ
pipenvもアレだったけどpoetryもアレだな
もう少しマシな奴が欲しい
def myfunc(arr): iflen(arr) <= 1: return arr left = [] right = [] ref = arr[0] ref_count = 0 for e in arr: if e < ref: left.append(e) elif e > ref: right.append(e) else: ref_count += 1 left = myfunc(left) right = myfunc(right) return left + [ref] * ref_count + right
1. こんな感じで使います。
$pythonparser.py sample.py
importparsercode ='''a = 1 + 1print(a)'''graph =parser.create_graph(code)graph.render("sample")
importastimport sysimportgraphvizdefcreate_graph(lines): graph =graphviz.Graph(format='png')root =ast.parse(lines) node_list = [root] _setup(graph, node_list)return graphdef_setup(graph, node_list):# node node = node_list[-1] node_identity =str(len(node_list)) node_name =type(node).__name__ graph.node(node_identity, node_name)# childrenfor childinast.iter_child_nodes(node): node_list.append(child) child_identity =str(len(node_list)) graph.edge(node_identity, child_identity) _setup(graph, node_list)if __name__ =='__main__': file_name = sys.argv[1]withopen(file_name)asfile: lines =file.read() graph = create_graph(lines) graph.render(file_name)
class mystring{public:char *buffer;mystring() {buffer = (char*)"";}void operator = (constchar*t){intlen = strlen(t);buffer = newchar[len + 47];strcpy(buffer, t);}void operator = (const mystring&src){intlen = strlen(src.buffer);buffer = newchar[len + 47];strcpy(buffer,src.buffer);}mystring& operator + (constchar*t){intlen = strlen(buffer);intlen2 = strlen(t);char *buffer2 = newchar[len +len2 + 47];strcpy(buffer2, buffer);strcpy(buffer2+len, t);buffer = buffer2;return *this;}mystring& operator + (const mystring&src){return ((*this) +src.buffer);}};
class mystringV{public:std::vector<char> buffer;mystringV(){buffer.resize(2);buffer[0] = ' ';buffer[1] = NULL;}void operator = (constchar*t){intlen = strlen(t);buffer.resize(len+1);strcpy(&buffer.at(0), t);}void operator = (const mystringV&src){buffer =src.buffer;}mystringV& operator + (constchar*t){intlen = strlen(&buffer.at(0));intlen2 = strlen(t);buffer.resize(len +len2 + 47);strcpy(&buffer.at(0) +len, t);return *this;}mystringV& operator + (const mystringV&src){return ((*this) + &src.buffer.at(0));}};
いろんな事をプログラマにかわってライブラリがやってしまうということ
どうなんだろうね。
この辺は あまりしっかり おしえてもらえないところではある。
でも プロならみんな 知っている
class mystring{public:char *buffer;mystring() {buffer = (char*)"";}void operator = (constchar*t){intlen = strlen(t);buffer = newchar[len + 47];strcpy(buffer, t);}void operator = (const mystring&src){intlen = strlen(src.buffer);buffer = newchar[len + 47];strcpy(buffer,src.buffer);}mystring& operator + (constchar*t){intlen = strlen(buffer);intlen2 = strlen(t);char *buffer2 = newchar[len +len2 + 47];strcpy(buffer2, buffer);strcpy(buffer2+len, t);buffer = buffer2;return *this;}mystring& operator + (const mystring&src){return ((*this) +src.buffer);}};
mystring my_space_org;for (int i = 0; i < 8; i++) {mystring space;space = my_space_org + " ";printf("%sHello world\n", space.buffer);my_space_org = space;}
whileTrue: num = input() '数値ではありません' if not num.isdigit() else '4桁ではありません' iflen(num) != 4 else [i for i in num]
from typing import Sequenceclass ReverseSequence(object):def __init__(self, sequence: Sequence): self.sequence = sequence # reference to container self.index =len(sequence) # currentindex #Step 1.define __iter__ method whitch returns self.def __iter__(self): return self #Step 2.define __next__ method # rasing StopIterationat the end of iteration.def __next__(self): if self.index> 0: self.index = self.index - 1 #nextindex return self.sequence[self.index] else: raise StopIterationclass ReverseSequenceGenerator(object):def __init__(self, sequence: Sequence): self.sequence = sequence self.index =len(sequence)def __iter__(self): while self.index> 0: self.index = self.index - 1 yield self.sequence[self.index] raise StopIterationassert list.__eq__( [element for element in ReverseSequence('spam')], [element for element in ReverseSequenceGenerator('spam')])
class Reverse:def __init__(self, data): self.data = data self.index =len(data)def __iter__(self): return selfdef __next__(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index]class ReverseGenerator:def __init__(self, data): self.data = data self.index =len(data)def __iter__(self): whileTrue: if self.index == 0: raise StopIteration self.index = self.index - 1 yield self.data[self.index]assert [s for s in Reverse('spam')] == [s for s in ReverseGenerator('spam')]