# -*- coding: utf-8 -*-
"""
Python HW1 02/08/2020

@author: Runxin Yu
"""
# 1.(a)
list1 = []
for i in range(1,21):
    list1.append(i)
print(list1)

# 1.(b)
list2 = []
for k in range(20,0,-1):
    list2.append(k)
print(list2)

# 1.(c)
list3 = list1.copy()
for j in range(19,0,-1):
    list3.append(j)
print(list3)

# 1.(d)
list3 = 10*[4,6,3]
print(list3)

# 1.(e)
list4 = 11*[4,6,3]
del list4[-1]
del list4[-1]
print(list4)

# 2.
list5 = []
import numpy
import math
for x in numpy.arange(3,6,0.1):
    list5.append(round(math.exp(x)*math.cos(x),2))
print(list5)

# 3.
list6 = []
for y in range(1,26):
    list6.append(round(pow(2,y)/y,2))
print(list6)

# 4.(a)
a = list1.copy()
a_new = [ a[x]- a[-1-x] for x in range(len(a)) ]
print(a_new)

# 4.(b)
a_boolean = [a[x] % 2 == 0 for x in range(len(a))]
print(a_boolean)

# 5.
with open('lorem.txt','r') as f:
    all_lines = f.readlines()
    f.close()

import re
text = ''.join(all_lines)
pat = re.compile('([A-Z][a-z]+)|([a-z]+)')
match = pat.findall(text)
# (a)
word = []
for l in all_lines:
    word.extend(re.split(r'[;,\s,.,:]\s*', l))

word4 =[]
word7 =[]
word8 =[]
for p in word:
    if len(p)>=1 and len(p)<=4:
        word4.append(p)
    elif len(p)>4 and len(p)<=7:
        word7.append(p)
    elif len(p)>=8:
        word8.append(p)
print("The number of strings whose lengths are between 1 and 4 is: %s" % (len(word4)))
print("The number of strings whose lengths are between 4 and 7 is: %s" % (len(word7)))
print("The number of strings whose lengths are 8 or greater is: %s" % (len(word8)))

# (b)
cap =[]
low = []
for m in match:
    if len(m[0]) > 0:
        cap.append(m[0])
    else:
        low.append(m[1])
print('The number of capitalized characters in the file is: %s\n' % (len(cap)))


import firebase_admin
from firebase_admin import firestore
from firebase_admin import credentials

cred = credentials.Certificate('aibigdata-ntut-107598064-firebase.json')
firebase_admin.initialize_app(cred)
dataBase = firestore.client().collection('test')
dataBase_sites = dataBase.document('myfirestore').collection('sites')
sites = []
for document in dataBase_sites.stream():
    site = document.to_dict()
    sites.append(site['id'])
print(sites)


from flask import flash
from models import User

def handle_signup_errors(username, email, id):
    """Handles errors for signup or updating profile"""

    existing_username = User.query.filter_by(username=username).one_or_none()
    existing_email = User.query.filter_by(email=email).one_or_none()

    if existing_username and existing_username.id != id:
        flash("Username already taken, try a different username", 'danger')
        return True
    if existing_email and existing_email.id != id:
        flash("Email already in use", "danger")
        return True

    else:
        return False


class Solution:
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        s = list(str(int("".join([str(i) for i in digits])) + 1))
        d = [int(i) for i in s]
        return d

s = Solution()
print(s.plusOne([1,2,3]))


from linkedLists import *

def kth_from_end(ll,k):
    runner = ll.head
    follower = ll.head
    for i in range(k):
        if runner is None:
            return None
        runner = runner.next

    while(runner.next):
        follower = follower.next
        runner = runner.next

    return follower.data

llist = LinkedList()

llist.head = Node(1)
second = Node(2)
third = Node(3)
llist.head.next = second
second.next = third

print(kth_from_end(llist, 2))


import sys
import os
beauvoir_path = os.path.dirname(os.path.realpath(__file__)) + '/'
sys.path.append(beauvoir_path)
sys.path.append('/usr/local/lib/python3.5/dist-packages/')
from utils.image_detector_generator import ImageDetectorGenerator

obj_model_directory = '../data/ShapeNetCore.v2/'
save_path = '../data/detection_data/'
background_path = '../data/backgrounds/'
class_names = ['airplane', 'bench', 'bottle', 'bus', 'camera', 'can', 'car',
               'cellular_telephone', 'chair', 'computer_keyboard', 'display',
               'earphone', 'faucet', 'guitar', 'knife', 'laptop', 'motorcycle',
               'mug', 'pillow', 'pistol', 'rifle', 'rocket', 'skateboard',
               'table']

num_images = 500
resolution = (300, 300)
background = 'crop'
max_num_lamps = 3
translation_range = [-1, 1]
max_num_objects_in_scene = 5

image_generator = ImageDetectorGenerator(
                        obj_model_directory, save_path,
                        class_names, num_images,
                        resolution, background=background,
                        background_images_directory=background_path,
                        max_num_lamps=max_num_lamps,
                        translation_range=translation_range,
                        max_num_objects_in_scene=max_num_objects_in_scene)

image_generator.render()


import numpy

class ClassWeights():
    def __init__(self, y, numClass, strategy, beta=0.9, normalise=False):
        self.weights = None
        if strategy == 'ENS':
            self.weights = self.get_class_weights_ENS(y, numClass, beta=beta, normalise=normalise)
        if strategy == 'INS':
            self.weights = self.get_class_weights_INS(y, numClass, beta=beta, normalise=normalise)
        if strategy == 'ISNS':
            self.weights = self.get_class_weights_ISNS(y, numClass, beta=beta, normalise=normalise)
        if strategy == 'IMF':
            self.weights = self.get_class_weights_IMF(y, numClass, beta=beta, normalise=normalise)

    def __call__(self):
        return self.weights

    def get_class_weights_ENS(self, y, numclass, beta=0.9, normalise=False):
        """
        y = classfrequency
        Get class weights for imbalanced dataset
        """
        effectiveNum = 1.0 - numpy.power(beta, y)
        weights = (1 - beta) / numpy.array(effectiveNum)
        if normalise:
            weights /= (numpy.sum(weights) * numclass)
        return weights

    def get_class_weights_INS(self, y, numclass, beta=0.9, normalise=False):
        """
        y = classfrequency
        Get class weights for imbalanced dataset
        """
        weights = 1 / (y)
        if normalise:
            weights /= (numpy.sum(weights) * numclass)
        return weights

    def get_class_weights_ISNS(self, y, numclass, beta=0.9, normalise=False):
        """
        y = classfrequency
        Get class weights for imbalanced dataset
        """
        weights = 1 / (numpy.sqrt(y))
        if normalise:
            weights /= (numpy.sum(weights) * numclass)
        return weights

    # Inverse median frequency weighting
    def get_class_weights_IMF(self, y, numclass, beta=0.9, normalise=False):
        """
        y = list of labels as is!
        """
        # Get class weights (inverse frequency) from training labels
        classes = numpy.asarray(y)
        weights = numpy.bincount(classes, minlength=numclass)  # occurences per class
        weights[weights == 0] = 1  # replace empty bins with 1
        weights = 1 / weights  # number of targets per class
        weights /= weights.sum()  # normalize
        return weights


