<?php
class User
{
public $name;
public $score;
public function __construct($name, $score)
{
$this->name = $name;
$this->score = $score;
}
public function getInfo()
{
return "{$this->name}, {$this->score}";
}
}
$user1 = new User("Taro", 70);
$user2 = new User("Jiro", 90);
echo $user1->getInfo() . PHP_EOL;
echo $user2->getInfo() . PHP_EOL;
カテゴリー: programming
NekoNekodouga.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ねこねこ動画 - 動画共有サイト</title>
<style>
/* ベーススタイル */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
header {
background-color: #333;
color: white;
padding: 10px;
text-align: center;
position: fixed;
width: 100%;
top: 0;
z-index: 100;
}
header h1 {
margin: 0;
font-size: 24px;
}
nav ul {
list-style-type: none;
padding: 0;
margin: 10px 0 0 0;
text-align: center;
}
nav ul li {
display: inline-block;
margin-right: 15px;
}
nav ul li a {
color: white;
text-decoration: none;
font-size: 16px;
}
#searchBar {
margin-top: 10px;
padding: 5px;
width: 300px;
max-width: 80%;
border: none;
border-radius: 4px;
}
.container {
margin-top: 100px;
padding: 20px;
max-width: 1200px;
margin-left: auto;
margin-right: auto;
}
.upload-container, .video-info, .description, .comments, .related-videos, .gallery {
background-color: white;
padding: 20px;
margin-top: 20px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.upload-container h2, .video-info h2, .description h2, .comments h2, .related-videos h2, .gallery h2 {
margin-top: 0;
}
.upload-container form input[type="file"],
.upload-container form input[type="text"],
.upload-container form textarea,
.upload-container form select {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border-radius: 4px;
border: 1px solid #ccc;
}
.upload-container form button {
padding: 10px 20px;
background-color: #333;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.upload-container form button:hover {
background-color: #555;
}
.video-container {
position: relative;
text-align: center;
width: 100%;
max-width: 800px;
margin: 0 auto;
}
.video-container video {
width: 100%;
height: auto;
border-radius: 10px;
}
.comment-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 10;
}
.comment {
position: absolute;
white-space: nowrap;
font-size: 20px;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
animation: moveComment linear forwards;
}
@keyframes moveComment {
from {
left: 100%;
}
to {
left: -100%;
}
}
.description p, .comments p, .gallery p {
margin: 10px 0;
}
.comments form textarea {
width: 100%;
padding: 10px;
border-radius: 4px;
border: 1px solid #ccc;
resize: vertical;
margin-bottom: 10px;
}
.comments form select {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border-radius: 4px;
}
.comments form button {
padding: 10px 20px;
background-color: #333;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.comments form button:hover {
background-color: #555;
}
.comment-list .comment {
background-color: #f9f9f9;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
}
.like-button, .dislike-button {
background-color: #333;
color: white;
border: none;
padding: 5px 10px;
margin: 5px;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.like-button:hover, .dislike-button:hover {
background-color: #555;
}
footer {
background-color: #333;
color: white;
text-align: center;
padding: 20px;
margin-top: 40px;
}
footer p {
margin: 0;
}
@media (max-width: 768px) {
nav ul li {
display: block;
margin: 10px 0;
}
#searchBar {
width: 80%;
}
.video-container {
max-width: 100%;
}
}
</style>
</head>
<body>
<!-- ヘッダー開始 -->
<header>
<h1>ねこねこ動画</h1>
<nav>
<ul>
<li><a href="#">ホーム</a></li>
<li><a href="#">人気動画</a></li>
<li><a href="#">カテゴリ</a></li>
<li><a href="#">ログイン</a></li>
</ul>
</nav>
<input type="text" id="searchBar" placeholder="動画を検索..." />
</header>
<!-- ヘッダー終了 -->
<div class="container">
<!-- 動画アップロードエリア -->
<div class="upload-container">
<h2>動画をアップロード</h2>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" id="videoFile" name="video" accept="video/*" required><br>
<input type="text" id="videoTitle" name="title" placeholder="動画タイトル" required><br>
<textarea id="videoDescription" name="description" rows="4" placeholder="動画の説明" required></textarea><br>
<button type="submit">アップロード</button>
</form>
<div id="uploadStatus"></div>
</div>
<!-- プレビューエリア -->
<div class="video-container" id="previewContainer" style="display: none;">
<h2 id="previewTitle">プレビュー: 動画タイトル</h2>
<video controls id="videoPreview"></video>
<div class="comment-overlay" id="commentOverlay"></div>
<p id="previewDescription">プレビュー: 動画の説明</p>
</div>
<!-- コメント投稿エリア -->
<div class="comments">
<h2>コメントを投稿</h2>
<form id="commentForm">
<textarea id="commentText" rows="4" cols="50" placeholder="コメントを追加..." required></textarea><br>
<label for="commentTime">表示タイミング (秒):</label>
<input type="number" id="commentTime" placeholder="0" min="0" required><br>
<label for="commentColor">コメントの色:</label>
<select id="commentColor">
<option value="white">白</option>
<option value="red">赤</option>
<option value="blue">青</option>
<option value="green">緑</option>
<option value="yellow">黄色</option>
</select><br>
<label for="commentFontSize">フォントサイズ:</label>
<select id="commentFontSize">
<option value="20px">小</option>
<option value="24px">中</option>
<option value="28px">大</option>
</select><br>
<label for="commentSpeed">表示速度 (秒):</label>
<input type="number" id="commentSpeed" placeholder="10" min="5" max="20" required><br>
<button type="submit">投稿</button>
</form>
<div id="commentList" class="comment-list"></div>
</div>
<!-- 評価機能 -->
<div class="rating">
<button class="like-button" id="likeButton">👍 いいね</button>
<span id="likeCount">0</span>
<button class="dislike-button" id="dislikeButton">👎 バッド</button>
<span id="dislikeCount">0</span>
</div>
</div>
<!-- フッター開始 -->
<footer>
<p>© 2023 ねこねこ動画. All Rights Reserved.</p>
</footer>
<!-- フッター終了 -->
<script>
let comments = [];
// 動画のアップロードとプレビュー処理
document.getElementById("uploadForm").addEventListener("submit", function(event) {
event.preventDefault();
const fileInput = document.getElementById("videoFile");
const file = fileInput.files[0];
const title = document.getElementById("videoTitle").value;
const description = document.getElementById("videoDescription").value;
if (!file) {
alert("動画ファイルを選択してください。");
return;
}
const reader = new FileReader();
reader.onload = function(e) {
const videoData = e.target.result;
document.getElementById("previewContainer").style.display = "block";
document.getElementById("videoPreview").src = videoData;
document.getElementById("previewTitle").textContent = "プレビュー: " + title;
document.getElementById("previewDescription").textContent = "プレビュー: " + description;
};
reader.readAsDataURL(file);
});
// コメント投稿処理
document.getElementById("commentForm").addEventListener("submit", function(event) {
event.preventDefault();
const commentText = document.getElementById("commentText").value;
const commentTime = parseInt(document.getElementById("commentTime").value);
const commentColor = document.getElementById("commentColor").value;
const commentFontSize = document.getElementById("commentFontSize").value;
const commentSpeed = parseInt(document.getElementById("commentSpeed").value);
if (commentText && commentTime >= 0) {
const comment = {
text: commentText,
time: commentTime,
color: commentColor,
fontSize: commentFontSize,
speed: commentSpeed
};
comments.push(comment);
displayCommentInList(comment);
document.getElementById("commentForm").reset();
}
});
// コメントリストに表示
function displayCommentInList(comment) {
const commentList = document.getElementById("commentList");
const commentDiv = document.createElement("div");
commentDiv.classList.add("comment");
commentDiv.textContent = `タイミング: ${comment.time}秒 - ${comment.text}`;
commentList.appendChild(commentDiv);
}
// 動画の再生に合わせてコメントを表示
const videoElement = document.getElementById("videoPreview");
videoElement.addEventListener("timeupdate", function() {
const currentTime = Math.floor(videoElement.currentTime);
comments.forEach(comment => {
if (comment.time === currentTime) {
displayCommentOnVideo(comment);
}
});
});
// 動画上にコメントを流す
function displayCommentOnVideo(comment) {
const overlay = document.getElementById("commentOverlay");
const commentElement = document.createElement("div");
commentElement.classList.add("comment");
commentElement.textContent = comment.text;
commentElement.style.color = comment.color;
commentElement.style.fontSize = comment.fontSize;
commentElement.style.animationDuration = `${comment.speed}s`;
commentElement.style.top = Math.random() * 80 + "%"; // ランダムな位置
overlay.appendChild(commentElement);
// 一定時間後にコメントを削除
setTimeout(() => {
commentElement.remove();
}, comment.speed * 1000);
}
// いいね・バッド機能
document.getElementById("likeButton").addEventListener("click", function() {
let likeCount = parseInt(document.getElementById("likeCount").textContent);
likeCount++;
document.getElementById("likeCount").textContent = likeCount;
});
document.getElementById("dislikeButton").addEventListener("click", function() {
let dislikeCount = parseInt(document.getElementById("dislikeCount").textContent);
dislikeCount++;
document.getElementById("dislikeCount").textContent = dislikeCount;
});
</script>
</body>
</html>
PHP array_map
<?php
// $addFive = function($n)
// {
// return $n + 5;
// };
// $addFive = fn($n) => $n + 5;
$scores = [70, 90, 80];
// $updatedScores = array_map($addFive, $scores);
$updatedScores = array_map(fn($n) => $n + 5, $scores);
print_r($updatedScores);
PHP 配列と新しい配列
<?php
$scores = [70, 90, 80];
$updatedScorfes = [];
foreach ($scores as $score){
$updatedScores[] = $score + 5;
}
print_r($updatedScores);
PHP 配列とforeach
<?php
$scores = [70, 90, 80];
foreach($scores as $key => $value){
echo “Score{{$key}}: {$value}” . PHP_EOL;
}
PHP 配列の要素を変数に代入
<?php
// $scores = [70, 90, 80];
// $firstScore = $scores[0];
// $secondScore = $scores[1];
// $thirdScore = $scores[2];
// list($firstScore, $secondScore, $thirdScore) = $scores;
// [$firstScore, $secondScore, $thirdScore] = $scores;
// echo $firstScore . PHP_EOL;
// echo $secondScore . PHP_EOL;
// echo $thirdScore . PHP_EOL;
$x = 10;
$y = 20;
[$y, $x] = [$x, $y];
echo $x . PHP_EOL;
echo $y . PHP_EOL;
PHP 配列の要素を入れ替える
<?php
$scores = [70, 90, 80];
// sort($scores);
// print_r($scores);
// rsort($scores);
// print_r($scores);
// asort($scores);
// print_r($scores);
// arsort($scores);
// print_r($scores);
// shuffle($scores);
// print_r($scores);
$reversed = array_reverse($scores);
print_r($reversed);
PHP array_splice
<?php
$scores = [70, 90, 80];
array_splice($scores, 1, 0, [30, 20]);
array_splice($scores, 2, 1);
$removedItems = array_splice($scores, 1, 1, [10, 15]);
print_r($scores);
print_r($removedItems);
二次元画像生成AI python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import matplotlib.pyplot as plt
from tqdm import tqdm
# データセットの変換(リサイズと正規化)
transform = transforms.Compose([
transforms.Resize((64, 64)),
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,)) # ピクセル値を[-1, 1]の範囲にスケーリング
])
# AnimeFaceDatasetのロード
dataset = datasets.ImageFolder(root='C:/Users/tyosu/projects/anime_faces',transform=transform)
dataloader = DataLoader(dataset, batch_size=64, shuffle=True)
# Generator(生成モデル)
class Generator(nn.Module):
def __init__(self):
super(Generator, self).__init__()
self.main = nn.Sequential(
nn.Linear(100, 256),
nn.ReLU(True),
nn.Linear(256, 512),
nn.ReLU(True),
nn.Linear(512, 1024),
nn.ReLU(True),
nn.Linear(1024, 64 * 64 * 3),
nn.Tanh()
)
def forward(self, input):
output = self.main(input)
return output.view(-1, 3, 64, 64)
# Discriminator(判別モデル)
class Discriminator(nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.main = nn.Sequential(
nn.Linear(64 * 64 * 3, 1024),
nn.ReLU(True),
nn.Linear(1024, 512),
nn.ReLU(True),
nn.Linear(512, 256),
nn.ReLU(True),
nn.Linear(256, 1),
nn.Sigmoid()
)
def forward(self, input):
input_flat = input.view(-1, 64 * 64 * 3)
return self.main(input_flat)
# モデルのインスタンス化
G = Generator()
D = Discriminator()
# ロス関数とオプティマイザ
criterion = nn.BCELoss()
optimizerD = optim.Adam(D.parameters(), lr=0.0002)
optimizerG = optim.Adam(G.parameters(), lr=0.0002)
# ランダムノイズ生成関数
def generate_noise(batch_size):
return torch.randn(batch_size, 100)
# トレーニングループ
num_epochs = 50
for epoch in range(num_epochs):
for i, (real_images, _) in enumerate(tqdm(dataloader)):
batch_size = real_images.size(0)
# 本物の画像のラベルは1、偽物の画像のラベルは0
real_labels = torch.ones(batch_size, 1)
fake_labels = torch.zeros(batch_size, 1)
# Discriminatorの学習
optimizerD.zero_grad()
outputs = D(real_images)
real_loss = criterion(outputs, real_labels)
noise = generate_noise(batch_size)
fake_images = G(noise)
outputs = D(fake_images.detach())
fake_loss = criterion(outputs, fake_labels)
d_loss = real_loss + fake_loss
d_loss.backward()
optimizerD.step()
# Generatorの学習
optimizerG.zero_grad()
outputs = D(fake_images)
g_loss = criterion(outputs, real_labels) # 生成画像を本物と認識させたい
g_loss.backward()
optimizerG.step()
print(f'Epoch [{epoch+1}/{num_epochs}] | d_loss: {d_loss.item()} | g_loss: {g_loss.item()}')
# 生成された画像を表示
if (epoch + 1) % 10 == 0:
fake_images = G(generate_noise(64)).detach().cpu()
plt.imshow(fake_images[0].permute(1, 2, 0) * 0.5 + 0.5)
簡単な画像生成AI python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from torchvision.utils import save_image # 画像保存のための関数
import os # ファイルの保存先を指定するためのライブラリ
# VAEのエンコーダーとデコーダー
class VAE(nn.Module):
def __init__(self, input_dim=784, hidden_dim=400, latent_dim=20):
super(VAE, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.fc21 = nn.Linear(hidden_dim, latent_dim)
self.fc22 = nn.Linear(hidden_dim, latent_dim)
self.fc3 = nn.Linear(latent_dim, hidden_dim)
self.fc4 = nn.Linear(hidden_dim, input_dim)
def encode(self, x):
h1 = torch.relu(self.fc1(x))
return self.fc21(h1), self.fc22(h1)
def reparameterize(self, mu, logvar):
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return mu + eps * std
def decode(self, z):
h3 = torch.relu(self.fc3(z))
return torch.sigmoid(self.fc4(h3))
def forward(self, x):
mu, logvar = self.encode(x.view(-1, 784))
z = self.reparameterize(mu, logvar)
return self.decode(z), mu, logvar
# VAEの損失関数
def loss_function(recon_x, x, mu, logvar):
BCE = nn.functional.binary_cross_entropy(recon_x, x.view(-1, 784), reduction='sum')
KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return BCE + KLD
# モデルの定義とデータローダーの準備
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
vae = VAE().to(device)
optimizer = optim.Adam(vae.parameters(), lr=1e-3)
transform = transforms.ToTensor()
train_dataset = datasets.MNIST('.', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True)
# トレーニングループ
vae.train()
for epoch in range(10): # 10エポックで学習
train_loss = 0
for batch_idx, (data, _) in enumerate(train_loader):
data = data.to(device)
optimizer.zero_grad()
recon_batch, mu, logvar = vae(data)
loss = loss_function(recon_batch, data, mu, logvar)
loss.backward()
train_loss += loss.item()
optimizer.step()
print(f'Epoch {epoch + 1}, Loss: {train_loss / len(train_loader.dataset)}')
# 学習したモデルで画像生成
vae.eval()
with torch.no_grad():
z = torch.randn(64, 20).to(device)
sample = vae.decode(z).cpu()
sample = sample.view(64, 1, 28, 28) # 28x28の画像サイズに変換 (MNISTデータのフォーマット)
# 保存先ディレクトリを指定
os.makedirs('generated_images', exist_ok=True)
save_image(sample, 'generated_images/sample.png')
print("画像生成完了: 'generated_images/sample.png' に保存されました")
