Harigami
ログイン
Harigamiは、ログイン不要のコード共有サービスです。コードの投稿後に発行されるURLでコードを共有できます。
PythonやRubyなど一部の言語は、投稿後にオンラインで実行することもできます。
誰でも無料で使えて、広告もありません。コードレビューやスニペットの代わりに使ってみてください。


詳細設定
+
anonymous タイトルなし
C#
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class WatchMap : MonoBehaviour
{
    [SerializeField] private Camera mapCamera = null;
    [SerializeField] private Transform playerIcon = null;
    [SerializeField] private Transform goalIcon = null;
    [SerializeField] private int minShootingRange = 10;//zoom時の撮影範囲
    [SerializeField] private int maxShootingRange = 50;//map全体撮影用の範囲
    [SerializeField] private Vector3 defaultIconScale = new Vector3(1.0f, 1.0f, 1.0f);
    private bool isZoomed = true;
    private float zoomMag = 1.0f;
    private Vector3 defaultGoalPos;//ゴールアイコンの初期位置
    private int defaultCameraY = 63;
    private int defaultIconY = 62;

    public void ChangePosition()
    {
        Vector3 toCameraPostion;
        if (isZoomed)
        {
            mapCamera.transform.parent = null;//カメラの追従を切る
            toCameraPostion = new Vector3(0, defaultCameraY, 0);//ワールド座標(0,64,0)から撮影する
            mapCamera.transform.position = toCameraPostion;
            ChangeShootingRange(minShootingRange, maxShootingRange);
            isZoomed = false;

        }
        else
        {
            toCameraPostion = playerIcon.transform.position;//プレイヤの上空前方から撮影する
            toCameraPostion.y = 63; toCameraPostion.z += 5;
            mapCamera.transform.parent = playerIcon.parent.transform;//カメラをプレイヤーに追従させる
            mapCamera.transform.position = toCameraPostion;
            ChangeShootingRange(maxShootingRange, minShootingRange);
            isZoomed = true;
        }
    }
    public void ChangeShootingRange(double nowSize, double toSize)
    {
        zoomMag *=(float)(toSize / nowSize);
        mapCamera.orthographicSize = minShootingRange * zoomMag;
        playerIcon.localScale =defaultIconScale*zoomMag;
        goalIcon.localScale = defaultIconScale*zoomMag;
    }
    private bool CheckInsideMap()
    {
        Vector3 cameraPos = mapCamera.transform.position;
        Vector3 targetPos = goalIcon.position;
        cameraPos.y = targetPos.y = 0;
       // Debug.Log((minShootingRange - 1) * zoomMag);
        Debug.Log(Vector3.Distance(cameraPos, targetPos));
        return Vector3.Distance(cameraPos, targetPos) <= (minShootingRange-1) * zoomMag;//goalがマップの範囲内にあるか否かを返す

    }
    private IEnumerator DispIcon()
    {
        while (true)
        {
            if (CheckInsideMap())
            {
                Debug.Log(defaultGoalPos);
                goalIcon.position = defaultGoalPos;
                //Debug.Log("IN");
            }
            else
            {
                Vector3 cameraPos = mapCamera.transform.position;
                Vector3 offset = goalIcon.position - cameraPos;//カメラからゴールに向けたベクトルを計算
                Vector3 toGoalIconPos = cameraPos + Vector3.ClampMagnitude(offset, (float)(minShootingRange * zoomMag*0.85));//ゴールアイコンの位置を上のベクトルをもとに設定
                toGoalIconPos.y = defaultIconY;
                goalIcon.position = toGoalIconPos;
            }
           // Debug.Log("out");
            yield return new WaitForSeconds(0.1f);
        }
    }
    private void Start()
    {
        defaultGoalPos = goalIcon.position;//
        StartCoroutine("DispIcon");
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            ChangePosition();
        }
    }
}
  • 1
  • 0
anonymous GAS
JavaScript
// 配列を使わない
function myFunction(){
  const sheet = SpreadsheetApp.getActiveSheet();
  let target = 0;
  for(let i = 1; i <= sheet.getLastRow(); i ++){
    if(sheet.getRange(i, 2).getValue() === 'keyword'){
      target = sheet.getRange(i, 1).getValue();
      console.log(target)
    };
  };
}