#!/usr/bin/env python

import rospy
from std_msgs.msg import Bool
from geometry_msgs.msg import Twist
from Adafruit_MotorHAT import Adafruit_MotorHAT

global width
width = 0.291

class WheelController(object):
	def __init__(self):
		self.node_name = rospy.get_name()
		rospy.loginfo("[%s] Initializing ..." %(self.node_name))
		# Motors
		self.mh = Adafruit_MotorHAT(addr=0x60)
		self.left_motor = self.mh.getMotor(1)
		self.right_motor = self.mh.getMotor(2)
		# Motor state and pwm
		self.state_l = None
		self.state_r = None
		self.pwm_l = None
		self.pwm_r = None
		# Motor velocity
		self.v_L = None
		self.v_R = None
		# Emergency stop flag
		self.e_stop = None
		# Subscribers
		self.sub_car_cmd = rospy.Subscriber("car_cmd", Twist, self.cb_car_cmd ,queue_size=1)
		self.sub_e_stop  = rospy.Subscriber("e_stop", Bool, self.cb_e_stop, queue_size = 10)

	def cb_e_stop(self, msg):
		self.e_stop = msg.data

	def cb_car_cmd(self, twist_msg):
		if(self.e_stop == True):
			self.left_motor.setSpeed(0)
			self.right_motor.setSpeed(0)
			self.left_motor.run(4)
			self.right_motor.run(4)
			rospy.loginfo("[%s] Emergency stop!" %(self.node_name))
			rospy.sleep(0.1)
		else:
			if(twist_msg.linear.x != 0):
				self.v_L = twist_msg.linear.x - width/2 * twist_msg.angular.z
				self.v_R = twist_msg.linear.x + width/2 * twist_msg.angular.z
				if(twist_msg.linear.x > 0):
					self.state_l = self.state_r = 1
				else:
					self.state_l = self.state_r = 2
				self.pwm_l = int(abs(self.v_L * 10000 / 7.48))
				self.pwm_r = int(abs(self.v_R * 10000 / 6.30))

			else:
				if(twist_msg.angular.z > 0):
					self.state_l = 4
					self.state_r = 1
					self.v_R = width * twist_msg.angular.z
					self.pwm_l = 0
					self.pwm_r = int(abs(self.v_R * 10000 / 6.63))
				else:
					self.state_l = 1
					self.state_r = 4
					self.v_L = width * twist_msg.angular.z
					self.pwm_l = int(abs(self.v_L * 10000 / 7.48))
					self.pwm_r = 0

			if(self.pwm_l > 255):
				self.pwm_l = 255
			if(self.pwm_r > 255):
				self.pwm_r = 255

			self.left_motor.setSpeed(self.pwm_l)
			self.right_motor.setSpeed(self.pwm_r)

			self.left_motor.run(self.state_l)
			self.right_motor.run(self.state_r)

			rospy.sleep(0.1)

	def on_shutdown(self):
		rospy.loginfo("[%s] Shutting down ..." %(self.node_name))
		self.left_motor.setSpeed(0)
		self.right_motor.setSpeed(0)
		self.left_motor.run(4)
		self.right_motor.run(4)
		rospy.sleep(1)
		del self.mh

if __name__ == "__main__":
	rospy.init_node('wheel_controller_node', anonymous = False)
	wheel_controller = WheelController()
	rospy.on_shutdown(wheel_controller.on_shutdown)
	rospy.spin()


import requests
from bs4 import BeautifulSoup
import wget

def parsUrlToPage(quotes):
    for title in quotes:
            s = title.text.strip(), title.get('href')
            b = "https://jut.su" + s[1]
            #b = b.split()
            f = open("url", "a")
            f.write("{};{};".format(s[0], b))
            f.close()
def parsVideoToPage(quotes):
    for title in quotes:
        s = title.text.strip(), title.get('src')
        return(s)
def main(quality, url):
    header = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0',}

    response = requests.get(url, headers=header)
    soup = BeautifulSoup(response.text, 'lxml')

    f = open("url", "w")
    f.close()

    quotes = soup.find_all('a', class_='short-btn black video the_hildi')
    parsUrlToPage(quotes)
    quotes = soup.find_all('a', class_='short-btn green video the_hildi')
    parsUrlToPage(quotes)
    download(header, quality)

def download(header, quality):
    f = open("url", "r")
    s = f.read()
    f.close()
    j = s.split(";")

    while True:
        if len(j) == 0 or len(j) == 1:
            print("\nСкачивание успешно завершенно... Приятного просмотра!")
        else:
            url = j[1]

            response = requests.get(url, headers=header)
            soup = BeautifulSoup(response.text, 'lxml')

            quotes = soup.find_all('source', label=quality)
            s = parsVideoToPage(quotes)
            print("\nИмя: {}, ссылка: {}, ссылка на видео: {}".format(j[0], j[1], s[1]))
            print("Начинаю скачивание видео...")

            f = open(j[0] + ".mp4", "wb")
            download = requests.get(s[1], headers=header)
            f.write(download.content)
            f.close()
            print("Закончил скачивать")

            j.pop(0)
            j.pop(0)

