import numpy as np
import pandas as pd
import pandas.testing as pdt
import pytest

from cod_analytics.classes import TransformReference
from cod_analytics.math.homography import Homography, HomographyCorrection

class TestHomography:
    xy_bounds = (-1, 1)
    xy_corners = [
        [-1, -1],
        [1, -1],
        [1, 1],
        [-1, 1],
    ]
    x_bounds = (-1, 1)
    y_bounds = (-2, 2)
    xy_rect_corners = [
        [-1, -2],
        [1, -2],
        [1, 2],
        [-1, 2],
    ]
    translate_bounds = (-5, 5)
    rotate_bounds = (-np.pi, np.pi)
    scale_bounds = (-1, 1)
    center_bounds = (-1, 1)
    size = (100, 2)

    rng = np.random.RandomState(956)
    xy = rng.uniform(*xy_bounds, size=size)
    x = rng.uniform(*x_bounds, size=size[0])
    y = rng.uniform(*y_bounds, size=size[0])
    xy_rect = np.vstack([x, y]).T
    translate = rng.uniform(*translate_bounds, size=2)
    rotate = rng.uniform(*rotate_bounds)
    scale = 2 ** rng.uniform(*scale_bounds)
    center = rng.uniform(*center_bounds, size=2)

    def transform(
        self,
        points: np.ndarray,
        translate: np.ndarray,
        rotate: float,
        scale: float,
        center: np.ndarray,
    ) -> np.ndarray:
        """Transform points using a translation, rotation, and scale."""
        rotate_array = np.array(
            [
                [np.cos(rotate), -np.sin(rotate)],
                [np.sin(rotate), np.cos(rotate)],
            ]
        )
        new_points = points - center
        new_points = new_points * scale
        new_points = new_points @ rotate_array
        new_points = new_points + center
        new_points = new_points + translate
        return new_points

    def test_homography_fitted_method(self) -> None:
        """Test the fitted_method decorator."""
        homography = Homography()

        @homography.fitted_method
        def test_method(self: Homography) -> None:
            pass

        with pytest.raises(RuntimeError):
            test_method(homography)

        homography.fitted = True
        test_method(homography)

    def test_homography_fit(self) -> None:
        """Test the fit method."""
        homography = Homography()
        source = np.array([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]])
        target = np.array([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]])

        homography.fit(source, target)

        assert homography.fitted
        assert np.allclose(homography.matrix, np.eye(3))

    def test_homography_add_correction(self) -> None:
        """Test the add_correction method."""
        homography = Homography()
        correction = HomographyCorrection()
        homography.add_correction(correction)
        assert homography.correction == correction

    @pytest.mark.parametrize("scale", [True, False], ids=["S", "NS"])
    @pytest.mark.parametrize("rotate", [True, False], ids=["R", "NR"])
    @pytest.mark.parametrize("translate", [True, False], ids=["T", "NT"])
    @pytest.mark.parametrize("center", [True, False], ids=["C", "NC"])
    @pytest.mark.parametrize("square", [True, False], ids=["Sq", "Rect"])
    def test_homography_transform(
        self,
        translate: bool,
        rotate: bool,
        scale: bool,
        center: bool,
        square: bool,
    ) -> None:
        """Test the transform method."""
        translate_val = self.translate if translate else np.zeros(2)
        rotate_val = self.rotate if rotate else 0.0
        scale_val = self.scale if scale else 1.0
        center_val = self.center if center else np.zeros(2)

        # Generate XY data
        XY = (self.xy if square else self.xy_rect) + center_val

        corners = np.array(self.xy_corners if square else self.xy_rect_corners)
        transformed_corners = self.transform(
            corners, translate_val, rotate_val, scale_val, center_val
        )
        expected = self.transform(
            XY, translate_val, rotate_val, scale_val, center_val
        )
        homography = Homography()
        homography.fit(corners, transformed_corners)
        XY_transformed = homography.transform(XY)
        assert np.allclose(XY_transformed, expected)

    @pytest.mark.parametrize("scale", [True, False], ids=["S", "NS"])
    @pytest.mark.parametrize("rotate", [True, False], ids=["R", "NR"])
    @pytest.mark.parametrize("translate", [True, False], ids=["T", "NT"])
    @pytest.mark.parametrize("center", [True, False], ids=["C", "NC"])
    @pytest.mark.parametrize("square", [True, False], ids=["Sq", "Rect"])
    def test_homography_transform_reference(
        self,
        translate: bool,
        rotate: bool,
        scale: bool,
        center: bool,
        square: bool,
    ) -> None:
        translate_val = self.translate if translate else np.zeros(2)
        rotate_val = self.rotate if rotate else 0.0
        scale_val = self.scale if scale else 1.0
        center_val = self.center if center else np.zeros(2)

        # Generate XY data
        XY = (self.xy if square else self.xy_rect) + center_val
        left, right = self.xy_bounds if square else self.x_bounds
        bottom, top = self.xy_bounds if square else self.y_bounds
        source = TransformReference(
            map_left=left + center_val[0],
            map_right=right + center_val[0],
            map_bottom=bottom + center_val[1],
            map_top=top + center_val[1],
            map_rotation=0.0,
        )
        corners = np.array(self.xy_corners if square else self.xy_rect_corners)
        corners = corners + np.array([center_val[0], center_val[1]])
        transformed_corners = self.transform(
            corners,
            translate_val,
            rotate_val,
            scale_val,
            center_val,
        )
        transformed_corners_nr = self.transform(
            corners,
            translate_val,
            0.0,
            scale_val,
            center_val,
        )
        new_left, new_right = (
            transformed_corners_nr[:, 0].min(),
            transformed_corners_nr[:, 0].max(),
        )
        new_bottom, new_top = (
            transformed_corners_nr[:, 1].min(),
            transformed_corners_nr[:, 1].max(),
        )
        target = TransformReference(
            map_left=new_left,
            map_right=new_right,
            map_bottom=new_bottom,
            map_top=new_top,
            map_rotation=rotate_val * 180.0 / np.pi,
        )
        homography_expected = Homography()
        homography_expected.fit(corners, transformed_corners)
        expected = homography_expected.transform(XY)
        homography = Homography.from_transform_reference(source, target)
        XY_transformed = homography.transform(XY)
        assert np.allclose(XY_transformed, expected)

    @pytest.mark.parametrize("scale", [True, False], ids=["S", "NS"])
    @pytest.mark.parametrize("rotate", [True, False], ids=["R", "NR"])
    @pytest.mark.parametrize("translate", [True, False], ids=["T", "NT"])
    @pytest.mark.parametrize("center", [True, False], ids=["C", "NC"])
    @pytest.mark.parametrize("square", [True, False], ids=["Sq", "Rect"])
    def test_homography_with_correction(
        self,
        translate: bool,
        rotate: bool,
        scale: bool,
        center: bool,
        square: bool,
    ) -> None:
        translate_val = self.translate if translate else np.zeros(2)
        rotate_val = self.rotate if rotate else 0.0
        scale_val = self.scale if scale else 1.0
        center_val = self.center if center else np.zeros(2)

        # Generate XY data
        XY = (self.xy if square else self.xy_rect) + center_val
        corners = np.array(self.xy_corners if square else self.xy_rect_corners)
        expected = self.transform(
            XY, translate_val, rotate_val, scale_val, center_val
        )
        correction = HomographyCorrection(
            translate=translate_val,
            rotate=rotate_val,
            scale=scale_val,
            center=center_val,
        )
        homography = Homography()
        homography.fit(corners, corners)
        homography.add_correction(correction)
        XY_transformed = homography.transform(XY)
        assert np.allclose(XY_transformed, expected)

    @pytest.mark.parametrize("scale", [True, False], ids=["S", "NS"])
    @pytest.mark.parametrize("rotate", [True, False], ids=["R", "NR"])
    @pytest.mark.parametrize("translate", [True, False], ids=["T", "NT"])
    @pytest.mark.parametrize("center", [True, False], ids=["C", "NC"])
    @pytest.mark.parametrize("square", [True, False], ids=["Sq", "Rect"])
    @pytest.mark.parametrize("n", [0, 1, 2, 5, 10])
    def test_homography_transform_df(
        self,
        translate: bool,
        rotate: bool,
        scale: bool,
        center: bool,
        square: bool,
        n: int,
    ) -> None:
        """Test the transform_df method."""
        translate_val = self.translate if translate else np.zeros(2)
        rotate_val = self.rotate if rotate else 0.0
        scale_val = self.scale if scale else 1.0
        center_val = self.center if center else np.zeros(2)

        # Generate XY data
        k = n if n > 0 else 1
        if square:
            xy_data = self.rng.uniform(
                *self.xy_bounds, size=(self.size[0], self.size[1] * k)
            ) + np.tile(center_val, k)
        else:
            x_data = self.rng.uniform(*self.x_bounds, size=(self.size[0], k))
            y_data = self.rng.uniform(*self.y_bounds, size=(self.size[0], k))
            # Interleave x and y data
            xy_data = np.empty((self.size[0], self.size[1] * k))
            xy_data[:, ::2] = x_data + center_val[0]
            xy_data[:, 1::2] = y_data + center_val[1]

        corners = np.array(self.xy_corners if square else self.xy_rect_corners)
        transformed_corners = self.transform(
            corners, translate_val, rotate_val, scale_val, center_val
        )

        if n == 0:
            labels: list[str] | list[list[str]] = ["x", "y"]
            flat_labels = ["x", "y"]
        else:
            labels = [[f"x_{i}", f"y_{i}"] for i in range(n)]
            flat_labels = [item for sublist in labels for item in sublist]

        df = pd.DataFrame(xy_data, columns=flat_labels)
        homography = Homography()
        homography.fit(corners, transformed_corners)
        df_transformed = homography.transform_dataframe(df, labels)

        if n == 0:
            expected = self.transform(
                xy_data, translate_val, rotate_val, scale_val, center_val
            )
            assert np.allclose(df_transformed.values, expected)
        else:
            for i in range(n):
                k = i * 2
                expected = self.transform(
                    xy_data[:, k : k + 2],
                    translate_val,
                    rotate_val,
                    scale_val,
                    center_val,
                )
                assert np.allclose(
                    df_transformed.iloc[:, k : k + 2].values, expected
                )


import importlib
import io
import math
import os
import typing
from enum import Enum

import discord
import humanize
from discord.ext import commands
from jishaku.functools import executor_function
from PIL import Image

import common.image_utils as image_utils
import common.utils as utils

