Share Code Quickly

What is Harigami?

Harigami is a simple source code sharing service. You can share source code by an URL which is issued after submission.
You can also run your source code online such as Python, Ruby, JavaScript and so on.
For free.Use for code review.
Preferences
anonymous No title
PHP
<h1><?php echo "登録完了";?></h1>

<?php
$dsn = "mysql:dbname=co_19_349_99sv_coco_com;host=localhost;charset=UTF8";
$name_db = "co-19-349.99sv-c";
$password_db = "U2j9s5dQ";
try {
  $mysql = new PDO($dsn,$name_db,$password_db);
} catch (PDOExcption $e){
  echo "エラー" . $e->getMessage() ;
}
$select_sql = "SELECT * FROM kadai_3_1 WHERE id=(select max(id) from kadai_3_1)";
$select_sql_query = $mysql->query($select_sql);
while ($select_sql_query_fetch = $select_sql_query->fetch(PDO::FETCH_ASSOC)) {
  echo "あなたのユーザー情報は" . "<br>" . "ID:{$select_sql_query_fetch["id"]}" . "<br>" . "名前:{$select_sql_query_fetch["name"]}" . "<br>" . "パスワード:{$select_sql_query_fetch["password"]}";
}
 ?>
anonymous No title
PHP
<?php
$dsn = "mysql:dbname=co_19_349_99sv_coco_com;host=localhost;charset=UTF8";
$name_db = "co-19-349.99sv-c";
$password_db = "U2j9s5dQ";
try {
  $mysql = new PDO($dsn,$name_db,$password_db);
} catch (PDOExcption $e){
  echo "エラー" . $e->getMessage() ;
}
if (!empty($_POST["submit"])) {
  if (!empty($_POST["password"])&&!empty($_POST["name"])) {
     if (preg_match("/^[a-zA-Z0-9]+$/",$_POST["password"])) {
        $name = $_POST["name"];
        $password = $_POST["password"];
        $insert_sql = "INSERT INTO kadai_3_1 (name, password) VALUES (?, ?)";
        $insert_sql_prepare = $mysql->prepare($insert_sql);
        $insert_sql_execute = $insert_sql_prepare->execute(array($name, $password));
        header('Location: kadai_3_1_entry.php');
     }else{
       echo "パスワードは半角英数字で入力してください";
     }
  }else{
    echo "パスワードと名前を両方入力してください";
  }
}
?>
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title>登録フォーム</title>
  </head>
  <body>
    <h1>新規登録</h1>
    <p>*名前とパスワードを半角で入力してください</p>
    <br />
    <form action="kadai_3_1.php" method="post">
      名前:<input type="text" name="name"><br>
      <br />
      パスワード:<input type="text" name="password"><br>
      <br />
      <input type="submit" name="submit" value="登録">
    </form>
  </body>
</html>
anonymous No title
C++
//迷路(改良ver) はぎさんのやり方を参考にしました
#include <iostream>
#include <random>
#include <ctime>
#include <vector>
#include <stdio.h>

using namespace std;

class Labyrinth {
    private: 
        int xSize;
        int ySize;
        int directionsArray[4][2] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}}; //コンパイル時warnigが出るが動作には問題なし
        vector<vector<bool> > maze;

    public:
        Labyrinth(int xSize, int ySize);
        bool JudgeEdge(int x_index, int y_index);
        bool judgeDirections(int x_index, int y_index, int direction);
        bool searchDigable();
        vector<int> getMovableDirections(int x_index, int y_index);
        vector<int> getRestartPoint(); 
        vector<int> digRoad(int x_index, int y_index, int digableDirection); 
        void digMaze();
        void print(); 
        ~Labyrinth();
};

//コンストラクタ
Labyrinth::Labyrinth(int xSize, int ySize) {
    srand(time(NULL));
    this->xSize = xSize;
    this->ySize = ySize;
    //迷路の土台を生成
    maze.resize(xSize, vector<bool>(ySize));
    for (int i = 0; i < xSize; i ++) {
        for (int j = 0; j < ySize; j ++) {
            maze[i][j] = false;
        }
    }
    maze[1][1] = true; //スタート地点
}

//引数によって与えられた座標が壁であるかを判定する
bool Labyrinth::JudgeEdge(int x_index, int y_index) {
    int edge_array[4] = {0, ySize - 1, xSize - 1, 0}; // 上, 右, 下, 左の順番
    for (int i = 0; i < 4; i ++) {
        if (i % 2 == 0 && x_index == edge_array[i]) {
            return false;
        } else if (i % 2 == 1 && y_index == edge_array[i]) {
            return false;
        }
    }
    return true;
}