print("Здравствуйте, я скачиваю аниме с сайта Jut.su\n")
print("Я могу просто спарсить url до нужной анимешки, потом вы подправите файл с ссылками и я скачаю все серри аниме из этого файла\nИли у вас уже есть файл, скажите если есть\n1. Скачай аниме из файла 2. Спарси url и скачай сразу 3. Просто спарси url")
parsOrNo = int(input())

if parsOrNo == 1:
    header = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0',}
    print("\nОкей, буду скачивать аниме из файла")
    print("В каком качестве скачивать?\n1. 360 2. 480 3. 720 4. 1080")
    quality = int(input())
    print("")

    if quality == 1:
        quality = "360p"
        download(header, quality)
    if quality == 2:
        quality = "480p"
        download(header, quality)
    if quality == 3:
        quality = "720p"
        download(header, quality)
    if quality == 4:
        quality = "1080p"
        download(header, quality)
    else:
        print("Вы написали что-то не то. Надо писать от 1 до 4. Запустите меня заново =)")

if parsOrNo == 2:
    print("\nУкажите ссылку на аниме, и начну его скачивать!")
    url = str(input())
    print("В каком качестве скачивать?\n1. 360 2. 480 3. 720 4. 1080")
    quality = int(input())

    if quality == 1:
        quality = "360p"
        main(quality, url)
    if quality == 2:
        quality = "480p"
        main(quality, url)
    if quality == 3:
        quality = "720p"
        main(quality, url)
    if quality == 4:
        quality = "1080p"
        main(quality, url)
    else:
        print("Вы написали что-то не то. Надо писать от 1 до 4. Запустите меня заново =)")

if parsOrNo == 3:
    print("\nУкажите ссылку на аниме, и начну его скачивать!")
    url = str(input())
    print("Начинаю парсить url в файл")

    f = open("url", "w")
    f.close()

    header = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0',}
    response = requests.get(url, headers=header)
    soup = BeautifulSoup(response.text, 'lxml')
    quotes = soup.find_all('a', class_='short-btn black video the_hildi')
    parsUrlToPage(quotes)
    quotes = soup.find_all('a', class_='short-btn green video the_hildi')
    parsUrlToPage(quotes)
    print("Готово, заверщаю работу")


"""The parmeterized notebook page service."""

from __future__ import annotations

from collections.abc import Mapping
from dataclasses import asdict
from datetime import UTC, datetime
from typing import Any

from httpx import AsyncClient
from structlog.stdlib import BoundLogger

from timessquare.config import config
from timessquare.domain.githubtree import GitHubNode
from timessquare.domain.nbhtml import NbDisplaySettings, NbHtmlKey, NbHtmlModel
from timessquare.domain.noteburst import (
    NoteburstApi,
    NoteburstJobResponseModel,
    NoteburstJobStatus,
)
from timessquare.domain.page import (
    PageExecutionInfo,
    PageInstanceModel,
    PageModel,
    PageSummaryModel,
    PersonModel,
)
from timessquare.exceptions import PageNotFoundError
from timessquare.storage.nbhtmlcache import NbHtmlCacheStore
from timessquare.storage.noteburstjobstore import NoteburstJobStore
from timessquare.storage.page import PageStore

class PageService:
    """A service manager for parameterized notebook pages.

    Parameters
    ----------
    page_store : `timessquare.storage.page.PageStore
        The PageStore, which adapts the database backend.
    logger : `structlog.stdlib.BoundLogger`
        The logger instance, bound with context about the request.
    """

    def __init__(
        self,
        page_store: PageStore,
        html_cache: NbHtmlCacheStore,
        job_store: NoteburstJobStore,
        http_client: AsyncClient,
        logger: BoundLogger,
    ) -> None:
        self._page_store = page_store
        self._html_store = html_cache
        self._job_store = job_store
        self._http_client = http_client
        self._logger = logger
        self.noteburst_api = NoteburstApi(http_client=http_client)

    async def create_page_with_notebook_from_upload(
        self,
        ipynb: str,
        title: str,
        uploader_username: str,
        description: str | None = None,
        cache_ttl: int | None = None,
        tags: list[str] | None = None,
        authors: list[PersonModel] | None = None,
    ) -> PageExecutionInfo:
        """Create a page resource given the parameterized Jupyter Notebook
        content.
        """
        page = PageModel.create_from_api_upload(
            title=title,
            ipynb=ipynb,
            uploader_username=uploader_username,
            description=description,
            cache_ttl=cache_ttl,
            tags=tags,
            authors=authors,
        )
        return await self.add_page_and_execute(page)

    async def add_page_to_store(self, page: PageModel) -> None:
        """Add a page to the page store.

        Parameters
        ----------
        page: `PageModel`
            The page model.

        Notes
        -----
        For API uploads, use `create_page_with_notebook_from_upload` instead.
        """
        self._page_store.add(page)

    async def add_page_and_execute(
        self, page: PageModel, *, enable_retry: bool = True
    ) -> PageExecutionInfo:
        """Add a page to the page store and execute it with defaults.

        Parameters
        ----------
        page: `PageModel`
            The page model.
        execute : `bool`
            Set this to `False` to disable the automatic noteburst execution
            of pages (useful for testing scenarios).

        Notes
        -----
        For API uploads, use `create_page_with_notebook_from_upload` instead.
        """
        await self.add_page_to_store(page)
        return await self.execute_page_with_defaults(
            page, enable_retry=enable_retry
        )

    async def get_page(self, name: str) -> PageModel:
        """Get the page from the data store, given its name."""
        page = await self._page_store.get(name)
        if page is None:
            raise PageNotFoundError(name)
        return page

    async def get_github_backed_page(self, display_path: str) -> PageModel:
        """Get the page based on its display path."""
        page = await self._page_store.get_github_backed_page(display_path)
        if page is None:
            raise PageNotFoundError(display_path)
        return page

    async def get_github_pr_page(
        self,
        *,
        owner: str,
        repo: str,
        commit: str,
        path: str,
    ) -> PageModel:
        """Get a page for a specific commit, corresponding to a GitHub PR's
        check run.

        Parameters
        ----------
        owner : `str`
            GitHub repository owner (username or organization).
        repo : `str`
            GitHub repository name.
        commit : `str`
            The SHA of the Git commit corresponding to the check run.
        path : `str`
            The page's path within the repository (without the file extension).

        Returns
        -------
        page : `PageModel`
            The domain model for a page. For PRs, this page is creating while
            processing the GitHub check suite.

        Raises
        ------
        PageNotFoundError
            Raised if the page is not found in the PageStore.
        """
        display_path = f"{owner}/{repo}/{path}"
        page = await self._page_store.get_github_backed_page(
            display_path, commit=commit
        )
        if page is None:
            # TODO add a commit attribute to the exception
            raise PageNotFoundError(display_path)
        return page

    async def get_page_summaries(self) -> list[PageSummaryModel]:
        """Get page summaries."""
        return await self._page_store.list_page_summaries()

    async def get_pages_for_repo(
        self, owner: str, name: str, commit: str | None = None
    ) -> list[PageModel]:
        """Get all pages backed by a specific GitHub repository."""
        return await self._page_store.list_pages_for_repository(
            owner=owner, name=name, commit=commit
        )

    async def get_github_tree(self) -> list[GitHubNode]:
        """Get the tree of GitHub-backed pages."""
        return await self._page_store.get_github_tree()

    async def get_github_pr_tree(
        self,
        *,
        owner: str,
        repo: str,
        commit: str,
    ) -> list[GitHubNode]:
        """Get the tree of GitHub-backed pages for a specific pull request."""
        return await self._page_store.get_github_pr_tree(
            owner=owner, repo=repo, commit=commit
        )

    async def update_page_in_store(self, page: PageModel) -> None:
        """Update the page in the database.

        Algorithm is:

        1. Update the page in Postgres
        2. Delete all cached HTML for the page from redis
        """
        await self._page_store.update_page(page)
        await self._html_store.delete_objects_for_page(page.name)

    async def update_page_and_execute(
        self, page: PageModel, *, enable_retry: bool = True
    ) -> PageExecutionInfo:
        await self.update_page_in_store(page)
        return await self.execute_page_with_defaults(
            page, enable_retry=enable_retry
        )

    async def execute_page_with_defaults(
        self, page: PageModel, *, enable_retry: bool = True
    ) -> PageExecutionInfo:
        """Request noteburst execution of with page's default values.

        This is useful for the `add_page` and `update_page` methods to start
        notebook execution as soon as possible.
        """
        resolved_values = page.resolve_and_validate_values({})
        page_instance = PageInstanceModel(
            name=page.name, values=resolved_values, page=page
        )
        return await self.request_noteburst_execution(
            page_instance, enable_retry=enable_retry
        )

    async def soft_delete_page(self, page: PageModel) -> None:
        """Soft delete a page by setting its date_deleted field."""
        page.date_deleted = datetime.now(UTC)
        await self.update_page_in_store(page)

    async def soft_delete_pages_for_repo(self, owner: str, name: str) -> None:
        """Soft delete all pages backed by a specific GitHub repository."""
        for page in await self.get_pages_for_repo(owner=owner, name=name):
            await self.soft_delete_page(page)

    async def render_page_template(
        self, name: str, values: Mapping[str, Any]
    ) -> str:
        """Render a page's jupyter notebook, with the given parameter values.

        Parameters
        ----------
        name : `str`
            Name (URL slug) of the page.
        values : `dict`
            Parameter values, keyed by parameter names. If values are
            missing, the default value is used instead.
        """
        page = await self.get_page(name)
        resolved_values = page.resolve_and_validate_values(values)
        return page.render_parameters(resolved_values)

    async def get_html(
        self, *, name: str, query_params: Mapping[str, Any]
    ) -> NbHtmlModel | None:
        """Get the HTML for a page given the query parameters, first
        from a cache or triggering a rendering if not available.

        Returns
        -------
        nbhtml : `NbHtmlModel` or `None`
            The NbHtmlModel if available, or `None` if the executed notebook is
            not presently available.
        query_params
            The request query parameters, which contain parameter values as
            well as display settings.
        """
        # Get display settings from parameters
        try:
            hide_code = bool(int(query_params.get("ts_hide_code", "1")))
        except Exception as e:
            raise ValueError("hide_code query parameter must be 1 or 0") from e
        display_settings = NbDisplaySettings(hide_code=hide_code)
        self._logger.debug(
            "Resolved display settings",
            display_settings=asdict(display_settings),
        )

        page = await self.get_page(name)
        resolved_values = page.resolve_and_validate_values(query_params)

        # First try to get HTML from redis cache
        page_key = NbHtmlKey(
            name=page.name,
            values=resolved_values,
            display_settings=display_settings,
        )
        nbhtml = await self._html_store.get_instance(page_key)
        if nbhtml is not None:
            self._logger.debug("Got HTML from cache")
            return nbhtml

        # Second, look if there's an existing job request. If the job is
        # done this renders it into HTML; otherwise it triggers a noteburst
        # request, but does not return any HTML for this request.
        page_instance = PageInstanceModel(
            name=page.name, values=resolved_values, page=page
        )
        return await self._get_html_from_noteburst_job(
            page_instance=page_instance,
            display_settings=display_settings,
        )

    async def _get_html_from_noteburst_job(
        self,
        *,
        page_instance: PageInstanceModel,
        display_settings: NbDisplaySettings,
    ) -> NbHtmlModel | None:
        """Convert a noteburst job for a given page and parameter values into
        HTML (caching that HTML as well), and triggering a new noteburst.

        Parameters
        ----------
        page_instance : `PageInstanceModel`
            The page instance (consisting of resolved parameter values).
        display_settings : `NbDisplaySettings`
            A display parameter passed to `NbHtml.create_from_noteburst_result`
            that indicates whether the returned HTML should include code input
            cells.

        Returns
        -------
        nbhtml : `NbHtmlModel` or `None`
            The NbHtmlModel if available, or `None` if the executed notebook is
            not presently available.
        """
        # Is there an existing job in the noteburst job store?
        job = await self._job_store.get_instance(page_instance)
        if not job:
            self._logger.debug("No existing noteburst job available")
            # A record of a noteburst job is not available. Send a request
            # to noteburst.
            await self.request_noteburst_execution(page_instance)
            return None

        r = await self._http_client.get(
            job.job_url, headers=self._noteburst_auth_header
        )
        if r.status_code == 200:
            noteburst_response = NoteburstJobResponseModel.parse_obj(r.json())
            self._logger.debug(
                "Got noteburst job metadata",
                status=str(noteburst_response.status),
            )
            if noteburst_response.status == NoteburstJobStatus.complete:
                ipynb = noteburst_response.ipynb
                if ipynb is None:
                    raise RuntimeError(
                        "Noteburst job is complete but has no ipynb"
                    )
                html_renders = await self._create_html_matrix(
                    page_instance=page_instance,
                    ipynb=ipynb,
                    noteburst_response=noteburst_response,
                )
                # return the specific HTML render that the client asked for
                return html_renders[display_settings]

            else:
                # Noteburst job isn't complete
                return None

        elif r.status_code != 404:
            # Noteburst lost the job; delete our record and try again
            self._logger.warning(
                "Got a 404 from a noteburst job", job_url=job.job_url
            )
            await self._job_store.delete_instance(page_instance)
            await self.request_noteburst_execution(page_instance)
        else:
            # server error from noteburst
            self._logger.warning(
                "Got unknown response from noteburst job",
                job_url=job.job_url,
                noteburst_status=r.status_code,
                noteburst_body=r.text,
            )
        return None

    async def request_noteburst_execution(
        self, page_instance: PageInstanceModel, *, enable_retry: bool = True
    ) -> PageExecutionInfo:
        """Request a notebook execution for a given page and parameters,
        and store the job.
        """
        ipynb = page_instance.page.render_parameters(page_instance.values)
        r = await self.noteburst_api.submit_job(
            ipynb=ipynb, enable_retry=enable_retry
        )
        if r.status_code != 202 or r.data is None:
            self._logger.warning(
                "Error requesting noteburst execution",
                noteburst_status=r.status_code,
                noteburst_body=r.error,
            )

            return PageExecutionInfo(
                name=page_instance.name,
                values=page_instance.values,
                page=page_instance.page,
                noteburst_job=None,
                noteburst_status_code=r.status_code,
                noteburst_error_message=r.error,
            )

        await self._job_store.store_job(
            job=r.data.to_job_model(), page_id=page_instance
        )
        self._logger.info(
            "Requested noteburst notebook execution",
            page_name=page_instance.name,
            parameters=page_instance.values,
            job_url=r.data.self_url,
        )
        if r.data is None:
            raise RuntimeError("Noteburst job has no data")
        return PageExecutionInfo(
            name=page_instance.name,
            values=page_instance.values,
            page=page_instance.page,
            noteburst_job=r.data.to_job_model(),
            noteburst_status_code=r.status_code,
            noteburst_error_message=r.error,
        )

    async def _create_html_matrix(
        self,
        *,
        page_instance: PageInstanceModel,
        ipynb: str,
        noteburst_response: NoteburstJobResponseModel,
    ) -> dict[Any, NbHtmlModel]:
        # These keys correspond to display arguments in
        # NbHtml.create_from_notebook_result
        matrix_keys = [
            NbDisplaySettings(hide_code=True),
            NbDisplaySettings(hide_code=False),
        ]
        html_matrix: dict[NbDisplaySettings, NbHtmlModel] = {}
        for matrix_key in matrix_keys:
            nbhtml = NbHtmlModel.create_from_noteburst_result(
                page_instance=page_instance,
                ipynb=ipynb,
                noteburst_result=noteburst_response,
                display_settings=matrix_key,
            )
            html_matrix[matrix_key] = nbhtml
            # TODO make lifetime a setting of page for pages that aren't
            # idempotent.
            await self._html_store.store_nbhtml(nbhtml=nbhtml, lifetime=None)
            self._logger.debug(
                "Stored new HTML", display_settings=asdict(matrix_key)
            )

        await self._job_store.delete_instance(page_instance)
        self._logger.debug("Deleted old job record")

        return html_matrix

    @property
    def _noteburst_auth_header(self) -> dict[str, str]:
        return {
            "Authorization": (
                f"Bearer {config.gafaelfawr_token.get_secret_value()}"
            )
        }


#! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# written by taichi sakakibara, 2018/5/26.
""" This program is the simuration of random walk in two-dimentional space.
"""
#ただの4点だけの移動をランダムで行う
import numpy as np
from numpy.random import *#乱数を生成
# from agent import Agent

#classでエージェントの生成したい
# class Agent:
#     def__init__(self,p)
#     #初期の場所の設定
#     P = np.array([[0,0],[1,0],[0,1],[1,1]]])

"""頂点(エリアの大きさ)の定義"""
P = np.array([[0,0],[0,2],[2,2],[2,0]]) #4点それぞれを定義

"""速度を設定"""
#それぞれの場所での速度を定義する
v0 = np.array([[1,0],[0,1]])#左下
v1 = np.array([[1,0],[0,-1]])#左上
v2 = np.array([[-1,0],[0,-1]])#右上
v3 = np.array([[-1,0],[0,1]])#右下

"""userの初期位置を決定する"""
user = ([0,0])
#初期位置を設定するために0~4の乱数を生成
a = randint(4)
user = user + P[a]
print("スタート地点は"+str(user))

"""userの試行"""
for i in range(10):
    #角に到達した時の2択を実行するための乱数
    b = randint(2)

    #位置によって処理を行う
    if (user == P[0]).all():#userが[0,0]
        #上か右か選択
        user = user + v0[b]
        vc = v0[b]
    elif (user == P[1]).all():#userが[0,1]
        user = user + v1[b]
        vc = v1[b]
    elif (user == P[2]).all():#userが[1,1]
        user = user + v2[b]
        vc = v2[b]
    elif (user == P[3]).all():#userが[1,0]
        user = user + v3[b]
        vc = v3[b]
    else:                     #userが頂点以外にいる
        user = user + vc     #保持する速度で移動を継続する

    # print(i+1)
    print("vc = " + str(vc))
    print("位置は"+str(user))


# doing the same as SampleDNNClassifier.py but with Keras API instead of estimators.

import tensorflow as tf
import numpy as np
import time, os, sys
tf.enable_eager_execution()
startTick = time.time()

if os.environ['COMPUTERNAME'] == 'DESKTOP-7KDG5DC':
    dataFolder = "C:\\Users\\shhey\\OneDrive - SUNY ESF\\Thesis\\TensorFlow\\Data\\"
elif os.environ['COMPUTERNAME'] == 'ESF-ERE107-1':
    dataFolder = "D:\\Shahriar\\OneDrive - SUNY ESF\\Thesis\\TensorFlow\\Data\\"
else:
    print('Unknown computer. Please add your computer name and OneDrive path to the code')
    sys.exit()

###############################################################################################
# Part I: Reading training/testing features from TFRecords and training a classifier with it  #
###############################################################################################

# These training and test data has been created before
tfrTrainFile = dataFolder + 'tf_demo_train.gz'
tfrTestFile = dataFolder + 'tf_demo_test.gz'
# Dataset = tf.data.TFRecordDataset(tfrTestFile, compression_type='GZIP')
# iterator = Dataset.make_one_shot_iterator()
# with tf.Session() as sess:
#     try:
#       while True:
#         foo = iterator.get_next()
#         print(sess.run([foo]))
#     except tf.errors.OutOfRangeError:
#         pass

# We should know the data structure (6 Landsat bands and one integer landcover class per each pixel
bands = ['B2', 'B3', 'B4', 'B5', 'B6', 'B7','landcover']
columns = [tf.FixedLenFeature(shape=[], dtype=tf.float32) for k in bands]
featuresDict = dict(zip(bands, columns))

def parse_tfrecord(example):
    features = tf.parse_single_example(example, featuresDict)
    # Extract landcover and remove it from dictionary
    labels = features.pop('landcover')
    labels = tf.one_hot(tf.cast(labels, tf.uint8), 3)
    return features, labels

# Optional processing: Add normalized differences to the dataset
def addFeatures(features, label=tf.one_hot(tf.cast(0, tf.uint8), 3)):
    # Compute normalized difference of two inputs.  If denomenator is zero, add a small delta.
    def normalizedDifference(a, b):
        nd = (a - b) / (a + b)
        nd_inf = (a - b) / (a + b + 0.000001)
        return tf.where(tf.is_finite(nd), nd, nd_inf)

    features['NDVI'] = normalizedDifference(features['B5'], features['B4'])
    # Return list of dictionary values (to be convertible to numpy array for Keras) and pixel label in one-hot format
    return list(features.values()), label

# Generator function to create batches of Keras-compatible training data and one-hot labels
def trainDataGenerator(fileName, numEpochs=None, shuffle=True, batchSize=None):

  dataset = tf.data.TFRecordDataset(fileName, compression_type='GZIP')

  # Map the parsing function over the dataset
  dataset = dataset.map(parse_tfrecord)
  dataset = dataset.map(addFeatures)
  # Shuffle, batch, and repeat.
  if shuffle:
    dataset = dataset.shuffle(buffer_size=batchSize * 10)
  dataset = dataset.batch(batchSize)
  dataset = dataset.repeat(numEpochs)

  return dataset

TR_EPOCHS = 64
training_data = trainDataGenerator(fileName=tfrTrainFile, numEpochs=TR_EPOCHS, batchSize=1, shuffle=False)
testing_data = trainDataGenerator(fileName=tfrTestFile, batchSize=1, shuffle=False)

def keras_model():
    from tensorflow.keras.layers import Dense, Input

    inputs = Input(shape=(7,))
    x = Dense(5, activation='relu')(inputs)
    x = Dense(7, activation='relu')(x)
    x = Dense(5, activation='relu')(x)
    outputs = Dense(3, activation='softmax')(x)

    return tf.keras.Model(inputs, outputs)

model = keras_model()
learning_rate = 0.05
model.compile(optimizer=tf.train.AdagradOptimizer(learning_rate),
              loss='categorical_crossentropy',
              metrics=['accuracy'])

model.fit(training_data, steps_per_epoch=65, epochs=TR_EPOCHS, verbose=0)
model.summary()
loss, test_acc = model.evaluate(testing_data, steps=33, verbose=0)
print('Test accuracy = ', test_acc)
trainingTick = time.time()
trainingTime = trainingTick - startTick
print("Training run time: %s seconds" % (trainingTime))

#model.save_weights(dataFolder+'keras_model_weights_'+str(test_acc)[0:4]+'.h5')
#for layer in model.layers:
#    weights = layer.get_weights()

###############################################################################################
# Part II: Reading a test image from TFRecords for prediction and saving the results          #
###############################################################################################

# Actual image size is 2048 (rows) x 3072 (columns)
image_array = np.zeros((2048, 3072))

# NOTE: You have to know the following data about your TFRecords image to be read.
PATCH_WIDTH = 256
PATCH_HEIGHT = 256
PATCH_SIZE = PATCH_WIDTH * PATCH_HEIGHT
NUM_PATCHES = int(2048*3072 / (PATCH_WIDTH*PATCH_HEIGHT))

# Set input file name(s)
fileNames = [dataFolder+'tf_demo_image_256patch-00000.tfrecord.gz', dataFolder+'tf_demo_image_256patch-00001.tfrecord.gz']

# Defining the data structure is similar to part I, but this time at patch length
bands = ['B2', 'B3', 'B4', 'B5', 'B6', 'B7']
columns = [tf.FixedLenFeature(shape=[PATCH_SIZE], dtype=tf.float32) for k in bands]
imageFeaturesDict = dict(zip(bands, columns))

def parse_image(example_proto):
    parsed_features = tf.parse_single_example(example_proto, imageFeaturesDict)
    return parsed_features

# Similar to part I, below input function reads in the TFRecord files exported from an image.
# We also moved parser and feature processing functions into it for more code clearance. Note that
# because the pixels are arranged in patches, we need some additional code to reshape the tensors.
def predictDataGenerator(fileNames):
    # Note that you can make one dataset from many files by specifying a list.
    dataset = tf.data.TFRecordDataset(fileNames, compression_type='GZIP')

    dataset = dataset.map(parse_image, num_parallel_calls=5)
    # Break our long tensors into many littler ones
    dataset = dataset.flat_map(lambda features: tf.data.Dataset.from_tensor_slices(features))
    # Add additional features (NDVI).
    dataset = dataset.map(addFeatures)
    # Read in batches corresponding to patch size.
    dataset = dataset.batch(PATCH_WIDTH * PATCH_HEIGHT)
    return dataset