class ImageCMDs(commands.Cog, name="Image"):
    """A series of commands for manipulating images in certain ways."""

    def __init__(self, bot):
        self.bot: utils.SeraphimBase = bot

    def get_size(self, image: io.BytesIO):
        old_pos = image.tell()
        image.seek(0, os.SEEK_END)
        size = image.tell()
        image.seek(old_pos, os.SEEK_SET)

        return size

    @executor_function
    def pil_compress(self, image, ext, flags):
        try:
            pil_image = Image.open(image)
            compress_image = io.BytesIO()

            if (
                flags.ori_ext in ("gif", "webp")
                and ext not in ("gif", "webp")
                and pil_image.is_animated
            ):
                raise commands.BadArgument(
                    "Cannot convert an animated image to this file type!"
                )

            if flags.shrink:
                width = pil_image.width
                height = pil_image.height

                if width > 1920 or height > 1920:
                    bigger = max(width, height)
                    factor = math.ceil(bigger / 1920)
                    pil_image = pil_image.reduce(factor=factor)

            if ext == "jpeg":
                if pil_image.mode != "RGB":
                    pil_image = pil_image.convert("RGB")
                pil_image.save(
                    compress_image, format=ext, quality=flags.quality, optimize=True
                )
            elif ext in ("gif", "png"):
                pil_image.save(compress_image, format=ext, optimize=True)
            elif ext == "webp":
                pil_image.save(
                    compress_image,
                    format=ext,
                    minimize_size=True,
                    quality=flags.quality,
                )
            else:
                compress_image.close()
                raise commands.BadArgument("Invalid file type!")

            compress_image.seek(0, os.SEEK_SET)

            return compress_image

        except:
            compress_image.close()
            raise
        finally:
            pil_image.close()

    @executor_function
    def pil_resize(
        self,
        image,
        ext,
        percent: typing.Optional[float],
        width: typing.Optional[int],
        height: typing.Optional[int],
        filter: int,
    ):
        resized_image = io.BytesIO()

        try:
            pil_image = Image.open(image)

            ori_width = pil_image.width
            ori_height = pil_image.height

            if percent:
                new_width = math.ceil(pil_image.width * (percent / 100))
                new_height = math.ceil(pil_image.height * (percent / 100))
            elif bool(width) ^ bool(height):
                if width:
                    new_width = width
                    percent = width / pil_image.width
                    new_height = math.ceil(pil_image.height * percent)
                else:
                    new_height = height
                    percent = height / pil_image.height
                    new_width = math.ceil(pil_image.width * percent)
            else:
                new_width = width
                new_height = height

            pil_image = pil_image.resize((new_width, new_height), filter)

            pil_image.save(resized_image, format=ext)
            resized_image.seek(0, os.SEEK_SET)

            return resized_image, ori_width, ori_height, new_width, new_height
        except:
            resized_image.close()
            raise
        finally:
            pil_image.close()

    class ImageFilters(Enum):
        # what Pillow should have done
        NEAREST = 0
        NONE = 0
        BOX = 4
        BILINEAR = 2
        LINEAR = 2
        HAMMING = 5
        BICUBIC = 3
        CUBIC = 3
        LANCZOS = 1
        ANTIALIAS = 1

    def str_to_filter(self, argument: str):
        try:
            return self.ImageFilters[argument.upper()].value
        except KeyError:
            raise commands.BadArgument(f"Invalid filter `{argument}` provided!")

    class CompressFlags(commands.FlagConverter):
        # TODO: move flag checks into a flag converter thing
        shrink: bool = True
        format: str = "default"
        quality: int = 70

    @commands.command(aliases=["image_compress"])
    async def img_compress(
        self, ctx, url: typing.Optional[image_utils.URLToImage], *, flags: CompressFlags
    ):
        """Compresses down the image given.
        It must be an image of type GIF, JPG, PNG, or WEBP. It must also be under 8 MB.
        Image quality will take a hit, and the image will shrink down if it's too big (unless you specify to not shrink the image).
        Flags:
        shrink: <true/false> (specifies to shrink the image - it will by default)
        format: <format> (converts the image to the specified format, and it must be 'gif, jpg, png, or webp' \
        - the resulting image will be in the same format as the original by default)
        quality: <number> (specifies quality from 0-100, only works with JPG and WEBP files, default is 70)"""

        if flags.format == "default":
            img_format = "default"
        else:
            img_type_checker = image_utils.ImageTypeChecker
            img_format = await img_type_checker.convert(
                img_type_checker, ctx, flags.format
            )

        if not 0 <= flags.quality <= 100:
            raise commands.BadArgument("Quality must be a number between 0-100!")

        if not url:
            url = image_utils.image_from_ctx(ctx)

        async with ctx.channel.typing():
            image_data = await image_utils.get_file_bytes(
                url, 8388608, equal_to=False
            )  # 8 MiB

            try:
                ori_image = io.BytesIO(image_data)

                mimetype = discord.utils._get_mime_type_for_image(image_data)
                ext = mimetype.split("/")[1]
                flags.ori_ext = ext  # yes, this is dirty

                if img_format != "default":
                    ext = img_format

                ori_size = self.get_size(ori_image)
                compress_image = await self.pil_compress(ori_image, ext, flags)
                compressed_size = self.get_size(compress_image)

            finally:
                del image_data
                if ori_image:
                    ori_image.close()

            try:
                com_img_file = discord.File(compress_image, f"image.{ext}")

                content = (
                    f"Original Size: {humanize.naturalsize(ori_size, binary=True)}\n"
                    + "Reduced Size:"
                    f" {humanize.naturalsize(compressed_size, binary=True)}\n"
                    + "Size Saved:"
                    f" {round(((1 - (compressed_size / ori_size)) * 100), 2)}%"
                )
            except:
                compress_image.close()
                raise

        await ctx.reply(content=content, file=com_img_file)

    class ConvertFlags(commands.FlagConverter):
        shrink: bool = False
        quality: int = 80

    @commands.command(aliases=["image_convert"])
    async def img_convert(
        self,
        ctx,
        url: typing.Optional[image_utils.URLToImage],
        img_type: image_utils.ImageTypeChecker,
        *,
        flags: ConvertFlags,
    ):
        """Converts the given image into the specified image type.
        Both the image and the specified image type must be of type GIF, JP(E)G, PNG, or WEBP. The image must also be under 8 MB.
        Flags:
        shrink: <true/false> (specifies to shrink the image - it won't by default)
        quality: <number> (specifies quality from 0-100, only works with JPG and WEBP files, default is 80)
        """

        if not 0 <= flags.quality <= 100:
            raise commands.BadArgument("Quality must be a number between 0-100!")

        if not url:
            url = image_utils.image_from_ctx(ctx)

        async with ctx.channel.typing():
            image_data = await image_utils.get_file_bytes(
                url, 8388608, equal_to=False
            )  # 8 MiB

            try:
                ori_image = io.BytesIO(image_data)

                mimetype = discord.utils._get_mime_type_for_image(image_data)
                flags.ori_ext = mimetype.split("/")[1]
                ext = img_type

                converted_image = await self.pil_compress(ori_image, ext, flags)
            finally:
                del image_data
                if ori_image:
                    ori_image.close()

            try:
                convert_img_file = discord.File(converted_image, f"image.{ext}")
            except:
                converted_image.close()
                raise

        await ctx.reply(file=convert_img_file)

    class ResizeFlags(commands.FlagConverter):
        percent: typing.Optional[float]
        width: typing.Optional[int]
        height: typing.Optional[int]
        filter: str = "BILINEAR"

    @commands.command(aliases=["image_resize"])
    async def img_resize(
        self, ctx, url: typing.Optional[image_utils.URLToImage], *, flags: ResizeFlags
    ):
        """Resizes the image as specified by the flags.
        The image must be of type GIF, JP(E)G, PNG, or WEBP. The image must also be under 8 MB.

        Required flags (one of these three must be present):
        percent: <percent> (specifies the percent to reduce it to - whole numbers with no %, like '50', please.)
        width: <width> (specifies the width to reduce it to - it must be a whole number and greater than 0.)
        height: <height> (specifies the height to reduce it to - it must be a whole number and greater than 0.)

        Optional flags:
        filter: <filter> (specifies which resampling filter to use while downsizing - see \
        https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-filters for the filters and which \
        one is best for you. Default is Bilinear.)
        """

        filter = self.str_to_filter(flags.filter)

        if not url:
            url = image_utils.image_from_ctx(ctx)

        if not (flags.percent or flags.width or flags.height):
            raise commands.BadArgument("No resizing arguments passed!")

        if flags.percent and (flags.width or flags.height):
            raise commands.BadArgument(
                "You cannot have a percentage and a width/height at the same time!"
            )

        if flags.percent and flags.percent <= 0:
            raise commands.BadArgument("The percent must be greater than 0!")

        if flags.width and flags.width <= 0:
            raise commands.BadArgument("The width must be greater than 0!")

        if flags.height and flags.height <= 0:
            raise commands.BadArgument("The height must be greater than 0!")

        async with ctx.channel.typing():
            image_data = await image_utils.get_file_bytes(
                url, 8388608, equal_to=False
            )  # 8 MiB

            try:
                ori_image = io.BytesIO(image_data)

                mimetype = discord.utils._get_mime_type_for_image(image_data)
                ext = mimetype.split("/")[1]

                (
                    resized_image,
                    ori_width,
                    ori_height,
                    new_width,
                    new_height,
                ) = await self.pil_resize(
                    ori_image,
                    ext,
                    flags.percent,
                    flags.width,
                    flags.height,
                    filter,
                )
                resize_size = self.get_size(resized_image)

                if resize_size > 8388608:
                    resized_image.close()
                    del resized_image
                    raise commands.BadArgument("Resulting image was over 8 MiB!")
            finally:
                del image_data
                if ori_image:
                    ori_image.close()

            try:
                resized_img_file = discord.File(resized_image, f"image.{ext}")

                content = (
                    f"Original Image Dimensions: {ori_width}x{ori_height}\n"
                    + f"New Image Dimensions: {new_width}x{new_height}\n"
                    + "Resized To:"
                    f" {flags.percent or round(((new_width / ori_width) * 100), 2)}%\n"
                    + "New Image Size:"
                    f" {humanize.naturalsize(resize_size, binary=True)}"
                )
            except:
                resized_image.close()
                raise

        await ctx.reply(content=content, file=resized_img_file)

async def setup(bot):
    importlib.reload(utils)
    importlib.reload(image_utils)

    await bot.add_cog(ImageCMDs(bot))


"""
填充每个节点的下一个右侧节点指针 II
"""

"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

# 1
class Solution:
    def connect(self, root: 'Node') -> 'Node':
        head = root
        while head:
            cur = head
            pre = head = None
            while cur:
                if cur.left:
                    if not pre:
                        pre = head =cur.left
                    else:
                        pre.next = cur.left
                        pre = pre.next
                if cur.right:
                    if not pre:
                        pre = head = cur.right
                    else:
                        pre.next = cur.right
                        pre = pre.next
                cur = cur.next
        return root

# 2
class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if root is None:
            return root

        def BFS(oneLayer):
            nextLayer = []
            for node in oneLayer:
                if node.left:
                    nextLayer.append(node.left)
                if node.right:
                    nextLayer.append(node.right)
            if len(nextLayer) > 1:
                for i in range(len(nextLayer) - 1):
                    nextLayer[i].next = nextLayer[i + 1]
            if nextLayer:
                BFS(nextLayer)
        BFS([root])
        return root

# 3
class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if root is None:
            return root

        def bfs(one_layer):
            next_layer = []
            for node in one_layer:
                if node.left:
                    next_layer.append(node.left)
                if node.right:
                    next_layer.append(node.right)
            if next_layer:
                for i in range(len(next_layer) - 1):
                    next_layer[i].next = next_layer[i + 1]
                bfs(next_layer)
        bfs([root])
        return root

# 4
class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if root is None:
            return root

        def bfs(one_layer):
            next_layer = []
            for node in one_layer:
                if node.left:
                    next_layer.append(node.left)
                if node.right:
                    next_layer.append(node.right)
            if next_layer:
                for i in range(len(next_layer) - 1):
                    next_layer[i].next = next_layer[i + 1]
                bfs(next_layer)
        bfs([root])
        return root

刷题狂魔/Week04/填充每个节点的下一个右侧节点指针 II.py

填充每个节点的下一个右侧节点指针 II.py


from django import forms
from django.contrib import admin

from .models import Category, Comment, Genre, Review, Title, User

EMPTY = '-пусто-'

class UserAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserAdminForm, self).__init__(*args, **kwargs)
        self.fields['password'].widget = forms.PasswordInput()

    class Meta:
        model = User
        fields = '__all__'

@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    list_display = (
        'username', 'email', 'first_name', 'last_name', 'role',
        'is_superuser', 'is_staff', 'date_joined',
    )
    empty_value_display = EMPTY
    form = UserAdminForm

@admin.register(Title)
class TitleAdmin(admin.ModelAdmin):
    list_display = ('pk', 'name', 'year', 'description', 'category')
    list_editable = ('category',)
    search_fields = ('name', 'description')
    empty_value_display = EMPTY

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('pk', 'name', 'slug')
    empty_value_display = EMPTY

@admin.register(Genre)
class GenreAdmin(admin.ModelAdmin):
    list_display = ('pk', 'name', 'slug')
    empty_value_display = EMPTY

@admin.register(Review)
class ReviewAdmin(admin.ModelAdmin):
    list_display = ('pk', 'title', 'text', 'author', 'pub_date')
    empty_value_display = EMPTY

@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    list_display = ('pk', 'text', 'author', 'review', 'pub_date')
    empty_value_display = EMPTY
    search_fields = ('text',)
    list_filter = ('pub_date',)


import pandas as pd
import pathlib
from model import toa

datadir = pathlib.Path(__file__).parents[0].joinpath('data')

def test_toa_per_region():
    # we use a modified version of the silvopasture TLA data as mock TLA values
    sp_land_dist_all = [331.702828, 181.9634517, 88.98630743, 130.15193962, 201.18287123,
                        0.,  # new ABNJ region
                        933.98739798, 37.60589239, 7.02032552, 43.64118779, 88.61837725]
    index = pd.Index(
        ['OECD90', 'Eastern Europe', 'Asia (Sans Japan)', 'Middle East and Africa', 'Latin America', 'ABNJ', 'Global',
         'China', 'India', 'EU', 'USA'])
    ocean_dist = pd.DataFrame(sp_land_dist_all, columns=['All'], index=index)
    expected = pd.read_csv(datadir.joinpath('sp_tla_with_abnj.csv'), index_col=0)
    result = toa.toa_per_region(ocean_dist=ocean_dist)
    pd.testing.assert_frame_equal(expected, result, check_dtype=False)


import pickle
import numpy as np

d = np.load('data/models_data.npz')
rr = d['rr']
cs = d['cs']
omb2 = d['omb2']
oma = d['oma']
rsun = d['rsun']

nx = len(rr)

e = np.load('data/return_radius.npz')
om = e['om']
rt = e['rt']

#lt = 42 # spherical harmonic degree

delta_theta = np.zeros(len(rt))

th_ray_list = []
rr_ray_list = []

for lt in range(1,len(rt)+1):
    kh2 = lt*(lt+1)/rr**2
    kh = np.sqrt(kh2)
    kr2 = (om**2 - oma**2)/cs**2 + lt*(lt+1)/rr**2*(omb2 - om**2)/om**2
    ff = kh/rr*(1-omb2/om**2)
    gg = kr2
    rtt = rt[lt-1]
    nt = np.argmin(abs(rtt-rr))

    th_ray = np.zeros(nx-nt)
    rr_ray = np.zeros(nx-nt)
    for n in range(nt,nx):
        gg1 = gg[n]
        gg2 = gg[n+1]
        dgg = gg2 - gg1
        ff1 = ff[n]
        ff2 = ff[n+1]
        dff = ff2 - ff1
        drr = rr[n+1] - rr[n]
        ep = dgg/gg1

        if gg1 > 0 and gg2 > 0:
            if abs(ep) >= 0.01:
                I0 = gg1**(-0.5)*2/ep*((1+ep)**(0.5) - 1)
                I1 = gg1**(-0.5)*4/3/ep**2*(1-(1-ep/2)*(1+ep)**0.5)
            else:
                I0 = gg1**(-0.5)*(1-ep/4+ep**2/8)
                I1 = gg1**(-0.5)*0.5*(1-ep/3+3*ep**2/16)

        else:
            if gg1 < 0:
                # gg1 < 0 and gg2 > 0
                I0 = 2*gg2**0.5/dgg
                I1 = 2*(gg2-3*gg1)*gg2**0.5/3/dgg**2
            else:
                # gg1 > 0 and gg2 < 0
                I0 = -2*gg1**0.5/dgg
                I1 = 4*gg1**1.5/3/dgg**2

        rr_ray[n-nt+1] = rr[n+1]
        if n == nt:
            th_ray[n-nt] = 0
            rr_ray[n-nt] = rr[n] - (rr[n+1]-rr[n])*gg1/dgg

        th_ray[n-nt+1] = th_ray[n-nt] + drr*(ff1*I0 + dff*I1)

        if gg1 > 0 and gg2 < 0:
            ns = n-nt+1
            break

    print(lt,th_ray.max()*2/np.pi*180,rtt/rsun)
    th_ray = th_ray[:ns+1]
    rr_ray = rr_ray[:ns+1]

    th_rayf = np.zeros(2*ns+1)
    rr_rayf = np.zeros(2*ns+1)

    th_rayf[:ns+1] = -np.flip(th_ray)
    rr_rayf[:ns+1] =  np.flip(rr_ray)

    th_rayf[ns+1:2*ns+1] = th_ray[1:ns+1]
    rr_rayf[ns+1:2*ns+1] = rr_ray[1:ns+1]

    th_ray_list.append(th_rayf)
    rr_ray_list.append(rr_rayf)
    delta_theta[lt-1] = th_ray.max()*2

np.savez('data/ray_calc.npz',delta_theta=delta_theta)
f = open('data/ray_calc_th_ray.npz','wb')
pickle.dump(th_ray_list,f)
f.close()

f = open('data/ray_calc_rr_ray.npz','wb')
pickle.dump(rr_ray_list,f)
f.close()

#plt.close('all')
#fig = plt.figure('frequency',figsize=(5,5))
#ax = fig.add_subplot(111,aspect='equal')

#x,y = rr_rayf/rsun*cos(th_rayf - th_rayf[0]), rr_rayf/rsun*sin(th_rayf - th_rayf[0])
#ax.plot(x, y,color='black',linestyle='--')
#c = patches.Circle(xy=(0, 0), radius=1, ec='black')
#ax.add_patch(c)

#ax11.plot(pr, omb2,color='black')
#ax11.plot(pr,-omb2,color='black',linestyle='--')

#ax11.plot(pr, oma**2,color=orange)

#ax11.set_xscale('log')
#ax11.set_yscale('log')

#np.savez('models_cs.npz',rr=rr,cs=cs,rsun=rsun)


from itertools import product
from random import choice
from time import sleep
from os import system
from math import floor
from colorama import Back, Fore, Style

################################################################################
# Simulation of Conway's Game of Life. The goal here was to write this with a
# small amount of code as a proof-of-concept that could be run in the terminal.
#
# If you'd like to tinker with the rules, see the conditionals defined in the
# `advance/1` function. For other parameters, like the board size and refresh
# rate, refer to the while-loop defined at the bottom of this file.
################################################################################

def init_board(n, init_alive_percentage):
    """Initialize a board of size `n` by `n`. Supply a percentage,
    `init_alive_percentage`, representing the number of cells in the board that
    should be alive from the start."""
    alive_count = floor(n * init_alive_percentage)
    distribution = [True] * alive_count + [False] * (n - alive_count)
    return [[choice(distribution) for _ in range(n)] for _ in range(n)]

def neighbors(coord, board):
    """Return the neighbors for a given `coord` on a `board`."""
    n = len(board)
    row, col = coord
    return [
        board[(row + row_d) % n][(col + col_d) % n]
        for row_d, col_d in product([-1, 0, 1], [-1, 0, 1])
        if (row_d, col_d) != (0, 0)
    ]

def advance(board):
    """Advance the state of the `board` from T[n] to T[n+1]."""
    n = len(board)
    new_board = [[False for _ in range(n)] for _ in range(n)]
    for row in range(n):
        for col in range(n):
            alive_count = len([x for x in neighbors((row, col), board) if x])
            # Loneliness
            if alive_count == 0:
                new_board[row][col] = False
            # Status Quo
            elif alive_count == 1:
                new_board[row][col] = board[row][col]
            # Cooperation
            elif alive_count == 2:
                new_board[row][col] = True
            # Resource starvation
            elif alive_count >= 3:
                new_board[row][col] = False
    return new_board

def print_board(board):
    """Print the game `board` in a human-readable way."""
    result = ''
    for row in board:
        for col in row:
            if col:
                result += Back.GREEN + '1 ' + Style.RESET_ALL
            else:
                result += Back.RED + '0 ' + Style.RESET_ALL
        result += '\n'
    print(result)

board = init_board(100, 0.50)
while True:
    system('clear')
    print_board(board)
    sleep(0.15)
    board = advance(board)


import webbrowser, os
import json
import boto3
import io
from io import BytesIO
import sys
from pprint import pprint
from dotenv import load_dotenv
import pandas as pd

load_dotenv()

AWSSecretKey = os.getenv('AWSSecretKey')
AWSAccessKeyId = os.getenv('AWSAccessKeyId')

def get_rows_columns_map(table_result, blocks_map):
    rows = {}
    for relationship in table_result['Relationships']:
        if relationship['Type'] == 'CHILD':
            for child_id in relationship['Ids']:
                cell = blocks_map[child_id]
                if cell['BlockType'] == 'CELL':
                    row_index = cell['RowIndex']
                    col_index = cell['ColumnIndex']
                    if row_index not in rows:
                        # create new row
                        rows[row_index] = {}

                    # get the text value
                    rows[row_index][col_index] = get_text(cell, blocks_map)
    return rows

def get_text(result, blocks_map):
    text = ''
    if 'Relationships' in result:
        for relationship in result['Relationships']:
            if relationship['Type'] == 'CHILD':
                for child_id in relationship['Ids']:
                    word = blocks_map[child_id]
                    if word['BlockType'] == 'WORD':
                        text += word['Text'] + ' '
                    if word['BlockType'] == 'SELECTION_ELEMENT':
                        if word['SelectionStatus'] =='SELECTED':
                            text +=  'X '
    return text

def get_table_csv_results(file_name):

    with open(file_name, 'rb') as file:
        img_test = file.read()
        bytes_test = bytearray(img_test)

    # process using image bytes
    # get the results
    client = boto3.client('textract', aws_access_key_id = AWSAccessKeyId,
            aws_secret_access_key = AWSSecretKey,
            region_name = 'ap-south-1')

    response = client.analyze_document(Document={'Bytes': bytes_test}, FeatureTypes=['TABLES'])

    # Get the text blocks
    blocks=response['Blocks']

    blocks_map = {}
    table_blocks = []
    for block in blocks:
        blocks_map[block['Id']] = block
        if block['BlockType'] == "TABLE":
            table_blocks.append(block)

    if len(table_blocks) <= 0:
        return "<b> NO Table FOUND </b>"

    csv = ''
    for index, table in enumerate(table_blocks):
        csv = generate_table_csv(table, blocks_map, index +1)

    return csv

def generate_table_csv(table_result, blocks_map, table_index):
    rows = get_rows_columns_map(table_result, blocks_map)

    columns = []
    entity = []
    obs = []
    unit = []
    interval = []

    for row_index, cols in rows.items():
        if row_index == 1:
            for col_index, text in cols.items():
                columns.append(text.strip())
        else:
            entity.append(cols[1].strip())
            if cols[2] == '':
                obs.append(-1)
            else:
                cols[2] = cols[2].replace(',', '')
                obs.append(float(cols[2]))
            unit.append(cols[3].strip())
            if cols[4] == '':
                interval.append(-1)
            else:
                interval.append(cols[4].strip())

    data = {
        columns[0] : entity,
        columns[1] : obs,
        columns[2] : unit,
        columns[3] : interval
    }

    df = pd.DataFrame(data)
    return df

def analysis(df):
    anomalies = {}
    columns = df.columns
    for i in range(len(df)):
        parameter = df.loc[i, columns[0]]
        observed = df.loc[i, columns[1]]
        limits = df.loc[i, columns[3]]
        vals = []
        if int(observed) == -1 and int(limits) == -1:
            pass
        else:
            limits = limits.split("-")
            max_limit = float(limits[1])
            min_limit = float(limits[0])
            adj_max = float(max_limit/0.9)
            adj_min = float(((min_limit/adj_max) - 0.1)*adj_max)
            if float(observed) < adj_min:
                vals.append("low")
                vals.append(1)
            elif float(observed) > adj_max:
                vals.append("high")
                vals.append(1)
            elif float(observed) < adj_max and float(observed) > max_limit:
                vals.append("high")
                vals.append(0)
            elif float(observed) > adj_min and float(observed) < min_limit:
                vals.append("low")
                vals.append(0)
        if vals != []:
            anomalies[parameter] = vals
    return anomalies

# def getPriorityValue(word, priority_list):
#   for key in priority_list:
#     if word == key:
#       return priority_list.get(key).get('priority')
#   for i in priority_list.keys():
#     if type(priority_list.get(i)) == list:
#       sub_list = priority_list.get(i)[0]
#       for key in sub_list:
#         if word == key:
#           return sub_list.get(key).get('priority')
#   return 6

# def getPriority(output, priority_list):
#   key_dict = list(output.keys())
#   final_list = []
#   final_priority = 5
#   for i in key_dict:
#     val = getPriorityValue(i, priority_list)
#     print(final_list)
#     if val < final_priority:
#       final_priority = val
#       final_list.clear()
#       final_list.append(i)
#     elif val == final_priority:
#       final_list.append(i)
#   return final_list

# def getAnalysis(result_list, output, report_list):
#   for i in result_list:
#     rep_list = report_list.get(i)
#     if rep_list == None:
#       for j in report_list.keys():
#         if type(report_list.get(j)) == list:
#           sub_list = report_list.get(j)[0]
#           for key in sub_list:
#             if i == key:
#               rep_list = sub_list.get(key)
#     print(rep_list)
#     output_value = output.get(i)
#     output_list = rep_list.get(output_value[0])
#     output_remedy = rep_list.get("remedy_" + output_value[0])
#     if output_value[1] == 1:
#       print("you need to visit a " + output_list[1])
#     if output_list[0]:
#       print(output_list[0])
#     print("Remedy: ", output_remedy)

def getAnalysis(output, report_list, priority_list):
  result_list = list(output.keys())
  final_dict = {}
  high_priority_dict = {}
  high_pri = 6
  for i in result_list:
    rep_list = report_list.get(i)
    if rep_list != None:
      priority = priority_list.get(i)
      rep_list['priority'] = priority['priority']
      final_dict[i] = rep_list
      if priority['priority'] < high_pri:
        high_pri = priority['priority']
        high_priority_dict.clear()
        high_priority_dict[i] = rep_list
      elif priority['priority'] == high_pri:
        high_priority_dict[i] = rep_list
  print("Final list of all: ", final_dict)
  print("Highest priority: ", high_priority_dict)

def main(file_name):
    table_csv = get_table_csv_results(file_name)
    anomalies = analysis(table_csv)
    print(anomalies)
    #Sample Output:
    output = {'Eosinophils ': ['high', 1], 'MPV (Mean Platelet Volume) ': ['high', 0]}

    f = open('../../Report Analysis/analysis.json')
    report_list = json.load(f)
    print(report_list)
    f.close()
    g = open('../../Report Analysis/priority.json')
    priority_list = json.load(g)
    print(priority_list)
    g.close()

    # result_list = getPriority(output, priority_list)
    # getAnalysis(result_list, output, report_list)

    getAnalysis(output, report_list, priority_list)

if __name__ == "__main__":
    file_name = sys.argv[1]
    main(file_name)


n = int(input())
s = [input() for _ in range(n)]

s_dict = dict()
s_max = 0

for i in s:
    if i not in s_dict:
        s_dict[i] = 1
        s_max = max(s_max, s_dict[i])
    else:
        s_dict[i] += 1
        s_max = max(s_max, s_dict[i])

ans = list()
for k, v in s_dict.items():
    if v == s_max:
        ans.append(k)

ans.sort()
for i in ans:
    print(i)


'''
如果你是哈利·波特迷，你会知道魔法世界有它自己的货币系统 —— 就如海格告诉哈利的：“十七个银西可(Sickle)兑一个加隆(Galleon)，二十九个纳特(Knut)兑一个西可，很容易。”现在，给定哈利应付的价钱 P 和他实付的钱 A，你的任务是写一个程序来计算他应该被找的零钱。
输入格式：

输入在 1 行中分别给出 P 和 A，格式为 Galleon.Sickle.Knut，其间用 1 个空格分隔。这里 Galleon 是 [0, 107] 区间内的整数，Sickle 是 [0, 17) 区间内的整数，Knut 是 [0, 29) 区间内的整数。
输出格式：

在一行中用与输入同样的格式输出哈利应该被找的零钱。如果他没带够钱，那么输出的应该是负数。
输入样例 1：

10.16.27 14.1.28

输出样例 1：

3.2.1

输入样例 2：

14.1.28 10.16.27

输出样例 2：

-3.2.1

'''

#####################################################
'''
非常简单的题目
'''
#####################################################

P, A = [i.split('.') for i in input().split()]
P = 29 * 17 * int(P[0]) + 29 * int(P[1]) + int(P[2])
A = 29 * 17 * int(A[0]) + 29 * int(A[1]) + int(A[2])
Waste = A - P
if Waste >= 0:
    flag = True
else:
    flag = False
    Waste = -Waste
Knut = Waste % (17 * 29) % 29
Gallen = Waste // (29 * 17)
Sickle = Waste % (17 * 29) // 29
if not flag:
    print('-',end='')
print(Gallen,Sickle,Knut,sep='.')

1037 在霍格沃茨找零钱.py

1037 在霍格沃茨找零钱.py


import time
from datetime import datetime
import webbrowser

from PySide2.QtSvg import QSvgRenderer

from PySide2.QtCore import Qt, QSize, QRect, QPoint
from PySide2.QtGui import QIcon, QPixmap, QColor, QPainter, QImage, QMouseEvent, QFont, QFontMetrics, QPen, QBrush
from PySide2.QtWidgets import QMainWindow, QHBoxLayout, QVBoxLayout, QPushButton, QGridLayout, QColorDialog, \
    QComboBox, QLabel, QDoubleSpinBox, QDialog, QCheckBox, QFrame, QApplication, QLineEdit, QFileDialog, QMenuBar, \
    QMenu, QAction, QTreeWidget, QTreeWidgetItem, QTreeWidgetItemIterator, QTabWidget, QWidget, QListWidget, \
    QListWidgetItem, QScrollBar
from maya import OpenMayaUI, cmds
import shiboken2
from functools import partial
import json
import os
from maya.api.OpenMaya import MMatrix, MEventMessage
from maya.app.general.mayaMixin import MayaQWidgetDockableMixin

dpiF = QApplication.desktop().logicalDpiX() / 96.0

def getMayaMainWindow():
    pointer = OpenMayaUI.MQtUtil.mainWindow()
    return shiboken2.wrapInstance(int(pointer), QMainWindow)

def createSeparator():
    separator = QFrame()
    separator.setFrameShape(QFrame.HLine)
    separator.setFrameShadow(QFrame.Sunken)
    return separator

def clamp(minimum, val, maximum):
    return max(minimum, min(val, maximum))

class SelectByNameLine(QLineEdit):

    def __init__(self, *args, **kwargs):
        super(SelectByNameLine, self).__init__(*args, **kwargs)

        self.history = list()
        self.index = -1

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Up:
            event.accept()
            try:
                txt = self.history[self.index + 1]
                self.index += 1
                self.setText(txt)
            except IndexError:
                pass

        elif event.key() == Qt.Key_Down:
            event.accept()
            newIndex = self.index - 1
            if newIndex >= 0:
                txt = self.history[newIndex]
                self.index = newIndex
            else:
                txt = ''
                self.index = -1
            self.setText(txt)

        elif event.key() == Qt.Key_Return:
            event.accept()
            self.index = -1
            self.history.insert(0, self.text())
            self.select()
            self.setText('')

        else:
            super(SelectByNameLine, self).keyPressEvent(event)

    def select(self):
        rawInput = self.text()

        name_filters = list()
        inverse_name_filters = list()

        type_filters = list()
        inverse_type_filters = list()

        for input_ in rawInput.split(','):
            flt = input_.strip()
            if '#' in flt:
                flt = flt.replace('#', '')
                if '!' in flt:
                    flt = flt.replace('!', '')
                    inverse_type_filters.append(flt)
                else:
                    type_filters.append(flt)

            else:
                if '!' in flt:
                    flt = flt.replace('!', '')
                    inverse_name_filters.append(flt)
                else:
                    name_filters.append(flt)

        name_filtered = cmds.ls(*name_filters, recursive=True) if name_filters else list()
        inverse_name_filtered = cmds.ls(*inverse_name_filters, recursive=True) if inverse_name_filters else list()
        name_set = set(name_filtered).difference(inverse_name_filtered)

        type_filtered = cmds.ls(type=type_filters, recursive=True) if type_filters else list()
        inverse_type_filtered = cmds.ls(type=inverse_type_filters, recursive=True) if inverse_type_filters else list()
        type_set = set(type_filtered).difference(inverse_type_filtered)

        if (name_filters + inverse_name_filters) and (type_filters + inverse_type_filters):
            final_set = name_set.intersection(type_set)
        elif (name_filters + inverse_name_filters) and not (type_filters + inverse_type_filters):
            final_set = name_set
        elif not (name_filters + inverse_name_filters) and (type_filters + inverse_type_filters):
            final_set = type_set
        else:
            final_set = set()

        cmds.select(list(final_set), noExpand=True)

class IconWidget(QWidget):

    images = dict()

    def __init__(self, node, parent):
        super(IconWidget, self).__init__(parent)

        nodeType = cmds.objectType(node)
        shapes = cmds.listRelatives(node, shapes=True, fullPath=True) if nodeType != 'objectSet' else None
        shapType = cmds.objectType(shapes[0]) if shapes else None

        self.type = nodeType if not shapType else shapType
        self.isShape = cmds.objectType(node, isAType='shape')
        self.isReferenced = cmds.referenceQuery(node, isNodeReferenced=True)
        self.isController = cmds.controller(node, q=True, isController=True)

    def paintEvent(self, event):
        painter = QPainter(self)

        # type
        img = QImage(':{}.svg'.format(self.type))
        if img.isNull():
            img = QImage(':default.svg')
        img = img.smoothScaled(self.width(), self.height())
        painter.drawImage(0, 0, img)

        # ref
        if self.isReferenced:
            refImg = QImage(':reference.svg').smoothScaled(self.width() * .5, self.height() * .5)
            painter.drawImage(0, 0, refImg)

        # shape
        if self.isShape:
            shapeImg = QImage(':nurbsSurface.svg').smoothScaled(self.width() * .5, self.height() * .5)
            painter.drawImage(self.width() * .5, self.height() * .5, shapeImg)

        # ctrl
        if self.isController:
            ctrlImg = QImage(':character.svg').smoothScaled(self.width() * .5, self.height() * .5)
            painter.drawImage(self.width() * .5, 0, ctrlImg)

        # painter.drawRect(0, 0, self.width() - 1, self.height() - 1)

class IconButton(QWidget):

    images = dict()

    def __init__(self, idleImageFile, checkedImageFile=None, checkable=False, parent=None, isChecked=False):
        super(IconButton, self).__init__(parent=parent)
        self.idleImageFile = idleImageFile
        self.checkedImageFile = checkedImageFile
        self.isCheckable = checkable

        self.clicked = list()
        self.checked = list()

        self.isHovered = False
        self.isClicked = False
        self.isChecked = isChecked

        self.hoveredColor = 50
        self.clickedColor = 100

    def enterEvent(self, *args, **kwargs):
        super(IconButton, self).enterEvent(*args, **kwargs)
        # print('ENTER')

        self.isHovered = True
        self.update()

    def leaveEvent(self, *args, **kwargs):
        super(IconButton, self).leaveEvent(*args, **kwargs)
        # print('LEAVE')

        self.isHovered = False
        self.update()

    def mousePressEvent(self, event):  # type: (QMouseEvent) -> None
        if event.button() == Qt.LeftButton:
            self.isClicked = True
            event.accept()
            self.update()
        else:
            super(IconButton, self).mousePressEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:

            self.isClicked = False

            if self.isCheckable:
                self.isChecked = not self.isChecked
                [func(self.isChecked) for func in self.checked]

            [func() for func in self.clicked]

            event.accept()
            self.update()
        else:
            super(IconButton, self).mouseReleaseEvent(event)

    def offsetImageColor(self, img, offsetColor):
        for x in range(img.width()):
            for y in range(img.height()):
                color = img.pixelColor(x, y)  # type: QColor

                r = min(color.red() + offsetColor, 255)
                g = min(color.green() + offsetColor, 255)
                b = min(color.blue() + offsetColor, 255)
                a = color.alpha()

                img.setPixelColor(x, y, QColor(r, g, b, a))

    def paintEvent(self, event):
        painter = QPainter(self)

        # img
        img = QImage(self.idleImageFile)
        if self.isCheckable and self.isChecked and self.checkedImageFile:
            img = QImage(self.checkedImageFile)

        if self.isClicked:
            self.offsetImageColor(img, self.clickedColor)
        elif self.isHovered:
            self.offsetImageColor(img, self.hoveredColor)

        img = img.smoothScaled(self.width(), self.height())
        painter.drawImage(0, 0, img)

class SelectionEditor(QDialog):   #  MayaQWidgetDockableMixin,

    def __init__(self, parent=getMayaMainWindow()):
        super(SelectionEditor, self).__init__(parent=parent)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
        self.setWindowTitle('Selection')

        self.selection = None
        self.historySelection = None
        self.historyEnabled = True
        self.selectionEnabled = True
        self.namespace = True

        #
        self.selectionTree = SelectionTree()
        self.selectionTree.itemSelectionChanged.connect(self.selectSelectionItem)

        # selection count
        self.selectionCount = QLabel()
        self.selectionCount.setToolTip('Number of Selected Objects')

        # select by name and type
        self.selectByNameTypeHistory = list()
        self.selectByNameTypeField = SelectByNameLine()
        pixmap = QPixmap(':quickSelect.png')

        selectByNameLabel = QLabel()
        selectByNameLabel.setToolTip('Select by Name and Type')
        selectByNameLabel.setPixmap(pixmap.scaled(40, 40))

        selectByNameTypeLayout = QHBoxLayout()
        selectByNameTypeLayout.addWidget(selectByNameLabel)
        selectByNameTypeLayout.addWidget(self.selectByNameTypeField)
        # selectByNameTypeLayout.addWidget(self.selectionCount)

        # selection tree
        lockSelection = IconButton(':unlockGeneric.png', ':lock.png', checkable=True)
        lockSelection.setToolTip('Lock/Unlock Auto-Reload')
        lockSelection.setMinimumSize(QSize(30, 30))
        lockSelection.checked.append(self.lockToggled)

        self.saveSelection = IconButton(':Bookmark.png')
        self.saveSelection.setToolTip('Save Current Selection')
        self.saveSelection.setMinimumSize(QSize(30, 30))
        self.saveSelection.clicked.append(self.test)

        self.saveWindow = QWidget(self.saveSelection)
        self.saveWindow.setFixedSize(QSize(100, 100))

        copySelectionTab = IconButton(':UVTkCopySet.png')
        copySelectionTab.setToolTip('Tear Off Selection in another Window')
        copySelectionTab.setMinimumSize(QSize(30, 30))
        copySelectionTab.clicked.append(self.tearOffSelectionCopy)

        displayNamespaces = IconButton(':switchOff.png', ':switchOn.png', checkable=True, isChecked=True)
        displayNamespaces.setToolTip('Show/Hide Namespaces')
        displayNamespaces.setMinimumSize(QSize(30, 30))
        displayNamespaces.checked.append(self.selectionTree.toggleNamespaces)

        selectionOptionsLayout = QHBoxLayout()
        selectionOptionsLayout.addWidget(lockSelection)
        selectionOptionsLayout.addWidget(self.saveSelection)
        selectionOptionsLayout.addWidget(copySelectionTab)
        selectionOptionsLayout.addWidget(displayNamespaces)
        # selectionOptionsLayout.addStretch()
        # for _ in range(5):
        #     icnBtn = IconButton(':Bookmark.png')
        #     icnBtn.setMinimumSize(QSize(30, 30))
        #     selectionOptionsLayout.addWidget(icnBtn)
        selectionOptionsLayout.addStretch()
        selectionOptionsLayout.addWidget(self.selectionCount)

        # self.selectionList.setSelectionMode(QListWidget.ExtendedSelection)

        refreshAct = QAction('Auto-Refresh', self)
        # refreshAct.setCheckable(True)

        displayMenu = QMenu('Display')
        displayMenu.addAction(refreshAct)

        menuBar = QMenuBar()
        menuBar.addMenu(displayMenu)

        # selectionLayout = QVBoxLayout()
        # selectionLayout.setSpacing(0)
        # selectionLayout.addLayout(selectionOptionsLayout)
        # selectionLayout.addWidget(self.selectionTree)

        #

        self.historyTree = QTreeWidget()
        self.historyTree.itemSelectionChanged.connect(self.selectHistoryItem)
        self.historyTree.setHeaderLabels(('time', 'len', 'content'))

        self.savedTree = QTreeWidget()

        # main layout
        mainLayout = QVBoxLayout(self)
        # mainLayout.setMargin(0)
        mainLayout.addLayout(selectByNameTypeLayout)
        mainLayout.addLayout(selectionOptionsLayout)
        mainLayout.addWidget(self.selectionTree)
        # mainLayout.addLayout(selectionLayout)

        #
        self.eventCallback = None

        self.resize(QSize(130 * dpiF, 260 * dpiF))

    def test(self):
        if self.saveWindow.isVisible():
            self.saveWindow.hide()
            return

        self.saveWindow.show()

        # x = self.saveSelection.x()
        # y = self.saveSelection.y() + self.saveSelection.height()
        #
        # self.saveWindow.move(self.mapToGlobal(QPoint(x, y)))
        # self.saveWindow.resize(QSize(500, 500))

    def lockToggled(self, state):
        self.selectionEnabled = not state
        if not state:
            self.reload()

    def selectHistoryItem(self, *args, **kwargs):
        items = self.historyTree.selectedItems()

        if not items:
            return

        item = items[-1]

        selection = item.data(0, Qt.UserRole)

        self.historyEnabled = False
        cmds.select(selection, noExpand=True)
        self.historyEnabled = True

    def selectSelectionItem(self, *args, **kwargs):
        self.selectionEnabled = False
        cmds.select(self.selectionTree.selectedNodes(), noExpand=True)
        self.selectionEnabled = True

    def removeCallBack(self):
        try:
            MEventMessage.removeCallback(self.eventCallback)
        except RuntimeError:
            pass
        except AttributeError:
            pass

    def deleteLater(self, *args, **kwargs):
        self.removeCallBack()
        self.saveWindow.deleteLater()
        super(SelectionEditor, self).deleteLater(*args, **kwargs)

    def closeEvent(self, *args, **kwargs):
        self.removeCallBack()
        self.saveWindow.close()
        super(SelectionEditor, self).closeEvent(*args, **kwargs)

    def hideEvent(self, *args, **kwargs):
        print('hide')
        self.removeCallBack()
        self.saveWindow.hide()
        super(SelectionEditor, self).hideEvent(*args, **kwargs)

    def showEvent(self, *args, **kwargs):
        self.eventCallback = MEventMessage.addEventCallback('SelectionChanged', self.reload)
        self.reload()
        super(SelectionEditor, self).showEvent(*args, **kwargs)

    def reload(self, *args, **kwargs):
        # print('SELECTION CHANGED')
        start = time.time()
        selection = cmds.ls(sl=True, long=True)

        self.selectionCount.setText('<b>{}</b>'.format(len(selection)))

        if selection != self.selection and self.selectionEnabled:
            self.selectionTree.load(selection)
            self.selection = selection

        # print('SELECTION CHANGED', time.time() - start)
        if selection and self.historyEnabled and selection != self.historySelection:
            self.addEntryToHistory(selection)
            self.historySelection = selection

    def addEntryToHistory(self, selection):
        pass
        # self.historyTree.clearSelection()
        #
        # currentDateAndTime = datetime.now()
        # selectionLabel = ', '.join([i.split('|')[-1] for i in selection])
        # item = QTreeWidgetItem((currentDateAndTime.strftime("%H:%M:%S"), str(len(selection)), selectionLabel,))
        #
        # item.setData(0, Qt.UserRole, selection)
        # self.historyTree.insertTopLevelItem(0, item)
        #
        # self.historyEnabled = False
        # item.setSelected(True)
        # self.historyEnabled = True

    def tearOffSelectionCopy(self):
        ui = TearOffSelectionWindow(self.selectionTree.nodes, parent=self)
        ui.show()

# class ObjectNameWidget(QWidget):
#
#     def __init__(self, longName, parent=None):
#         super(ObjectNameWidget, self).__init__(parent)
#
#         name = longName.split('|')[-1]
#         nameSplit = name.split(':')
#         namespace = ':'.join(nameSplit[:-1])
#         shortName = nameSplit[-1]
#
#         objType = cmds.objectType(longName)
#
#         item = QListWidgetItem()
#         item.setData(Qt.UserRole, longName)
#         item.setToolTip('{} ({})'.format(name, objType))
#
#         icon = IconWidget(longName, self)
#         icon.setFixedSize(QSize(35, 35))
#
#         shortNameLabel = QLabel(shortName)
#         # shortNameLabel.setFixedWidth(shortNameLabel.width())
#
#         nameLayout = QHBoxLayout()
#         nameLayout.setAlignment(Qt.AlignLeft)
#         nameLayout.setSpacing(0)
#         if namespace:
#             namespaceLabel = QLabel('{}:'.format(namespace))
#             namespaceLabel.setStyleSheet("QLabel {color: rgb(150, 150, 150);}")
#             nameLayout.addWidget(namespaceLabel)
#         nameLayout.addWidget(shortNameLabel)
#
#         lay = QHBoxLayout(self)
#         lay.setMargin(2)
#         lay.setAlignment(Qt.AlignLeft)
#         lay.addWidget(icon)
#         lay.addLayout(nameLayout)

