Skip to content

Instantly share code, notes, and snippets.

@ypsilon-takai
Created May 1, 2023 02:32
Show Gist options
  • Save ypsilon-takai/d60b937dadfb225ad80f2f9e22ec2e90 to your computer and use it in GitHub Desktop.
Save ypsilon-takai/d60b937dadfb225ad80f2f9e22ec2e90 to your computer and use it in GitHub Desktop.
#%%
print("5".isdigit())
print("123".isdigit())
print("nine".isdigit())
# %%
import tkinter as tk
from tkinter import ttk
import random
root=tk.Tk()
root.geometry('400x600')
root.title('クトゥルフ神話ツール')
flame=tk.Frame(root)
flame.grid(row=0,column=0)
def roll(i):
def x():
global amount_status
status_amount=0
if i==2 or i==5:
status_amount=random.randint(8,18)
amount_status[i].set(status_amount)
else:
status_amount=random.randint(3,18)
amount_status[i].set(status_amount)
point_label=tk.Label(flame,text=amount_status[5].get()*10+amount_status[7].get()*20,
font=('HG丸ゴシックM-PRO',30),foreground='#ff0000')
point_label.grid(row=8,column=2)
return x
def roll_all():
def x():
global amount_status
for i in range(8):
status_amount=0
if i==2 or i==5:
status_amount=random.randint(8,18)
amount_status[i].set(status_amount)
else:
status_amount=random.randint(3,18)
amount_status[i].set(status_amount)
point_label=tk.Label(flame,text=amount_status[5].get()*10+amount_status[7].get()*20,
font=('HG丸ゴシックM-PRO',30),foreground='#ff0000')
point_label.grid(row=8,column=2)
return x
status=['STR','CON','SIZ','DEX','APP','INT','POW','EDU']
amount_status = []
for i in range(8):
amount_status.append(tk.IntVar())
for i in range(8):
label=tk.Label(flame,text=status[i],font=('HG丸ゴシックM-PRO',30))
button=tk.Button(flame,text='ROLL',font=('HG丸ゴシックM-PRO',15),command=roll(i))
label.grid(row=i,column=0)
button.grid(row=i,column=1)
amount_label=tk.Label(flame,textvariable=amount_status[i],font=('HG丸ゴシックM-PRO',30),foreground='#ff0000')
amount_label.grid(row=i,column=2)
ginou_label=tk.Label(flame,text='技能ポイント',font=('HG丸ゴシックM-PRO',20))
ginou_label.grid(row=8,column=1)
all_push=tk.Button(flame,text='ROLL ALL',font=('HG丸ゴシックM-PRO',15),command=roll_all())
all_push.grid(row=8,column=0)
root.mainloop()
# %%
import struct
import csv
with open('test.csv', mode='r') as inf, \
open('output_file.hex', mode='wb') as outf:
reader = csv.reader(inf)
for row in reader:
for float_str in row:
outf.write(struct.pack('>d', float(float_str.strip())))
# %%
strings = r"\abc\aaa\www\hhh\a\j\d"
byte_str = strings.encode('utf-8')
print(byte_str)
with open('output_file.hex', mode='wb') as outf:
outf.write(byte_str)
# %%
import re
s = r'適当な文章\n都道府県:北海道\n\nてすとてすと\n'
pre_regex = r'(?<=都道府県:)(.*?)(?=\\n)'
pre_pattern = re.compile(pre_regex)
result = pre_pattern.search(s)
print(result)
# %%
#!/usr/bin/env python
# coding: utf-8
import struct
import csv
import os
csv_dir = "csv/"
csv_file = os.listdir(csv_dir)
csv_filepath_list = []
csv_file_name_list = []
for i in csv_file:
csv_filepath = csv_dir + i
csv_file_name = os.path.splitext(os.path.basename(csv_filepath))
print("csvファイルパス:",csv_filepath)
print("csvファイル名",csv_file_name[0])
csv_filepath_list.append(csv_filepath)
csv_file_name_list.append(csv_file_name[0])
print("csvファイル数:",len(csv_filepath_list))
print(csv_file_name_list)
#保存フォルダ作成 リトルエンディアン
os.makedirs("results/", exist_ok=True)
# %%
type_def = ['double','char','double','double','double','double','double','double']
for i,j in zip(csv_filepath_list,csv_file_name_list):
with open(i, mode='r') as inf, open("results/" + j + ".dat", mode='wb') as outf:
reader = csv.reader(inf)
for row in reader:
for type, data in zip(type_def, row):
if type == 'double':
outf.write(struct.pack('<d', float(float_str.strip())))
elif type == 'char':
outf.write(struct.pack('@64s', ))
# %%
import struct
import csv
type_def = ['double','char64','double','double',
'double','double','double','double']
with open('test.csv', mode='r') as inf, \
open('output_file.hex', mode='wb') as outf:
reader = csv.reader(inf)
for row in reader:
for type, data in zip(type_def, row):
if type == 'double':
byte_data = float(data.strip())
outf.write(struct.pack('>d', byte_data))
elif type == 'char64':
byte_data = data.strip().encode(encoding='ascii')
outf.write(struct.pack('<64s', byte_data))
else:
pass
#%%
print("abc".encode(encoding='ascii'))
# %%
with open('test.csv', mode='r', encoding='utf-8') as inf,\
open('outf.csv', mode='w', encoding='utf-8' ) as outf:
for row in inf:
cols = row.strip().split(',')
outf.write(f'{cols[0]},{cols[2]},\n')
# %%
print("abc\n")
print("abc\n".strip())
print('abc')
# %%
import json
class A(dict):
def __init__(self, a, b):
dict.__init__(self, data_a=a, class_b=b)
self.data_a = a
self.class_b = b
class B(dict):
def __init__(self, b):
dict.__init__(self, data_b=b)
self.data_b = b
b = B('b')
a = A('a', b)
print(json.dumps(a))
print(a['class_b'])
print(a.class_b)
# %%
import tkinter as tk
# rootウィンドウの作成
root = tk.Tk()
root.title("TkTrain")
root.geometry("400x300")
# ボタンが配置されたフレーム作成のためのクラスを定義
class ButtonFrame(tk.Frame):
def __init__(self, master=None, bg=None, text=None, width=None, height=None):
super().__init__(master, bg=bg, width=width, height=height)
self.button = tk.Button(self, text=text)
self.button.grid(row=0, column=0, sticky="nsew")
def switch_frame(self, new_frame):
self.grid_forget()
new_frame.grid(row=0, column=0, sticky=tk.NSEW)
# frame1のインスタンス化及びボタンコマンドの設定
frame1 = ButtonFrame(root, bg="red", text = "button1", width=200, height=300)
frame1.button["command"] = lambda: frame1.switch_frame(frame2)
# frame2のインスタンス化及びボタンコマンドの設定
frame2 = ButtonFrame(root, bg="blue", text = "button2", width=200, height=300)
frame2.button["command"] = lambda: frame2.switch_frame(frame1)
# frame1の初期配置
frame1.grid(column=0, row=0, sticky=tk.NSEW)
# メインループ(gridの行列が2以上になった時用にfor文で記述しています。)
for i in range(1):
root.grid_columnconfigure(i, weight=1)
for i in range(1):
root.grid_rowconfigure(i, weight=1)
root.mainloop()
# %%
img = cv2.imread(r'C:\Users\q3197c\OneDrive - Nokia\Pictures\yosi_avater1.png')
cv2.imshow("test", img, "new imshow")
cv2.waitKey(3000)
# %%
cv2.destroyWindow('test')
# %%
import cv2
def new_imshow(title, img, str):
cv2.imshow(title, img)
print(f"string= {str}")
cv2.imshow = new_imshow
# %%
import PySimpleGUI as sg
import random
sg.theme("Darkbrown3")
layout = [[sg.Text(key="txt")],
[sg.Button("だれが",key="btn0"),
sg.Button("どこで",key="btn1"),
sg.Button("何をした",key="btn2")]]
win = sg.Window("だれがどこで何をしたゲーム",layout,font=(None,14))
who = ["A","B","C"]
conjunction= ["が"]
where= ["○○で","□□で","△△で"]
do =["☓☓した","**した","--した"]
who_str = "WHO"
where_str = "WHERE"
do_str = "DO"
def execute():
txt = f'{who_str} {where_str} {do_str}'
win['txt'].update(txt)
while True:
event,values= win.read()
if event == 'btn0':
who_str = random.choice(who) + random.choice(conjunction)
execute()
elif event == 'btn1':
where_str = random.choice(where)
execute()
elif event == 'btn2':
do_str = random.choice(do)
execute()
elif event == sg.WIN_CLOSED:
break
# %%
with open('test.csv', mode='r', encoding='utf-8') as f:
print(f.readlines())
# %%
import csv
out_data = {}
with open('test.csv', mode='r') as inf:
reader = csv.DictReader(inf)
for row in reader:
cat1 = out_data.get(row['階層1'], {})
cat2 = cat1.get(row['階層2'], {})
cat2[row['階層3']] = row['所有者']
cat1[row['階層2']] = cat2
out_data[row['階層1']] = cat1
import pprint
pprint.pprint(out_data, width=15)
# %%
def data(file: str) -> str:
f = open(file, 'r', encoding='utf-8')
line = f.read().strip('\n')
return line
d = data('test.csv')
print(d)
# %%
data = ['202130041401',
'202130041402',
'202130041403',
'202130041404',
'202130041405',
'202130041406',
'202130041407',
'202130041408',
'202130041409',
'202130041410',
'202130041411',
'202130041412',
'202130041501',
'202130041502',
'202130041503',
'202130041504',
'202130041505',
'202130041506',
'202130041507',
'202130041508',
'202130041509',
'202130041510',
'202130041511',
'202130041512',
'202130042101',
'202130042102',
'202130042103',
'202130042104',
'202130042105',
'202130042106',
'202130042107',
'202130042108',
'202130042109',
'202130042110',
'202130042111']
n = 10
res = {}
for s in data:
key = ''.join(s[:n])
res[key] = res.get(key, 0) + 1
print(res)
# %%
import traceback as tb
def f(a):
stack_data = tb.format_stack(limit=2)
print(stack_data[0])
x = 10
f(x)
# %%
import pandas as pd
f_d = pd.read_csv("test.csv")
f_d
# %%
print(f_d[['階層1', '所有者', 'test']])
# %%
import json
def create_method(r):
return f"""
def {r['name']}():
print(\'{r['question']} [yes/no]\')
res = input()
if res=="yes":
{r['yes']}()
elif res=="no":
{r['no']}()
else:
print('invalid input')
"""
def create_result(r):
return f"""
def {r['name']}():
print(\'{r['result']}\')
"""
with open('sample.json', mode='r', encoding='utf-8') as rule:
rules = json.load(rule)
for rule in rules:
if rule['name'].startswith('q'):
exec(create_method(rule))
elif rule['name'].startswith('r'):
exec(create_result(rule))
# %%
q1()
# %%
ans = input("実際の年齢よりも、年上にみられることが多い[yes/no]")
if ans == 'yes':
ans = input("声がでかい[yes/no]")
if ans == "yes":
print("人前で注目を浴びるのが好き")
else:
ans = input("手先が器用で、結構まめだ。簡単な料理は作れる。")
if ans == "yes":
print("好きなことには、ご飯を忘れても熱中する方")
else:
print("君はクラス一のひょうきん君")
else:
ans = input("手先が器用で、結構まめだ。簡単な料理は作れる。[yes/no]")
if ans == "yes":
print("好きなことには、ご飯を忘れても熱中する方")
else:
print("君はクラス一のひょうきん君")
#%%
import pandas as pd
f_d = pd.read_csv('test.csv')
# %%
feature = pd.DataFrame()
feature['label'] = "abc"
feature
# %%
f_d.append(feature)
f_d
# %%
f_d.describe()
# %%
epsilon = 0.0001
maxLoop = 1_0000
numGuesses = 0
a = float(input("Please input a positive integer: "))
x = 5.0
def f(x, a):
return x ** 2 - a
def f_d(x):
return 2 * x
for _ in range(maxLoop):
x = x - f(x, a) / f_d(x)
numGuesses += 1
if abs(f(x, a)) <= epsilon:
print(f"numGuesses = {numGuesses}") # 調べた回数
print(f"{x} is close to square root of {a}")
break
else:
print(f"Failed on square root of {a} within {maxLoop} iteration.")
# %%
a = float(input("Please input a positive integer: "))
x = 5.0
epsilon = 0.01
numGuesses = 0
while abs(x**2 - a)>=epsilon:
x1 = x - (x**2-a)/(2*x)
x = x1
numGuesses += 1
if(abs(x**2-a)<=epsilon):
break
print("numGuesses = ", numGuesses) # 調べた回数
if abs(x**2 - a) >= epsilon:
print("Failed on square root of ", a)
else:
print(x, " is close to square root of ", a)
# %%
y = 0
def a(z):
def wrap(*args):
global y
y += 1
print(y)
z(*args)
return wrap
@a
def b(z):
def wrap(*args):
global y
y += 1
print(y)
z(*args)
return wrap
@b
def c(z):
def wrap(*args):
print(y)
z(*args)
return wrap
def d(z):
def wrap(*args):
global y
y += 1
print(y)
z(*args)
return wrap
# %%
x = b(lambda x: x + 1)
print(x)
# %%
import tkinter
import tkinter.ttk as ttk
class Frame5(tkinter.Frame):
def __init__(self, master):
super().__init__(master)
self.ra_v = tkinter.IntVar(value=1)
self.ra_v.set(1)
self.textEntry1 = tkinter.StringVar()
self.textEntry1.set("wowowo")
self.textEntry2 = tkinter.StringVar()
self.textEntry2.set("yayaya")
self.radio1 = tkinter.Radiobutton(
self,
text="A",
command = self.radio_click, # クリックされたときに呼ばれるメソッド
variable = self.ra_v,
value=1,
)
self.radio1.grid(column=0,row=0,padx=10)
self.radio2 = tkinter.Radiobutton(
self,
text="B",
command = self.radio_click, # クリックされたときに呼ばれるメソッド
variable = self.ra_v,
value=2,
)
self.radio2.grid(column=0,row=1)
self.entry1 = tkinter.Entry(
self,
textvariable = self.textEntry1 #表示種類
)
self.entry1.grid(column=1,row=0)
self.entry1['state'] = tkinter.DISABLED
self.entry2 = tkinter.Entry(
self,
textvariable = self.textEntry2 #表示種類
)
self.entry2.insert(0, "名前") #表示種類
self.entry2.grid(column=1,row=1)
self.entry2['state'] = tkinter.NORMAL
# entry1
def radio_click(self):
if self.entry1['state'] == 'disabled':
self.entry1['state'] = 'normal'
self.textEntry2.set("jajaja")
else:
self.entry1['state'] = 'disabled'
self.textEntry1.set("mememe")
def radio_click1(self):
# ラジオボタンの値を取得
value = self.ra_v.get()
print(f"ラジオボタンの値は {value} です")
# メインウィンドウを作成
app = tkinter.Tk()
app.minsize(width=350, height=400)
# メインウィンドウ上にフレームを作成
frame5 = Frame5(app)
# フレームを配置
frame5.place(relx=0.1,rely=0.7)
# メインループ
app.mainloop()
# %%
fig = 104.7
num = 2
print(f'{fig:.{num}e}')
# %%
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,11,1)
a=1;b=2
def func(x,a,b):
y=a*x+b
return y
plt.plot(x,func(x,a,b))
plt.show()
# %%
import os
from reportlab.lib.units import mm
from reportlab.pdfgen import canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
import barcode
from barcode.writer import ImageWriter
from PIL import Image
file = "label.pdf"
file_path = os.path.expanduser("~") + "/Desktop/" + file
pdf_width, pdf_height = 62 * mm, 40 * mm
c = canvas.Canvas(file_path, pagesize=(pdf_width, pdf_height))
hinban = "11111-1111"
konpou_bangou = "230424008000"
suryo = "100"
bc = barcode.get_barcode_class('ean13')
writer=ImageWriter()
img = bc(konpou_bangou,)
img.save('barcode')
ImageWriter()
img = Image.open('C:/Users/user/Desktop/barcode.png')
img_resize = img.resize((img.width // 4, img.height // 4), Image.ANTIALIAS)
img_resize.save('C:/Users/user/Desktop/barcode1.png')
pdfmetrics.registerFont(TTFont("HGRGE", "C:/Windows/Fonts/HGRGE.TTC"))
c.setFont("HGRGE", 12)
c.line(1*mm, 1*mm, 1*mm, 39*mm)
c.line(1*mm, 39*mm, 61*mm, 39*mm)
c.line(61*mm, 39*mm, 61*mm, 1*mm)
c.line(61*mm, 1*mm, 1*mm, 1*mm)
c.drawString(3*mm, 34*mm,hinban)
c.drawString(3*mm, 29*mm,suryo+"pcs")
img_path = os.path.expanduser("C:/Users/user/Desktop") + "/barcode1.png"
# 画像ファイルの挿入
c.drawImage(img_path, 3*mm, 3*mm)
c.showPage()
c.save()
subprocess.Popen(["start", "", r"C:/Users/user/Desktop/label.pdf"], shell=True)
### 試したこと
python-barcodeで直接小さなサイズのバーコードを出力(まだうまくいっていない)
### 補足情報(FW/ツールのバージョンなど)
# %%
import math
import decimal
x = float(input())
print(decimal.Decimal(x))
print(int(x+0.5))
print(math.floor(x+0.5))
# %%
import numpy as np
p2 = np.loadtxt('test.csv',delimiter=',', encoding='utf-8-sig', skiprows=1)
# %%
def stringCompression(s):
for i in range(len(s)):
if s[i] != s[0]:
return f"{s[0]}{i if i != 1 else ''}" + stringCompression(s[i:])
else:
return f"{s[0]}{i+1}"
#%%
def stringCompression(s):
for i in range(len(s)):
if s[i] != s[0]: #先頭と違う文字が出たら数えおわり
if i == 1:
len_str = "" # 文字の個数は1個だったらなにも無し
else:
len_str = f"{i}" # その他は数文字の個数
compressed = f"{s[0]}{len_str}" # 圧縮した表現
remainder = s[i:] # 残りの文字列
return compressed + stringCompression(remainder)
else: # 全部同じ文字だったら
compressed = f"{s[0]}{i+1}" # 全部数えて圧縮
return compressed
# %%
print(stringCompression("abceeaaaddbbb"))
# %%
def sum_of_digits(num):
if num < 10:
return num
else:
return (num % 10) + sum_of_digits(num // 10)
def recursiveDigitsAdded(digits):
# 各桁の合計
sum = sum_of_digits(digits)
if sum < 10:
return sum
else:
return sum + recursiveDigitsAdded(sum)
# %%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment