from rest_framework import serializers
from rest_framework.relations import SlugRelatedField
from rest_framework.validators import UniqueTogetherValidator

from posts.models import Comment, Follow, Group, Post, User

class PostSerializer(serializers.ModelSerializer):
    author = SlugRelatedField(slug_field='username', read_only=True)

    class Meta:
        fields = '__all__'
        model = Post

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = Group

class CommentSerializer(serializers.ModelSerializer):
    post = serializers.ReadOnlyField(source='post.id')
    author = serializers.SlugRelatedField(
        read_only=True,
        slug_field='username',
    )

    class Meta:
        fields = '__all__'
        model = Comment

class FollowSerializer(serializers.ModelSerializer):
    user = serializers.SlugRelatedField(
        slug_field='username',
        read_only=True,
        default=serializers.CurrentUserDefault()
    )
    following = serializers.SlugRelatedField(
        slug_field='username',
        queryset=User.objects.all()
    )

    class Meta:
        fields = ('user', 'following')
        model = Follow
        validators = [
            UniqueTogetherValidator(
                queryset=Follow.objects.all(),
                fields=['user', 'following']
            )
        ]

    def validate_following(self, value):
        if self.context['request'].user != value:
            return value
        raise serializers.ValidationError("Self-follow is not allowed")


import sys
import pygame
import random
from pygame.sprite import Sprite
from ship import Ship
from alien import Alien
from alien_2 import Alien_2
from bullet import Bullet
from explosion import Explosion
from settings import Settings

def start_menu_off(aigame):
    aigame.background = pygame.image.load(
        'E:\\Programming\\Projects\\Alien Invasion\\images\\stars.jpg')
    aigame.background_rect = aigame.background.get_rect()

class AlienInvasion:
    """Main game class that manages game behaviour."""

    def __init__(self):
        """Initialises the main game attributes."""
        pygame.init()
        pygame.font.init()
        self.game_font = pygame.font.Font(None, 30)
        # Creates settings instance.
        self.settings = Settings()
        # Initialises screen.
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        self.screen_rect = self.screen.get_rect()
        # creates ship, alien and explosion instances.
        self.ship = Ship(self)
        self.alien = Alien(self)
        self.alien_2 = Alien_2(self)
        # Creates sprite groups.
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()
        self.aliens_2 = pygame.sprite.Group()
        self.explosions = pygame.sprite.Group()
        # Background.
        self.background = pygame.image.load(
            'E:\\Programming\\Projects\\Alien Invasion\\images\\start_screen.jpg')
        self.background_rect = self.background.get_rect()
        self.background_rect.center = self.screen_rect.center
        # Other Attributes.
        self.max_bullets = self.settings.max_bullets
        # Timer Attributes for Ship and Alien animation.
        self.timer = 0
        self.animation_timer = 0
        self.current_image = 1
        self.current_explosion = 1
        # Amount of time the game waits before spawning aliens after start screen.
        self.game_start_timer = 0
        self.alien_timer = random.randint(
            self.settings.alien_min_time, self.settings.alien_max_time)
        # Score counter
        self.score = 0

        # Start game after start screen

        self.game_on = 0

    def run_game(self):
        """Starts the game loop."""
        while True:
            self._check_events()
            self._update_screen()
            self._check_collisions()

    def _animate_image(self):
        """Changes images of Ship, Alien and Explosions to show illusion
         of animation."""
        # Increment timer
        self.timer += 1
        self.animation_timer += 1
        self.game_start_timer += 1
        if self.timer == self.alien_timer:
            self.spawn_alien()
            self._randomise_spawn()
            self.timer = 0
        if self.animation_timer == 200:
            if self.current_image == 1:
                self.ship.image = pygame.image.load(
                    'E:\\Programming\\Projects\\Alien Invasion\\images\\player_idle2.png')
                if self.settings.logs == 2:
                    print(f"Set Alien and ship images to 2.")
                for a in self.aliens:
                    a.image = pygame.image.load(
                        'E:\\Programming\\Projects\\Alien Invasion\\images\\Alien1_2.png')
                self.current_image = 2
                self.animation_timer = 0
                # if self.settings.logs == 1:
                #    print("Changed Ship and Alien images to 2")
            else:
                self.ship.image = pygame.image.load(
                    'E:\\Programming\\Projects\\Alien Invasion\\images\\player_idle1.png')
                if self.settings.logs == 2:
                    print(f"Set Alien and ship images to 1.")
                for a in self.aliens:
                    a.image = pygame.image.load(
                        'E:\\Programming\\Projects\\Alien Invasion\\images\\Alien1_1.png')
                self.current_image = 1
                self.animation_timer = 0
                # if self.settings.logs == 1:
                #    print("Changed Ship and Alien images to 1")
        # Animate explosions
        """The following block uses timers and a boolean to animate to the 1st,
         2nd, 3rd image of explosion. Then back to
         2nd and 1st again, before deleting itslef."""
        if self.animation_timer % 50 == 0:
            for e in self.explosions:
                if e.current_image == 1:
                    if self.settings.logs > 2:
                        print(f"Set {e} image to 2.")
                    e.image = pygame.image.load(
                        'E:\\Programming\\Projects\\Alien Invasion\\images\\boom2.PNG')
                    if e.first_pass == True:
                        e.current_image = 2
                elif e.current_image == 2:
                    e.image = pygame.image.load(
                        'E:\\Programming\\Projects\\Alien Invasion\\images\\boom3.PNG')
                    if self.settings.logs > 2:
                        print(f"Set {e} image to 3.")
                    if e.first_pass == True:
                        e.current_image = 3
                else:
                    e.image = pygame.image.load(
                        'E:\\Programming\\Projects\\Alien Invasion\\images\\boom1.PNG')
                    if self.settings.logs > 2:
                        print(f"Set {e} image to 1.")
                        e.current_image = 1
                    else:
                        self.explosions.remove(e)

    def _check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if self.game_on == 0:
                    self.game_on = 1
                    start_menu_off(self)

    def _check_keydown_events(self, event):
        if event.key == pygame.K_RIGHT:
            # Move the ship to the right.
            self.ship.moving_right = True
        elif event.key == pygame.K_LEFT:
            # Move the ship to the right.
            self.ship.moving_left = True
        elif event.key == pygame.K_SPACE:
            # Fires bulets
            self._fire_bullets()
            if self.game_on == 0:
                self.game_on = 1
                start_menu_off(self)

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            # Stop moving the ship to the right.
            self.ship.moving_right = False
        elif event.key == pygame.K_LEFT:
            # Stop moving the ship to the left.
            self.ship.moving_left = False
        elif event.key == pygame.K_q:
            # Quit game if 'q' is pressed
            sys.exit()

    def _update_bullets(self):
        """Updates position of bullets and deletes old bullets."""
        # Removes bullets off screen
        for bullet in self.bullets:
            if bullet.rect.bottom <= 0:
                self.bullets.remove(bullet)

        # Updates bullets on screen.
        self.bullets.update()
        for b in self.bullets:
            b.draw_bullet()

    def _update_alien(self):
        """Draws each alien."""
        # Deletes alien when it gets to the bottom of the screen
        for a in self.aliens:
            if a.rect.top > self.screen_rect.bottom:
                self.aliens.remove(a)
        # Draws and updates each alien individually
        for a in self.aliens:
            a.image = pygame.transform.scale(
                a.image, self.settings.alien_scale)
            a.update_alien()
        #    a._blitme()

    def _fire_bullets(self):
        new_bullet = Bullet(self)
        if len(self.bullets) < self.settings.max_bullets:
            self.bullets.add(new_bullet)
            if self.settings.logs >= 1:
                print(f"Bullet Fired! Total bullets : {len(self.bullets)}")

    def spawn_alien(self):
        new_alien = Alien(self)
        if len(self.aliens) < self.settings.max_aliens and self.game_start_timer > 1000:
            self.aliens.add(new_alien)
            if self.settings.logs >= 1:
                print(f"Alien spawned! Toal aliens : {len(self.aliens)}")

    def _check_collisions(self):
        """Checks to see if X and Y coordinates of any bullets collide with Aliens."""
        for bullet in self.bullets:
            for a in self.aliens:
                if bullet.rect.top > a.rect.top and bullet.rect.top < a.rect.bottom and bullet.rect.centerx > a.rect.left and bullet.rect.centerx < a.rect.right:
                    self._alien_hit(self, bullet, a)
                    self.aliens.remove(a)
                    self.bullets.remove(bullet)
                    self.score += 1

    def _alien_hit(self, aigame, bullet, a):
        """Registers the hit and calls the explosion animation."""
        new_explosion = Explosion(self, bullet, a)
        self.explosions.add(new_explosion)

    def _draw_explosions(self):
        """Draws the explosion images."""
        for explosion in self.explosions:
            explosion._draw_explosion()

    def _randomise_spawn(self):
        """Randomises the value the timer needs to reach before spawning another alien."""
        self.alien_timer = random.randint(
            self.settings.alien_min_time, self.settings.alien_max_time)

    def _draw_score(self):
        """Draws the score on the top left."""
        score_text = self.game_font.render(
            f"Score : {str(self.score)}", True, (255, 255, 255))
        score_rect = score_text.get_rect()
        score_rect.x, score_rect.y = self.screen_rect.right - \
            (score_rect.right - score_rect.left) - 10, 5
        self.screen.blit(score_text, score_rect)

    def _check_for_level_up(self):
        """Compares score to that of level up requirements, and modifies game accordingly."""
        if self.score >= self.settings.level_1up_score:
            self._levelup(1)

    def _levelup(self, level):
        """Changes game behaviour for a levelup."""
        if level == 1:  # Current level
            """Spawn alien2."""
            new_alien_2 = Alien_2(self)
            if len(self.aliens) < self.settings.max_aliens and self.game_start_timer > 1000:
                self.aliens_2.add(new_alien_2)

    def _update_screen(self):
        """Updates the screen with new info."""
        self.screen.fill(self.settings.bg_color)
        self.screen.blit(self.background, self.background_rect)
        # Draws images to screen
        if self.game_on == 1:
            # self._check_for_level_up()
            self.ship.blitme()
            self.ship.update(self)
            self._update_bullets()
            self._update_alien()
            self.aliens.draw(self.screen)
            self._draw_explosions()
            self._animate_image()
            self._draw_score()
        # Flips the newest drawn screen for the old one.
        pygame.display.flip()

if __name__ == '__main__':
    ai = AlienInvasion()
    ai.run_game()


import os
import enum
import mmap
import errno
import fcntl
import select
import logging
import pathlib
import fractions
import collections

import raw

log = logging.getLogger(__name__)

def _enum(name, prefix, klass=enum.IntEnum):
    return klass(
        name,
        (
            (name.replace(prefix, ""), getattr(raw, name))
            for name in dir(raw)
            if name.startswith(prefix)
        ),
    )