class SelectionTree(QListWidget):
    def __init__(self, *args, **kwargs):
        super(SelectionTree, self).__init__(*args, **kwargs)
        # self.setStyleSheet('QListWidget {background: rgb(50, 50, 50);} QListWidget::item:selected {background: rgb(100, 100, 100);}')
        self.setSelectionMode(QListWidget.ExtendedSelection)
        self.nodes = list()
        self.itemSelectionChanged.connect(self.selectItems)

        self.displayNamespaces = True

    def selectItems(self):
        selectedItems = self.selectedItems()

        items = [self.item(x) for x in range(self.count())]

        for item in items:
            wid = self.itemWidget(item)
            if not wid:
                continue
            wid.isSelected = item in selectedItems

    def toggleNamespaces(self, state):
        self.displayNamespaces = state
        items = [self.item(x) for x in range(self.count())]

        for item in items:
            wid = self.itemWidget(item)
            wid.displayNamespace = state

    def selectedNodes(self):
        return [i.data(Qt.UserRole) for i in self.selectedItems()]

    def load(self, nodes):
        self.clear()
        self.nodes = nodes

        for index, longName in enumerate(nodes):
            objType = cmds.objectType(longName)
            item = QListWidgetItem()
            item.setData(Qt.UserRole, longName)

            nodeType = cmds.objectType(longName)
            shapes = cmds.listRelatives(longName, shapes=True, fullPath=True) if nodeType != 'objectSet' else None
            shapType = cmds.objectType(shapes[0]) if shapes else None

            finalType = nodeType if not shapType else shapType
            isReferenced = cmds.referenceQuery(longName, isNodeReferenced=True)

            name = longName.split('|')[-1]
            item.setToolTip('{} ({})'.format(name, objType))
            wid = NodeWidget(name, objectType=finalType, isReferenced=isReferenced, parent=self)
            wid.displayNamespace = self.displayNamespaces
            # wid.secondaryColor = QColor(175, 125, 125)
            wid.setFixedHeight(35)

            self.addItem(item)
            self.setItemWidget(item, wid)
            item.setSizeHint(QSize(0, 40))

class NodeWidget(QWidget):

    def __init__(self, longName, objectType=None, isReferenced=False, parent=None):
        super(NodeWidget, self).__init__(parent)

        longNameSplit = longName.split(':')
        namespace = ':'.join(longNameSplit[:-1])
        self.namespace = '{}:'.format(namespace) if namespace else namespace
        self.name = longNameSplit[-1]
        self.objectType = objectType
        self.isReferenced = isReferenced

        self.mainColor = QColor(200, 200, 200)
        self.secondaryColor = QColor(125, 125, 125)
        self.selectedColor = QColor(255, 255, 255)

        self.setMinimumHeight(35)

        self._displayNamespace = True
        self.isSelected = False

    @property
    def displayNamespace(self):
        return self._displayNamespace

    @displayNamespace.setter
    def displayNamespace(self, value):
        self._displayNamespace = value
        self.update()

    def paintEvent(self, *args, **kwargs):
        painter = QPainter(self)
        font = QFont()
        font.setPixelSize(self.height() * .66)
        fontMetrics = QFontMetrics(font)
        fontHeight = fontMetrics.height()

        typeImage = QImage(':{}.svg'.format(self.objectType))
        if typeImage.isNull():
            typeImage = QImage(':default.svg')
        typeImage = typeImage.smoothScaled(self.height(), self.height())

        namespacePen = QPen()
        namespacePen.setColor(self.secondaryColor if not self.isSelected else self.selectedColor)

        namePen = QPen()
        namePen.setColor(self.mainColor if not self.isSelected else self.selectedColor)

        namespaceWidth = fontMetrics.horizontalAdvance(self.namespace) if self.displayNamespace else 0
        nameWidth = fontMetrics.horizontalAdvance(self.name)

        typeRect = QRect(0, 0, self.height(), self.height())

        namespaceRect = QRect(typeRect.x() + typeRect.width(), 0, namespaceWidth, fontHeight)
        nameRect = QRect(namespaceRect.x() + namespaceRect.width(), 0, nameWidth, fontHeight)

        # draw
        painter.drawImage(typeRect, typeImage)
        if self.isReferenced:
            refRect = QRect(0, 0, self.height() * .5, self.height() * .5)
            refImage = QImage(':reference.svg').smoothScaled(self.height() * .5, self.height() * .5)
            painter.drawImage(refRect, refImage)

        painter.setFont(font)
        painter.setPen(namespacePen)
        if self.displayNamespace:
            painter.drawText(namespaceRect, self.namespace)

        painter.setPen(namePen)
        painter.drawText(nameRect, self.name)

class TearOffSelectionWindow(QDialog):

    def __init__(self, nodes, parent=None):
        super(TearOffSelectionWindow, self).__init__(parent)
        self.setWindowTitle('Tear Off Selection')

        self.selectionTree = SelectionTree()
        self.selectionTree.load(nodes)
        self.selectionTree.itemSelectionChanged.connect(self.selectSelectionItem)

        layout = QVBoxLayout(self)
        layout.addWidget(self.selectionTree)

    def selectSelectionItem(self, *args, **kwargs):
        cmds.select(self.selectionTree.selectedNodes(), noExpand=True)


from __future__ import absolute_import, division, print_function, unicode_literals

import os
import csv
import sys
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import matplotlib.pyplot as plt
import tensorflow_docs.plots
import pandas as pd

print(tf.version.VERSION)

column_names = ['id', 'point', 'rssi_a', 'rssi_b', 'rssi_c', 'rssi_d', 'rssi_e',
                'distance_a', 'distance_b', 'distance_c', 'distance_d', 'distance_e', 'timestamp']

dataset_path = 'measurements.csv'
raw_dataset = pd.read_csv(dataset_path, names=column_names, na_values="?", comment='\t', sep=";", skipinitialspace=True)
dataset = raw_dataset.copy()
dataset = dataset.dropna()

train_dataset = dataset.sample(frac=0.9, random_state=0)
test_dataset = dataset.drop(train_dataset.index)
# test_dataset = dataset

test_labels_a = test_dataset.pop('distance_a')
test_labels_b = test_dataset.pop('distance_b')
test_labels_c = test_dataset.pop('distance_c')
test_labels_d = test_dataset.pop('distance_d')
test_labels_e = test_dataset.pop('distance_e')
points = test_dataset.pop('point')

test_dataset.drop(["id"], axis=1, inplace=True)
test_dataset.drop(["timestamp"], axis=1, inplace=True)

train_stats = test_dataset.describe()
train_stats = train_stats.transpose()
print('train_stats')
print(train_stats)

def norm(x):
    return (x - train_stats['mean']) / train_stats['std']

normed_test_data = norm(test_dataset)

checkpoint_path_a = 'training/training_a/cp_a.ckpt'
checkpoint_dir_a = os.path.dirname(checkpoint_path_a)

checkpoint_path_b = 'training/training_b/cp_b.ckpt'
checkpoint_dir_b = os.path.dirname(checkpoint_path_b)

checkpoint_path_c = 'training/training_c/cp_c.ckpt'
checkpoint_dir_c = os.path.dirname(checkpoint_path_c)

checkpoint_path_d = 'training/training_d/cp_d.ckpt'
checkpoint_dir_d = os.path.dirname(checkpoint_path_d)

checkpoint_path_e = 'training/training_e/cp_e.ckpt'
checkpoint_dir_e = os.path.dirname(checkpoint_path_e)

def create_model():
    model = keras.Sequential([
        layers.Dense(256, activation='relu', input_shape=[len(train_dataset.keys())]),
        layers.Dense(256, activation='relu'),
        layers.Dense(128, activation='relu'),
        layers.Dense(128, activation='relu'),
        layers.Dense(64, activation='relu'),
        layers.Dense(1)
    ])

    optimizer = tf.keras.optimizers.Adam()

    model.compile(loss='mae', optimizer=optimizer, metrics=['mae', 'mse'])
    return model

def get_position_from_distance(distance):
    switcher = {
        1: [50, 50],
        2: [100, 50],
        3: [150, 50],
        4: [200, 50],
        5: [250, 50],
        6: [300, 50],
        7: [350, 50],
        8: [400, 50],
        9: [450, 50],
        10: [500, 50],
        11: [550, 50],
        12: [50, 100],
        13: [100, 100],
        14: [150, 100],
        15: [200, 100],
        16: [250, 100],
        17: [300, 100],
        18: [350, 100],
        19: [400, 100],
        20: [450, 100],
        21: [500, 100],
        22: [550, 100],
        23: [50, 150],
        24: [100, 150],
        25: [150, 150],
        26: [200, 150],
        27: [250, 150],
        28: [300, 150],
        29: [350, 150],
        30: [400, 150],
        31: [450, 150],
        32: [500, 150],
        33: [550, 150],
        34: [50, 200],
        35: [100, 200],
        36: [150, 200],
        37: [200, 200],
        38: [250, 200],
        39: [300, 200],
        40: [350, 200],
        41: [400, 200],
        42: [450, 200],
        43: [500, 200],
        44: [550, 200],
        45: [50, 250],
        46: [100, 250],
        47: [150, 250],
        48: [200, 250],
        49: [250, 250],
        50: [300, 250],
        51: [350, 250],
        52: [400, 250],
        53: [450, 250],
        54: [500, 250],
        55: [550, 250],
        56: [50, 300],
        57: [100, 300],
        58: [150, 300],
        59: [200, 300],
        60: [250, 300],
        61: [300, 300],
        62: [350, 300],
        63: [400, 300],
        64: [450, 300],
        65: [500, 300],
        66: [550, 300],
        67: [50, 350],
        68: [100, 350],
        69: [150, 350],
        70: [200, 350],
        71: [250, 350],
        72: [300, 350],
        73: [350, 350],
        74: [400, 350],
        75: [450, 350],
        76: [500, 350],
        77: [550, 350],
        78: [50, 400],
        79: [100, 400],
        80: [150, 400],
        81: [200, 400],
        82: [250, 400],
        83: [300, 400],
        84: [350, 400],
        85: [400, 400],
        86: [450, 400],
        87: [500, 400],
        88: [550, 400],
        89: [50, 450],
        90: [100, 450],
        91: [150, 450],
        92: [200, 450],
        93: [250, 450],
        94: [300, 450],
        95: [350, 450],
        96: [400, 450],
        97: [450, 450],
        98: [500, 450],
        99: [550, 450],
        100: [50, 500],
        101: [100, 500],
        102: [150, 500],
        103: [200, 500],
        104: [250, 500],
        105: [300, 500],
        106: [350, 500],
        107: [400, 500],
        108: [450, 500],
        109: [500, 500],
        110: [550, 500]
    }

    return switcher.get(distance)

latest_a = tf.train.latest_checkpoint(checkpoint_dir_a)
print(latest_a)

latest_b = tf.train.latest_checkpoint(checkpoint_dir_b)
print(latest_b)

latest_c = tf.train.latest_checkpoint(checkpoint_dir_c)
print(latest_c)

latest_d = tf.train.latest_checkpoint(checkpoint_dir_d)
print(latest_d)

latest_e = tf.train.latest_checkpoint(checkpoint_dir_e)
print(latest_e)

# Create a new model instance
model_a = create_model()
model_b = create_model()
model_c = create_model()
model_d = create_model()
model_e = create_model()

# Load the previously saved weights
model_a.load_weights(latest_a)
model_b.load_weights(latest_b)
model_c.load_weights(latest_c)
model_d.load_weights(latest_d)
model_e.load_weights(latest_e)

print("Model A")
print(model_a)

print("Normed test data: ")
print(normed_test_data)

print("Test labels A")
test_points = points.tolist()
print(test_labels_a)
print(test_labels_b)
print(test_labels_c)
print(test_labels_d)
print(test_labels_e)
real_positions = []

for i in range(len(test_points)):
    real_positions.append(get_position_from_distance(test_points[i]))

test_predictions_a = model_a.predict(normed_test_data).flatten()
test_predictions_b = model_b.predict(normed_test_data).flatten()
test_predictions_c = model_c.predict(normed_test_data).flatten()
test_predictions_d = model_d.predict(normed_test_data).flatten()
test_predictions_e = model_e.predict(normed_test_data).flatten()

print("Test Predictions A")
print(test_predictions_a)
print(test_predictions_b)
print(test_predictions_c)
print(test_predictions_d)
print(test_predictions_e)