dataset = predictDataGenerator(fileNames)
# iterator = dataset.make_one_shot_iterator()
# print(iterator.get_next())

def predict_classes(probs):
    if probs.shape[-1] > 1:
        return probs.argmax(axis=-1)
    else:
        return (probs > 0.5).astype('int32')

# Do the prediction from the trained classifier
predictions = predict_classes(model.predict(dataset, steps = NUM_PATCHES))

predictionTick = time.time()
predictionTime = predictionTick - trainingTick
print("Prediction run time: %s seconds" % (predictionTime))

PATCH_PER_ROW , _ = divmod(3072, PATCH_WIDTH)
for patchIndex in range(0,NUM_PATCHES):
    pr, pc = divmod(patchIndex, PATCH_PER_ROW)
    image_array[pr*PATCH_HEIGHT:(pr+1)*PATCH_HEIGHT,pc*PATCH_WIDTH:(pc+1)*PATCH_WIDTH] = \
        predictions[patchIndex * PATCH_SIZE: (patchIndex+1)*PATCH_SIZE].reshape(PATCH_WIDTH,PATCH_HEIGHT)
    print('Patch # ', patchIndex, ' filled')

exportTick = time.time()
exportTime = exportTick - predictionTick
print("Image export run time: %s seconds" % (exportTime))

import matplotlib.pyplot as plt
import matplotlib.image as img
fig = plt.figure()
plt.imshow(image_array)
plt.show()
img.imsave(dataFolder+'image_classified_keras_epochs'+str(TR_EPOCHS)+'_'+str(test_acc)[0:4]+'.png', image_array)


from  math import *
a, b, c = map(int, input().split())  #하루 오르는 양 , 미끄러지는 양, 총 높이

#전체-마지막날 오르는양 = last

#아침이 되었을떄 last 만큼 올라와있어야함
#(아침-저녁) * 일수 >= last

last=c-a
tday=ceil(last/(a-b))

print(tday+1)

백준/Bronze/2869. 달팽이는 올라가고 싶다/달팽이는 올라가고 싶다.py

달팽이는 올라가고 싶다.py


# Modification of PhysicsTools.PatAlgos.patTemplate_cfg

# IMPORTS
import FWCore.ParameterSet.Config as cms			# Standard config file information.
#from PhysicsTools.PatAlgos.tools.pfTools import *		# Deep in here (PhysicsTools.PatAlgos.tools.jetTools) is addJetCollection.
from Configuration.AlCa.autoCond import autoCond		# For automatically determining global tags

# CONSTRUCT
process = cms.Process("fatjets")

# DEFINE CONFIGURATION
# Reports
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.options = cms.untracked.PSet(
	wantSummary = cms.untracked.bool(True)			# Long summary after job.
)
# Input
process.source = cms.Source("PoolSource",
	fileNames = cms.untracked.vstring(),
#	eventsToProcess = cms.untracked.VEventRange('1:44929-1:44938'),
)
# Output
from PhysicsTools.PatAlgos.patEventContent_cff import patEventContent
process.out = cms.OutputModule("PoolOutputModule",
	fileName = cms.untracked.string('out.root'),
	SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('p') ),	# Save only events passing the full pathway
	outputCommands = cms.untracked.vstring('drop *', "keep *_*_*_fatjets")	# https://twiki.cern.ch/twiki/bin/view/CMSPublic/SWGuideSelectingBranchesForOutput
#	outputCommands = cms.untracked.vstring('drop *', *patEventContent )
)
process.outpath = cms.EndPath(process.out)

process.TFileService = cms.Service("TFileService",
	fileName = cms.string('out2.root')
)
# Events
process.maxEvents = cms.untracked.PSet(
	input = cms.untracked.int32(100)
)

# PRODUCTION
## Geometry and Detector Conditions (needed for a few patTuple production steps)
process.load("Configuration.Geometry.GeometryIdeal_cff")
process.load("Configuration.StandardSequences.MagneticField_cff")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
process.GlobalTag.globaltag = cms.string(autoCond['startup'])		# Set global tags automatically.
#process.GlobalTag.globaltag = cms.string('START53_V27::All')		# Set global tags by hand.
##process.load('RecoJets.JetProducers.caSubjetFilterGenJets_cfi')
##process.caSubjetFilterGenJets.verbose = cms.untracked.bool(False)
##process.caSubjetFilterGenJets.src     = 'genParticles'	# Input module label
##process.caSubjetFilterGenJets.Rho_EtaMax = cms.double(5.0)
##process.caSubjetFilterGenJets.rParam = cms.double(0.5)

process.analyzer = cms.EDAnalyzer('Fatjets',
	v = cms.bool(False),		# verbose mode
	R = cms.double(0.7),
	make_gen = cms.bool(True),
	make_pf = cms.bool(True),
	do_true = cms.bool(False),
	do_prune = cms.bool(False),
	do_trim = cms.bool(False),
	trim_R = cms.double(0.3),
	trim_ptf = cms.double(0.2)
)

## ------------------------------------------------------
#  NOTE: you can use a bunch of core tools of PAT to
#  taylor your PAT configuration; for a few examples
#  uncomment the lines below
## ------------------------------------------------------
#from PhysicsTools.PatAlgos.tools.coreTools import *

## remove MC matching from the default sequence
# removeMCMatching(process, ['Muons'])
# runOnData(process)

## remove certain objects from the default sequence
# removeAllPATObjectsBut(process, ['Muons'])
# removeSpecificPATObjects(process, ['Electrons', 'Muons', 'Taus'])

## let it run

process.p = cms.Path(
	  process.analyzer
)
## ------------------------------------------------------
# Commonly Changed User Parameters:
## ------------------------------------------------------

# PARAMETERS
msg = 850
msq = 250
R = 1.2
trim_R = 1.0
trim_ptf = 0.1
#process.analyzer.v = True
process.analyzer.v = False
process.analyzer.R = R
process.analyzer.make_gen = True
process.analyzer.make_pf = True
process.analyzer.do_true = False
process.analyzer.do_prune = False
process.analyzer.do_trim = False
process.analyzer.trim_R = trim_R
process.analyzer.trim_ptf = trim_ptf
# INPUT FILES
process.source.fileNames = cms.untracked.vstring(
	'file:/cms/tote/jet/reco/mgo{0}_msq{1}.root'.format(msg, msq),
)
# OUTPUT FILES
process.out.fileName = 'test/fatjets_test.root'
output_string = ""
if (process.analyzer.do_true == True):
	output_string += "_true"