Capability = _enum("Capability", "V4L2_CAP_", klass=enum.IntFlag)
PixelFormat = _enum("PixelFormat", "V4L2_PIX_FMT_")
BufferType = _enum("BufferType", "V4L2_BUF_TYPE_")
Memory = _enum("Memory", "V4L2_MEMORY_")
ImageFormatFlag = _enum("ImageFormatFlag", "V4L2_FMT_FLAG_", klass=enum.IntFlag)
Field = _enum("Field", "V4L2_FIELD_")
FrameSizeType = _enum("FrameSizeType", "V4L2_FRMSIZE_TYPE_")
FrameIntervalType = _enum("FrameIntervalType", "V4L2_FRMIVAL_TYPE_")
IOC = _enum("IOC", "VIDIOC_", klass=enum.Enum)

Info = collections.namedtuple(
    "Info",
    "driver card bus_info version physical_capabilities capabilities crop_capabilities buffers formats",
)

ImageFormat = collections.namedtuple(
    "ImageFormat", "type description flags pixel_format"
)

Format = collections.namedtuple("Format", "width height pixel_format")

CropCapability = collections.namedtuple(
    "CropCapability", "type bounds defrect pixel_aspect"
)

Rect = collections.namedtuple("Rect", "left top width height")

Size = collections.namedtuple("Size", "width height")

FrameType = collections.namedtuple(
    "FrameType", "type pixel_format width height min_fps max_fps step_fps"
)

INFO_REPR = """\
driver = {info.driver}
card = {info.card}
bus = {info.bus_info}
version = {info.version}
physical capabilities = {physical_capabilities}
capabilities = {capabilities}
buffers = {buffers}
"""

def flag_items(flag):
    return [item for item in type(flag) if item in flag]

def Info_repr(info):
    caps = "|".join(cap.name for cap in flag_items(info.capabilities))
    pcaps = "|".join(cap.name for cap in flag_items(info.physical_capabilities))
    buffers = "|".join(buff.name for buff in info.buffers)
    return INFO_REPR.format(
        info=info, capabilities=caps, physical_capabilities=pcaps, buffers=buffers
    )

Info.__repr__ = Info_repr

def read_capabilities(fd):
    caps = raw.v4l2_capability()
    fcntl.ioctl(fd, IOC.QUERYCAP.value, caps)
    return caps

def read_info(fd):
    caps = read_capabilities(fd)
    version_tuple = (
        (caps.version & 0xFF0000) >> 16,
        (caps.version & 0x00FF00) >> 8,
        (caps.version & 0x0000FF),
    )
    version_str = ".".join(map(str, version_tuple))
    device_capabilities = Capability(caps.device_caps)
    buffers = [typ for typ in BufferType if Capability[typ.name] in device_capabilities]

    fmt = raw.v4l2_fmtdesc()
    img_fmt_stream_types = {
        BufferType.VIDEO_CAPTURE,
        BufferType.VIDEO_CAPTURE_MPLANE,
        BufferType.VIDEO_OUTPUT,
        BufferType.VIDEO_OUTPUT_MPLANE,
        BufferType.VIDEO_OVERLAY,
    } & set(buffers)

    formats = []
    pixel_formats = set()
    for stream_type in img_fmt_stream_types:
        fmt.type = stream_type
        for index in range(128):
            fmt.index = index
            try:
                fcntl.ioctl(fd, IOC.ENUM_FMT.value, fmt)
            except OSError as error:
                if error.errno == errno.EINVAL:
                    break
                else:
                    raise
            try:
                pixel_format = PixelFormat(fmt.pixelformat)
            except ValueError:
                continue
            formats.append(
                ImageFormat(
                    type=stream_type,
                    flags=ImageFormatFlag(fmt.flags),
                    description=fmt.description.decode(),
                    pixel_format=pixel_format,
                )
            )
            pixel_formats.add(pixel_format)

    crop = raw.v4l2_cropcap()
    crop_stream_types = {
        BufferType.VIDEO_CAPTURE,
        BufferType.VIDEO_OUTPUT,
        BufferType.VIDEO_OVERLAY,
    } & set(buffers)
    crop_caps = []
    for stream_type in crop_stream_types:
        crop.type = stream_type
        try:
            fcntl.ioctl(fd, IOC.CROPCAP.value, crop)
        except OSError:
            continue
        crop_caps.append(
            CropCapability(
                type=stream_type,
                bounds=Rect(
                    crop.bounds.left,
                    crop.bounds.top,
                    crop.bounds.width,
                    crop.bounds.height,
                ),
                defrect=Rect(
                    crop.defrect.left,
                    crop.defrect.top,
                    crop.defrect.width,
                    crop.defrect.height,
                ),
                pixel_aspect=crop.pixelaspect.numerator / crop.pixelaspect.denominator,
            )
        )

    return Info(
        driver=caps.driver.decode(),
        card=caps.card.decode(),
        bus_info=caps.bus_info.decode(),
        version=version_str,
        physical_capabilities=Capability(caps.capabilities),
        capabilities=device_capabilities,
        crop_capabilities=crop_caps,
        buffers=buffers,
        formats=formats,
    )

def fopen(path, rw=False):
    return open(path, "rb+" if rw else "rb", buffering=0, opener=opener)

def opener(path, flags):
    return os.open(path, flags | os.O_NONBLOCK)

class Device:
    def __init__(self, filename):
        filename = pathlib.Path(filename)
        self._log = log.getChild(filename.stem)
        self._context_level = 0
        self._fobj = fopen(filename, rw=True)
        self.info = read_info(self.fileno())
        self.filename = filename
        if Capability.VIDEO_CAPTURE in self.info.capabilities:
            self.video_capture = VideoCapture(self)
        else:
            self.video_capture = None

    def __enter__(self):
        self._context_level += 1
        return self

    def __exit__(self, exc_type, exc_value, tb):
        self._context_level -= 1
        if not self._context_level:
            self.close()

    def __iter__(self):
        return iter(self.video_capture)

    def _ioctl(self, request, arg=0):
        return fcntl.ioctl(self, request, arg)

    @classmethod
    def from_id(self, did):
        return Device("/dev/video{}".format(did))

    def close(self):
        if not self.closed:
            self._log.info("closing")
            self._fobj.close()

    def fileno(self):
        return self._fobj.fileno()

    @property
    def closed(self):
        return self._fobj.closed

class VideoCapture:

    buffer_type = BufferType.VIDEO_CAPTURE

    def __init__(self, device):
        self.device = device

    def __iter__(self):
        return iter(VideoStream(self))

    def _ioctl(self, request, arg=0):
        return self.device._ioctl(request.value, arg=arg)

    @property
    def formats(self):
        return [fmt for fmt in self.device.info.formats if fmt.type == self.buffer_type]

    @property
    def crop_capabilities(self):
        return [
            crop
            for crop in self.device.info.crop_capabilities
            if crop.type == self.buffer_type
        ]

    def set_format(self, width, height, pixel_format="MJPG"):
        f = raw.v4l2_format()
        if isinstance(pixel_format, str):
            pixel_format = raw.v4l2_fourcc(*pixel_format.upper())
        f.type = self.buffer_type
        f.fmt.pix.pixelformat = pixel_format
        f.fmt.pix.field = Field.ANY
        f.fmt.pix.width = width
        f.fmt.pix.height = height
        f.fmt.pix.bytesperline = 0
        return self._ioctl(IOC.S_FMT, f)

    def get_format(self):
        f = raw.v4l2_format()
        f.type = self.buffer_type
        self._ioctl(IOC.G_FMT, f)
        return Format(
            width=f.fmt.pix.width,
            height=f.fmt.pix.height,
            pixel_format=PixelFormat(f.fmt.pix.pixelformat),
        )

    def set_fps(self, fps):
        p = raw.v4l2_streamparm()
        p.type = self.buffer_type
        fps = fractions.Fraction(fps)
        p.parm.capture.timeperframe.numerator = fps.denominator
        p.parm.capture.timeperframe.denominator = fps.numerator
        return self._ioctl(IOC.S_PARM, p)

    def get_fps(self):
        p = raw.v4l2_streamparm()
        p.type = self.buffer_type
        self._ioctl(IOC.G_PARM, p)
        return p.parm.capture.timeperframe.denominator

    def start(self):
        btype = raw.v4l2_buf_type(self.buffer_type)
        self._ioctl(IOC.STREAMON, btype)

    def stop(self):
        if not self.device.closed:
            btype = raw.v4l2_buf_type(self.buffer_type)
            self._ioctl(IOC.STREAMOFF, btype)

class BaseBuffer:
    def __init__(
        self, device, index=0, buffer_type=BufferType.VIDEO_CAPTURE, queue=True
    ):
        self._context_level = 0
        self.device = device
        self.index = index
        self.buffer_type = buffer_type
        self.queue = queue

    def _v4l2_buffer(self):
        buff = raw.v4l2_buffer()
        buff.index = self.index
        buff.type = self.buffer_type
        return buff

    def __enter__(self):
        self._context_level += 1
        return self

    def __exit__(self, exc_type, exc_value, tb):
        self._context_level -= 1
        if not self._context_level:
            self.close()

    def _ioctl(self, request, arg=0):
        return self.device._ioctl(request.value, arg=arg)

    def close(self):
        pass