with open('predictions_file.csv', mode='w') as predictions_file:
    for i in range(len(test_predictions_a)):
        predictions_writer = csv.writer(predictions_file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        predictions_writer.writerow([test_predictions_a[i], test_predictions_b[i], test_predictions_c[i],
                                     test_predictions_d[i], test_predictions_e[i], real_positions[i]
                                     ])

a = plt.axes(aspect='equal')
plt.scatter(test_labels_a, test_predictions_a)
plt.xlabel('True Values [Distance]')
plt.ylabel('Predictions [Distance]')
lims = [0, 700]
plt.xlim(lims)
plt.ylim(lims)
_ = plt.plot(lims, lims)
plt.show()

a = plt.axes(aspect='equal')
plt.scatter(test_labels_b, test_predictions_b)
plt.xlabel('True Values [Distance]')
plt.ylabel('Predictions [Distance]')
lims = [0, 700]
plt.xlim(lims)
plt.ylim(lims)
_ = plt.plot(lims, lims)
plt.show()

a = plt.axes(aspect='equal')
plt.scatter(test_labels_c, test_predictions_c)
plt.xlabel('True Values [Distance]')
plt.ylabel('Predictions [Distance]')
lims = [0, 700]
plt.xlim(lims)
plt.ylim(lims)
_ = plt.plot(lims, lims)
plt.show()

a = plt.axes(aspect='equal')
plt.scatter(test_labels_d, test_predictions_d)
plt.xlabel('True Values [Distance]')
plt.ylabel('Predictions [Distance]')
lims = [0, 700]
plt.xlim(lims)
plt.ylim(lims)
_ = plt.plot(lims, lims)
plt.show()

a = plt.axes(aspect='equal')
plt.scatter(test_labels_e, test_predictions_e)
plt.xlabel('True Values [Distance]')
plt.ylabel('Predictions [Distance]')
lims = [0, 700]
plt.xlim(lims)
plt.ylim(lims)
_ = plt.plot(lims, lims)
plt.show()


from django.contrib import admin
from .models import Quiz, Category, Question, Answer, UserAnswers

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    """
    Модель категорий для вывода в админ панели.
    """

    list_display = ('id', 'category_name', 'created_at')
    list_display_links = ('id', 'category_name')
    search_fields = ('category_name',)
    list_filter = ('created_at',)

@admin.register(Quiz)
class QuizAdmin(admin.ModelAdmin):
    """
    Модель опросов для вывода в админ панели.
    """

    list_display = ('id', 'quiz_name', 'category', 'created_at')
    list_display_links = ('id', 'quiz_name')
    search_fields = ('quiz_name',)
    list_filter = ('created_at', 'category')

class AnswerInline(admin.StackedInline):
    model = Answer
    min_num = 4
    extra = 0

@admin.register(Question)
class QuestionAdmin(admin.ModelAdmin):
    """
    Модель вопросов для вывода в админ панели.
    """

    inlines = [AnswerInline]
    list_display = ('id', 'question', 'quiz', 'created_at')
    list_display_links = ('id', 'question')
    search_fields = ('quiz',)
    list_filter = ('quiz', 'created_at')

@admin.register(Answer)
class AnswerAdmin(admin.ModelAdmin):
    """
    Модель ответов для вывода в админ панели.
    """

    list_display = ('id', 'answer', 'is_correct', 'question', 'created_at')
    list_display_links = ('id', 'answer')
    search_fields = ('answer', 'question')
    list_filter = ('is_correct', 'question', 'created_at')

@admin.register(UserAnswers)
class UserAnswersAdmin(admin.ModelAdmin):
    """
    Модель ответов пользователей для админ панели.
    """

    list_display = ('user', 'answer')
    list_filter = ('answer',)
    search_fields = ('answer',)


# -*- coding: utf-8 -*-

import os

def pobierz_dane(plikcsv):
	"""
	funkcja zwraca tuplę tupli zawierajacych dane
	z pliku csv do zapisania w tabeli"""

	dane = [] #deklarujemy pustą liste
	if os.path.isfile(plikcsv): #sprawdzamy czy plik istnieje na dysku
		with open(plikcsv, "r") as zawartosc: #otwieramy plik do odczytu
			zawartosc.readline()
			for linia in zawartosc:
				#linia = linia.remove("\n","")#usuwamy znaki końca lini
				#linia = linia.replace("\r", "")#usuwamy znaki konca lini
				#linia = linia.replace("utf-8", "")#odczytujemy znaki jako utf-8
				#dodajemy elementy do tupli a tuplę do listy
				dane.append(tuple(linia.split(";")))
	else:
		print("Plik z danymi: ",plikcsv, " nie istnieje!")

	return tuple(dane) # przeksztalcamy liste na tuple i zwracamy ja


n=int(input())
t=n
l=len(str(n))
s=0
while(n!=0):
    r=n%10
    s+=r**l
    l=l-1
    n=n//10
if s==t:
    print('True')
else:
    print('False')


import torch
from torch import nn
import os
import argparse
import torch.utils.data as data
from torch import optim
from torch.autograd import Variable
import torchvision.transforms as transforms
import tqdm
import numpy as np
import random
from tensorboardX import SummaryWriter
from datetime import datetime
import dateutil.tz

def trainer(opt):
    path = "./kills_per_state_per_month.csv"
    logger_path = mk_log_dir("./Logs/", opt)
    writer = SummaryWriter(logger_path['log_path'])
    print("loading")
    transform = transforms.Compose([
            #transforms.RandomCrop(crop_size, padding=padding),
            #transforms.RandomHorizontalFlip(),
            transforms.ToTensor()
            #transforms.Normalize((0.4914, 0.4822, 0.4465),
            #                     (0.2023, 0.1994, 0.2010)),
        ])
    train_data = train_data_sequence(path, transform)
    test_data = test_data_sequence(path, transform)
    print(len(train_data))
    print(len(test_data))
    train_dataloader = torch.utils.data.DataLoader(
                            train_data,
                            batch_size=opt.batch_size,
                            shuffle=True,
                            num_workers=opt.n_threads,
                            pin_memory=True)
    test_dataloader = torch.utils.data.DataLoader(
                            test_data,
                            batch_size=90,
                            shuffle=True,
                            num_workers=opt.n_threads,
                            pin_memory=True)
    gpu_ids = [i for i in range(len(opt.gpu_ids.split(",")))]
    model = TemporalModel()
    model = nn.DataParallel(model.to("cuda:0"), device_ids=gpu_ids)
    model = model.to("cuda:0")
    optimizer = optim.SGD(
            model.parameters(),
            lr=opt.learning_rate,
            momentum=0.9,
            weight_decay=opt.weight_decay
            )
    loss = nn.CrossEntropyLoss()
    for epoch in range(0, 1000):
        train_loss = training(model, optimizer, loss, train_dataloader, epoch, writer)
        test_loss = testing(model, optimizer, loss, test_dataloader, epoch, writer)
        update_learning_rate(optimizer, opt.learning_rate, epoch)

def training(model, optimizer, Loss, data_loader, epoch, writer):
    model.train()
    losses = AverageMeter()
    for i, (inputs, state, month, targets) in enumerate(data_loader):
        inputs = Variable(inputs.cuda())
        targets = Variable(targets.cuda())
        state = Variable(state.cuda())
        month = Variable(month.cuda())
        outputs = model(inputs, state, month)
        loss = Loss(outputs, targets)
        losses.update(loss.item(), inputs.size(0))
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    print(inputs[0],state[0], month[0], torch.max(outputs[0], 0)[1].item(), targets[0].item())
    print("Epoch: " + str(epoch) + ", avg loss: " + str(losses.avg))
    writer.add_scalar("loss/train", losses.avg, epoch)
    return losses.avg

def testing(model, optimizer, Loss, data_loader, epoch, writer):
    model.eval()
    losses = AverageMeter()
    for i, (inputs, state, month, targets) in enumerate(data_loader):
        inputs = Variable(inputs.cuda())
        targets = Variable(targets.cuda())
        state = Variable(state.cuda())
        month = Variable(month.cuda())
        outputs = model(inputs, state, month)
        loss = Loss(outputs, targets)
        losses.update(loss.item(), inputs.size(0))
    print("Test, " + "Epoch: " + str(epoch) + ", avg loss: " + str(losses.avg))
    writer.add_scalar("loss/test", losses.avg, epoch)
    return losses.avg

class TemporalModel(nn.Module):
    def __init__(self):
        super(TemporalModel, self).__init__()

        #self.fc = nn.Linear(3, )
        self.h_size = 1000
        self.layer = 3
        self.lstm = nn.LSTM(input_size=1, hidden_size=self.h_size, num_layers=self.layer, batch_first=True)
        #self.embedding_1 = nn.Linear(2, 3*self.h_size)
        self.embedding_2 = nn.Linear(3*self.h_size,200)
    def forward(self, x, s, m):
        x = x.unsqueeze(2)
        # x = self.embedding(x)
        h0 = Variable(torch.randn(self.layer, x.size(0), self.h_size).cuda())
        c0 = Variable(torch.randn(self.layer, x.size(0), self.h_size).cuda())
        #output = self.fc(x)
        output, _ = self.lstm(x, (h0, c0))
        output = output.contiguous().view(output.size(0), 3*self.h_size)
        #condition = torch.cat((s.unsqueeze(1), m.unsqueeze(1)), dim=1)
        #condition_feature = self.embedding_1(condition)
        #output = torch.cat((output, s.unsqueeze(1), m.unsqueeze(1)), dim=1)
        output = self.embedding_2(output)
        return output

class train_data_sequence(data.Dataset):
    def __init__(self, path, transform):
        self.path = path
        data_file = open(path, "r")
        self.data = []
        for line in data_file.readlines():
            line = line.replace("\n", "")
            line = [int(i) for i in line.split(",")]
            self.data.append(line)
        #print(self.data[0:5])
        self.transform = transform

    def __getitem__(self, index):
        data = self.data[index]
        killed_list = data[3:6]
        rand_num = int(6*random.random())
        for i in range(len(killed_list)):
            if killed_list[i] > 10 and data[6] > 10:
                killed_list[i] = int(max(killed_list[i] + rand_num-3, 0))
        killed_list = np.array(killed_list).astype(np.float32)
        killed_num = torch.from_numpy(killed_list)
        if data[6] > 10:
            target = torch.tensor(int(data[6])+ rand_num-3)
        else:
            target = torch.tensor(int(data[6]))
        state = torch.tensor(float(data[0]))
        month = torch.tensor(float(data[1]))
        return killed_num, state, month, target

    def __len__(self):
        return len(self.data)

class test_data_sequence(data.Dataset):
    def __init__(self, path, transform):
        self.path = path
        data_file = open(path, "r")
        self.data = []
        for line in data_file.readlines():
            line = line.replace("\n", "")
            line = [int(i) for i in line.split(",")]
            if line[7] > 10:
                self.data.append(line[0:2]+line[4:8])
            if line[2] > 10:
                self.data.append(line[0:6])
        #print(self.data[0:5])
        self.transform = transform

    def __getitem__(self, index):
        data = self.data[index]
        killed_list = data[2:5]
        killed_list = np.array(killed_list).astype(np.float32)
        killed_num = torch.from_numpy(killed_list)
        target = torch.tensor(int(data[5]))
        state = torch.tensor(float(data[0]))
        month = torch.tensor(float(data[1]))
        return killed_num, state, month, target

    def __len__(self):
        return len(self.data)

def update_learning_rate(optimizer, lr, epoch):
    if epoch > 200:
        lr = lr/10.
    if epoch > 400:
        lr = lr/100.
    if epoch > 600:
        lr = lr/1000.
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr

class AverageMeter(object):
    """Computes and stores the average and current value"""

    def __init__(self):
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

def mk_log_dir(save_root, opt):
    path_dict = {}
    save_root = save_root
    os.makedirs(save_root, exist_ok=True)
    exp_name = os.path.join(save_root, opt.exp_name)
    # set log path
    now = datetime.now(dateutil.tz.tzlocal())
    timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')
    prefix = exp_name + '_' + timestamp
    os.makedirs(prefix, exist_ok=True)
    path_dict['prefix'] = prefix

    # set checkpoint path
    model_restore_path = os.path.join(prefix, 'Model')
    os.makedirs(model_restore_path, exist_ok=True)
    path_dict['model_restore_path'] = model_restore_path

    log_path = os.path.join(prefix, 'Log')
    os.makedirs(log_path, exist_ok=True)
    path_dict['log_path'] = log_path

    # # set sample image path for fid calculation
    # sample_path = os.path.join(prefix, 'Samples')
    # os.makedirs(sample_path, exist_ok=True)
    # path_dict['sample_path'] = sample_path

    return path_dict

def parse_opts():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--manual_seed', default=1, type=int, help='Manually set random seed')
    parser.add_argument(
        '--port', default=23412, type=int, help='Manually set random seed')
    parser.add_argument(
        '--learning_rate', default=1e-4, type=float, help='learning rate')
    parser.add_argument(
        '--weight_decay', default=5e-3, type=float, help='learning rate')
    parser.add_argument(
        '--exp_name', required=True, type=str, help='learning rate')
    parser.add_argument(
        '--n_threads', default=8, type=int, help='num_workers')
    parser.add_argument(
        '--batch_size', default=16, type=int, help='Manually set random seed')
    parser.add_argument(
        '--gpu_ids', default="0", type=str, help='gpus id')
    args = parser.parse_args()

    return args

if __name__ == "__main__":
    opt = parse_opts()
    torch.manual_seed(12345)
    torch.cuda.manual_seed(12345)
    os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
    os.environ["CUDA_VISIBLE_DEVICES"]= opt.gpu_ids
    # os.environ['MASTER_PORT'] = opt.port
    trainer(opt)


import _pickle as pickle
from chai.src import master
from sys import path
import os
from chai.src.Utils.logger import logger
path.append('./src/master')
path.append('./src')

logger.info("PATH %s", os.getcwd())

def pickle_data(data, filename):

    try:
        with open(filename,'wb') as handle:
            pickle.dump(data,handle)
    except MemoryError:
        return 0

    return 1

def unpickle_data(filename):

    try:
        with open(filename, 'rb') as handle:
            b = pickle.load(handle)
    except MemoryError:
        return None

    return b

def pickle_dict(dictionary,filename):

    try:
        with open(filename,'wb') as handle:
            pickle.dump(dictionary,handle)
    except MemoryError:
        return 0

    return 1

def unpickle_dict(filename):

    try:
        with open(filename, 'rb') as handle:
            b = pickle.load(handle)
    except MemoryError:
        return None

    return b


"""
    Objet Contact représentant un contact de l'Annuaire

    Author: Tristan Colombo <tristan@gnulinuxmag.com>
                            (@TristanColombo)

    Date: 17-12-2015

    Last modification: 17-12-2015

    Licence: GNU GPL v3 (voir fichier gpl_v3.txt joint)
"""

import sqlite3
import pystache
import os

class Contact:

    base = None
    cursor = None
    template = None

    def __init__(self, name, db_args):
        name = name.split(' ')

        if len(name) != 2:
            print('Vous devez saisir un prénom suivi du nom')
            print('Syntaxe: Prénom Nom')
            exit(1)

        if Contact.base is None:
            Contact.base = db_args[0]
        if Contact.cursor is None:
            Contact.cursor = db_args[1]

        if Contact.template is None:
            try:
                with open('doc.tex', 'r') as fic:
                    Contact.template = fic.read()
            except:
                print('Accès impossible au gabarit')
                exit(3)

        self.forename = Contact.capitalizeName(name[0])
        self.name = Contact.capitalizeName(name[1])
        self.mail = self.searchMail()

    @staticmethod
    def capitalizeName(name):
        capitalized = ''
        pred = ''
        for letter in name:
            if pred in ('', ' ', '-'):
                if letter != ' ':
                    capitalized += letter.upper()
            else:
                capitalized += letter
            pred = letter

        return capitalized

    def isInDB(self):
        result = Contact.cursor.execute("""select name from Contact
                               where forename = ?
                               and name = ?""", (self.forename,
                                                 self.name))
        result = result.fetchone()
        return result is not None

    def addInDB(self):
        try:
            Contact.cursor.execute("""insert into Contact
                                   values(NULL, ?, ?, ?)""",
                                   (self.name, self.forename, self.mail))
            Contact.base.commit()
        except sqlite3.OperationalError:
            print('Erreur d\'écriture dans la base')
            exit(2)

    def searchMail(self):
        mail = Contact.cursor.execute("""select mail from Contact
                               where forename = ?
                               and name = ?""", (self.forename,
                                                 self.name))
        mail = mail.fetchone()
        if mail is None:
            return None
        else:
            return mail[0]

    def getMail(self):
        if self.__mail is None:
            return self.searchMail()
        else:
            return self.__mail
    def setMail(self, mail):
        if mail is None:
            self.__mail = None
        else:
            self.__mail = mail.lower()
            if self.isInDB():
                try:
                    Contact.cursor.execute("""update Contact
                                   set mail = ?
                                   where name = ?
                                   and forename = ?""",
                                   (self.mail, self.name, self.forename))
                    Contact.base.commit()
                except sqlite3.OperationalError:
                    print('Erreur d\'écriture dans la base')
                    exit(2)
            else:
                self.addInDB()
    mail = property(getMail, setMail)

    def getName(self):
        return self.__name
    def setName(self, name):
        self.__name = name
    name = property(getName, setName)

    def getForename(self):
        return self.__forename
    def setForename(self, forename):
        self.__forename = forename
    forename = property(getForename, setForename)

    def generateDoc(self, sun=False):
        try:
            with open('doc_contact.tex', 'w') as fic:
                fic.write(pystache.render(Contact.template,
                              {'name': self.name,
                               'forename': self.forename,
                               'sun': sun}))

            # Génération du PDF
            os.system('pdflatex doc_contact.tex 1>/dev/null')
        except:
            print('Erreur lor de la génération du PDF')
            exit(4)


from tkinter import *
import tkinter.messagebox as msg
import random
import os

n1 = random.randint(0, 9999999999999)
n2 = random.randint(0, 1000)

def file_clearer():
    main_folder_clear = open('Mainfoldernames.txt', 'w')
    main_folder_clear.write('')
    main_folder_clear.close()
    sub_folder_clear = open('Subfoldernames.txt', 'w')
    sub_folder_clear.write('')
    sub_folder_clear.close()

file_clearer()

def Maker():
    root.destroy()
    fileg = f'{str(n1) + str(n2)}.bat'

    def cmdworker():
        a = addressbar_input.get()
        b = a.replace("\\", "//")
        c = path_input.get()
        d = c.replace("\\", "//")
        os.system(f'cmd /c "Move {fileg} {d}"')
        os.system(f'cmd /k "{b}: & cd {d} & {d}//{fileg} & exit"')
        root2.destroy()

    root2 = Tk()
    root2.geometry('900x600')
    root2.maxsize(900, 200)
    root2.minsize(900, 200)
    root2.configure(background='light grey')
    root2.title('Define Path')
    Label(root2, text='Disk name:', bg='light grey', font='arial 20').grid(pady=5)
    Label(root2, text='Path:', bg='light grey', font='arial 20').grid(row=1, column=0)
    Button(root2, text='Create', bg='navy', command=cmdworker, font='arial 20').grid(row=3, column=1)
    address_disk = StringVar()
    addressbar_input = Entry(root2, textvariable=address_disk, font='arial 20')
    addressbar_input.grid(row=0, column=1)
    address_path = StringVar()
    path_input = Entry(root2, textvariable=address_path, font='arial 20')
    path_input.grid(row=1, column=1)
    Label(root2, text="If a folder name contains space in between its name\n"
                      "like (new folder) so please enclose it in (\" \") like\n"
                      "if path = (D:\\New folder) so change path = (D:\\\"New folder\") ",
          borderwidth=5, relief=SUNKEN, fg='red', bg='grey', font='arial 15') \
        .grid(row=3, padx=3, pady=5)
    root2.mainloop()

def Mainfoldersaver():
    main_file = open("Mainfoldernames.txt", "w")
    main_file.write(main_text_input.get(1.0, END))
    main_file.close()

def Subfoldersaver():
    sub_file = open("Subfoldernames.txt", "w")
    sub_file.write(sub_text_input.get(1.0, END))
    sub_file.close()

def main():
    Mainfoldersaver()
    Subfoldersaver()
    bat_file = open(str(n1) + str(n2) + '.bat', 'a')
    main_folder_out = open('Mainfoldernames.txt')
    input_reader = main_folder_out.readlines()
    for names in input_reader:
        bat_file.write('mkdir ')
        bat_file.write(names)
        bat_file.write('\n')
    sub_folder_out = open('Subfoldernames.txt')
    input_reader2 = sub_folder_out.readlines()
    for names in input_reader:
        bat_file.write(f'\ncd {names}\n')
        for naam in input_reader2:
            bat_file.write('mkdir ')
            bat_file.write(str(naam))
            bat_file.write('\n')
        bat_file.write('cd..\n')
    bat_file.close()
    main_folder_out.close()
    sub_folder_out.close()
    Maker()

def hlp():
    msg.showinfo('how to use', '1:Paste main folder names\n2:Paste sub folder names\n3:Press SAVE\n4:Give disk name(It '
                               'is '
                               'always a alphabet)\n5:Copy and paste path\n6:Press create\n~~~for more info read ('
                               'readme.txt)..')

root = Tk()
root.geometry('450x550')
root.maxsize(450, 550)
root.minsize(450, 550)
root.title('Folder maker-By Ravi sharma')
frame1 = Frame(root, width=100, height=50, borderwidth=10, relief=SUNKEN, bg='grey')
frame1.grid(pady=5, padx=5)
frame2 = Frame(root, width=100, height=50, borderwidth=10, relief=SUNKEN, bg='grey')
frame2.grid(row=2, column=0, pady=5, padx=5)
scrollbar = Scrollbar(frame1)
scrollbar.grid(column=1)
scrollbar2 = Scrollbar(frame2)
scrollbar2.grid(row=2, column=1)
Label(frame1, text='Main Folder Names', bg='grey', fg='red').grid()
main_text_input = Text(frame1, width=30, height=5, yscrollcommand=scrollbar.set, font=' 20', bg='grey')
main_text_input.grid(row=0)
Label(frame2, text='Sub Folder Names', bg='grey', fg='red').grid()
sub_text_input = Text(frame2, width=30, height=5, yscrollcommand=scrollbar2.set, font=' 20', bg='grey')
sub_text_input.grid(row=2)
Label(root, text=f'File name:{str(n1) + str(n2)}.bat', font='Fantasy 15 bold', borderwidth=10, relief=RAISED, fg='Blue',
      bg='lightgrey') \
    .grid(row=4, pady=10)
Button(root, text='SAVE', command=main, font='arial 40', fg='White', bg='navy').grid(row=3, )
help1 = Menu(root)
help1.add_command(label='How to use', command=hlp)
root.config(menu=help1)
Label(root, text='NOTE:Do not give extra empty line after names of folder', fg='red', borderwidth=5, relief=SUNKEN,
      font='arial 12 bold') \
    .grid(row=5, padx=5)
root.mainloop()