//リスタート地点の取得
vector<int> Labyrinth::getRestartPoint() {
    vector<int> restart_point;
    vector<vector <int> > restart_points;
    for (int i = 1; i < xSize - 1; i ++) {
        for (int j = 1; j < ySize - 1; j ++) {
            if (maze[i][j]) {
                if (getMovableDirections(i, j).size() > 0) {
                    //リスタート地点の座標が入ったらforを抜ける
                    restart_point.push_back(i); //0番目にはx座標
                    restart_point.push_back(j); //1番目にはy座標
                    restart_points.push_back(restart_point);
                    restart_point.clear();
                    break;
                }
            }
        }
    }
    if (restart_points.size() > 0) {
        //x, yの要素番号は一対一対応であるのでxだけ求めれば良い
        int restart_point_index = rand() % restart_points.size();
        restart_point.push_back(restart_points[restart_point_index][0]); //x座標にpush_back
        restart_point.push_back(restart_points[restart_point_index][1]); //y座標にpush_back
        return restart_point;
    }

    restart_point.clear();
    return restart_point;
}

//上下左右に対してその方向に進めるかを判定する
bool Labyrinth::judgeDirections(int x_index, int y_index, int direction) {
    //指定した座標がまだ掘られていない場所かつ壁ではなければ通る
    if (maze[x_index + directionsArray[direction][0]][y_index + directionsArray[direction][1]] == false &&
        JudgeEdge(x_index + directionsArray[direction][0], y_index + directionsArray[direction][1])) {
        return true;
    }

    return false;
}

//judgeDirectionsで返された値からさらにその先へ進めるかの判定->進めたらその方向を返す
vector<int> Labyrinth::getMovableDirections(int x_index, int y_index) {
    vector<int> digable_directions;
    int more_directions[4][3] = {{3, 0, 1}, {0, 1, 2}, {1, 2, 3}, {2, 3, 0}}; //三方向の判定->4パターンあり, 時計回りの順番で判定
    int judge_count = 0; 
    for (int i = 0; i < 4; i ++) {
        for (int j = 0; j < 3; j ++) {
            if (judgeDirections(x_index, y_index, i)) { 
                if (maze[x_index + directionsArray[i][0] + directionsArray[more_directions[i][j]][0]][y_index + directionsArray[i][1] + directionsArray[more_directions[i][j]][1]] == false) {
                    judge_count ++;
                }
            }
        }
        if (judge_count == 3) {
            digable_directions.push_back(i);
        }
        judge_count = 0;
    }    

    return digable_directions;
}

bool Labyrinth::searchDigable() {
    //迷路全体の調査
    for (int i = 1; i < xSize - 1; i ++) {
        for (int j = 1; j < ySize - 1; j ++) {
            if (maze[i][j]) {
                for (int k = 0; k < 4; k ++) {
                    if (getMovableDirections(i, j).size() != 0) {
                        return true;
                    }
                }
            }
        }
    }

    return false;
}

//迷路を作っていく
void Labyrinth::digMaze() {
    int x_index = 1;
    int y_index = 1;
    while(searchDigable() != false) {
        vector<int> directions = getMovableDirections(x_index, y_index);
        if (directions.size() > 0) {
            int digableDirection = rand() % directions.size();
            vector<int> next_point = digRoad(x_index, y_index, directions[digableDirection]);
            //次の座標の設定
            if (next_point.size() > 0) {
                x_index = next_point[0];
                y_index = next_point[1];
            }
        }  else if (directions.size() == 0) {
            vector<int> restart_point = getRestartPoint();
            if (restart_point.size() > 0) {
                x_index = restart_point[0];
                y_index = restart_point[1];
            }
        }
        directions.clear();
    }
    //ゴール地点の生成
    if (maze[xSize - 2][ySize - 2] == false) {
        maze[xSize - 2][ySize - 2] = true;
    }
}

//引数の示す方向に道を作る
vector<int> Labyrinth::digRoad(int x_index, int y_index, int digableDirection) {
    vector<int> next_point;
    for (int i = 0; i < 4; i ++) {
        next_point.push_back(x_index + directionsArray[i][0]);
        next_point.push_back(y_index + directionsArray[i][1]);
        if (i == digableDirection && JudgeEdge(next_point[0], next_point[1]) && maze[next_point[0]][next_point[1]] == false) {
            maze[next_point[0]][next_point[1]] = true;
            return next_point;
        }
        next_point.clear();
    }

    return next_point;
}

//表示関数
void Labyrinth::print() {
    //"◇" : スタート地点, "☆" : ゴール地点
    const char *wall = "■";
    const char *hole = "□";
    const char *start = "◇";
    const char *goal = "☆";
    for (int i = 0; i < xSize; i++) {
        for (int j = 0; j < ySize; j++) {
            printf("%s ", maze[i][j] == false ? (i == 0 && j == 1 ? start : (i == xSize - 1 && j == ySize - 2) ? goal : wall) : hole);
        }
        printf("\n");
    }
}

Labyrinth::~Labyrinth() { //デストラクタ
    vector<vector<bool> >().swap(maze);
}


int main() {
    Labyrinth obj(15, 15);
    obj.digMaze();
    obj.print();

    return 0;
}
anonymous No title
PHP
<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>簡易掲示板</title>
</head>