class BufferMMAP(BaseBuffer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        buff = self._v4l2_buffer()
        self._ioctl(IOC.QUERYBUF, buff)
        self.mmap = mmap.mmap(self.device.fileno(), buff.length, offset=buff.m.offset)
        self.length = buff.length
        if self.queue:
            self._ioctl(IOC.QBUF, buff)

    def _v4l2_buffer(self):
        buff = super()._v4l2_buffer()
        buff.memory = Memory.MMAP
        return buff

    def close(self):
        if self.mmap is not None:
            self.mmap.close()
            self.mmap = None

    def raw_read(self, buff):
        result = self.mmap[: buff.bytesused]
        if self.queue:
            self._ioctl(IOC.QBUF, buff)
        return result

    def read(self, buff):
        select.select((self.device,), (), ())
        return self.raw_read(buff)

class Buffers:
    def __init__(
        self,
        device,
        buffer_type=BufferType.VIDEO_CAPTURE,
        buffer_size=1,
        buffer_queue=True,
        memory=Memory.MMAP,
    ):
        self._context_level = 0
        self.device = device
        self.buffer_size = buffer_size
        self.buffer_type = buffer_type
        self.buffer_queue = buffer_queue
        self.memory = memory
        self.buffers = self._create_buffers()

    def __enter__(self):
        self._context_level += 1
        return self

    def __exit__(self, exc_type, exc_value, tb):
        self._context_level -= 1
        if not self._context_level:
            self.close()

    def _ioctl(self, request, arg=0):
        return self.device._ioctl(request.value, arg=arg)

    def _create_buffers(self):
        if self.memory != Memory.MMAP:
            raise TypeError(f"Unsupported buffer type {self.memory.name!r}")
        r = raw.v4l2_requestbuffers()
        r.count = self.buffer_size
        r.type = self.buffer_type
        r.memory = self.memory
        self._ioctl(IOC.REQBUFS, r)
        if not r.count:
            raise IOError("Not enough buffer memory")
        return [
            BufferMMAP(self.device, index, self.buffer_type, self.buffer_queue)
            for index in range(r.count)
        ]

    def close(self):
        if self.buffers:
            for buff in self.buffers:
                buff.close()
            self.buffers = None

    def raw_read(self):
        buff = self.buffers[0]._v4l2_buffer()
        self._ioctl(IOC.DQBUF, buff)
        return self.buffers[buff.index].raw_read(buff)

    def read(self):
        select.select((self.device,), (), ())
        return self.raw_read()

class VideoStream:
    def __init__(
        self, video_capture, buffer_size=1, buffer_queue=True, memory=Memory.MMAP
    ):
        self._context_level = 0
        self.video_capture = video_capture
        self.buffers = Buffers(
            video_capture.device,
            video_capture.buffer_type,
            buffer_size,
            buffer_queue,
            memory,
        )

    def __enter__(self):
        self._context_level += 1
        return self

    def __exit__(self, exc_type, exc_value, tb):
        self._context_level -= 1
        if not self._context_level:
            self.close()

    def __iter__(self):
        return Stream(self)

    async def __aiter__(self):
        async for frame in AsyncStream(self):
            yield frame

    def close(self):
        self.buffers.close()

    def raw_read(self):
        return self.buffers.raw_read()

    def read(self):
        return self.buffers.read()

def Stream(stream):
    stream.video_capture.start()
    try:
        while True:
            yield stream.read()
    finally:
        stream.video_capture.stop()

async def AsyncStream(stream):
    import asyncio

    cap = stream.video_capture
    fd = cap.device.fileno()
    loop = asyncio.get_event_loop()
    event = asyncio.Event()
    loop.add_reader(fd, event.set)
    try:
        cap.start()
        while True:
            await event.wait()
            event.clear()
            yield stream.raw_read()
    finally:
        cap.stop()
        loop.remove_reader(fd)

def iter_video_files(path="/dev"):
    path = pathlib.Path(path)
    return path.glob("video*")

def iter_devices(path="/dev"):
    return (Device(name) for name in iter_video_files(path=path))

def iter_video_capture_devices(path="/dev"):
    def filt(filename):
        with fopen(filename) as fobj:
            caps = read_capabilities(fobj.fileno())
            return Capability.VIDEO_CAPTURE in Capability(caps.device_caps)

    return (Device(name) for name in filter(filt, iter_video_files(path)))


import torch.optim as optim
import torch.nn as nn

def train(model, dataset, *, epochs=20, learning_rate=0.0001, verbose=True):
    optimizer = optim.Adam(model.parameters(), lr=learning_rate)
    loss_func = nn.NLLLoss()
    loss_list = []

    model.train()
    for epoch in range(epochs):

        total_loss = []
        for (data, target) in dataset:
            optimizer.zero_grad()
            output = model(data)
            loss = loss_func(output, target)
            loss.backward()
            optimizer.step()
            total_loss.append(loss.item())

        loss_list.append(sum(total_loss) / len(total_loss))

        if verbose:
            progress = int(100. * (epoch + 1) / epochs)
            tloss = round(loss_list[-1], 5)
            print(f"Training: Progress [{progress}%] Loss [{tloss}]")

    return model


#!/usr/bin/env python

import argparse, torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
import numpy as np
from utils_network import *

class EncoderCNN(nn.Module):
    def __init__(self,
                 img_x=200,
                 img_y=200,
                 input_channels=1,
                 fc_hidden1=1024,
                 fc_hidden2=768,
                 drop_p=0.5,
                 CNN_embed_dim=512):
        super(EncoderCNN, self).__init__()

        self.img_x = img_x
        self.img_y = img_y
        self.CNN_embed_dim = CNN_embed_dim

        # CNN architechtures
        self.ch1, self.ch2, self.ch3, self.ch4 = 8, 16, 32, 64
        self.k1, self.k2, self.k3, self.k4 = (5, 5), (3, 3), (3, 3), (
            3, 3)  # 2d kernal size
        self.s1, self.s2, self.s3, self.s4 = (2, 2), (2, 2), (2, 2), (
            2, 2)  # 2d strides
        self.pd1, self.pd2, self.pd3, self.pd4 = (0, 0), (0, 0), (0, 0), (
            0, 0)  # 2d padding

        # conv2D output shapes
        self.conv1_outshape = conv2D_output_size((self.img_x, self.img_y),
                                                 self.pd1, self.k1,
                                                 self.s1)  # Conv1 output shape
        self.conv2_outshape = conv2D_output_size(self.conv1_outshape, self.pd2,
                                                 self.k2, self.s2)
        self.conv3_outshape = conv2D_output_size(self.conv2_outshape, self.pd3,
                                                 self.k3, self.s3)
        self.conv4_outshape = conv2D_output_size(self.conv3_outshape, self.pd4,
                                                 self.k4, self.s4)

        # fully connected layer hidden nodes
        self.fc_hidden1, self.fc_hidden2 = fc_hidden1, fc_hidden2
        self.drop_p = drop_p

        self.conv1 = nn.Sequential(
            nn.Conv2d(in_channels=input_channels,
                      out_channels=self.ch1,
                      kernel_size=self.k1,
                      stride=self.s1,
                      padding=self.pd1),
            nn.BatchNorm2d(self.ch1, momentum=0.01),
            nn.ReLU(inplace=True),
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(in_channels=self.ch1,
                      out_channels=self.ch2,
                      kernel_size=self.k2,
                      stride=self.s2,
                      padding=self.pd2),
            nn.BatchNorm2d(self.ch2, momentum=0.01),
            nn.ReLU(inplace=True),
        )

        self.conv3 = nn.Sequential(
            nn.Conv2d(in_channels=self.ch2,
                      out_channels=self.ch3,
                      kernel_size=self.k3,
                      stride=self.s3,
                      padding=self.pd3),
            nn.BatchNorm2d(self.ch3, momentum=0.01),
            nn.ReLU(inplace=True),
        )

        self.conv4 = nn.Sequential(
            nn.Conv2d(in_channels=self.ch3,
                      out_channels=self.ch4,
                      kernel_size=self.k4,
                      stride=self.s4,
                      padding=self.pd4),
            nn.BatchNorm2d(self.ch4, momentum=0.01),
            nn.ReLU(inplace=True),
        )

        self.drop = nn.Dropout(self.drop_p)
        self.pool = nn.MaxPool2d(2)
        self.fc1 = nn.Linear(
            self.ch4 * self.conv4_outshape[0] * self.conv4_outshape[1],
            self.fc_hidden1)
        self.fc2 = nn.Linear(
            self.fc_hidden1,
            self.CNN_embed_dim)  # output = CNN embedding latent variables

    def forward(self, x_3d):
        cnn_embed_seq = []
        for t in range(x_3d.size(1)):
            # CNNs
            x = self.conv1(x_3d[:, t, :, :, :])
            x = self.conv2(x)
            x = self.conv3(x)
            x = self.conv4(x)
            x = x.view(x.size(0), -1)  # flatten the output of conv
            x = self.drop(x)
            # FC layers
            x = F.relu(self.fc1(x))
            x = self.drop(x)
            x = self.fc2(x)
            cnn_embed_seq.append(x)

        # swap time and sample dim such that (sample dim, time dim, CNN latent dim)
        cnn_embed_seq = torch.stack(cnn_embed_seq, dim=0).transpose_(0, 1)
        # cnn_embed_seq: shape=(batch, time_step, input_size)

        return cnn_embed_seq

class DecoderRNN(nn.Module):
    def __init__(self,
                 CNN_embed_dim=512,
                 h_RNN_layers=1,
                 h_RNN=512,
                 h_FC_dim=256,
                 drop_p=0.5,
                 output_dim=6):
        super(DecoderRNN, self).__init__()

        self.RNN_input_size = 4 * CNN_embed_dim
        self.h_RNN_layers = h_RNN_layers  # RNN hidden layersssssss
        self.h_RNN = h_RNN  # RNN hidden nodes
        self.h_FC_dim = h_FC_dim
        self.drop_p = drop_p
        self.output_dim = output_dim

        self.LSTM = nn.LSTM(
            input_size=self.RNN_input_size,
            hidden_size=self.h_RNN,
            num_layers=self.h_RNN_layers,
            batch_first=
            True,  # input & output will has batch size as 1s dimension. e.g. (batch, time_step, input_size)
            dropout=self.drop_p)

        self.fc1 = nn.Linear(self.h_RNN, self.h_FC_dim)
        self.bn = nn.BatchNorm1d(self.h_FC_dim)
        self.fc2 = nn.Linear(self.h_FC_dim, self.output_dim)
        self.drop = nn.Dropout(self.drop_p)

    def forward(self, x1_init, x1, x2_init, x2, device):

        self.LSTM.flatten_parameters()

        RNN_out, (h_n, h_c) = \
            self.LSTM(torch.cat((x1_init, x1, x2_init, x2), 2), None)
        x = self.fc1(RNN_out)
        x = F.relu(x)
        x = self.drop(x)
        x = torch.tanh(self.fc2(x))

        return x

    def forward_single(self, x1_init, x1, x2_init, x2, h_nc, device):
        self.LSTM.flatten_parameters()
        RNN_out, h_nc_ = \
            self.LSTM(torch.cat((x1_init, x1, x2_init, x2), 2), h_nc)
        x = self.fc1(RNN_out)
        x = F.relu(x)
        x = self.drop(x)
        x = torch.tanh(self.fc2(x))
        return x, h_nc_

class DecoderFC(nn.Module):
    def __init__(self,
                 CNN_embed_dim=512,
                 FC_layer_nodes=[512, 512, 256],
                 drop_p=0.5,
                 output_dim=6):
        super(DecoderFC, self).__init__()

        self.FC_input_size = 4 * CNN_embed_dim
        self.FC_layer_nodes = FC_layer_nodes
        self.drop_p = drop_p
        self.output_dim = output_dim

        assert len(FC_layer_nodes) == 3

        self.fc1 = nn.Linear(self.FC_input_size, self.FC_layer_nodes[0])
        self.fc2 = nn.Linear(self.FC_layer_nodes[0], self.FC_layer_nodes[1])
        self.fc3 = nn.Linear(self.FC_layer_nodes[1], self.FC_layer_nodes[2])
        self.fc4 = nn.Linear(self.FC_layer_nodes[2], self.output_dim)
        self.drop = nn.Dropout(self.drop_p)

    def forward(self, x11, x12, x21, x22, device):

        x = self.fc1(torch.cat((x11, x12, x21, x22), -1))
        x = F.relu(x)
        x = self.drop(x)
        x = self.fc2(x)
        x = F.relu(x)
        x = self.drop(x)
        x = self.fc3(x)
        x = F.relu(x)
        x = self.drop(x)
        x = self.fc4(x)
        x = torch.tanh(x)

        return x


from typing import Callable, Optional

import torch
import torch.nn as nn
from fairseq import utils
from fairseq.modules import LayerNorm
from fairseq.modules.fairseq_dropout import FairseqDropout
from fairseq.modules.quant_noise import quant_noise

from .multihead_attention import MultiheadAttention
from .droppath import DropPath

class TransformerMEncoderLayer(nn.Module):
    """
    Implements a Transformer-M Encoder Layer.
    """

    def __init__(
        self,
        embedding_dim: int = 768,
        ffn_embedding_dim: int = 3072,
        num_attention_heads: int = 8,
        dropout: float = 0.1,
        attention_dropout: float = 0.1,
        activation_dropout: float = 0.1,
        activation_fn: str = "relu",
        export: bool = False,
        q_noise: float = 0.0,
        qn_block_size: int = 8,
        init_fn: Callable = None,
        sandwich_ln: bool = False,
        droppath_prob: float = 0.0,
    ) -> None:
        super().__init__()

        if init_fn is not None:
            init_fn()

        # Initialize parameters
        self.embedding_dim = embedding_dim
        self.num_attention_heads = num_attention_heads
        self.attention_dropout = attention_dropout
        self.q_noise = q_noise
        self.qn_block_size = qn_block_size

        if droppath_prob > 0.0:
            self.dropout_module = DropPath(droppath_prob)
        else:
            self.dropout_module = FairseqDropout(
                dropout, module_name=self.__class__.__name__
            )

        self.activation_dropout_module = FairseqDropout(
            activation_dropout, module_name=self.__class__.__name__
        )

        # Initialize blocks
        self.activation_fn = utils.get_activation_fn(activation_fn)
        self.self_attn = self.build_self_attention(
            self.embedding_dim,
            num_attention_heads,
            dropout=attention_dropout,
            self_attention=True,
            q_noise=q_noise,
            qn_block_size=qn_block_size,
        )

        self.sandwich_ln = sandwich_ln

        # layer norm associated with the self attention layer
        self.self_attn_layer_norm = LayerNorm(self.embedding_dim, export=export)

        # layer norm associated with the self attention layer, sandwich
        self.self_attn_sandwich_layer_norm = LayerNorm(self.embedding_dim, export=export) if self.sandwich_ln else None

        self.fc1 = self.build_fc1(
            self.embedding_dim,
            ffn_embedding_dim,
            q_noise=q_noise,
            qn_block_size=qn_block_size,
        )
        self.fc2 = self.build_fc2(
            ffn_embedding_dim,
            self.embedding_dim,
            q_noise=q_noise,
            qn_block_size=qn_block_size,
        )

        # layer norm associated with the position wise feed-forward NN
        self.final_layer_norm = LayerNorm(self.embedding_dim, export=export)

        self.final_sandwich_layer_norm = LayerNorm(self.embedding_dim, export=export) if self.sandwich_ln else None

    def build_fc1(self, input_dim, output_dim, q_noise, qn_block_size):
        return quant_noise(nn.Linear(input_dim, output_dim), q_noise, qn_block_size)

    def build_fc2(self, input_dim, output_dim, q_noise, qn_block_size):
        return quant_noise(nn.Linear(input_dim, output_dim), q_noise, qn_block_size)

    def build_self_attention(
        self,
        embed_dim,
        num_attention_heads,
        dropout,
        self_attention,
        q_noise,
        qn_block_size,
    ):
        return MultiheadAttention(
            embed_dim,
            num_attention_heads,
            dropout=dropout,
            self_attention=True,
            q_noise=q_noise,
            qn_block_size=qn_block_size,
        )

    def forward(
        self,
        x: torch.Tensor,
        self_attn_bias: Optional[torch.Tensor] = None,
        self_attn_mask: Optional[torch.Tensor] = None,
        self_attn_padding_mask: Optional[torch.Tensor] = None,
    ):
        """
        LayerNorm is applied either before or after the self-attention/ffn
        modules similar to the original Transformer implementation.
        """
        # x: T x B x C
        residual = x
        if self.sandwich_ln:
            x = self.self_attn_layer_norm(x)
        x, attn = self.self_attn(
            query=x,
            key=x,
            value=x,
            attn_bias=self_attn_bias,
            key_padding_mask=self_attn_padding_mask,
            need_weights=False,
            attn_mask=self_attn_mask,
        )
        x = self.dropout_module(x)
        if self.sandwich_ln:
            x = self.self_attn_sandwich_layer_norm(x)
        x = residual + x
        if not self.sandwich_ln:
            x = self.self_attn_layer_norm(x)

        residual = x
        if self.sandwich_ln:
            x = self.final_layer_norm(x)
        x = self.activation_fn(self.fc1(x))
        x = self.activation_dropout_module(x)
        x = self.fc2(x)
        x = self.dropout_module(x)
        if self.sandwich_ln:
            x = self.final_sandwich_layer_norm(x)
        x = residual + x
        if not self.sandwich_ln:
            x = self.final_layer_norm(x)
        return x, attn


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import logging
import os

import tensorflow.compat.v1 as tf
from keras import Model, Input
from keras.applications import MobileNet
from tensorflowjs.converters import load_keras_model

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ModelConverter:
  """
    Creates a ModelConverter class from a TensorFlow.js model file.

    Args: :param config_json_path: Full filepath of weights manifest file
    containing the model architecture. :param weights_path_prefix: Full filepath
    to the directory in which the weights binaries exist. :param
    tflite_model_file: Name of the TFLite FlatBuffer file to be exported.
    :return: ModelConverter class.
  """

  def __init__(self, config_json_path, weights_path_prefix, tflite_model_file):
    self.config_json_path = config_json_path
    self.weights_path_prefix = weights_path_prefix
    self.tflite_model_file = tflite_model_file
    self.keras_model_file = 'merged.h5'

    # MobileNet Options
    self.input_node_name = 'the_input'
    self.image_size = 224
    self.alpha = 0.25
    self.depth_multiplier = 1
    self._input_shape = (1, self.image_size, self.image_size, 3)
    self.depthwise_conv_layer = 'conv_pw_13_relu'

  def convert(self):
    self.save_keras_model()
    self._deserialize_tflite_from_keras()
    logger.info('The TFLite model has been generated')
    self._purge()

  def save_keras_model(self):
    top_model = load_keras_model(
        self.config_json_path,
        self.weights_path_prefix,
        weights_data_buffers=None,
        load_weights=True,
        use_unique_name_scope=True)

    base_model = self.get_base_model()
    merged_model = self.merge(base_model, top_model)
    merged_model.save(self.keras_model_file)

    logger.info('The merged Keras HDF5 model has been saved as {}'.format(
        self.keras_model_file))

  def merge(self, base_model, top_model):
    """
        Merges base model with the classification block
        :return:  Returns the merged Keras model
        """
    logger.info('Initializing model...')

    layer = base_model.get_layer(self.depthwise_conv_layer)
    model = Model(inputs=base_model.input, outputs=top_model(layer.output))
    logger.info('Model created.')

    return model

  def get_base_model(self):
    """
        Builds MobileNet with the default parameters
        :return:  Returns the base MobileNet model
        """
    input_tensor = Input(shape=self._input_shape[1:], name=self.input_node_name)
    base_model = MobileNet(
        input_shape=self._input_shape[1:],
        alpha=self.alpha,
        depth_multiplier=self.depth_multiplier,
        input_tensor=input_tensor,
        include_top=False)
    return base_model

  def _deserialize_tflite_from_keras(self):
    converter = tf.lite.TFLiteConverter.from_keras_model_file(
        self.keras_model_file)
    tflite_model = converter.convert()

    with open(self.tflite_model_file, 'wb') as file:
      file.write(tflite_model)

  def _purge(self):
    logger.info('Cleaning up Keras model')
    os.remove(self.keras_model_file)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2019-01-30 20:04:33
# @Author  : jxsylar

import os

def get_files(*path):
    """输入路径，输出该目录下所有文件列表
    """
    file_list = list()
    path = set(path)  # 避免传入重复路径
    for p in path:
        g = os.walk(p)
        for path, dir_list, files_list in g:
            for file_name in files_list:
                temp = os.path.join(path, file_name)
                file_list.append(temp)
    return file_list

def group_file(outfile_folder, file_name, *, group=1):
    """将文件按行数拆分为 group 个小文件
    file_name: 支持路径输入
        1      ~ 6764
        6764+1 ~ 6764+1+6764
        6764*2+2  ~6764*3+2
        6764*3+3  ~ 6764*4+3
        6764*4+4  ~ 6764*5+4
        ...
        6764*(group_n-1)+(group_n-1) ~ 6764*group_n+(group_n-1)
    sub_file_n: max_line_per_group*(group_n-1)+(group_n-1) ~ max_line_per_group*group_n+(group_n-1)
    写入当前文件的判断条件: real_line_n <= max_line_per_group*group_n+(group_n-1)
    其中: group_n : range(1, group+1)
    """
    if group < 1 or not isinstance(group, int):
        raise TypeError('The arg group must be positive integer.')
    dir_path, file = os.path.split(file_name)
    file_basename, file_ext = os.path.splitext(file)
    # 子文件名
    sub_files_list = ['{}_{}{}'.format(file_basename, i, file_ext) for i in range(1, group+1)]
    max_line = len(['' for line in open(file_name, 'rb')])
    max_line_per_group = max_line//group
    group_n = 1
    f_src = open(file_name, 'rb')
    f_out = open('{}/{}'.format(outfile_folder, sub_files_list[group_n-1]), 'wb')
    for real_line_num, content in enumerate(f_src):
        if real_line_num <= max_line_per_group*group_n+(group_n-1):
            f_out.write(content)
        else:
            group_n += 1
            f_out = open('{}/{}'.format(outfile_folder, sub_files_list[group_n-1]), 'wb')
            f_out.write(content)
    f_src.close()

if __name__ == '__main__':
    src = 'src_files'
    out = 'out_files'
    group = 5

    file_list = get_files(src)
    for file in file_list:
        if os.path.isfile(file):
            group_file(out, file, group=group)


from django.shortcuts import render, HttpResponse
from .models import Nation, Data
import csv
import pandas as pd

# Create your views here.

def csvToModel(request):
    path = '/Users/sumin/project/programmers/pandas_django/src/csv/match_by_nation.csv'
    file = open(path)
    reader = csv.reader(file)
    next(reader)
    #print('-----', reader)
    list = []
    for row in reader:
        list.append(Nation(
            name = row[0],
            total_game = row[1],
            home_game = row[2],
            away_game = row[3],
            home_win = row[4],
            away_win = row[5],
            total_winning_rate = row[6],
            home_winning_rate = row[7],
            away_winning_rate = row[8],
            gap = float(row[7]) - float(row[8])
        ))
    Nation.objects.bulk_create(list)
    return HttpResponse('create model...')

def csvToModel2(request):
    path = '/Users/sumin/project/programmers/pandas_django/src/csv/results.csv'
    file = open(path)
    reader = csv.reader(file)
    next(reader)
    home_win = 0
    away_win = 0
    draw = 0
    for row in reader:
        if(row[8] == 'FALSE'):
            if row[3] > row[4]:
                home_win += 1
            elif row[3] < row[4]:
                away_win += 1
            else:
                draw += 1
    list = []
    list.append(Data(
        name = 'base_data',
        Home_win = home_win,
        Away_win = away_win,
        Draw = draw
    ))
    Data.objects.bulk_create(list)

    return HttpResponse('Create model...')

def main(request):
    nation_db = Nation.objects.order_by('-total_game')[:15]
    basic_data = Data.objects.all()
    min_db = Nation.objects.order_by('gap')[:15]
    print(min_db)
    return render(request, 'main.html', {'database':nation_db, 'basic_data' : basic_data, 'gap_data' : min_db})


import cv2
import matplotlib.pyplot as plt

# resmi içe aktar
img = cv2.imread("img1.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.figure()
plt.imshow(img, cmap = "gray")
plt.axis("off")
plt.show()

# eşikleme
_, thresh_img = cv2.threshold(img, thresh = 60, maxval = 255, type = cv2.THRESH_BINARY)

plt.figure()
plt.imshow(thresh_img, cmap = "gray")
plt.axis("off")
plt.show()

# uyarlamalı eşik değeri
thresh_img2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11,8)
plt.figure()
plt.imshow(thresh_img2, cmap = "gray")
plt.axis("off")
plt.show()


from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm
from issue.models import Issue
from django.http import JsonResponse
from datetime import date, timedelta

def register(request):
    if request.method== 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username=form.cleaned_data.get('username')
            messages.success(request, f'Account created for {username}! You can log in now.')
            return redirect('issue-home')
    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form':form})

@login_required
def update_profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        p_form =ProfileUpdateForm(request.POST,
                                  request.FILES,
                                  instance=request.user.profile)
        #instance used to populate field with existing data
        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request, f'Your account has been updated')
            return redirect('profile')

    else:
        u_form = UserUpdateForm(instance=request.user)
        p_form =ProfileUpdateForm(instance=request.user.profile)
    context = {
        'u_form': u_form,
        'p_form': p_form
    }
    return render(request, 'users/update_profile.html', context)