if (process.analyzer.do_prune == True):
	output_string += "_pruned"
if (process.analyzer.do_trim == True):
	output_string += "_trimmed_{0}_{1}".format(int(trim_R*10), int(trim_ptf*10))
#process.TFileService.fileName = 'test/test.root'
process.TFileService.fileName = 'test/fatjets_sgtosq_msg{0}_msq{1}_R{2}{3}.root'.format(msg, msq, int(R*10), output_string)
# NUMBER OF EVENTS
process.maxEvents.input = 10000
# REPORTS
process.options.wantSummary = cms.untracked.bool(False)		# Turn off the long job summary.


import numpy as np

def poly_features(X, p):
    # You need to return the following variable correctly.
    X_poly = np.zeros((X.size, p))

    # ===================== Your Code Here =====================
    # Instructions : Given a vector X, return a matrix X_poly where the p-th
    #                column of X contains the values of X to the p-th power.
    #
    # ==========================================================
    X = X.reshape(X.size,1)
    X_poly[:,0] = X[:,0]
    for i in range(1,p):
        X_poly[:,i] = np.power(X_poly[:,0],i+1)
    return X_poly


## BIBLIOTECA ##
from tkinter import *
from tkinter import messagebox
import tkinter as tk

import main
import pokedex
import credits

def Close():
    root.destroy()

def Botao1():
    main()
    return

def Botao2():
    return (pokedex)

def Botao3():
    print(credits)

## MENU ##
root = Tk()
root.geometry("1024x768")

bg = PhotoImage(file="images/background_menu.png")
label1 = Label(root, image=bg)
label1.place(x=0, y=0)

frame1 = Frame(root)
frame1 = Frame(root, bg='#05a5e1')
frame1.pack(pady=200)

# Botões
button1 = Button(frame1, text="Battle Pokemon", relief='raised', overrelief=RIDGE,
                 compound=CENTER, anchor=NW, padx=5, font=('Rockwell 30'), bg='#ed5564', command=Botao1)
button1.pack(pady=5)

button2 = Button(frame1, text="Pokedex", relief='raised', overrelief=RIDGE,
                 compound=CENTER, anchor=NW, padx=5, font=('Rockwell 30'), bg='#ed5564', command=Botao2)
button2.pack(pady=5)

button3 = Button(frame1, text="Credits", relief='raised', overrelief=RIDGE,
                 compound=CENTER, anchor=NW, padx=5, font=('Rockwell 30'), bg='#ed5564', command=Botao3)
button3.pack(pady=5)

button4 = Button(frame1, text="Quit", relief='raised', overrelief=RIDGE,
                 compound=CENTER, anchor=NW, padx=5, font=('Rockwell 30'), bg='#ed5564', command=Close)
button4.pack(pady=5)

frame1.mainloop()


from typing import *

class Solution:
    def largestPerimeter(self, A: List[int]) -> int:
        A.sort()
        for i in range(len(A)-1, 1, -1):
            if A[i-2]+A[i-1] > A[i]:
                return A[i-2]+A[i-1]+A[i]
        return 0

def test(test_name, A, expected):
    res = Solution().largestPerimeter(A)
    print(f'res = {res}')
    if res == expected:
        print(test_name + ' success.')
    else:
        print(test_name + ' failed.')

if __name__ == "__main__":
    A1 = [2,1,2]
    expected1 = 5
    test('test1', A1, expected1)

    A2 = [1,2,1]
    expected2 = 0
    test('test2', A2, expected2)

    A3 = [3,2,3,4]
    expected3 = 10
    test('test3', A3, expected3)

    A4 = [3,6,2,3]
    expected4 = 8
    test('test4', A4, expected4)

# Given an array A of positive lengths,
# return the largest perimeter of a triangle with non-zero area,
# formed from 3 of these lengths.

# If it is impossible to form any triangle of non-zero area, return 0.

# Example 1:

# Input: [2,1,2]
# Output: 5

# Example 2:

# Input: [1,2,1]
# Output: 0

# Example 3:

# Input: [3,2,3,4]
# Output: 10

# Example 4:

# Input: [3,6,2,3]
# Output: 8
#

# Note:

# 3 <= A.length <= 10000
# 1 <= A[i] <= 10^6


import csv
from collections import Counter

with open("SOCR-HeightWeight.csv",newline='') as f:
    reader = csv.reader(f)
    list_data = list(reader)

list_data.pop(0)

whole_data = []
for i in range(len(list_data)):
    full_list = list_data[i][2]
    whole_data.append(float(full_list))     #(correction:you wrote  list_data.append)

#Calculating the mean
length = len(whole_data)
total = 0
for x in whole_data :
    total += x

mean = total/length

print("Mean of weight is -> " + str(mean))

#Calculating the median
whole_data.sort()
if length % 2 == 0:
    median1 = float(whole_data[length//2])
    median2 = float(whole_data[length//2 - 1])
    median = (median1 + median2)/2
else :
    median = whole_data[length//2]

print("Median is -> "+ str(median))

#Calculating the mode
data = Counter(whole_data)
mode_range_of_data = {
    "75-85" : 0,              #Correction(range will come like this because this is for weight not height)
    "85-95" : 0,
    "95-105" : 0
}
for weight, occurence in data.items():       #correction
    if 75 < float(weight) < 85:
        mode_range_of_data["75-85"] += occurence
    elif 85< float(weight) < 95:
        mode_range_of_data["85-95"] += occurence
    elif 95 < float(weight) < 105:
        mode_range_of_data["95-105"] += occurence

mode_range, mode_occurence = 0, 0
for range, occurence in mode_range_of_data.items():      #correction
    if occurence > mode_occurence:
        mode_range, mode_occurence = [int(range.split("-")[0]), int(range.split("-")[1])], occurence
mode = float((mode_range[0] + mode_range[1]) / 2)
print(f"Mode is -> {mode:2f}")