<body>

    <h2>入力フォーム</h2>
    <form action="" method="POST">
        <input type="hidden" name="editnumber" size='20' value='' placeholder="名前"><br />
        <input type="text" name="name" size='20' value='' placeholder="名前"><br />
        <input type="text" name="comment" size='20' value='' placeholder="コメント"><br />
        <input type="password" name="password" size='20' value='' placeholder="パスワード"><br />
        <br />
        <input type="submit" name='submit' value='送信' />
    </form>

    <form action="" method="POST">
        <h2>削除フォーム</h2>
        <input type="number" name="deletenumber" size='20' placeholder="削除番号"><br />
        <input type="password" name="deletepassword" placeholder="パスワード"><br />
        <br />
        <input type="submit" name='delete' value='削除' onclick="return confirm('削除しますか?')" />
        <br />
        <br />
    </form>

    <form action="" method="POST">
        <h2>編集フォーム</h2>
        <input type="text" name="editnumber" placeholder="編集番号"><br />
        <input type="password" name="editpassword" placeholder="パスワード"><br />
        <br />
        <input type="submit" name="edit" value="編集"><br />
        <br />
        <br />
    </form>


    <?php
    // データベースへ接続
    try {
        $dsn = 'mysql:dbname=co_19_349_99sv_coco_com;host=localhost';
        $user = 'co-19-349.99sv-c';
        $password = 'U2j9s5dQ';
        $pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
    } catch (PDOException $e) {
        echo 'DB接続エラー' . $e->getMessage;
    }


    // リセット用
    // $sql = "DROP TABLE kadai2a";
    // $pdo->query($sql);


    // テーブルを作成
    $sql = "CREATE TABLE IF NOT EXISTS kadai2a"
        . "("
        . "id INT AUTO_INCREMENT PRIMARY KEY,"
        . "name char(32),"
        . "comment TEXT,"
        . "date DATETIME,"
        . "password TEXT"
        . ");";
    $stmt = $pdo->query($sql);


    // 新規投稿
    if (isset($_POST['submit'])) {
        if (isset($_POST['name']) && (isset($_POST['comment'])) && (isset($_POST['password']))) {
            $sql = $pdo->prepare("INSERT INTO kadai2a (name,comment,date,password) VALUES (:name,:comment,:date,:password)");
            $sql->bindParam(':name', $name, PDO::PARAM_STR);
            $sql->bindParam(':comment', $comment, PDO::PARAM_STR);
            $sql->bindParam(':date', $date, PDO::PARAM_STR);
            $sql->bindParam(':password', $password, PDO::PARAM_STR);
            $name = $_POST['name'];
            $comment = $_POST['comment'];
            date_default_timezone_set('Asia/Tokyo');
            $date = date("Y/m/d H:i:s");
            $password = $_POST['password'];
            $sql->execute();
        }
        if ((empty($name)) || (empty($comment)) || (empty($password))) {
            echo "<script>alert('未入力項目があります')</script>";
        }
    }

    // 編集
    if (isset($_POST['edit'])) {
        if ((isset($_POST['editnumber'])) && (isset($_POST['editpassword']))) {
            $editnumber = $_POST['editnumber'];
            $editpassword = $_POST['editpassword'];
            $results = $pdo->query("SELECT * FROM kadai2a WHERE id= $editnumber");
            foreach ($results as $result) {
                if ($editnumber == $result['id'] && $editpassword == $result['password']) {
                    $editnumber = $result['id'];
                    $editname = $result['name'];
                    $editcomment = $result['comment'];
                    $editpassword = $result['password'];
                    echo "編集番号" . $editnumber
    ?>
                    <form action="<?php echo ($_SERVER['PHP_SELF']) ?>" method="POST">
                        <input type="hidden" name="editnumber" value="<?php if (isset($editnumber)) {
                                                                            echo $editnumber;
                                                                        } ?>">
                        <h3>名前:</h3>
                        <input type="text" name="editname" value="<?php if (isset($editname)) {
                                                                        echo $editname;
                                                                    } ?>">
                        <h3>コメント:</h3>
                        <input type="text" name="editcomment" value="<?php if (isset($editcomment)) {
                                                                            echo $editcomment;
                                                                        } ?>">
                        <h3>パスワード:</h3>
                        <input type="password" name="editpassword" value="<?php if (isset($editpassword)) {
                                                                                echo $editpassword;
                                                                            } ?>"><br />
                                                                            <br />
                        <input type="submit" name="editsubmit" value="編集"><br /><br /><br />
                    </form>
    <?php
                    break;
                } elseif ($editnumber == $result['id'] && $editpassword != $result['password']) {
                    echo "<script>alert('パスワードが違います')</script>";
                }
            }
        }
    }
    if (isset($_POST['editsubmit'])) {
        if (!empty($_POST["editname"]) && (!empty($_POST["editcomment"])) && (!empty($_POST["editpassword"]))) {
            try {
                $dsn = 'mysql:dbname=co_19_349_99sv_coco_com;host=localhost';
                $user = 'co-19-349.99sv-c';
                $password = 'U2j9s5dQ';
                $pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
                $editnumber = $_POST['editnumber'];
                $name = $_POST['editname'];
                $comment = $_POST['editcomment'];
                date_default_timezone_set('Asia/Tokyo');
                $date = date("Y/m/d H:i:s");
                $password = $_POST['editpassword'];
                $sql = "UPDATE kadai2a SET name=:name,comment=:comment,date=:date,password=:password WHERE id=$editnumber";
                $stmt = $pdo->prepare($sql);
                $stmt->execute(array(':name' => $name, ':comment' => $comment, ':date' => $date, ':password' => $password));
            } catch (PDOException $e) {
                echo 'DB接続エラー' . $e->getMessage;
            }
        }
    }


    // 削除
    if (isset($_POST['delete'])) {
        if ((isset($_POST['delete'])) && (isset($_POST['deletepassword']))) {
            $deletenumber = $_POST['deletenumber'];
            $deletepassword = $_POST['deletepassword'];
            $res = $pdo->query('SELECT * FROM kadai2a');
            foreach ($res as $value) {
                if ($deletenumber == $value['id'] && $deletepassword == $value['password']) {
                    $id = $deletenumber;
                    $sql = 'delete from kadai2a where id=:id';
                    $stmt = $pdo->prepare($sql);
                    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                    $stmt->execute();
                } elseif ($deletenumber == $value['id'] && $deletepassword != $value['password']) {
                    echo "<script>alert('パスワードが違います')</script>";
                }
            }
        }
    }




    // データを表示する
    $sql = 'SELECT * FROM kadai2a';
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $results = $stmt->fetchAll();
    foreach ($results as $row) {
        echo $row['id'] . ',';
        echo $row['name'] . ',';
        echo $row['comment'] . ',';
        echo $row['date'] . '<br>';
        echo "<hr>";
    }
    ?>