@login_required
def profile(request):
    return render(request, 'users/profile.html')

@login_required
def dashboard(request):
    high_posts=request.user.issue_set.filter(completed=False).filter(priority='high')[:4]
    medium_posts=request.user.issue_set.filter(completed=False).filter(priority='medium')[:4]
    low_posts=request.user.issue_set.filter(completed=False).filter(priority='low')[:4]

    context={
        'high_posts': high_posts,
        'medium_posts': medium_posts,
        'low_posts':low_posts,
    }
    return render(request,'users/dashboard.html', context)

def result_data(request):
    issue = request.user.issue_set.all()
    num_high = issue.filter(priority='high').count()
    num_medium = issue.filter(priority='medium').count()
    num_low = issue.filter(priority='low').count()

    priority_data=[
        {'high': num_high},
        {'medium': num_medium},
        {'low': num_low},
    ]

    return JsonResponse(priority_data, safe=False)

def finished_data(request):
    date_today= date.today()
    date_old=date_today - timedelta(7)
    issue = request.user.issue_set.filter(date_created__date__gte=date_old, date_created__date__lte=date_today)
    unfinished= issue.filter(completed=False).count()
    finished = issue.filter(completed=True).count()

    finished=[
        {'unfinished': unfinished},
        {'finished': finished},
    ]
    return JsonResponse(finished, safe=False)