// 配列を使う
function myFunction2(){
  const sheet = SpreadsheetApp.getActiveSheet();
  const data = sheet.getDataRange().getValues();
  let target = data.filter(x => x[1] === 'keyword').map(y => y[0]);
  console.log(target);
}
  • 0
  • 0
anonymous タイトルなし
Python
function() {
  return ({{Items}}||[]).map(function(item){
    return item.id;
  })
}
  • 0
  • 0
anonymous タイトルなし
Python
<?php  
$script_name=$_SERVER["SCRIPT_NAME"];
$dataFile ='index2.txt';  

if (isset($_POST['delete'])) {
    $delete = $_POST['delete'];
    $delCon = file("index2.txt");
    for ($j = 0; $j < count($delCon) ; $j++) {
        $delData = explode("<>", $delCon[$j]);

        if ($delData[0] == $delete) {
            array_splice($delCon, $j, 1);
            file_put_contents($dataFile, $delCon);
        }
    }
    header("location:$script_name");
}

//入力フォーム
if(isset($_POST["user"]) || isset($_POST["message"])){
//入力フォームのデータを受け取る
  $count = (sizeof(file($dataFile)) + 1);
  $message = ($_POST['message']);  
  $user = ($_POST['user']);  
  $postedAt = date('Y-m-d H:i:s');  

  // まとめた変数
  $newData = $count."<>".$message."<>".$user."<>".$postedAt. "\n"; 

  $fp = fopen($dataFile,'a');  
  fwrite($fp, $newData);  
  fclose($fp);  
  header("location:$script_name");
}  
 ?>  
  • 0
  • 0
anonymous タイトルなし
Python
<?php  
$script_name=$_SERVER["SCRIPT_NAME"];
$dataFile ='index2.txt';  

if (isset($_POST['delete'])) {
    $delete = $_POST['delete'];
    $delCon = file("index2.txt");
    for ($j = 0; $j < count($delCon) ; $j++) {
        $delData = explode("<>", $delCon[$j]);

        if ($delData[0] == $delete) {
            array_splice($delCon, $j, 1);
            file_put_contents($dataFile, $delCon);
        }
    }
}

//入力フォーム
if(isset($_POST["user"]) || isset($_POST["message"])){
//入力フォームのデータを受け取る
  $count = (sizeof(file($dataFile)) + 1);
  $message = ($_POST['message']);  
  $user = ($_POST['user']);  
  $postedAt = date('Y-m-d H:i:s');  

  // まとめた変数
  $newData = $count."<>".$message."<>".$user."<>".$postedAt. "\n"; 

  $fp = fopen($dataFile,'a');  
  fwrite($fp, $newData);  
  fclose($fp);  
  header("location:$script_name");
}  
 ?>  

<!DOCTYPE html>
<html lang="ja">
  <head>
      <meta charset="UTF-8" />
      <title>簡易掲示板</title>
  </head>
  <body>
      <h1>簡易掲示板</h1>
      <form action="" method="post">
      <p> コメント: <input type="text" name="message"></p>
      <p>名前: <input type="text" name="user"></p>
      <input type="submit" value="投稿">
      </form>
      <!--削除用の入力フォーム-->
      <form action="" method="post"> 
      <p>削除対象番号<input type="text" name="delete"></p> 
      <input type="submit" name="deleteNo" value="削除"> 
     </form>
    
    <?php
    // ファイルの内容を配列に格納 
    $file_name = file("index2.txt");

    for($i=0;$i<count($file_name);++$i){
    $file_names=explode("<>",$file_name[$i]);
    // 改行しながら値を表示 
    echo $file_names[0]."</br>";
    echo $file_names[1]."</br>";
    echo $file_names[2]."</br>";
    echo $file_names[3]."</br>";
    }
    ?>

  </body>
</html>
  • 0
  • 0