</body>

</html>
anonymous No title
Python
#!python3

'''
This script implements a simple calculator in the Today widget.

You can toggle between two different button layouts (compact/expanded) using the widget's
built-in "Show More/Less" button. This is accomplished by overriding the `ui.View.layout`
method in the `CalcView` class.
'''

import appex, ui
import console
import os

op_symbols = ('+', '\u2212', '\u00F7', '\u00D7')
operators = {'+': '+', '\u2212': '-', '\u00F7': '/', '\u00D7': '*'}

class CalcView (ui.View):
	def __init__(self, *args, **kwargs):
		super().__init__(self, *args, **kwargs)
		self.shows_result = False
		self.bounds = (0, 0, 400, 200)
		button_style = {'background_color': (0, 0, 0, 0.05), 'tint_color': 'black', 'font': ('HelveticaNeue-Light', 24), 'corner_radius': 3}
		self.number_buttons = [ui.Button(title=str(i), action=self.button_tapped, **button_style) for i in range(10)]
		self.op_buttons = [ui.Button(title=s, action=self.button_tapped, **button_style) for s in op_symbols]
		self.ac_button = ui.Button(title='AC', action=self.button_tapped, **button_style)
		self.ac_button.tint_color = 'red'
		self.add_subview(self.ac_button)
		self.c_button = ui.Button(title='C', action=self.button_tapped, **button_style)
		self.c_button.tint_color = 'red'
		self.add_subview(self.c_button)
		self.eq_button = ui.Button(title='=', action=self.button_tapped, **button_style)
		self.add_subview(self.eq_button)
		self.dot_button = ui.Button(title='.', action=self.button_tapped, **button_style)
		self.add_subview(self.dot_button)
		for b in self.number_buttons + self.op_buttons:
			self.add_subview(b)
		self.display_view = ui.View(background_color=(.54, .94, 1.0, 0.2))
		self.display_label = ui.Label(frame=self.display_view.bounds.inset(0, 8), flex='wh', text='0', alignment=ui.ALIGN_RIGHT)
		self.display_label.font = ('HelveticaNeue-Light', 32)
		self.display_view.add_subview(self.display_label)
		self.add_subview(self.display_view)
	
	def layout(self):
		compact = self.height < 150
		bw = self.width / 10 if compact else self.width / 5
		bh = self.height / 3 if compact else self.height / 5
		for i, b in enumerate(self.number_buttons):
			if compact:
				frame = ui.Rect(((i - 1) % 10) * bw, bh, bw, bh)
			else:
				frame = ui.Rect(max(i-1, 0) % 3 * bw, 3 * bh - (i-1) // 3 * bh, bw, bh)
			b.frame = frame.inset(1, 1)
		for i, b in enumerate(self.op_buttons):
			if compact:
				frame = ui.Rect((4 + i) * bw, 2 * bh, bw, bh)
			else:
				frame = ui.Rect((3 + i % 2) * bw, (2 + i//2) * bh, bw, bh)
			b.frame = frame.inset(1, 1)
		if compact:
			self.ac_button.frame = ui.Rect(0, 2 * bh, 2 * bw, bh).inset(1, 1)
			self.c_button.frame = ui.Rect(2 * bw, 2 * bh, bw, bh).inset(1, 1)
			self.eq_button.frame = ui.Rect(8 * bw, 2 * bh, 2*bw, bh).inset(1, 1)
			self.dot_button.frame = ui.Rect(3 * bw, 2 * bh, bw, bh).inset(1, 1)
		else:
			self.ac_button.frame = ui.Rect(3 * bw, bh, bw, bh).inset(1, 1)
			self.c_button.frame = ui.Rect(4 * bw, bh, bw, bh).inset(1, 1)
			self.eq_button.frame = ui.Rect(3 * bw, 4 * bh, 2*bw, bh).inset(1, 1)
			self.dot_button.frame = ui.Rect(bw, 4 * bh, bw, bh).inset(1, 1)
		self.display_view.frame = (0, 0, self.width, bh)
	
	def button_tapped(self, sender):
		t = sender.title
		label = self.display_label
		if t in '0123456789':
			if self.shows_result or label.text == '0':
				label.text = t
			else:
				label.text += t
		elif t == '.' and label.text[-1] != '.':
			label.text += t
		elif t in op_symbols:
			if label.text[-1] in op_symbols:
				label.text = label.text[:-1] + t
			else:
				label.text += t
		elif t == 'AC':
			label.text = '0'
		elif t == 'C':
			label.text = label.text[:-1]
			if len(label.text) == 0:
				label.text = '0'
		elif t == '=':
			try:
				expr = label.text
				for symbol in op_symbols:
					expr = expr.replace(symbol, operators[symbol])
				result = str(eval(expr))
				if result.endswith('.0'):
					result = result[:-2]
				label.text = result
			except (SyntaxError, ZeroDivisionError):
				label.text = 'ERROR'
			self.shows_result = True
		if t != '=':
			self.shows_result = False

def main():
	# Optimization: Don't create a new view if the widget already shows the calculator.
	widget_name = __file__ + str(os.stat(__file__).st_mtime)
	widget_view = appex.get_widget_view()
	if widget_view is None or widget_view.name != widget_name:
		widget_view = CalcView()
		widget_view.name = widget_name
		appex.set_widget_view(widget_view)

if __name__ == '__main__':
	main()
こだっく python_cavbity_PVF
Python
import numpy as np
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
pi=math.pi
Re=float(10.0)
N=20
M=50
r=1.72
T=int(1000)
dx=1.0/N
dy=1.0/N
dt=0.001
nu=np.zeros((N+2,N+2))
ou=np.zeros((N+2,N+2))
us=np.zeros((N+2,N+2))
nv=np.zeros((N+2,N+2))
ov=np.zeros((N+2,N+2))
vs=np.zeros((N+2,N+2))
pre=np.zeros((N+2,N+2))


for t in range(T):
    
    for i in range(N+2):
        ou[i][0]=-ou[i][1]
        ou[i][N+1]=2*math.sin(i*dx*pi)*math.sin(i*dx*pi)-ou[i][N-1]
        ov[0][i]=-ov[1][i]
        ov[N+1][i]=-ov[N][i]

    #u^*,v^*の計算
    for i in range(0,N):
        for j in range(1,N):
            vs[i+1][j]=ov[i+1][j]+dt*(-0.25*(ou[i][j+1]+ou[i][j]+ou[i+1][j+1]+ou[i+1][j])*(ov[i+2][j]-ov[i][j])/(2*dx)-ov[i][j]*(ov[i+1][j+1]-ov[i+1][j-1])/(2*dx))+(dt/(Re*dx*dx))*(-4*ov[i+1][j]+ov[i+2][j]+ov[i][j]+ov[i+1][j+1]+ov[i+1][j-1])
    
    for i in range(1,N):
        for j in range(0,N):
            us[i][j+1]=ou[i][j+1]+dt*(-ou[i][j+1]*(ou[i+1][j+1]-ou[i-1][j+1])/(2*dx)-0.25*(ov[i+1][j]+ov[i][j]+ov[i+1][j+1]+ov[i][j+1])*(ou[i][j+2]-ou[i][j])/(2*dx))+(dt/(Re*dx*dx))*(-4*ou[i][j+1]+ou[i+1][j+1]+ou[i-1][j+1]+ou[i][j+2]+ou[i][j])
    

 #圧力の境界条件   
    for i in range(N):
        pre[0][i+1]=pre[1][i+1]-(dx/Re)*(-ou[3][i+1]+4*ou[2][i+1]-5*ou[1][i+1]+2*ou[0][i+1])
        pre[N+1][i+1]=pre[N][i+1]-(dx/Re)*(-ou[N-2][i+1]+4*ou[N-1][i+1]-5*ou[N][i+1]+2*ou[N+1][i+1])
        pre[i+1][0]=pre[i+1][1]-(dx/Re)*(-ov[i+1][3]+4*ov[i+1][2]-5*ov[i+1][1]+2*ov[i+1][0])
        pre[i+1][N+1]=pre[i+1][N]-(dx/Re)*(-ov[i+1][N-2]+4*ov[i+1][N-1]-5*ov[i+1][N]+2*ov[i+1][N+1])
    pre[0][0]=pre[1][0]
    pre[0][N+1]=pre[0][N]
    pre[N+1][0]=pre[N][0]
    pre[N+1][N+1]=pre[N][N+1]
               #緩和法
    for k in range(M):
        for i in range(0,N):
            for j in range(0,N):
                pre[i+1][j+1]=(-Re*dx/4*dt)*(us[i+1][j+1]-us[i][j+1]+vs[i+1][j+1]-vs[i+1][j])+0.25*(pre[i+2][j+1]+pre[i][j+1]+pre[i+1][j+2]+pre[i+1][j])
            #n+1における速度の計算
    for i in range(1,N):
        for j in range(0,N):
            nv[i+1][j]=vs[i+1][j]-dt*(pre[i+1][j+1]-pre[i+1][j])/(dx)

    for i in range(0,N):
        for j in range(1,N):
            nv[i+1][j]=vs[i+1][j]-dt*(pre[i+1][j+1]-pre[i+1][j])/(dx)

    
        #古い速度と新しい速度を更新
    for i in range(0,N+2):
        for j in range(0,N+2):
             ou[i][j]=nu[i][j]
             ov[i][j]=nv[i][j]
    #print(pre[15][15])
    #print(pre[14][14])


x=np.arange(0,dx+1.0+dx,dx)
y=np.arange(0,dx+1.0+dx,dx)
X,Y=np.meshgrid(x,y,indexing='ij')

fig=plt.figure()
ax=Axes3D(fig)

ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("v")


#print(psi)
ax.plot_wireframe(X, Y, pre)
plt.show()
こだっく No title
Python
import numpy as np
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
pi=math.pi
Re=float(10.0)
N=20
M=50
r=1.72
T=int(1000)
dx=1.0/N
dy=1.0/N
dt=0.001
nu=np.zeros((N+2,N+2))
ou=np.zeros((N+2,N+2))
us=np.zeros((N+2,N+2))
nv=np.zeros((N+2,N+2))
ov=np.zeros((N+2,N+2))
vs=np.zeros((N+2,N+2))
pre=np.zeros((N+2,N+2))


for t in range(T):
    
    for i in range(N+2):
        ou[i][0]=-ou[i][1]
        ou[i][N+1]=2*math.sin(i*dx*pi)*math.sin(i*dx*pi)-ou[i][N-1]
        ov[0][i]=-ov[1][i]
        ov[N+1][i]=-ov[N][i]

    #u^*,v^*の計算
    for i in range(0,N):
        for j in range(1,N):
            vs[i+1][j]=ov[i+1][j]+dt*(-0.25*(ou[i][j+1]+ou[i][j]+ou[i+1][j+1]+ou[i+1][j])*(ov[i+2][j]-ov[i][j])/(2*dx)-ov[i][j]*(ov[i+1][j+1]-ov[i+1][j-1])/(2*dx))+(dt/(Re*dx*dx))*(-4*ov[i+1][j]+ov[i+2][j]+ov[i][j]+ov[i+1][j+1]+ov[i+1][j-1])
    
    for i in range(1,N):
        for j in range(0,N):
            us[i][j+1]=ou[i][j+1]+dt*(-ou[i][j+1]*(ou[i+1][j+1]-ou[i-1][j+1])/(2*dx)-0.25*(ov[i+1][j]+ov[i][j]+ov[i+1][j+1]+ov[i][j+1])*(ou[i][j+2]-ou[i][j])/(2*dx))+(dt/(Re*dx*dx))*(-4*ou[i][j+1]+ou[i+1][j+1]+ou[i-1][j+1]+ou[i][j+2]+ou[i][j])
    

 #圧力の境界条件   
    for i in range(N):
        pre[0][i+1]=pre[1][i+1]-(dx/Re)*(-ou[3][i+1]+4*ou[2][i+1]-5*ou[1][i+1]+2*ou[0][i+1])
        pre[N+1][i+1]=pre[N][i+1]-(dx/Re)*(-ou[N-2][i+1]+4*ou[N-1][i+1]-5*ou[N][i+1]+2*ou[N+1][i+1])
        pre[i+1][0]=pre[i+1][1]-(dx/Re)*(-ov[i+1][3]+4*ov[i+1][2]-5*ov[i+1][1]+2*ov[i+1][0])
        pre[i+1][N+1]=pre[i+1][N]-(dx/Re)*(-ov[i+1][N-2]+4*ov[i+1][N-1]-5*ov[i+1][N]+2*ov[i+1][N+1])
    pre[0][0]=pre[1][0]
    pre[0][N+1]=pre[0][N]
    pre[N+1][0]=pre[N][0]
    pre[N+1][N+1]=pre[N][N+1]
               #緩和法
    for k in range(M):
        for i in range(0,N):
            for j in range(0,N):
                pre[i+1][j+1]=(-Re*dx/4*dt)*(us[i+1][j+1]-us[i][j+1]+vs[i+1][j+1]-vs[i+1][j])+0.25*(pre[i+2][j+1]+pre[i][j+1]+pre[i+1][j+2]+pre[i+1][j])
            #n+1における速度の計算
    for i in range(1,N):
        for j in range(0,N):
            nv[i+1][j]=vs[i+1][j]-dt*(pre[i+1][j+1]-pre[i+1][j])/(dx)

    for i in range(0,N):
        for j in range(1,N):
            nv[i+1][j]=vs[i+1][j]-dt*(pre[i+1][j+1]-pre[i+1][j])/(dx)

    
        #古い速度と新しい速度を更新
    for i in range(0,N+2):
        for j in range(0,N+2):
             ou[i][j]=nu[i][j]
             ov[i][j]=nv[i][j]
    #print(pre[15][15])
    #print(pre[14][14])


x=np.arange(0,dx+1.0+dx,dx)
y=np.arange(0,dx+1.0+dx,dx)
X,Y=np.meshgrid(x,y,indexing='ij')

fig=plt.figure()
ax=Axes3D(fig)

ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("v")


#print(psi)
ax.plot_wireframe(X, Y, pre)
plt.show()
anonymous No title
Python
import numpy as np
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
pi=math.pi
Re=float(10.0)
N=20
M=50
r=1.72
T=int(1000)
dx=1.0/N
dy=1.0/N
dt=0.001
nu=np.zeros((N+1,N+1))
ou=np.zeros((N+1,N+1))
us=np.zeros((N+1,N+1))
nv=np.zeros((N+1,N+1))
ov=np.zeros((N+1,N+1))
vs=np.zeros((N+1,N+1))
pre=np.zeros((N+1,N+1))

#初期条件セッツ
for i in range(N):
    ou[i][N-1]=math.sin(pi*i*dx)*math.sin(pi*i*dx)
    nu[i][N-1]=math.sin(pi*i*dx)*math.sin(pi*i*dx)
    us[i][N-1]=math.sin(pi*i*dx)*math.sin(pi*i*dx)
    

for t in range(T):
    
    #u^*,v^*の計算
    for i in range(1,N-1):
        for j in range(1,N-1):
            vs[i][j]=ov[i][j]+dt*(-ou[i][j]*(ov[i+1][j]-ov[i-1][j])/(2*dx)-ov[i][j]*(ov[i][j+1]-ov[i][j-1])/(2*dx))+(dt/(Re*dx*dx))*(-4*ov[i][j]+ov[i+1][j]+ov[i-1][j]+ov[i][j+1]+ov[i][j-1])
            us[i][j]=ou[i][j]+dt*(-ou[i][j]*(ou[i+1][j]-ou[i-1][j])/(2*dx)-ov[i][j]*(ou[i][j+1]-ou[i][j-1])/(2*dx))+(dt/(Re*dx*dx))*(-4*ou[i][j]+ou[i+1][j]+ou[i-1][j]+ou[i][j+1]+ou[i][j-1])


    #緩和法
    for k in range(M):
        for i in range(2,N-2):  
            pre[i][1]=(-dx/(2*dt))*(us[i+1][1]-us[i-1][1]+vs[i][2]-vs[i][0])+0.25*(pre[i+2][1]+pre[i-2][1]+pre[i][3]+pre[i][1])
            pre[i][N-2]=(-dx/(2*dt))*(us[i+1][N-2]-us[i-1][N-2]+vs[i][N-1]-vs[i][N-3])+0.25*(pre[i+2][N-2]+pre[i-2][N-2]+pre[i][N-2]+pre[i][N-4])
        for j in range(2,N-2):
            pre[1][j]=(-dx/(2*dt))*(us[2][j]-us[0][j]+vs[1][j+1]-vs[1][j-1])+0.25*(pre[1+2][j]+pre[1][j]+pre[1][j+2]+pre[1][j-2])
            pre[N-2][j]=(-dx/(2*dt))*(us[N-1][j]-us[N-3][j]+vs[N-2][j+1]-vs[N-2][j-1])+0.25*(pre[N-2][j]+pre[N-4][j]+pre[N-2][j+2]+pre[N-2][j-2])
       
        pre[1][1]=(-dx/(2*dt))*(us[2][1]-us[0][1]+vs[1][2]-vs[1][0])+0.25*(pre[3][1]+pre[1][1]+pre[1][3]+pre[1][1])
        pre[N-2][1]=(-dx/(2*dt))*(us[N-1][1]-us[N-3][1]+vs[N-2][2]-vs[N-2][0])+0.25*(pre[N-2][1]+pre[N-4][1]+pre[N-2][3]+pre[N-2][1])
        pre[1][N-2]=(-dx/(2*dt))*(us[2][N-2]-us[0][N-2]+vs[1][N-1]-vs[1][N-3])+0.25*(pre[3][N-2]+pre[1][N-2]+pre[1][N-2]+pre[1][N-4])
        pre[N-2][N-2]=(-dx/(2*dt))*(us[N-1][N-2]-us[N-3][N-2]+vs[N-2][N-1]-vs[N-2][N-3])+0.25*(pre[N-2][N-2]+pre[N-4][N-2]+pre[N-2][N-2]+pre[N-2][N-4])
        
        for i in range(2,N-2):
            for j in range(2,N-2):
                    pre[i][j]=(-dx/(2*dt))*(us[i+1][j]-us[i-1][j]+vs[i][j+1]-vs[i][j-1])+0.25*(pre[i+2][j]+pre[i-2][j]+pre[i][j+2]+pre[i][j-2])
    
        for i in range(N):
            pre[0][i]=pre[1][i]-(dx/Re)*(-ou[3][i]+4*ou[2][i]-5*ou[1][i]+2*ou[0][i])
            pre[N-1][i]=pre[N-2][i]-(dx/Re)*(-ou[N-4][i]+4*ou[N-3][i]-5*ou[N-2][i]+2*ou[N-1][i])
            pre[i][0]=pre[i][1]-(dx/Re)*(-ov[i][3]+4*ov[i][2]-5*ov[i][1]+2*ov[i][0])
            pre[i][N-1]=pre[i][N-2]-(dx/Re)*(-ov[i][N-4]+4*ov[i][N-3]-5*ov[i][N-2]+2*ov[i][N-1])
         #n+1における速度の計算
    for i in range(1,N-1):
        for j in range(1,N-1):
            nu[i][j]=us[i][j]-dt*(pre[i+1][j]-pre[i-1][j])/(2*dx)
            nv[i][j]=vs[i][j]-dt*(pre[i][j+1]-pre[i][j-1])/(2*dx)


    
        #古い速度と新しい速度を更新
    for i in range(1,N-1):
        for j in range(1,N-1):
             ou[i][j]=nu[i][j]
             ov[i][j]=nv[i][j]
    print(nu[15][15])

x=np.arange(0,1.0+dx,dx)
y=np.arange(0,1.0+dx,dx)
X,Y=np.meshgrid(x,y,indexing='ij')

fig=plt.figure()
ax=Axes3D(fig)

ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("v")


#print(psi)
ax.plot_wireframe(X, Y, nv)
plt.show()
anonymous No title
PHP
<?php
 echo "Hello World";
?>
anonymous No title
C++
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// Script to reflect OpenCV extrinsic parameters to the object.
/// * Detail
///     The object attached this script will be translated based on the attitude of the parent object.
/// * Coordinate
///     Assume that Unity coordinate and OpenCV coordinate share X / Z axises (Y axis is inversed).
///     
/// OpenCVとUnity場の座標軸が反転しているから
/// Y軸を反転させる OpenCV(1,2,3)→Unity(1,-2,3)であるとする
/// 外部パラメータを対応させる

public class OpenCVTranslate : MonoBehaviour
{
    // OpenCVでは回転ベクトル=外部パラメータの行列は、
    // 変換後→前の座標系への右回転を表したもの
    // いまは、カメラの位置を対応させるため、変換前→後の行列が欲しい・・・左回転すると考える
    // Unityでは左回転が正方向であるから、+vベクトル分だけ回転させればいい

    public float RotationX;
    public float RotationY;
    public float RotationZ;

    public float TranslationX;
    public float TranslationY;
    public float TranslationZ;

    void Start()
    {
        
    }

    void Update()
    {
        // 外部パラメータの回転成分に関わる話
        //var rod = new Vector3(RotationX, RotationY, -RotationZ); //先生のコード出力する時点でマイナスになっているかも だからUnity上で反転させないOpenCVでの回転ベクトル(X,Y,Z)はUnity上では(X,-Y,Z)で表される
        //var rod = new Vector3(RotationX, RotationY, RotationZ); //先生のコード出力する時点でマイナスになっているかも だからUnity上で反転させないOpenCVでの回転ベクトル(X,Y,Z)はUnity上では(X,-Y,Z)で表される
        var rod = new Vector3(RotationX, -RotationY, RotationZ); //OpenCVでの回転ベクトル(X,Y,Z)はUnity上では(X,-Y,Z)で表される
        this.transform.localRotation = Quaternion.AngleAxis(rod.magnitude * 180 / Mathf.PI, rod); //回転量を定義している 後→前を前→後で座標変わって結局+で表される

        // 外部パラメータの並進移動に関わる話
        // OpenCVから取得できる並進ベクトルは、(後→前)変換後の座標系原点から変換前の座標系原点までの距離を回転後の座標系において表現したもの
        var xdir = this.transform.localRotation * Vector3.right;
        var ydir = this.transform.localRotation * Vector3.up;
        var zdir = this.transform.localRotation * Vector3.forward;
        this.transform.localPosition = xdir * TranslationX - ydir * TranslationY + zdir * TranslationZ; //並進させるのは反対の動きをするようにしてY軸は座標系がOpenCVとUnityで反対だから+に動かすことになる
        //this.transform.localPosition = -xdir * TranslationX + ydir * TranslationY - zdir * TranslationZ; //並進させるのは反対の動きをするようにしてY軸は座標系がOpenCVとUnityで反対だから+に動かすことになる

    }
}