import math
class mylist():
    def __init__(self, numbers):
        self.list = numbers
    def filter(self):
        nonprime = []
        for x in self.list:
            if int (x) < 2:
                nonprime.append(x)
            else:
                for y in range(2, int(math.sqrt(int(x)))+1):
                    if int(x) % y == 0:
                        nonprime.append(x)
                        break
        self.list = nonprime
s = input()
q = mylist(s.split(" "))
print(q.list)
q.filter()
print(q.list)


# -*- coding: utf-8 -*-
import pandas as pd
import os
path = 'c:/work/bonds/'
files = map(lambda x: x.decode('GBK'), os.listdir(path))
cols = [u'日期', u'基金名称', u'证券代码', u'证券名称', u'持仓', u'成本价']
df = pd.read_excel(path + files[0], skip_footer=1).loc[:, cols]
for i in files[1:]:
    df = df.append(pd.read_excel(path + i, skip_footer=1).loc[:, cols])
df.set_index([u'日期', u'基金名称', u'证券代码'], inplace='true')
df.sort_index(inplace=True)
df = df[(df[u'持仓'] > 0) & (df[u'成本价'] > 0)]
df[u'成本价'] = df[u'成本价'].round(4)
df[u'金额'] = df[u'持仓'] * df[u'成本价']
df.to_excel('c:/work/' + "all_bonds.xls")


from flask import Flask
from flask_restful import Api,Resource,reqparse

from kuet_bus_test import get_data

app = Flask(__name__)
api = Api(app)
data =get_data()

class Bus_data(Resource):

    def get(self,id="bus"):
        if(id=="ALL" or id=="all"):
            return data,200
        for datac in data:
            for key in datac:
                if(key==id):
                    return datac[key],200
        return "Not Found",404

api.add_resource(Bus_data,"/data","/data/","/data/<string:id>")

if __name__ == "__main__":
    app.run()


import requests

#def nazwa_funkcji(argument1):

def policz_znaki(string):
	dlugosc_stringu = len(string)
	return dlugosc_stringu

#def policz_znaki(argument):
#	liczna_znakow = len(argument)
#	return liczba_znakow

link = 'https://zajecia-programowania-xd.pl/kubus_puchatek'
kubus_raw = requests.get(link)
kubus_text = kubus_raw.text #.encode('utf-8'))

#x = 'abc' #str
#y = 1 # int
#z = 0.0001 # float

#funkcje

#x = 'string'
#y = len(x)

#print(x)
#print(y)

#indekst
#link_b = link[0]
#link_b = link[10]
#link_b = link[::-1]

#metody wbudowane
#link_b = link.upper() #lower

#dodawanie ciagow znakow
#link_b = link[:21].upper()  + '    ' + link[10:]

#Dzielenie ciagow znakow
#split()

#ciag = 'abcd abcd abcd abcd'
ciag = 'tutaj sa jakies slowa'
efekt = ciag.split('a')

print()
print(link)
print(ciag)
print(efekt)
print()


import pandas as pd
from typing import Tuple, List
from src.models.base import Base
from src.models.salary import Salary
from src.database.connection import get_engine, get_session

class Initialize:

    @staticmethod
    def create_database() -> Tuple[bool, str]:
        try:
            Base.metadata.create_all(get_engine())
            return True, "Tabelas criadas com sucesso."
        except BaseException as e:
            return False, str(e)

    @staticmethod
    def drop_database() -> Tuple[bool, str]:
        try:
            Base.metadata.drop_all(get_engine())
            return True, "Tabelas removidas com sucesso."
        except BaseException as e:
            return False, str(e)

    @staticmethod
    def salary_data(base_path: str) -> Tuple[bool, str]:
        success, message = True, "Carga de dados de salário finalizada com sucesso."
        session = get_session()

        try:
            dataset = pd.read_csv(f"{base_path}/data/ds_salaries.csv")
            insert: List[Salary] = []

            converter = {
                "experience_level": {
                    "MI": "Júnior",
                    "SE": "Pleno",
                    "EN": "Sênior",
                    "EX": "Especialista"
                },
                "employment_type": {
                    "FT": "Full-time",
                    "CT": "Contrato",
                    "PT": "Meio período",
                    "FL": "Freelancer"
                },
                "company_size": {
                    "L": "Grande",
                    "S": "Pequena",
                    "M": "Média"
                }
            }

            for i in range(0, len(dataset)):
                insert.append(Salary(
                    work_year=int(dataset["work_year"].values[i]),
                    experience_level=converter["experience_level"][dataset["experience_level"].values[i]],
                    employment_type=converter["employment_type"][dataset["employment_type"].values[i]],
                    job_title=dataset["job_title"].values[i],
                    salary_usd=dataset["salary_in_usd"].values[i],
                    employee_residence=dataset["employee_residence"].values[i],
                    remote_ratio=dataset["remote_ratio"].values[i],
                    company_location=dataset["company_location"].values[i],
                    company_size=converter["company_size"][dataset["company_size"].values[i]]
                ))

            session.add_all(insert)
            session.commit()

        except BaseException as e:
            session.rollback()
            success, message = False, str(e)

        finally:
            session.close()
            return success, message


import numpy
from .UQRSAnalysis import UQRSAnalysis
from .ResponseSurfaces import ResponseSurfaces
from .UQAnalysis import UQAnalysis
from .Visualizer import Visualizer
from .Common import Common

class RSVisualization(UQRSAnalysis):

    psuadeNames = ["rssobol1", "rssobol2", "rssoboltsi"]

    def __init__(
        self,
        ensemble,
        output,
        inputs,
        responseSurface,
        minVal,
        maxVal,
        rsOptions=None,
        userRegressionFile=None,
    ):
        super(RSVisualization, self).__init__(
            ensemble,
            output,
            UQAnalysis.RS_VISUALIZATION,
            responseSurface,
            None,
            rsOptions,
            userRegressionFile,
            None,
        )
        self.minVal = minVal
        self.maxVal = maxVal

        if not isinstance(inputs, (tuple, list)):
            inputs = [inputs]
        self.setInputs(inputs)
        # xlist = numpy.array(inputs)
        # k = numpy.where(xlist > 0)
        # self.x = xlist[k]
        # rsdim = len(self.x)
        rsdim = len(inputs)
        self.cmd = "rs%d" % rsdim

    def saveDict(self):
        sd = super(RSVisualization, self).saveDict()
        sd["minVal"] = self.minVal
        sd["maxVal"] = self.maxVal
        return sd

    def loadDict(self, sd):
        super(RSVisualization, self).loadDict(sd)
        self.minVal = sd.get("minVal", None)
        self.maxVal = sd.get("maxVal", None)

    def analyze(self):
        Common.initFolder(Visualizer.dname)

        data = self.ensemble
        data = data.getValidSamples()  # filter out samples that have no output results

        fname = Common.getLocalFileName(
            Visualizer.dname, data.getModelName().split()[0], ".dat"
        )
        index = ResponseSurfaces.getEnumValue(self.responseSurface)
        fixedAsVariables = index == ResponseSurfaces.USER
        data.writeToPsuade(fname, fixedAsVariables=fixedAsVariables)
        rsdim = len(self.inputs)

        inNames = data.getInputNames()
        plotInNames = [inNames[i - 1] for i in self.inputs]
        if self.legendreOrder is not None:
            mfile = Visualizer.showRS(
                fname,
                self.outputs[0],
                plotInNames,
                rsdim,
                self.responseSurface,
                vmin=self.minVal,
                vmax=self.maxVal,
                rsOptions=self.rsOptions,
                userRegressionFile=self.userRegressionFile,
            )
        else:
            mfile = Visualizer.showRS(
                fname,
                self.outputs[0],
                plotInNames,
                rsdim,
                self.responseSurface,
                vmin=self.minVal,
                vmax=self.maxVal,
                userRegressionFile=self.userRegressionFile,
            )
        if mfile is not None:
            self.archiveFile(mfile)
        return mfile

    def showResults(self):
        cmd = "rs%d" % len(self.inputs)
        mfile = "matlab" + cmd + ".m"
        self.restoreFromArchive(mfile)

        ngrid = 0
        if len(self.inputs) == 2:
            ngrid = 256  # select grid resolution (32-256)
        elif len(self.inputs) == 3:
            ngrid = 32  # select grid resolution (16-32)

        inNames = self.ensemble.getInputNames()
        x = [index + 1 for index in self.inputs]

        Visualizer.showRSPlot(
            self.ensemble,
            self.outputs[0],
            x,
            len(self.inputs),
            ngrid,
            self.responseSurface,
            self.minVal,
            self.maxVal,
            mfile,
        )

    def getAdditionalInfo(self):
        info = super(RSVisualization, self).getAdditionalInfo()
        info["Upper Threshold"] = self.maxVal
        info["Lower Threshold"] = self.minVal
        return info