anonymous タイトルなし
PHP
<?php  
$script_name=$_SERVER["SCRIPT_NAME"];
$dataFile ='index2.txt';  
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
if (isset($_POST['delete']))
{

$delete = $_POST['delete'];
$delCon = file("index2.txt");
for ($j = 0; $j < count($delCon) ; $j++){ 
$delData = explode("<>", $delCon[$j]);

if ($delData[0] == $delete) { 
array_splice($delCon, $j, 1);
file_put_contents($dataFile,  $delCon);
}
}
} else {
//入力フォームのデータを受け取る
  $count = (sizeof(file($dataFile)) + 1);
  $message = ($_POST['message']);  
  $user = ($_POST['user']);  
  $postedAt = date('Y-m-d H:i:s');  
  }

  // まとめた変数
  $newData = $count."<>".$message."<>".$user."<>".$postedAt. "\n"; 

  $fp = fopen($dataFile,'a');  
  fwrite($fp, $newData);  
  fclose($fp);  

header("location:$scripy_name");
}  
 ?>  

<!DOCTYPE html>
<html lang="ja">
  <head>
      <meta charset="UTF-8" />
      <title>簡易掲示板</title>
  </head>
  <body>
      <h1>簡易掲示板</h1>
      <form action="" method="post">
      <p> コメント: <input type="text" name="message"></p>
      <p>名前: <input type="text" name="user"></p>
      <input type="submit" value="投稿">
      </form>
      <!--削除用の入力フォーム-->
      <form action="" method="post"> 
      <p>削除対象番号<input type="text" name="delete"></p> 
      <input type="submit" name="deleteNo" value="削除"> 
     </form>
    
    <?php
    // ファイルの内容を配列に格納 
    $file_name = file("index2.txt");

    for($i=0;$i<count($file_name);++$i){
    $file_names=explode("<>",$file_name[$i]);
    // 改行しながら値を表示 
    echo $file_names[0]."</br>";
    echo $file_names[1]."</br>";
    echo $file_names[2]."</br>";
    echo $file_names[3]."</br>";
    }
    ?>

  </body>
</html>
  • 0
  • 0
anonymous タイトルなし
Python
<?php  
//ここと
$script_name = $_SERVER["SCRIPT_NAME"];
$dataFile ='kadai_2.txt';  
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
if (isset($_POST['delete']))
{

$delete = $_POST['delete'];
$delCon = file("kadai_2.txt");
for ($j = 0; $j < count($delCon) ; $j++){ 
$delData = explode("<>", $delCon[$j]);

if ($delData[0] == $delete) { 
array_splice($delCon, $j, 1);
file_put_contents($dataFile,  $delCon);
}
}
} else {
//入力フォームのデータを受け取る
  $count = (sizeof(file($dataFile)) + 1);
  $message = ($_POST['message']);  
  $user = ($_POST['user']);  
  $postedAt = date('Y-m-d H:i:s');  


  // まとめた変数
  $newData = $count."<>".$message."<>".$user."<>".$postedAt."\n"; 

  $fp = fopen($dataFile,'a');  
  fwrite($fp, $newData);  
  fclose($fp);  
}
//ここを追加
header("location: $script_name");
}  
 ?>  
  • 0
  • 0
anonymous タイトルなし
PHP
<?php  
$dataFile ='kadai_2.txt';  
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
if (isset($_POST['delete']))
{

$delete = $_POST['delete'];
$delCon = file("kadai_2.txt");
for ($j = 0; $j < count($delCon) ; $j++){ 
$delData = explode("<>", $delCon[$j]);

if ($delData[0] == $delete) { 
array_splice($delCon, $j, 1);
file_put_contents($dataFile, implode("\n", $delCon));
}
}
} else {
//入力フォームのデータを受け取る
  $count = (sizeof(file($dataFile)) + 1);
  $message = ($_POST['message']);  
  $user = ($_POST['user']);  
  $postedAt = date('Y-m-d H:i:s');  


  // まとめた変数
  $newData = $count."<>".$message."<>".$user."<>".$postedAt. "\n"; 

  $fp = fopen($dataFile,'a');  
  fwrite($fp, $newData);  
  fclose($fp);  
}
}  
 ?>  

