from transformers import GPT2LMHeadModel, GPT2Tokenizer
def generate_text(prompt, max_length=100):
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
model = GPT2LMHeadModel.from_pretrained("gpt2")
inputs = tokenizer.encode(prompt, return_tensors='pt')
outputs = model.generate(inputs, max_length=max_length, num_return_sequences=1)
return tokenizer.decode(outputs[0], skip_special_tokens=True)
prompt = "こんにちは"
generated_text = generate_text(prompt)
print(generated_text)カテゴリー: programming
Javascirpt カレンダー
<!DOCTYPE html>style.css
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Calendar</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<table>
<thead>
<tr>
<th id="prev">«</th>
<th id="title" colspan="5">2020/05</th>
<th id="next">»</th>
</tr>
<tr>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td id="today" colspan="7">Today</td>
</tr>
</tfoot>
</table>
<script src="js/main.js"></script>
</body>
</html>style.css
body {
font-family: 'Courier New', monospace;
font-size: 14px;
}
table {
border-collapse: collapse;
border: 2px solid #eee;
}
thead,
tfoot {
background: #eee;
}
th,
td {
padding: 8px;
text-align: center;
}
tbody td:first-child {
color: red;
}
tbody td:last-child {
color: blue;
}
tfoot {
font-weight: bold;
}
td.disabled {
opacity: 0.3;
}
td.today {
font-weight: bold;
}
#prev,
#next,
#today {
cursor: pointer;
user-select: none;
}'use strict';
console.clear();
{
const today = new Date();
let year = today.getFullYear();
let month = today.getMonth();
function getCalendarHead() {
const dates = [];
const d = new Date(year, month, 0).getDate();
const n = new Date(year, month, 1).getDay();
for (let i = 0; i < n; i++) {
// 30
// 29, 30
// 28, 29, 30
dates.unshift({
date: d - i,
isToday: false,
isDisabled: true,
});
}
return dates;
}
function getCalendarBody() {
const dates = []; // date: 日付, day: 曜日
const lastDate = new Date(year, month + 1, 0).getDate();
for (let i = 1; i <= lastDate; i++) {
dates.push({
date: i,
isToday: false,
isDisabled: false,
});
}
if (year === today.getFullYear() && month === today.getMonth()) {
dates[today.getDate() - 1].isToday = true;
}
return dates;
}
function getCalendarTail() {
const dates = [];
const lastDay = new Date(year, month + 1, 0).getDay();
for (let i = 1; i < 7 - lastDay; i++) {
dates.push({
date: i,
isToday: false,
isDisabled: true,
});
}
return dates;
}
function clearCalendar() {
const tbody = document.querySelector('tbody');
while (tbody.firstChild) {
tbody.removeChild(tbody.firstChild);
}
}
function renderTitle() {
const title = `${year}/${String(month + 1).padStart(2, '0')}`;
document.getElementById('title').textContent = title;
}
function renderWeeks() {
const dates = [
...getCalendarHead(),
...getCalendarBody(),
...getCalendarTail(),
];
const weeks = [];
const weeksCount = dates.length / 7;
for (let i = 0; i < weeksCount; i++) {
weeks.push(dates.splice(0, 7));
}
weeks.forEach(week => {
const tr = document.createElement('tr');
week.forEach(date => {
const td = document.createElement('td');
td.textContent = date.date;
if (date.isToday) {
td.classList.add('today');
}
if (date.isDisabled) {
td.classList.add('disabled');
}
tr.appendChild(td);
});
document.querySelector('tbody').appendChild(tr);
});
}
function createCalendar() {
clearCalendar();
renderTitle();
renderWeeks();
}
document.getElementById('prev').addEventListener('click', () => {
month--;
if (month < 0) {
year--;
month = 11;
}
createCalendar();
});
document.getElementById('next').addEventListener('click', () => {
month++;
if (month > 11) {
year++;
month = 0;
}
createCalendar();
});
document.getElementById('today').addEventListener('click', () => {
year = today.getFullYear();
month = today.getMonth();
createCalendar();
});
createCalendar();
}python タスク
import os
import json
from datetime import datetime
class Task:
def __init__(self, description, deadline=None, completed=False):
self.description = description
self.deadline = deadline
self.completed = completed
def to_dict(self):
return {
"description": self.description,
"deadline": self.deadline.strftime("%Y-%m-%d %H:%M") if self.deadline else None,
"completed": self.completed
}
@classmethod
def from_dict(cls, task_dict):
deadline_str = task_dict.get("deadline")
deadline = datetime.strptime(deadline_str, "%Y-%m-%d %H:%M") if deadline_str else None
return cls(task_dict["description"], deadline, task_dict["completed"])
class TaskList:
def __init__(self, filename):
self.filename = filename
self.tasks = []
self.load_tasks()
def load_tasks(self):
if os.path.exists(self.filename):
with open(self.filename, 'r') as file:
task_data = json.load(file)
self.tasks = [Task.from_dict(task_dict) for task_dict in task_data]
def save_tasks(self):
with open(self.filename, 'w') as file:
task_data = [task.to_dict() for task in self.tasks]
json.dump(task_data, file, indent=4)
def add_task(self, description, deadline_str=None):
deadline = datetime.strptime(deadline_str, "%Y-%m-%d %H:%M") if deadline_str else None
task = Task(description, deadline)
self.tasks.append(task)
self.save_tasks()
print("タスクを追加しました")
def edit_task(self, task_index, description=None, deadline_str=None):
if 1 <= task_index <= len(self.tasks):
task = self.tasks[task_index - 1]
if description:
task.description = description
if deadline_str:
task.deadline = datetime.strptime(deadline_str, "%Y-%m-%d %H:%M") if deadline_str else None
self.save_tasks()
print("タスクを編集しました")
else:
print("無効なタスク番号です")
def display_tasks(self):
if not self.tasks:
print("タスクはありません")
else:
print("タスク一覧:")
for i, task in enumerate(self.tasks, 1):
status = "完了" if task.completed else "未完了"
deadline = task.deadline.strftime("%Y-%m-%d %H:%M") if task.deadline else "なし"
print(f"{i}. [{status}] {task.description} (締切: {deadline})")
def mark_task_completed(self, task_index):
if 1 <= task_index <= len(self.tasks):
task = self.tasks[task_index - 1]
task.completed = True
self.save_tasks()
print(f"タスク '{task.description}' を完了にしました")
else:
print("無効なタスク番号です")
def delete_task(self, task_index):
if 1 <= task_index <= len(self.tasks):
deleted_task = self.tasks.pop(task_index - 1)
self.save_tasks()
print(f"タスク '{deleted_task.description}' を削除しました")
else:
print("無効なタスク番号です")
def main():
filename = "tasks.json"
task_list = TaskList(filename)
while True:
print("\n操作を選択してください:")
print("1. タスクを追加")
print("2. タスクを編集")
print("3. タスク一覧を表示")
print("4. タスクを完了にする")
print("5. タスクを削除する")
print("6. 終了")
choice = input("選択 (1/2/3/4/5/6): ")
if choice == '6':
break
elif choice == '1':
description = input("新しいタスクの説明を入力してください: ")
deadline_str = input("締切日時 (YYYY-MM-DD HH:MM) を入力してください (未入力可): ")
task_list.add_task(description, deadline_str)
elif choice == '2':
task_list.display_tasks()
task_index = int(input("編集するタスクの番号を入力してください: "))
description = input("新しい説明を入力してください (未入力で変更なし): ")
deadline_str = input("新しい締切日時 (YYYY-MM-DD HH:MM) を入力してください (未入力で変更なし): ")
task_list.edit_task(task_index, description, deadline_str)
elif choice == '3':
task_list.display_tasks()
elif choice == '4':
task_list.display_tasks()
task_index = int(input("完了にするタスクの番号を入力してください: "))
task_list.mark_task_completed(task_index)
elif choice == '5':
task_list.display_tasks()
task_index = int(input("削除するタスクの番号を入力してください: "))
task_list.delete_task(task_index)
else:
print("無効な選択です")
if __name__ == "__main__":
main()
python 検索エンジン
# データ
documents = [
"Python is a popular programming language.",
"It is known for its simplicity and readability.",
"Python has a large community of developers.",
"Python is widely used in web development."
]
# データの前処理
def preprocess(text):
return text.lower()
# インデックスの作成
def create_index(documents):
index = {}
for doc_id, doc in enumerate(documents):
doc = preprocess(doc)
words = doc.split()
for word in words:
if word not in index:
index[word] = []
index[word].append(doc_id)
return index
# クエリ処理
def search(query, index):
query = preprocess(query)
words = query.split()
result = set(range(len(documents)))
for word in words:
if word in index:
result &= set(index[word])
return [documents[i] for i in result]
# メイン
if __name__ == "__main__":
index = create_index(documents)
while True:
query = input("検索クエリを入力してください (終了するには 'exit' を入力): ")
if query == 'exit':
break
results = search(query, index)
if results:
for i, result in enumerate(results, start=1):
print(f"{i}. {result}")
else:
print("一致する文書はありません。")
python todoリスト
import os
# ファイル名
todo_filename = 'todo.txt'
# TODOリストを表示する関数
def show_todo_list():
if os.path.exists(todo_filename):
with open(todo_filename, 'r') as file:
todo_list = file.readlines()
if todo_list:
print("TODOリスト:")
for i, item in enumerate(todo_list, start=1):
print(f"{i}. {item.strip()}")
else:
print("TODOリストは空です。")
else:
print("TODOリストはまだ作成されていません。")
# TODOアイテムを追加する関数
def add_todo_item(item):
with open(todo_filename, 'a') as file:
file.write(item + '\n')
print(f"'{item}' をTODOリストに追加しました。")
# TODOアイテムを削除する関数
def remove_todo_item(item_number):
if os.path.exists(todo_filename):
with open(todo_filename, 'r') as file:
todo_list = file.readlines()
if 1 <= item_number <= len(todo_list):
removed_item = todo_list.pop(item_number - 1).strip()
with open(todo_filename, 'w') as file:
file.writelines(todo_list)
print(f"'{removed_item}' をTODOリストから削除しました。")
else:
print("指定された番号のTODOアイテムは存在しません。")
else:
print("TODOリストはまだ作成されていません。")
# メインメニューを表示する関数
def main_menu():
while True:
print("\nメニュー:")
print("1. TODOリストを表示")
print("2. TODOアイテムを追加")
print("3. TODOアイテムを削除")
print("4. 終了")
choice = input("選択してください: ")
if choice == '1':
show_todo_list()
elif choice == '2':
item = input("追加するTODOアイテムを入力してください: ")
add_todo_item(item)
elif choice == '3':
show_todo_list()
item_number = int(input("削除するTODOアイテムの番号を入力してください: "))
remove_todo_item(item_number)
elif choice == '4':
print("アプリケーションを終了します。")
break
else:
print("無効な選択です。再度選択してください。")
if __name__ == "__main__":
main_menu()
Javascript 複数のスクリプトを読みこむ
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My JavaScript</title>
</head>
<body>
<script src="main.js"></script>
<script src="sub.js"></script>
</body>
</html>main.js
'use strict';
{
let x = 10;
console.log(x);
}
sub.js
'use strict';
{
let x = 20;
console.log(x);
}Javascript スコープ
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My JavaScript</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>main.js
'use strict';
let x = 10;
{
x = 20;
console.log(x);
}
console.log(x);Javascript 論理演算子
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My JavaScript</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>main.js
'use strict';
const english = Number(prompt('English'));
const math = Number(prompt('Math?'));
if(!(english >= 80 && math >= 80)){
console.log(`A`);
}else{
console.log(`B`);
}Javascript break、continue
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My JavaScript</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>main.js
'use strict';
let amount = 100;
for (let year = 1; year <= 30; year++){
amount *= 1.05;
if(amount < 200){
continue;
}
if(amount > 300){
break;
}
console.log(`Year ${amount}`);
}Javascript do while
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My JavaScript</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>main.js
'use strict';
// const command = Number(prompt('Menu 1, 2, 3 or 0 to exit'));
// console.log(`Menu ${command} processed.`);
//let command = Number(prompt('Menu 1, 2, 3 or 0 to exit'));
//while (command !== 0) {
// console.log(`Menu ${command} processed.`);
// command = Number(prompt('Menu 1, 2, 3 or 0 to exit'));
//}
let command;
do {
command = Number(prompt('Menu 1, 2, 3 or 0 to exit'));
if (command === 0) {
console.log('Exited');
} else {
console.log(`Menu ${command} processed.`);
}
} while (command !== 0);