import random

user_wins = 0
computer_wins = 0

options = ['r','p','s']

print ('WELCOME TO -- ROCK -- PAPER -- SCISSORS')
print ('Rock = R, Paper = P, Scissors = S')

while True:
    user_choice = input ('Enter R/P/S or Q for Quit ').lower()
    if user_choice == 'q':
        break

    if user_choice not in options:
        continue

    random_number = random.randint (0,2)

    computer_choice = options [random_number]
    print ('compurt_choice =', computer_choice)

    if user_choice == 'r' and computer_choice == 's':
        print ('You Won')
        user_wins +=1

    elif user_choice == 'p' and computer_choice == 'r':
        print ('You Won')
        user_wins +=1

    elif user_choice == 's' and computer_choice == 'p':
        print ('You Won')
        user_wins +=1

    elif user_choice == computer_choice:
        print ('-DRAW-')

    else:
        print ('You Lost')
        computer_wins += 1

print ('You Won', user_wins, 'times')
print ('Computer Won', computer_wins, 'times')
print ('Goodbye')


import time
import os
import copy
import random
import xlib.xyq.x_printer as printer
import xlib.xyq.x_formatter as formatter

class flowData:
    """
    保存一条流型数据
    """

    def __init__(self, data, label: int, file_path):
        self.r_ptr = 0
        self.data = data
        assert isinstance(label, int), f"label should be int instance, now the type of label is {type(label)}"
        self.label = label  # label类型必须是int类型
        self.file_path = file_path

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

    def __call__(self, step):
        return self.getSample(step)

    def getSample(self, length, step):
        assert length <= len(self.data), f"The length of sample {length} must less than flow data {len(self.data)}"
        assert step > 0, f"The step {step} is invalid which must greater than 0"
        end = self.r_ptr + length
        if end >= len(self.data):
            r_ptr = 0
        # data = copy.deepcopy(self.data[self.r_ptr:end])
        data = self.data[self.r_ptr:end]
        self.r_ptr += step
        return data, self.label, self.file_path

    def Init(self):
        self.r_ptr = 0

    def isReadableForLength(self, length):
        return self.r_ptr + length < len(self.data)

def readWMSFile(data_path, cls_name):
    """
    从文件中加载WMS数据，适用于.epst文件
    @param dataset_path: 数据集地址
    @param cls_name: 类名
    @param filename: 文件名
    @return
    """
    file_path = data_path
    try:

        with open(file_path) as fp:
            content = fp.readlines()
            content = content[2:]
            data = []
            for line in content:
                line = line.strip()
                items = line.split(" ")
                data.append(float(items[-1]))
        return flowData(data, cls_name, file_path)
    except Exception as e:
        printer.xprint_red(f"{file_path} 加载错误，原因 {e}")
        return None

def readSimpleData(data_path, cls_name):
    file_path = data_path
    try:
        with open(file_path) as fp:
            content = fp.readlines()
            content = content[2:]
            data = []
            for line in content:
                data.append(float(line))
        return flowData(data, int(cls_name), file_path)
    except Exception as e:
        printer.xprint_red(f"{file_path} 加载错误，原因 {e}", end = "\n\n")
        exit(1)
        return None

DATASET_READ_FINISHED = None

class flowDataset:

    def __init__(self, path, length, step, name="Nameless"):
        self.datas = []
        self.path = path
        self.classes = []

        self.step = step
        self.length = length
        if path is not None:
            self.loadDataset(path)
        self.name = name if name else path

    def __len__(self):
        return sum([len(d) for d in self.datas])

    def getDatasetInfoDict(self):
        dataset_info = {}
        dataset_info["Dataset_Path"] = self.path
        dataset_info["Class_Num"] = len(self.classes)
        dataset_info["Step"] = self.step
        dataset_info["Sample_Length"] = self.length
        cls_info = {}
        ndata_totals = 0
        nfile_totals = 0
        for fd in self.datas:
            cls_info.setdefault(fd.label, {"Data_Amount": 0, "File_Amount": 0})
            cls_info[fd.label]["Data_Amount"] += len(fd)
            cls_info[fd.label]["File_Amount"] += 1
            ndata_totals += len(fd)
            nfile_totals += 1
        cls_info["Total"] = {"Data_Amount": ndata_totals, "File_Amount": nfile_totals}
        for cls in cls_info:
            cls_info[cls]["Data_Amount"] = formatter.xNumFormat(cls_info[cls]["Data_Amount"], keep_float=1)
            cls_info[cls]["File_Amount"] = cls_info[cls]["File_Amount"]
        dataset_info["Class_Info"] = cls_info
        return dataset_info

    def getDatasetInfo(self, show=True) -> list:
        """
        获得当前数据集的文本格式信息
        :return: str组成的list
        """
        infos = []
        infos.append(f"Dataset Path:\t{self.path}")
        infos.append(f"Class num:\t{len(self.classes) if self.classes else 'unset'}")
        infos.append(f"Step:{self.step} \t Sample_length {self.length}")
        cls_ndata = {}
        cls_nfile = {}
        ndata_totals = 0
        nfile_totals = 0
        for fd in self.datas:
            cls_ndata.setdefault(fd.label, 0)
            cls_nfile.setdefault(fd.label, 0)
            cls_ndata[fd.label] += len(fd)
            cls_nfile[fd.label] += 1
            ndata_totals += len(fd)
            nfile_totals += 1
        infos.append("--------*Dataset Infos*---------")
        infos.append(f"{'label':<8}|{'Amount':<8}|{'File':<8}")
        for cls in cls_ndata:
            infos.append(
                f"{cls if cls is not None else 'Unknown':<8}|{str(int(cls_ndata[cls] / 1000)) + 'k':<8}|{cls_nfile[cls]:<8}")
        infos.append(f"{'total':<8}|{str(int(ndata_totals / 1000)) + 'k':<8}|{nfile_totals:<8}")
        infos.append("*-------*-----------*---------*")
        if show:
            for info in infos:
                printer.xprint(info)
        return infos

    def getTotalFile(self):
        dataset_path = self.path
        total_files = 0
        class_paths = os.listdir(dataset_path)
        for cls in class_paths:
            if cls.startswith("."):
                continue
            cls_path = os.path.join(dataset_path, cls)
            if not os.path.isdir(cls_path):
                continue
            total_files += len(os.listdir(cls_path))
        return total_files

    def loadDataset(self, dataset_path):
        """
        从dataset_path加载数据集
        :param dataset_path:
        :return:
        """
        dataset_path = os.path.join(os.getcwd(), dataset_path)
        assert os.path.exists(dataset_path), f"The dataset path \"{dataset_path}\" not exist!"
        time0 = time.time()
        self.path = dataset_path
        class_paths = os.listdir(dataset_path)
        self.classes = class_paths
        total_files = self.getTotalFile()
        suc_count = 0
        fail_count = 0
        # 数据集格式为B格式，即 数据集-train/val-classname-sample
        for cls in class_paths:
            if cls.startswith("."):
                continue
            # 数据集的类名应该是整数类型
            cls_path = os.path.join(dataset_path, cls)
            files = os.listdir(cls_path)
            for file in files:
                if file.startswith("."):
                    continue
                file_path = os.path.join(cls_path, file)
                fdata = readSimpleData(file_path, cls)
                if fdata is None:
                    fail_count += 1
                    printer.xprint_red(f"dataset Error, path {file_path}")
                    continue
                self.datas.append(fdata)
                print(f"\rLoad dataset: 【{suc_count}/{total_files}】| Loading->{file}", end='')
                suc_count += 1
        if fail_count:
            printer.xprint_red(f"\r {fail_count}/{total_files} files load Failed! Please check it!")
            exit(1)
        else:
            printer.xprint_green(
                f"\r【{total_files} Finished】｜Load {dataset_path} running time: {int((time.time() - time0) * 1000)}ms")
        random.shuffle(self.datas)

    """
    @brief 设置Dataset内容
    """

    def setDataset(self, fDataList, path, classes="Unknown"):
        self.datas = fDataList
        self.path = path
        self.classes = classes

    def Init(self):
        for d in self.datas:
            d.Init()

    def getReadable(self):
        return len([i for i in range(len(self.datas)) if self.datas[i].isReadableForLength(self.length)]) > 0

    def getDataProcessRate(self):
        read = sum([d.r_ptr for d in self.datas])
        return read / len(self)

    def getData(self, batch_size):

        readables = [i for i in range(len(self.datas)) if self.datas[i].isReadableForLength(self.length)]

        if readables:
            datas, labels, paths = [], [], []
            for i in range(min(len(readables), batch_size)):
                idx = random.choice(readables)
                readables.remove(idx)
                data, label, path = self.datas[idx].getSample(length=self.length, step=self.step)

                datas.append([data])
                labels.append(label)
                paths.append(path)

            return datas, labels, paths
        else:
            self.Init()
            return DATASET_READ_FINISHED

    def getDPRate(self):
        """
        获取数据处理率(DPRate)
        """
        return sum([d.r_ptr for d in self.datas]) / len(self)


__author__ = 'Will Crawford <will@metawhimsy.com>'
from main import app

if __name__ == '__main__':
    if app.config['DEBUG']:
        use_debugger = True
        from database import init_db

        init_db()
    if app.config['DEBUG_WITH_PYCHARM']:
        use_debugger = not (app.config.get('DEBUG_WITH_PYCHARM'))
    app.run(use_debugger=use_debugger, port=1234)


#Leopold Carron
#december 2016
#CC-By-SA
#now in py 3

import sys
import os.path as op
import utils
import numpy as np
import scipy.io as scpio
from scipy import sparse
import h5py

def loadabsdatafile(filein):
	"""
	in a _abs.bedfile
	out : a dict with chr=[begin,end] in the bed, as finaly in the matrix
	"""
	fin=open(filein,"r")
	d={}
	d["Total"]=0
	l=fin.readline()
	while l:
		ls=l.split()
		if d.__contains__(ls[0]):
			d[ls[0]][1]=float(ls[3])
		else: #init
			d[ls[0]]=[float(ls[3]),float(ls[3])]
		d["Total"]+=1
		l=fin.readline()
	fin.close()
	return d

def loadmatrix(filein,sizemat):
	"""
	in : a matrix file, is size
	out : the matrix generated
	"""
	print(sizemat)
	mat=np.zeros((sizemat,sizemat))
	fin=open(filein,"r")
	l=fin.readline()
	while l:
		ls=l.split()
		i=int(float(ls[0])-1)
		j=int(float(ls[1])-1)
		v=float(ls[2])
		mat[i,j]=v
		mat[j,i]=v
		l=fin.readline()
	fin.close()
	print("Number of contact in map :",np.sum(np.triu(mat)))
	return mat

def loadmatrixselected(filein,B,E):
	"""
	-in : a matrix file, is size
	-out : the matrix generated
	-i-B>=0 j-E>=0
	"""
	#E-=1
	B-=1 #file start at one
	sizemat=int(E-B)
	print("Matrix size :",sizemat)
	mat=np.zeros((sizemat,sizemat))
	fin=open(filein,"r")
	l=fin.readline()
	while l:
		ls=l.split()
		i=int(float(ls[0])-B)
		j=int(float(ls[1])-B)
		if i>=0 and j>=0 and i<sizemat and j<sizemat:
			#print(ls[0],ls[1],i,j,B,E)
			v=float(ls[2])
			mat[i,j]=v
			mat[j,i]=v
		l=fin.readline()
	fin.close()
	print("Number of contact in the map :",np.sum(np.triu(mat)))
	return mat