<!DOCTYPE html>
<html lang="ja">
  <head>
      <meta charset="UTF-8" />
      <title>簡易掲示板</title>
  </head>
  <body>
      <h1>簡易掲示板</h1>
      <form action="" method="post">
      <p> コメント: <input type="text" name="message"></p>
      <p>名前: <input type="text" name="user"></p>
      <input type="submit" value="投稿">
      </form>
      <!--削除用の入力フォーム-->
      <form action="" method="post"> 
      <p>削除対象番号<input type="text" name="delete"></p> 
      <input type="submit" name="deleteNo" value="削除"> 
     </form>
    
    <?php
    // ファイルの内容を配列に格納 
    $file_name = file("kadai_2.txt");

    for($i=0;$i<count($file_name);++$i){
    $file_names=explode("<>",$file_name[$i]);
    // 改行しながら値を表示 
    echo $file_names[0]."</br>";
    echo $file_names[1]."</br>";
    echo $file_names[2]."</br>";
    echo $file_names[3]."</br>";
    }
    ?>

  </body>
</html>
  • 0
  • 0
anonymous タイトルなし
Python
#!/bin/env python
import requests
import re
import json
import os
import sys
import time
import hashlib
import subprocess as prc
import shutil
import pathlib
from distutils.dir_util import copy_tree
from datetime import datetime as d
from bs4 import BeautifulSoup

class TeraClass(object):

    #使いまわし初期設定
    def __init__(self,url):
        self.newdir = os.path.dirname(os.path.abspath(__file__)) + "/new/"
        self.olddir = os.path.dirname(os.path.abspath(__file__)) + "/old/"
        self.session = requests.session()
        self.user_agent = {"User-Agent": "Mozilla/5.0 (Linux; Android 9; SOV42) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.136 Mobile Safari/537.36"}
        time.sleep(1)
        try:
            self.reqest = self.session.get(url,timeout=5,headers=self.user_agent)
        except requests.exceptions.ConnectTimeout: sys.exit()
        if self.reqest.status_code != 200: print(self.reqest.status_code);sys.exit()
        self.soup = BeautifulSoup(self.reqest.content, "lxml", from_encoding='utf-8')

    #HTMLを監視するタグ(自由に増減できる)
    def dict_format(self,param):
        dicts = {
            0:"[イベント] ",
            1:"[お知らせ] ",
            2:"[定期メンテ] ",
            3:"[キャンペーン] ",
            4:"[生放送] ",
            5:"[重要] ",
            6:"[アップデート] ",
            7:"[ガチャ]",
            }
        result = dicts.get(param)
        item_count = len(dicts)
        return result,item_count

    #最新情報のページを1ページ分(20項目)取得
    def news_data(self,subject,table):
        title = note_url = ""
        for ttl in range (1, 21):
            if table[ttl].text[1:3] in subject:
                title_list = [table[ttl].find_all("td", attrs={"class" : "title"})]
                for list_num in range(len(title_list)):
                    title += (title_list[list_num][0].text + "\n")
                    note_url += "https://tera.pmang.jp" + title_list[list_num][0].find("a").get("href") + "\n"

        return title[:-1],note_url[:-1]

    #各ページの内容を記録、記録との差分を監視
    def main(self):
        change_file = change_list = text = ""
        news = news_list = ""
        table = self.soup.find_all("div", class_="list_news")[0].find_all("tr")
        shutil.rmtree(self.newdir)
        pathlib.Path(self.newdir).mkdir()
        for x in range(self.dict_format(0)[1]):
            subject = self.dict_format(x)[0]
            sub_title = self.news_data(subject,table)[0].split("\n")
            sub_url = self.news_data(subject,table)[1].split()
            if sub_title != [''] and sub_url != ['']:
                for url_cnt in range(len(sub_url)):
                    cb_title = sub_title[url_cnt].strip("\t")
                    cb_title_hash = hashlib.sha256(cb_title.encode('utf-8')).hexdigest()
                    oldfilepath = self.olddir + cb_title_hash + ".txt"
                    newfilepath = self.newdir + cb_title_hash + ".txt"
                    sub_tera = TeraClass(sub_url[url_cnt])
                    sub_result = sub_tera.soup.find_all("div", attrs={"id" : "deco"})
                    #1文字以下を退避
                    p_tag_check = sub_result[0].find_all("p")
                    p_tag = ""
                    for p_cnt in range(len(p_tag_check)):
                        if not len(p_tag_check[p_cnt].text) <= 1:
                            p_tag += p_tag_check[p_cnt].text

                    #CR改行をLFに変換
                    lf_cnv = '\n'.join(p_tag.splitlines())
                    text_fmt = lf_cnv.replace('。', '。\n')

                    with open(newfilepath, mode="w") as f: f.write(text_fmt + "\n")

                    if os.path.isfile(oldfilepath):
                        command = ['diff','-C','0',oldfilepath,newfilepath]
                        with open(oldfilepath, mode="r") as f: old_text = f.read()
                        with open(newfilepath, mode="r") as f: new_text = f.read()
                        if new_text != old_text:
                            ret = prc.run(command, stdout=prc.PIPE)
                            output = ret.stdout.decode()
                            lines = output.splitlines()
                            text = ""
                            cnt = 0
                            for line in lines:
                                m = re.match("\+ ", line)
                                n = re.match("\! ", line)
                                p = re.match("\- ", line)

                                if m != None:
                                    text += "【追記された箇所です】\n" + line + "\n\n"
                                elif n != None:
                                    if cnt == 0:
                                        text += "【以下が変更前の箇所です。】\n" + line + "\n\n"
                                    elif cnt == 1:
                                        text += "【以下が変更後の箇所です。】\n" + line + "\n\n"
                                    cnt += 1
                                elif p != None:
                                    text += "【削除された箇所です。】\n" + line + "\n\n"

                            change_file += "\n" + subject + "[" + cb_title + "](<" + sub_url[url_cnt] + ">)\n" + text