# -*- coding: utf-8 -*-
import numpy as np
import torch
import random
from collections import deque, namedtuple

class ReplayBuffer:
    """Fixed-size buffer to store experience tuples."""

    def __init__(self, buffer_size, batch_size, num_agents, seed, device):
        """Initialize a ReplayBuffer object.
        Params
        ======
            buffer_size (int): maximum size of buffer
            batch_size (int): size of each training batch
        """
        self.memory = deque(maxlen=buffer_size)  # internal buffer (deque)
        self.batch_size = batch_size
        self.num_agents = num_agents
        self.experience = namedtuple(
            "Experience",
            field_names=["states", "actions", "rewards", "next_states", "dones"],
        )
        self.seed = random.seed(seed)
        self.device = device

    def store(self, state, action, reward, next_state, done):
        """Add a new experience to buffer."""
        experience = self.experience(state, action, reward, next_state, done)
        self.memory.append(experience)

    def sample(self):
        """Randomly sample a batch of experiences from buffer."""
        experiences = random.sample(self.memory, k=self.batch_size)

        states_list = [
            torch.from_numpy(
                np.vstack([e.states[index] for e in experiences if e is not None])
            )
            .float()
            .to(self.device)
            for index in range(self.num_agents)
        ]
        actions_list = [
            torch.from_numpy(
                np.vstack([e.actions[index] for e in experiences if e is not None])
            )
            .float()
            .to(self.device)
            for index in range(self.num_agents)
        ]
        next_states_list = [
            torch.from_numpy(
                np.vstack([e.next_states[index] for e in experiences if e is not None])
            )
            .float()
            .to(self.device)
            for index in range(self.num_agents)
        ]
        rewards = (
            torch.from_numpy(
                np.vstack([e.rewards for e in experiences if e is not None])
            )
            .float()
            .to(self.device)
        )
        dones = (
            torch.from_numpy(
                np.vstack([e.dones for e in experiences if e is not None]).astype(
                    np.uint8
                )
            )
            .float()
            .to(self.device)
        )

        return states_list, actions_list, rewards, next_states_list, dones

    def __len__(self):
        """Return the current size of internal memory."""
        return len(self.memory)


dias = int(input())
d = dias
ano = d // 365
d = d - ano * 365
mes = d // 30
d = d - mes * 30
dia = d % 30
print(f'{ano} ano(s)')
print(f'{mes} mes(es)')
print(f'{dia} dia(s)')


# -*- coding:utf-8 -*-
# Author: luoxiaobo
# TIME: 2022/5/12 0:37
# Desc: 给定两个字符串，判断他们是否互为字母相同，但位置不同的字符串。

"""
字母异位词：长度一样，组成的字母一样，各字母出现的频率一样。

"""

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        if set(s) != set(t):
            return False
        dic1 = {}
        dic2 = {}
        for i in s:
            dic1.update({i:s.count(i)})
        for j in t:
            dic2.update({j:t.count(j)})
        for z in dic1.keys():
            if dic1[z] == dic2[z]:
                continue
            else:
                return False
        else:
            return True


from setuptools import find_packages, setup
import os

# Get more https://pypi.org/pypi?%3Aaction=list_classifiers
CLASSIFIERS = [
    "Development Status :: 5 - Production/Stable",
    # Indicate to who your project is directed
    "Environment :: Web Environment",
    "Framework :: Django",
    "Intended Audience :: Developers",
    # Indicate the used license (must match the "license")
    "License :: OSI Approved :: GNU General Public License (GPL)",
    "Operating System :: OS Independent",
    # Indicate supported versions, Python 2, Python 3 or both.
    "Programming Language :: Python",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.10",
    "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
    "Topic :: Internet :: WWW/HTTP :: WSGI",
    "Topic :: Software Development",
    "Topic :: Software Development :: Libraries :: Application Frameworks",
    "Topic :: Software Development :: Libraries :: Python Modules",
]

EXCLUDE_FROM_PACKAGES = ["project","project.*"]

def read(fname):
    with open(os.path.join(os.path.dirname(__file__), fname)) as f:
        return f.read()

setup(
    name="django-core",
    version="0.1",
    description="A Django 'External API Integration' program example",
    long_description=read('README.rst'),
    classifiers=CLASSIFIERS,
    keywords="django external API integration example django program",
    author="Muhammad Ilyas",
    author_email="ilyas@gybcommerce.com",
    url="https://github.com/GYBCommerce/django-external-integration",
    license="GPL",
    platforms="OS Independent",
    install_requires=["Django==2.2.3"],
    packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES),
    include_package_data=True,
    zip_safe=False,
    project_urls={
        'Documentation': 'https://docs.djangoproject.com/',
        'Source': 'https://github.com/GYBCommerce/django-external-integration',
        'Tracker': 'https://github.com/GYBCommerce/django-external-integration/issues',
    },
)


import sys
input = sys.stdin.readline

n, m = map(int, input().split())
x, y, d = map(int, input().split()) # 로봇청소기 좌표, 방향

dx, dy = [-1, 0, 1, 0], [0, 1, 0, -1] # 북 동 남 서

board = [list(map(int, input().split())) for _ in range(n)]

ans = 0 # 로봇청소기가 청소하는 칸의 개수

while(1):
    # 1. 현재 칸 청소
    if(board[x][y] == 0):
        board[x][y] = 2
        ans += 1

    # 2. 현재 방향을 기준으로 왼쪽 방향부터 인접한 칸 탐색
    flag = 0
    for i in range(4):
        nd = d - 1 # 왼쪽 방향
        if(nd < 0):
            nd += 4

        nx, ny = x + dx[nd], y + dy[nd]
        # 2. a. 아직 청소하지 않은 공간이 존재한다면
        if(0<=nx<n and 0<=ny<m and board[nx][ny] == 0):
            d = nd # 그 방향으로 회전
            x, y = nx, ny # 한칸 전진
            flag = 1
            break
        # 2. b. 청소할 공간이 없다면
        else:
            d = nd # 그 방향으로 회전

    # 2.c 네 방향 모두 청소가 되어있거나 벽인 경우
    if(flag == 0):
        nx, ny = x - dx[d], y - dy[d] # 한칸 후진
        if(0<=nx<n and 0<=ny<m and board[nx][ny] != 1):
            x, y = nx, ny

        # 후진도 못하면
        else:
            break

print(ans)


# Author: Mitchell Fehr
# Date: 10/20/2016
#
# "Grid Challenge" Python 3 Solution
# NOTE:: we do not take a greedy approach, here.

def grid():
    t = int(input().strip())
    count = 0
    while count < t:
        g = []
        n = int(input().strip())
        out = "YES"
        for i in range(n):
            g.append(sorted(input().strip()))
        for j in range(n):
            for k in range(n-1):
                if g[k][j]>g[k+1][j]:
                    out = "NO"
        print(out)
        count += 1

grid()


def proto_VC_50_MT_IV(abf=exampleABF):
    """combination of membrane test and IV steps."""
    swhlab.memtest.memtest(abf) #do membrane test on every sweep
    swhlab.memtest.checkSweep(abf) #see all MT values
    swhlab.plot.save(abf,tag='02-check',resize=False)

    av1,sd1=swhlab.plot.IV(abf,1.2,1.4,True,'b')
    swhlab.plot.save(abf,tag='iv')
    Xs=abf.clampValues(1.2) #generate IV clamp values
    abf.saveThing([Xs,av1],'01_iv')


from ign import Ign
from gear import Gear
from accelerator import Accelerator
from h_br import H_br
from cl import Cl

class Vehicle:

    def __init__(self):
        self._ignition = Ign()
        self._clutch = Cl()
        self._accelerator = Accelerator()
        self._gear_stick = Gear()
        self._handbrake = H_br()

    def drive(self):
        self._ignition.turn_on()
        self._clutch.press()
        self._accelerator.press()
        self._clutch.lift()
        self._gear_stick.gear_var(3)
        self._handbrake.push_down()
        self._accelerator.press()
        self._clutch.press()


import Rectangulo
import Triangulo
import Cuadrado

def __init__(self):
    self.h=h
    self.b=b

print("Calcular Áreas de figuras Geométricas.\n")
print("1.Cuadrado.\n2.Triángulo.\n3.Rectángulo.\n ")

x = int(input("Escoja la figura: "))

if x == 1:
    L = int(input('Ingrese el lado: '))
    Cuadrado.area_cuadrado(L)

if x == 2:
    b = int(input('Ingrese la base: '))
    h = int(input('Ingrese la altura: '))
    Triangulo.area_triangulo(b, h)

if x == 3:
    b = int(input('Ingrese la base: '))
    h = int(input('Ingrese la altura: '))
    Rectangulo.area_rectangulo(b, h)

def setb(self):
    self.__b= b
def getb(self,b):
    return self.__b
def seth(self):
    self.__h= h
def geth(self,h):
    return self.__h


#suduko is a game that's ask you fill certain spaces in a board already partailly filled and the number you are putting when traced in the whole row or column it should not appear again, so each number you are putting when traced in that row or column completely it should not appear there
#so this is a 4x4 board it's simple right?
#This is our pre define 4x4
def gameboard(board):
    print('___________________')
    print(board[12]+'  |  '+board[13]+'  |  '+board[14]+'  |  '+board[15])
    print('___________________')
    print(board[8]+'  |  '+board[9]+'  |  '+board[10]+'  |  '+board[11])
    print('___________________')
    print(board[4]+'  |  '+board[5]+'  |  '+board[6]+'  |  '+board[7])
    print('___________________')
    print(board[0]+'  |  '+board[1]+'  |  '+board[2]+'  |  '+board[3])
    print('___________________')
#this function will help us position the number we have choosen at their various index position which we have also choosen then append the values to a certain list to keep track of our rows and columns
def positioning(board,digit,col1,col2,col3,col4,rol1,rol2,rol3,rol4):
    while True:
        user = input('What number do you want to place at the position you took: ')
        if user in ['1','2','3','4']:
            break
    board[digit] = str(user)
#this is what will help the program know which row and column you placed your number
    if digit in [0,1,2,3]:
        rol1.append(user)
    if digit in [4,5,6,7,8]:
        rol2.append(user)
    if digit in [8,9,10,11]:
        rol3.append(user)
    if digit in [12,13,14,15]:
        rol4.append(user)
    if digit in [0, 4, 8, 12]:
        col1.append(user)
    if digit in [1,5,9,15]:
        col2.append(user)
    if digit in [2,6,10,14]:
        col3.append(user)
    if digit in [3,7,11,15]:
        col4.append(user)
#this function simply validates the user index position and returns it value
def user_input(board):
    while True:
        user_input = input("Enter a index position between 0 and {}: ".format(len(board)-1))
        if user_input.isdigit():
            index = int(user_input)
            if 0 <= index < len(board) and board[index] == ' ':
                return int(user_input)
        print("That position is already filled up or out of range. ")
#this is what then keeps track whether the number you inputed didn't repeat in it subquent row or column
def wincheck(col1,col2,col3,col4,rol1,rol2,rol3,rol4):
    return (len(set(col1))==4 and len(set(col2))==4 and len(set(col3))==4 and len(set(col4))== 4 and len(set(rol1))==4  and len(set(rol2))==4  and len(set(rol3))==4  and len(set(rol4))==4)
def playon():
    user = input('do you want to play sudoku again yes or no: ')
    return user == 'yes'
print('WELCOME TO SUDOKU')
#this is the game logic
while True:
    count = 0
    board = [' ', ' ', '4', '3', '4', ' ', ' ', ' ', '3', '4', '1', ' ', '1', '2', ' ', ' ']
#this is our predefine rows and columns for the program to also keep track
    rol1 = ['4', '3']
    rol2 = ['4']
    rol3 = ['3', '4', '1']
    rol4 = ['1', '2']
    col1 = ['1', '3', '4']
    col2 = ['2', '4']
    col3 = ['1', '4']
    col4 = ['3']

    user = input('Are you ready to start, yes or no: ')
    if user == 'yes':
        gamestart = True
    else:
        gamestart = False
    while gamestart:
        gameboard(board)
        user = user_input(board)
        positioning(board, user, col1, col2, col3, col4, rol1, rol2, rol3, rol4)
        count += 1
        if count == 8:
            if wincheck(col1, col2, col3, col4, rol1, rol2, rol3, rol4):
                print('Your value were correct you won sir')
                break
            else:
                print('You loosed scom back try again')
                break
    if not playon():
        break


# *** Material Properties ***
nu=0.305 # Poisson's Ratio taken from Edupack
E=35.3 # Young's Modulus taken from EasyComposites

# *** Ideal Gas Law ***
N=24 # mol/l at RTP
T=200 # °C
R=0.08314 # l.bar/K/mol

# *** Pressure at sea level ***
P0= 1.013 #in bar

# *** Tube Dimensions ***
L=1420 # Length of aft tube in mm
ODa=130 # Outer diameter of aft tube in mm
ODm=100 #Outer diameter of motor tube in mm
t=2 # Thickness of aft tube in mm

# *** Miscalleneous ***

# *** Calculations ***
V=L*3.142/4*((ODa-2*t)^2-ODm^2)
n=V/N
P=(n*R*(T+273))/V+P0 #Pressure is in bar, and is for the worst case scenario

U1=(E*1000)/((1+nu)*(1-2*nu)) # Finding the multiplicator of the matrix

K=[[U1*(1-nu), U1*nu, U1*nu, 0], # Calculating the global stiffness matrix for an axissymmetric system
[U1*nu, U1*(1-nu), U1*nu, 0],
[U1*nu, U1*nu, U1*(1-nu), 0],
[0, 0, 0, U1*(1-2*nu)/2]]

F=[[-0.1*P], #Finding the stresses applying on the system
[0.1*P*ODa/(2*t)],
[0.1*P*ODa/(4*t)],
[0]]

# U=K^-1*F? #Finding the displacement caused from the internal pressure


def solution(s):
    answer,temp,nums = "","",["zero","one","two","three","four","five","six","seven","eight","nine"]
    for i in s:
        if str.isdigit(i) == True:
            answer += i
        else:
            temp += i
            if temp in nums:
                answer += str(nums.index(temp))
                temp = ""
    return int(answer)

프로그래머스/lv1/숫자 문자열과 영단어.py

숫자 문자열과 영단어.py


# -*- coding: utf-8 -*-
"""
Create item database.
"""
import logging
import os
import re

from .options import Options

from ... import common
from ... import logutils
from ...scrubbing import ffxiah
from ...itemlist import ItemList

def main():
    """
    Main function.
    """
    # get options
    opts = Options()

    # check output file name validity
    oname = os.path.abspath('{}.csv'.format(re.sub(r'\.csv$', '', opts.stub)))
    if not opts.overwrite and not opts.backup:
        if os.path.exists(oname):
            logging.error('output file already exists!\n\t%s', oname)
            logging.error('please use --overwrite or --backup')
            exit(-1)

    # scub data
    scrubber = ffxiah.FFXIAHScrubber()
    scrubber.save = False
    data = scrubber.scrub(force=True, threads=-1, urls=opts.urls, ids=opts.itemids)

    # create item list from data
    ilist = ItemList()
    for itemid in data:
        kwargs = ffxiah.extract(data, itemid, stock01=opts.stock01, stock12=opts.stock12)
        ilist.add(itemid, **kwargs)

    # backup file
    if opts.backup:
        common.backup(oname, copy=True)

    # overwrites if exists, but we checked already
    ilist.savecsv(oname)

def cleanup():
    logging.info('exit\n')

if __name__ == '__main__':
    with logutils.capture():
        main()
    cleanup()


'''
@Author: Yingshi Chen

@Date: 2020-04-10 11:22:27
@
# Description:
'''

import torch
from .Z_utils import COMPLEX_utils as Z
from .some_utils import *
import numpy as np
import random
import torch.nn as nn
import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt

class FFT_Layer(torch.nn.Module):
    def SomeInit(self, M_in, N_in,isInv=False):
        assert (M_in == N_in)
        self.M = M_in
        self.N = N_in
        self.isInv = isInv

    def __repr__(self):
        i_ = "_i" if self.isInv else ""
        main_str = f"FFT_Layer{i_}_[{self.M},{self.N}]"
        return main_str

    def __init__(self, M_in, N_in,config,isInv=False):
        super(FFT_Layer, self).__init__()
        self.SomeInit(M_in, N_in,isInv)
        assert config is not None
        self.config = config
        #self.init_value = init_value

    def visualize(self,visual,suffix, params):
        param = self.transmission.data
        name = f"{suffix}_{self.config.modulation}_"
        return visual.image(name,param, params)

    def Diffractive_(self,u0,  theta=0.0):
        if Z.isComplex(u0):
            z0 = u0
        else:
            z0 = u0.new_zeros(u0.shape + (2,))
            z0[...,0] = u0

        N = self.size
        df = 1.0 / self.dL

        z0 = Z.fft(z0)
        u1 = Z.Hadamard(z0,self.H_z.float())
        u2 = Z.fft(u1,"C2C",inverse=True)
        return  u2 * N * N * df * df

    def forward(self, x):
        #return x
        if Z.isComplex(x):
            z0 = x
        else:
            z0 = x.new_zeros(x.shape + (2,))
            z0[...,0] = x
        if self.isInv:
            x = Z.fft(z0,"C2C",inverse=self.isInv)
        else:
            x = (Z.fft(z0,"C2C",inverse=self.isInv))
        x_0,x_1 = torch.min(x),torch.max(x)
        return x

    def trans(img):
        plt.figure(figsize=(10,8))
        plt.subplot(121),plt.imshow(img, cmap = 'gray')
        plt.title('Input Image'), plt.xticks([]), plt.yticks([])
        f = (abs(np.fft.fftshift(fftn(img))))**0.25*(255)**3  # Amplify
        plt.subplot(122),plt.imshow(f, cmap = 'gray')
        plt.title('Spectrum'), plt.xticks([]), plt.yticks([])
        plt.show()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb  3 16:44:46 2020

@author: xavier
"""

import subprocess

class hdfs_command(object):

   def __init__(self, **kwargs):
        self.file =  kwargs.get("file")
        self. hdfs_directory = kwargs.get("hdfs_directory")
        self.local_directory = kwargs.get("local_directory")
        self.run()
        self.output = ""
   def gethdfs_directory(self):
       return self.hdfs_directory
   def run(self):
       pass
   def getOutput(self):
       return self.Output

# =============================================================================
#     deleteCall = HDFSCommandFactory().command(
#             typ="delete",
#             hdfs_directory="hdfs://127.0.0.1:9000/user/xavier/US_Stocks/*.*")
# =============================================================================
class delete(hdfs_command):
    def run(self):
        print("run delete")
        try:
            print(self.hdfs_directory)
            command = "hadoop fs -rm " + self.hdfs_directory+ "  "
            print("run delete command: "+command)
            (status, self.output) = subprocess.getstatusoutput(command)
            print(self.output)
        except ValueError:
            print(ValueError.__str__)
            print("error, delete_file request could not be completed")
        return self.output

# =============================================================================
#     QueryCall = HDFSCommandFactory().command(
#             typ="query",
#             file =  "*.*,
#             hdfs_directory="hdfs://127.0.0.1:9000/user/xavier/US_Stocks/")
# =============================================================================
class Query(hdfs_command):
    def run(self):
        try:
            command = "hadoop fs -ls " + self.gethdfs_directory()+self.file +" "
            print("run query command: "+command)
            (status, self.output) = subprocess.getstatusoutput(command)
        except ValueError:
            print(ValueError.__str__)
            print("error,query_file request could not be completed")
        return self.output

# =============================================================================
#     PutCall = HDFSCommandFactory().command(
#             typ="put",
#             file =  "*.*,
#             localdirectory = "/home/xavier/Documents/"
#             hdfs_directory="hdfs://127.0.0.1:9000/user/xavier/US_Stocks")
# =============================================================================
class Put(hdfs_command):
    def run(self):
         try:
             command = "hadoop fs -put " + self.localdirectory + self.file +" "+ self.directory
             print("run put command: "+command)
             (status, self.output) = subprocess.getstatusoutput(command)
         except ValueError:
             print(ValueError.__str__)
             print("error, get_file request could not be completed")
         return self.output

# =============================================================================
#     GetCall = HDFSCommandFactory().command(
#             typ="get",
#             file =  "*.*,
#             localdirectory = "/home/xavier/Documents/"
#             hdfs_directory="hdfs://127.0.0.1:9000/user/xavier/US_Stocks/")
# =============================================================================
class Get(hdfs_command):
    def run(self):
         try:
             command = "hadoop fs -get " + self.hdfs_directory + self.file +" "+ self.localdirectory
             print("run get command: "+command)
             (status, self.output) = subprocess.getstatusoutput(command)
         except ValueError:
             print(ValueError.__str__)
             print("error, get_file request could not be completed")

         return self.output

class HDFSCommandFactory():
   def command(self, typ, **kwargs):
      print(typ.capitalize())
      targetclass = typ.capitalize()
      return globals()[targetclass](**kwargs)


def prepareImages(self, fileName, logType):
        """Convert supplied QPixmap object to image file."""
        import subprocess

        if self.imageType == "png":
            self.imagePixmap.save(fileName + ".png", "PNG", -1)
            if logType == "Physics":
                makePostScript = "convert " + fileName + ".png " + fileName + ".ps"
                process = subprocess.Popen(makePostScript, shell=True)
                process.wait()
                thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio)
                thumbnailPixmap.save(fileName + ".png", "PNG", -1)
        else:
            renameImage = "cp " + self.image + " " + fileName + ".gif"
            process = subprocess.Popen(renameImage, shell=True)
            process.wait()
            if logType == "Physics":
                thumbnailPixmap = self.imagePixmap.scaled(500, 450, Qt.KeepAspectRatio)
                thumbnailPixmap.save(fileName + ".png", "PNG", -1)