#                        else: print ("【一致】 " + sub_title[url_cnt].strip("\t"))

                    else:
                        news += "\n" + subject + "[" + cb_title + "](<" + sub_url[url_cnt] + ">)\n"

        if news[:-1] != "":
            news_list = "【新しい記事があります!】" + news[:-1]

        if change_file[:-1] != "":
            change_list = "【内容の更新があります!】" + change_file[:-1]

        shutil.rmtree(self.olddir)
        pathlib.Path(self.olddir).mkdir()
        copy_tree(self.newdir,self.olddir)

#        print (news_list + "\n\n" + change_list)
        return news_list + "\n\n" + change_list

#if __name__ == "__main__":
#    url = "https://tera.pmang.jp/notices"
#    tera = TeraClass(url)
#    tera.main()
  • 0
  • 0
anonymous タイトルなし
Python
#!/bin/env python
import requests
import re
import json
import os
import sys
import time
import hashlib
import subprocess as prc
import shutil
import pathlib
from distutils.dir_util import copy_tree
from datetime import datetime as d
from bs4 import BeautifulSoup

class TeraClass(object):

    #使いまわし初期設定
    def __init__(self,url):
        self.newdir = os.path.dirname(os.path.abspath(__file__)) + "/new/"
        self.olddir = os.path.dirname(os.path.abspath(__file__)) + "/old/"
        self.session = requests.session()
        self.user_agent = {"User-Agent": "Mozilla/5.0 (Linux; Android 9; SOV42) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.136 Mobile Safari/537.36"}
        time.sleep(1)
        try:
            self.reqest = self.session.get(url,timeout=5,headers=self.user_agent)
        except requests.exceptions.ConnectTimeout: sys.exit()
        if self.reqest.status_code != 200: print(self.reqest.status_code);sys.exit()
        self.soup = BeautifulSoup(self.reqest.content, "lxml", from_encoding='utf-8')

    #HTMLを監視するタグ(自由に増減できる)
    def dict_format(self,param):
        dicts = {
            0:"[イベント] ",
            1:"[お知らせ] ",
            2:"[定期メンテ] ",
            3:"[キャンペーン] ",
            4:"[生放送] ",
            5:"[重要] ",
            6:"[アップデート] ",
#           7:"[障害]",
            }
        result = dicts.get(param)
        item_count = len(dicts)
        return result,item_count

    #最新情報のページを1ページ分(20項目)取得
    def news_data(self,subject,table):
        title = note_url = ""
        for ttl in range (1, 21):
            if table[ttl].text[1:3] in subject:
                title_list = [table[ttl].find_all("td", attrs={"class" : "title"})]
                for list_num in range(len(title_list)):
                    title += (title_list[list_num][0].text + "\n")
                    note_url += "https://tera.pmang.jp" + title_list[list_num][0].find("a").get("href") + "\n"

        return title[:-1],note_url[:-1]

    #各ページの内容を記録、記録との差分を監視
    def main(self):
        change_file = change_list = text = ""
        news = news_list = ""
        table = self.soup.find_all("div", class_="list_news")[0].find_all("tr")
        shutil.rmtree(self.newdir)
        pathlib.Path(self.newdir).mkdir()
        for x in range(self.dict_format(0)[1]):
            subject = self.dict_format(x)[0]
            sub_title = self.news_data(subject,table)[0].split("\n")
            sub_url = self.news_data(subject,table)[1].split()
            if sub_title != [''] and sub_url != ['']:
                for url_cnt in range(len(sub_url)):
                    cb_title = sub_title[url_cnt].strip("\t")
                    cb_title_hash = hashlib.sha256(cb_title.encode('utf-8')).hexdigest()
                    oldfilepath = self.olddir + cb_title_hash + ".txt"
                    newfilepath = self.newdir + cb_title_hash + ".txt"
                    sub_tera = TeraClass(sub_url[url_cnt])
                    sub_result = sub_tera.soup.find_all("div", attrs={"id" : "deco"})
                    #1文字以下を退避
                    p_tag_check = sub_result[0].find_all("p")
                    p_tag = ""
                    for p_cnt in range(len(p_tag_check)):
                        if not len(p_tag_check[p_cnt].text) <= 1:
                            p_tag += p_tag_check[p_cnt].text

                    #CR改行をLFに変換
                    lf_cnv = '\n'.join(p_tag.splitlines())
                    text_fmt = lf_cnv.replace('。', '。\n')

                    with open(newfilepath, mode="w") as f: f.write(text_fmt + "\n")

                    if os.path.isfile(oldfilepath):
                        command = ['diff','-C','0',oldfilepath,newfilepath]
                        with open(oldfilepath, mode="r") as f: old_text = f.read()
                        with open(newfilepath, mode="r") as f: new_text = f.read()
                        if new_text != old_text:
                            ret = prc.run(command, stdout=prc.PIPE)
                            output = ret.stdout.decode()
                            lines = output.splitlines()
                            text = ""
                            cnt = 0
                            for line in lines:
                                m = re.match("\+ ", line)
                                n = re.match("\! ", line)
                                p = re.match("\- ", line)

                                if m != None:
                                    text += "【追記された箇所です】\n" + line + "\n\n"
                                elif n != None:
                                    if cnt == 0:
                                        text += "【以下が変更前の箇所です。】\n" + line + "\n\n"
                                    elif cnt == 1:
                                        text += "【以下が変更後の箇所です。】\n" + line + "\n\n"
                                    cnt += 1
                                elif p != None:
                                    text += "【削除された箇所です。】\n" + line + "\n\n"

                            change_file += "\n" + subject + "[" + cb_title + "](<" + sub_url[url_cnt] + ">)\n" + text

#                        else: print ("【一致】 " + sub_title[url_cnt].strip("\t"))

                    else:
                        news += "\n" + subject + "[" + cb_title + "](<" + sub_url[url_cnt] + ">)\n"

        if news[:-1] != "":
            news_list = "【新しい記事があります!】" + news[:-1]

        if change_file[:-1] != "":
            change_list = "【内容の更新があります!】" + change_file[:-1]

        shutil.rmtree(self.olddir)
        pathlib.Path(self.olddir).mkdir()
        copy_tree(self.newdir,self.olddir)

#        print (news_list + "\n\n" + change_list)
        return news_list + "\n\n" + change_list

#if __name__ == "__main__":
#    url = "https://tera.pmang.jp/notices"
#    tera = TeraClass(url)
#    tera.main()
  • 0
  • 0