import os
import unittest
import unittest.mock
import app
import database
import tempfile

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

import models

class APITestCase(unittest.TestCase):
    class DatabaseMock:
        pass

    def setUp(self):
        self.engine = create_engine('sqlite:///:memory:')
        self.session = scoped_session(sessionmaker(autocommit=False,
                                                   autoflush=False,
                                                   bind=self.engine))
        database.Base.query = self.session.query_property()
        database.Base.metadata.create_all(bind=self.engine)

        self.db_fd, app.app.config['DATABASE'] = tempfile.mkstemp()
        app.app.config['TESTING'] = True
        self.app = app.app.test_client()
        with app.app.app_context():
            database.init_db()

        board = models.Board(
            status='OPEN'
        )
        task1 = models.Task(
            status=False,
            text="TEST TEXT",
            board_id=1
        )
        task2 = models.Task(
            status=True,
            text="TEST TEXT",
            board_id=1
        )
        self.session.add(board)
        self.session.add(task1)
        self.session.add(task2)
        self.session.commit()

    def tearDown(self):
        self.session.remove()
        os.close(self.db_fd)
        os.unlink(app.app.config['DATABASE'])

    def test_get_boards(self):
        rv = self.app.get('/todo/api/v1.0/board')
        self.assertEqual(rv.status_code, 200)
        self.assertNotEqual(len(rv.json), 0)

    def test_get_tasks(self):
        rv = self.app.get('/todo/api/v1.0/tasks')
        self.assertEqual(len(rv.json), 2)
        self.assertEqual(rv.status_code, 200)

    def test_get_tasks_with_status(self):
        rv = self.app.get('todo/api/v1.0/tasks?status=False')
        data = rv.json
        self.assertEqual(data[0]['status'], False)
        self.assertEqual(rv.status_code, 200)

    def test_get_tasks_with_board_id(self):
        rv = self.app.get('/todo/api/v1.0/tasks?board=1')
        data = rv.json
        self.assertEqual(data[0]['board_id'], 1)
        self.assertEqual(rv.status_code, 200)

    def test_get_tasks_with_board_id_error_1(self):
        rv = self.app.get('/todo/api/v1.0/tasks?board=99999999')
        self.assertEqual(rv.status_code, 400)

    def test_get_tasks_with_board_id_error_2(self):
        rv = self.app.get('/todo/api/v1.0/tasks?board=1.2')
        data = rv.json
        self.assertEqual(rv.status_code, 500)
        self.assertEqual(data['error'], 'board must be integer')

    def test_get_tasks_with_query_error(self):
        rv = self.app.get('/todo/api/v1.0/tasks?accord=999')
        self.assertEqual(rv.status_code, 400)

    def test_get_tasks_with_status_error(self):
        rv = self.app.get('/todo/api/v1.0/tasks?status=1')
        self.assertEqual(rv.status_code, 400)

    @unittest.mock.patch('database.db_session.commit', DatabaseMock)
    def test_create_task(self):
        rv = self.app.post('/todo/api/v1.0/tasks', json={"text": "Create test task", "board_id": "1"})
        self.assertEqual(rv.status_code, 201)

    def test_create_task_error_empty_json(self):
        rv = self.app.post('/todo/api/v1.0/tasks', json={})
        self.assertEqual(rv.status_code, 400)

    def test_create_task_error_json(self):
        rv = self.app.post('/todo/api/v1.0/tasks', json={"text_1": "Create new task", "board_id": "2"})
        self.assertEqual(rv.status_code, 400)

    def test_create_task_error_board_id(self):
        rv = self.app.post('/todo/api/v1.0/tasks', json={"text": "Create 2 new task", "board_id": '999999'})
        self.assertEqual(rv.status_code, 500)

    def test_get_tasks_with_id(self):
        rv = self.app.get('/todo/api/v1.0/tasks/1')
        self.assertEqual(rv.status_code, 200)

    def test_get_tasks_with_error_id(self):
        rv = self.app.get('/todo/api/v1.0/tasks/99999')
        self.assertEqual(rv.status_code, 404)

    def test_update_task(self):
        task = models.Task.query.filter_by(id=1).first()
        status = task.status
        self.assertFalse(status)
        rv = self.app.put('/todo/api/v1.0/tasks/1', json={"status": "true"})
        task2 = models.Task.query.filter_by(id=1).first()
        new_status = task2.status
        self.assertTrue(new_status)
        self.assertEqual(rv.status_code, 204)

    def test_update_task_empty_json(self):
        rv = self.app.put('/todo/api/v1.0/tasks/1', json={})
        self.assertEqual(rv.status_code, 400)

    def test_update_task_error_json(self):
        rv = self.app.put('/todo/api/v1.0/tasks/1', json={"status": "TRUE1"})
        self.assertEqual(rv.status_code, 400)

    @unittest.mock.patch('database.db_session.commit', DatabaseMock)
    def test_delete_task(self):
        task = models.Task(
            text='TEST',
            board_id=1
        )
        self.session.add(task)
        self.session.commit()
        id_task = task.id
        rv = self.app.delete(f'/todo/api/v1.0/tasks/{id_task}')
        self.assertEqual(rv.status_code, 204)

    def test_delete_task_error(self):
        rv = self.app.delete(f'/todo/api/v1.0/tasks/99999999')
        self.assertEqual(rv.status_code, 404)

if __name__ == '__main__':
    unittest.main()


"""Metadata scraper for AV files."""
from __future__ import unicode_literals

import re
import six

from file_scraper.base import BaseMeta
from file_scraper.defaults import UNAP, UNAV
from file_scraper.exceptions import SkipElementException
import file_scraper.mediainfo
from file_scraper.utils import iso8601_duration, strip_zeros, metadata

class BaseMediainfoMeta(BaseMeta):
    # pylint: disable=too-many-public-methods
    """Metadata models for streams scraped using MediainfoScraper."""

    def __init__(self, tracks, index):
        """
        Initialize the metadata model.

        :tracks: list of all tracks in the file
        :index: index of the track represented by this metadata model
        """
        self._stream = tracks[index]
        self._tracks = tracks
        self._track_index = index

        # Find out if file is a video container
        if len(self._tracks) > 2 or tracks[0].format != tracks[1].format:
            self._container = tracks[0]
        else:
            self._container = None

    @metadata()
    def mimetype(self):
        """Return mimetype for stream."""
        return file_scraper.mediainfo.track_mimetype(self._stream) or UNAV

    @metadata()
    def version(self):
        """Return version of stream."""
        if self._stream.format_version is not None:
            return self._stream.format_version.replace("Version ", "")
        return UNAV

    @metadata()
    def stream_type(self):
        """Return stream type."""
        if self._container and self._stream == self._container:
            return "videocontainer"

        if self._stream.track_type == "Audio":
            return 'audio'

        if self._stream.track_type == "Video":
            return 'video'

        # For example "General" tracks are not streams, unless they are
        # videocontainers
        return None

    @metadata()
    def index(self):
        """Return stream index."""
        if self._container:
            return self._track_index

        # Since file is not a container, the first track is not a
        # stream. It is just general information that is skipped.
        return self._track_index - 1

    @metadata()
    def color(self):
        """
        Return color information.

        Only values from fixed list are allowed. Must be resolved, if
        returns None.
        """
        if self.stream_type() not in ["video"]:
            raise SkipElementException()
        if self._stream.color_space is not None:
            if self._stream.color_space in ["RGB", "YUV"]:
                return "Color"
            if self._stream.color_space in ["Y"]:
                return "Grayscale"
        if self._stream.chroma_subsampling is not None:
            return "Color"
        return UNAV

    @metadata()
    def signal_format(self):
        """Return signal format."""
        if self.stream_type() not in ["video"]:
            raise SkipElementException()
        if self._stream.standard is not None:
            return self._stream.standard

        return UNAV

    @metadata()
    def width(self):
        """Return frame width."""
        if self.stream_type() not in ["video"]:
            raise SkipElementException()
        if self._stream.width is not None:
            return six.text_type(self._stream.width)
        return UNAV

    @metadata()
    def height(self):
        """Return frame height."""
        if self.stream_type() not in ["video"]:
            raise SkipElementException()
        if self._stream.height is not None:
            return six.text_type(self._stream.height)
        return UNAV

    @metadata()
    def par(self):
        """Return pixel aspect ratio."""
        if self.stream_type() not in ["video"]:
            raise SkipElementException()
        if self._stream.pixel_aspect_ratio is not None:
            return strip_zeros(six.text_type(self._stream.pixel_aspect_ratio))
        return UNAV

    @metadata()
    def dar(self):
        """Return display aspect ratio."""
        if self.stream_type() not in ["video"]:
            raise SkipElementException()
        if self._stream.display_aspect_ratio is not None:
            return strip_zeros(six.text_type(
                self._stream.display_aspect_ratio))
        return UNAV

    @metadata()
    def data_rate(self):
        """Return data rate (bit rate)."""
        if self.stream_type() not in ["video", "audio"]:
            raise SkipElementException()
        if self._stream.bit_rate is not None:
            if self._stream.track_type == "Video":
                return strip_zeros(six.text_type(float(
                    self._stream.bit_rate) / 1000000))
            return strip_zeros(six.text_type(float(
                self._stream.bit_rate)/1000))
        return UNAV

    @metadata()
    def frame_rate(self):
        """Return frame rate."""
        if self.stream_type() not in ["video"]:
            raise SkipElementException()
        if self._stream.frame_rate is not None:
            return strip_zeros(six.text_type(self._stream.frame_rate))
        return UNAV

    @metadata()
    def sampling(self):
        """Return chroma subsampling method."""
        if self.stream_type() not in ["video"]:
            raise SkipElementException()
        if self._stream.chroma_subsampling is not None:
            return self._stream.chroma_subsampling
        return UNAV

    @metadata()
    def sound(self):
        """Return "Yes" if sound channels are present, otherwise "No"."""
        if self.stream_type() not in ["video"]:
            raise SkipElementException()
        if (self._tracks[0].count_of_audio_streams is not None and
                int(self._tracks[0].count_of_audio_streams) > 0):
            return "Yes"
        if (self._tracks[0].audio_count is not None and
                int(self._tracks[0].audio_count) > 0):
            return "Yes"
        return "No"

    @metadata()
    def codec_quality(self):
        """
        Return codec quality.

        Must be resolved, if returns None. Only values "lossy" or
        "lossless" are allowed.
        """
        if self.stream_type() not in ["video", "audio"]:
            raise SkipElementException()
        if self._stream.compression_mode is not None:
            return self._stream.compression_mode.lower()
        return UNAV

    @metadata()
    def data_rate_mode(self):
        """
        Return data rate mode.

        Must be resolved, if returns None. The allowed values are
        "Fixed" and "Variable".
        """
        if self.stream_type() not in ["video", "audio"]:
            raise SkipElementException()
        if self._stream.bit_rate_mode == "CBR":
            return "Fixed"
        if self._stream.bit_rate_mode is not None:
            return "Variable"
        return UNAV

    @metadata()
    def audio_data_encoding(self):
        """Return audio data encoding."""
        if self.stream_type() not in ["audio"]:
            raise SkipElementException()
        if self._stream.format is not None:
            return six.text_type(self._stream.format)
        return UNAV

    @metadata()
    def sampling_frequency(self):
        """Return sampling frequency."""
        if self.stream_type() not in ["audio"]:
            raise SkipElementException()
        if self._stream.sampling_rate is not None:
            return strip_zeros(six.text_type(float(
                self._stream.sampling_rate)/1000))
        return UNAV

    @metadata()
    def num_channels(self):
        """Return number of channels."""
        if self.stream_type() not in ["audio"]:
            raise SkipElementException()
        if self._stream.channel_s is not None:
            return six.text_type(self._stream.channel_s)
        return UNAV

    @metadata()
    def codec_creator_app(self):
        """Return creator application."""
        if self.stream_type() not in ["video", "audio", "videocontainer"]:
            raise SkipElementException()
        if self._tracks[0].writing_application is not None:
            return self._tracks[0].writing_application
        return UNAV

    @metadata()
    def codec_creator_app_version(self):
        """Return creator application version."""
        if self.stream_type() not in ["video", "audio", "videocontainer"]:
            raise SkipElementException()
        if self._tracks[0].writing_application is not None:
            reg = re.search(r"([\d.]+)$",
                            self._tracks[0].writing_application)
            if reg is not None:
                return reg.group(1)
        return UNAV

    @metadata()
    def codec_name(self):
        """Return codec name."""
        if self.stream_type() not in ["video", "audio", "videocontainer"]:
            raise SkipElementException()
        if self._stream.format is not None:
            return self._stream.format
        return UNAV

    @metadata()
    def duration(self):
        """Return duration."""
        if self.stream_type() not in ["video", "audio"]:
            raise SkipElementException()
        if self._stream.duration is not None:
            return iso8601_duration(float(
                self._stream.duration) / 1000)
        return UNAV

    @metadata()
    def bits_per_sample(self):
        """Return bits per sample."""
        if self.stream_type() not in ["video", "audio"]:
            raise SkipElementException()
        if self._stream.bit_depth is not None:
            return six.text_type(self._stream.bit_depth)
        return UNAV

class ContainerMediainfoMeta(BaseMediainfoMeta):
    """Metadata model for container streams."""

    _supported = {"video/quicktime": [""],
                  "video/MP1S": [""],
                  "video/MP2P": [""],
                  "video/MP2T": [""],
                  "video/avi": [""],
                  "video/x-ms-asf": [""]}
    _allow_versions = True  # Allow any version

    @metadata()
    def version(self):
        """Return version of stream.

        Container streams do not have version, and therefore the result
        is unapplicable (:unap).
        """
        return UNAP

class MkvMediainfoMeta(BaseMediainfoMeta):
    """Metadata model for Matroska AV container."""

    _supported = {"video/x-matroska": ["4"]}
    _allow_versions = True  # Allow any version

    @metadata()
    def version(self):
        """Return version of stream."""
        version = super(MkvMediainfoMeta, self).version()
        if isinstance(version, six.text_type):
            version = version.split(".")[0]
        return version

class FfvMediainfoMeta(BaseMediainfoMeta):
    """Metadata model for FF Video Codec 1."""

    _supported = {"video/x-ffv": [""]}
    _allow_versions = True  # Allow any version

    @metadata()
    def signal_format(self):
        """Return signal format."""
        return UNAP

    @metadata()
    def version(self):
        """Return version of stream."""
        version = super(FfvMediainfoMeta, self).version()
        if isinstance(version, six.text_type):
            version = version.split(".")[0]
        return version

class DvMediainfoMeta(BaseMediainfoMeta):
    """Metadata model for Digital Video."""

    _supported = {"video/dv": [""]}
    _allow_versions = True  # Allow any version

    @metadata()
    def version(self):
        """Return version of stream.

        DV streams do not have version, and therefore the result is
        unapplicable (:unap).
        """
        return UNAP

class LpcmMediainfoMeta(BaseMediainfoMeta):
    """Metadata model for Linear Pulse-Code Modulation audio."""

    _supported = {"audio/L8": [""],
                  "audio/L16": [""],
                  "audio/L20": [""],
                  "audio/L24": [""]}
    _allow_versions = True  # Allow any version

    @metadata()
    def version(self):
        """Return version of stream.

        PCM audio streams (i.e. audio/L*) do not have version, and
        therefore the result is unapplicable (:unap).
        """
        return UNAP

    @metadata()
    def codec_quality(self):
        """Return codec quality."""
        if self._stream.compression_mode is not None:
            return self._stream.compression_mode.lower()

        return "lossless"

class AiffMediainfoMeta(BaseMediainfoMeta):
    """Metadata model for AIFF audio."""

    _supported = {"audio/x-aiff": ["", "1.3"]}
    _allow_versions = True  # Allow any version

    def __init__(self, tracks, index):
        """Initialize the metadata model.

        AIFF is a special container format. For AIFF files, no
        distinction between container and soundtrack needs to be made,
        as both are treated as one in the DPS.
        """
        super(AiffMediainfoMeta, self).__init__(tracks, index)
        self._container = None

    @metadata()
    def mimetype(self):
        """Return mimetype."""
        return 'audio/x-aiff'

    @metadata()
    def codec_name(self):
        """Return codec name.

        The codec name for AIFF-C files is ready from the codec_id
        key. AIFF files should have PCM in the format key.
        """
        if self._stream.codec_id is not None:
            return self._stream.codec_id.lower()

        if self._stream.format is not None:
            return self._stream.format

        return UNAV

    @metadata()
    def codec_quality(self):
        """Return codec quality.

        AIFF-C can contain lossless or lossy compression. We'll set the
        codec quality based on the codec ID.
        """
        if self._stream.compression_mode is not None:
            return self._stream.compression_mode.lower()

        if self._stream.codec_id is not None:
            if self._stream.codec_id not in [
                    "raw", "twos", "swot", "fl32", "fl64", "in24", "in32"]:
                return "lossy"

        return "lossless"

class WmaMediainfoMeta(BaseMediainfoMeta):
    """Metadata model for WMA audio."""

    _supported = {"audio/x-ms-wma": ["9"]}
    _allow_versions = True  # Allow any version

    @metadata()
    def mimetype(self):
        """Return mimetype."""
        return 'audio/x-ms-wma'

    @metadata()
    def version(self):
        """Return version of stream."""
        if any((self._stream.description_of_the_codec is not None and
                self._stream.description_of_the_codec == 'wmav1',
                self._stream.format_version is not None and
                self._stream.format_version == 'Version 1')):
            return "7"
        if any((self._stream.description_of_the_codec is not None and
                self._stream.description_of_the_codec == 'wmav2',
                self._stream.format_version is not None and
                self._stream.format_version == 'Version 2')):
            return "8"
        if any((self._stream.description_of_the_codec is not None and
                self._stream.description_of_the_codec in ['wmav3', 'wmapro'],
                self._stream.format_profile is not None and
                self._stream.format_profile in ['Pro', 'Lossless'])):
            return "9"
        return UNAV

    @metadata()
    def codec_quality(self):
        """Return codec quality.

        Most common WMA codecs are lossy, but some WMA files can use
        the Windows Media Audio Lossless codec.
        """
        if any((self._stream.codec_id_info is not None
                and "Lossless" in self._stream.codec_id_info,
                self._stream.format_profile is not None
                and "Lossless" in self._stream.format_profile)):
            return "lossless"
        return "lossy"

    @metadata()
    def data_rate_mode(self):
        """Return data rate mode.

        WMA supports both fixed and variable bit rates. Variable
        bit rate mode was officially introduced in WMA9.
        """
        mode = super(WmaMediainfoMeta, self).data_rate_mode()
        if mode not in [UNAV, None]:
            return mode

        # Overall data rate mode is reported in the container stream.
        # It can be used if the file contains max. two tracks (General
        # + Audio)
        if len(self._tracks) <= 2:
            if self._tracks[0].overall_bit_rate_mode == "CBR":
                return "Fixed"
            if self._tracks[0].overall_bit_rate_mode is not None:
                return "Variable"
        return UNAV

class WmvMediainfoMeta(BaseMediainfoMeta):
    """Metadata model for WMV video."""

    _supported = {"video/x-ms-wmv": ["9"]}
    _allow_versions = True  # Allow any version

    @metadata()
    def mimetype(self):
        """Return mimetype."""
        return 'video/x-ms-wmv'

    @metadata()
    def version(self):
        """Return version of stream."""
        if self._stream.codec_id is not None and \
                self._stream.codec_id == 'WMV1':
            return "7"
        if self._stream.codec_id is not None and \
                self._stream.codec_id == 'WMV2':
            return "8"
        if self._stream.codec_id is not None and \
                self._stream.codec_id in ['WVC1', 'WMV3', 'WMVA', 'WMVP']:
            return "9"
        return UNAV

    @metadata()
    def codec_quality(self):
        """Return codec quality.

        WMV codecs are lossy codecs.
        """
        return "lossy"

    @metadata()
    def signal_format(self):
        """Return signal format."""
        return UNAP

    @metadata()
    def data_rate_mode(self):
        """Return data rate mode.

        WMV supports both fixed and variable bit rates.
        """
        mode = super(WmvMediainfoMeta, self).data_rate_mode()
        if mode not in [UNAV, None]:
            return mode

        # Overall bit rate mode is reported in the container stream
        # It can be used if the file contains max. two tracks (General
        # + Video)
        if len(self._tracks) <= 2:
            if self._tracks[0].overall_bit_rate_mode == "CBR":
                return "Fixed"
            if self._tracks[0].overall_bit_rate_mode is not None:
                return "Variable"
        return UNAV

    @metadata()
    def color(self):
        """Return color information.

        WMV files are by default based on the YUV 4:2:0 color
        sampling.

        NOTE: FFMpeg can detect the color in the "pix_fmt" metadata.
        However, combining MediaInfo and FFMpeg is difficult and since
        WMV files are by default in color, we can just use it as a
        default value if no other value is found.
        """
        mode = super(WmvMediainfoMeta, self).color()
        if mode not in [UNAV, None]:
            return mode

        return "Color"

class FlacMediainfoMeta(BaseMediainfoMeta):
    """Metadata model for FLAC audio."""

    _supported = {"audio/flac": ["1.2.1"]}
    _allow_versions = True  # Allow any version

    @metadata()
    def version(self):
        """Return version of stream.

        The version number 1.2.1 of FLAC comes from PRONOM registry.
        This is actually the version number of FLAC tools containing
        FLAC format specification. Although the latest FLAC tools
        version is 1.3.3, version 1.2.1 still includes the latest format
        change and was released in 2007. There is no separate version
        numbering in FLAC format itself, and therefore, there is no
        proper way to extract it.
        """
        return "1.2.1"

class WavMediainfoMeta(BaseMediainfoMeta):
    """Metadata model for WAV audio."""

    _supported = {"audio/x-wav": ["2", ""]}
    _allow_versions = True  # Allow any version

    def __init__(self, tracks, index):
        """Initialize the metadata model.

        WAV is a special container format. For WAV files, no
        distinction between container and soundtrack needs to be made,
        as both are treated as one in the DPS.
        """
        super(WavMediainfoMeta, self).__init__(tracks, index)
        self._container = None

    @metadata()
    def mimetype(self):
        """Return mimetype."""
        return 'audio/x-wav'

    @metadata()
    def version(self):
        """Return version."""
        if self._tracks[0].bext_present is not None \
                and self._tracks[0].bext_present == "Yes":
            return "2"
        return UNAP

    @metadata()
    def codec_quality(self):
        """Return codec quality."""
        return "lossless"

class MpegMediainfoMeta(BaseMediainfoMeta):
    """Metadata model for MPEG audio."""

    # Supported mimetypes
    _supported = {"audio/mpeg": ["1", "2"],
                  "audio/mp4": [""],
                  "video/mpeg": ["1", "2"],
                  "video/mp4": [""]}
    _allow_versions = True  # Allow any version

    @metadata()
    def signal_format(self):
        """Return signal format."""
        if self.stream_type() not in ["video"]:
            raise SkipElementException()
        if self._stream.standard is not None:
            return self._stream.standard
        return UNAP

    @metadata()
    def codec_quality(self):
        """Return codec quality."""
        if self._stream.compression_mode is not None:
            return self._stream.compression_mode.lower()
        return "lossy"

    @metadata()
    def data_rate_mode(self):
        """Return data rate mode.

        MP4 is assumed to always have variable bit rate, based on e.g.
        https://slhck.info/video/2017/03/01/rate-control.html claiming
        that MP4 does not support NAL stuffing and thus it cannot be
        forced to have constant bit rate.
        """
        mode = super(MpegMediainfoMeta, self).data_rate_mode()
        if mode not in [UNAV, None]:
            return mode
        if self._stream.bit_rate_mode == "CBR":
            return "Fixed"
        return "Variable"

    @metadata()
    def version(self):
        """Return version of stream.

        MP4 streams do not have version, and and therefore the result is
        unapplicable (:unap).

        MP3 "container" does not know the version, so it has to be
        checked from the first stream.
        """
        if self.mimetype() in ["audio/mp4", "video/mp4"]:
            return UNAP

        if (self.mimetype() == "audio/mpeg" and
                self._stream.track_type == "General" and
                len(self._tracks) >= 2):
            return six.text_type(self._tracks[1].format_version)[-1]

        if self._stream.format_version is not None:
            return six.text_type(self._stream.format_version)[-1]
        return UNAV

class VersionlessFormatMeta(BaseMediainfoMeta):
    """Generic metadata model for stream formats, which do not have a version.
    """

    _supported = {"video/x.fi-dpres.prores": [""]}
    _allow_versions = True  # Allow any version

    @metadata()
    def version(self):
        """Return version of stream.

        Result is always unapplicable (:unap), because these formats do not
        have a version.
        """
        return UNAP

class UnknownStreamFormatMeta(BaseMediainfoMeta):
    """Metadata model for streams that were not detected."""

    _supported = {None: [""]}
    _allow_versions = True  # Allow any version


import collections
from dis import disco
N, M, V = map(int, input().split())

graph = collections.defaultdict(list)

for _ in range(M):
    N1, N2 = map(int, input().split())
    graph[N1].append(N2)
    graph[N2].append(N1)

for _ in graph.values():
    _.sort()

def DFS(v, discovered=[]):
    discovered.append(v)
    for w in graph[v]:
        if w not in discovered:
            discovered = DFS(w, discovered)
    return discovered

def BFS(start_v):
    discovered = [start_v]
    queue = [start_v]
    while queue:
        v = queue.pop(0)
        for w in graph[v]:
            if w not in discovered:
                discovered.append(w)
                queue.append(w)
    return discovered

print(*DFS(V))
print(*BFS(V))


import tkinter as tk
from tkinter import messagebox
from typing import List, Optional

class TicTacToe:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Tic Tac Toe")
        self.player_turn = 'X'

        # Initialize buttons
        self.buttons: List[List[Optional[tk.Button]]] = [[None for _ in range(3)] for _ in range(3)]

        for i in range(3):
            for j in range(3):
                self.buttons[i][j] = tk.Button(self.root, width=10, height=5,
                                               command=lambda row=i, col=j: self.click(row, col),
                                               bg='white', fg='black')
                self.buttons[i][j].grid(row=i, column=j)

        self.reset_button = tk.Button(self.root, text="Reset", command=self.reset_game)
        self.reset_button.grid(row=3, columnspan=3)

    def click(self, i, j):
        if self.buttons[i][j]["text"] == "":
            self.buttons[i][j]["text"] = self.player_turn
            if self.player_turn == 'X':
                self.buttons[i][j]["fg"] = 'red'
            else:
                self.buttons[i][j]["fg"] = 'blue'
            self.buttons[i][j]["state"] = 'disabled'
            if self.check_winner(self.player_turn):
                messagebox.showinfo("Game Over", "{} Wins!".format(self.player_turn))
                self.reset_game()
                return
            elif self.player_turn == 'X':
                self.player_turn = 'O'
            else:
                self.player_turn = 'X'

    def check_winner(self, player):
        for i in range(3):
            row_win = all(self.buttons[i][j]['text'] == player for j in range(3))
            col_win = all(self.buttons[j][i]['text'] == player for j in range(3))
            if row_win or col_win:
                return True

        diagonal1_win = all(self.buttons[i][i]['text'] == player for i in range(3))
        diagonal2_win = all(self.buttons[i][2 - i]['text'] == player for i in range(3))

        if diagonal1_win or diagonal2_win:
            return True

        return False

    def reset_game(self):
        for i in range(3):
            for j in range(3):
                self.buttons[i][j]["text"] = ""
                self.buttons[i][j]["state"] = "normal"
                self.buttons[i][j]["fg"] = "black"
        self.player_turn = 'X'

    def run(self):
        self.root.mainloop()

if __name__ == "__main__":
    game = TicTacToe()
    game.run()


import sys
import random
sys.setrecursionlimit(10000)

import itertools as I
Any_plus = '<$.+>' # this is a nonterminal
Any_one = '{$.}' # this is a terminal
def Any_not(t): return '{!%s}' % t # this is a terminal.
def is_not(t):
    if len(t) > 1:
        if  t[1] == '!':
            return t[2]
    return None

def is_not_match(letter, col_letter):
    l = is_not(letter)
    if l is not None:
        return l != col_letter
    else:
        return False

def letter_match(letter, col_letter):
    if letter == col_letter: return True
        # letter can be any: <$.+> or not: <!x>
    if letter == Any_one: return True
    if is_not_match(letter, col_letter): return True
    return False

def new_start(old_start):
    old_start_ = old_start[1:-1]
    return '<$%s>' % old_start_

def add_any(g):
    g[Any_plus] = [
            add_weight([Any_plus, Any_one], 1),
            add_weight([Any_one], 1)]
    return g

def add_start(g, old_start):
    alts = [alt for alt,w in g[old_start]]
    for alt in alts:
        g[old_start].append(add_weight(list(alt) + ['<$ .+>'], 0))
    return g

def print_g(g):
    for k in g:
        print('#',k)
        for rule in g[k]:
            print('#  ', rule)

def add_weight(rule, weight):
    assert isinstance(rule, list)
    return [tuple(rule), weight]

def add_weights_to_grammar(g):
    return {k:[add_weight(rule, 0) for rule in g[k]] for k in g}

def fix_terminal(g, t):
    nt_t = to_term(t)
    if nt_t not in g:
        g[nt_t] = [ # Any_plus already has at least 1 weight.
                add_weight([t], 0),
                add_weight([Any_plus, t], 0),
                add_weight([], 1),
                add_weight([Any_not(t)], 1)
        ]

def to_term(t): return '<$ %s>' % t

def change_t(t):
    if is_nt(t):
        return t
    else:
        return to_term(t)

def fix_weighted_terminals(g):
    keys = [k for k in g]
    for k in keys:
        for alt,w in g[k]:
            for t in alt:
                if t not in g:
                    fix_terminal(g, t)

    g_ = {}
    for k in g:
        if k[1] == '$':
            g_[k] = g[k]
        else:
            g_[k] = [(tuple([change_t(a) for a in alt]),w) for (alt,w) in g[k]]
    return g_

class Column:
    def __init__(self, index, letter):
        self.index, self.letter = index, letter
        self.states, self._unique = [], {}

    def __str__(self):
        return "%s chart[%d]\n%s" % (self.letter, self.index, "\n".join(
            str(state) for state in self.states if state.finished()))

    def add(self, state):
        if state in self._unique:
            if self._unique[state].weight > state.weight:
                # delete from self.states in fill_chart
                state.e_col = self
                self.states.append(state)
                self._unique[state] = state
            return self._unique[state]
        self._unique[state] = state
        self.states.append(state)
        state.e_col = self
        return self._unique[state]

    def remove_extra_states(self):
        my_states = []
        for state in self._unique:
            cur_states = [s for s in self.states if s == state]
            if len(cur_states) > 1:
                cur_states = sorted(cur_states, key=lambda s: s.weight)
            my_states.append(cur_states[0])
        self.states = my_states
        return

class State:
    def __init__(self, name, expr, dot, s_col, e_col=None):
        self.name, self.expr_, self.dot = name, expr, dot
        self.s_col, self.e_col = s_col, e_col
        self.expr, self.weight = expr

    def finished(self):
        return self.dot >= len(self.expr)

    def at_dot(self):
        return self.expr[self.dot] if self.dot < len(self.expr) else None

    def __str__(self):
        def idx(var):
            return var.index if var else -1

        return self.name + ':= ' + ' '.join([
            str(p)
            for p in [*self.expr[:self.dot], '|', *self.expr[self.dot:]]
            ]) + "(%d,%d):%d" % (idx(self.s_col), idx(self.e_col), self.weight)

    def copy(self):
        return State(self.name, (self.expr, self.weight), self.dot, self.s_col, self.e_col)

    def _t(self):
        return (self.name, self.expr, self.dot, self.s_col.index)

    def __hash__(self):
        return hash(self._t())

    def __eq__(self, other):
        return self._t() == other._t()

    def advance(self):
        return State(self.name, (self.expr, self.weight), self.dot + 1, self.s_col)

class Parser:
    def parse_on(self, text, start_symbol):
        raise NotImplemented()

class EarleyParser(Parser):
    def __init__(self, grammar, log=False, **kwargs):
        g_e = add_weights_to_grammar(grammar)
        # need to update terminals
        g_e = fix_weighted_terminals(g_e)
        self.epsilon = nullable(grammar)
        self._grammar = g_e
        self.log = log

        self._grammar = add_any(self._grammar)

def is_nt(k):
    if len(k) == 1: return False
    return (k[0], k[-1]) == ('<', '>')

def rem_terminals(g):
    g_cur = {}
    for k in g:
        alts = []
        for alt in g[k]:
            ts = [t for t in alt if not is_nt(t)]
            if not ts:
                alts.append(alt)
        if alts:
            g_cur[k] = alts
    return g_cur

def nullable(g):
    nullable_keys = {k for k in g if [] in g[k]}

    unprocessed  = list(nullable_keys)

    g_cur = rem_terminals(g)
    while unprocessed:
        nxt, *unprocessed = unprocessed
        g_nxt = {}
        for k in g_cur:
            g_alts = []
            for alt in g_cur[k]:
                alt_ = [t for t in alt if t != nxt]
                if not alt_:
                    nullable_keys.add(k)
                    unprocessed.append(k)
                    break
                else:
                    g_alts.append(alt_)
            if g_alts:
                g_nxt[k] = g_alts
        g_cur = g_nxt

    return nullable_keys

class EarleyParser(EarleyParser):
    def chart_parse(self, tokens, start, alt):
        chart = [Column(i, tok) for i, tok in enumerate([None, *tokens])]
        chart[0].add(State(start, alt, 0, chart[0]))
        return self.fill_chart(chart)

class EarleyParser(EarleyParser):
    def predict(self, col, sym, state):
        for alt in self._grammar[sym]:
            col.add(State(sym, alt, 0, col))
        if sym in self.epsilon:
            col.add(state.advance())

class EarleyParser(EarleyParser):
    def scan(self, col, state, letter):
        if letter_match(letter, col.letter):
            s = state.advance()
            s.expr = col.letter
            col.add(s)

class EarleyParser(EarleyParser):
    def complete(self, col, state):
        parent_states = [st for st in state.s_col.states
                 if st.at_dot() == state.name]
        for st in parent_states:
            s = st.advance()
            s.weight += state.weight
            col.add(s)

class EarleyParser(EarleyParser):
    def fill_chart(self, chart):
        for i, col in enumerate(chart):
            for state in col.states:
                if state.finished():
                    self.complete(col, state)
                else:
                    sym = state.at_dot()
                    if sym in self._grammar:
                        self.predict(col, sym, state)
                    else:
                        if i + 1 >= len(chart):
                            continue
                        self.scan(chart[i + 1], state, sym)
            col.remove_extra_states()
            if self.log: print(col, '\n')
        return chart

class EarleyParser(EarleyParser):
    def parse_prefix(self, text, start_symbol, alt):
        self.table = self.chart_parse(text, start_symbol, alt)
        for col in reversed(self.table):
            states = [st for st in col.states
                if st.name == start_symbol and st.expr == alt[0] and st.s_col.index == 0
            ]
            if states:
                return col.index, states
        return -1, []

class EarleyParser(EarleyParser):
    def parse_paths(self, named_expr, chart, frm, til):
        def paths(state, start, k, e):
            if not e:
                return [[(state, k)]] if start == frm else []
            else:
                return [[(state, k)] + r
                        for r in self.parse_paths(e, chart, frm, start)]

        *expr, var = named_expr
        starts = None
        if var not in self._grammar:
            starts = ([(var, til - len(var),
                        't')] if til > 0 and chart[til].letter == var else [])
        else:
            starts = [(s, s.s_col.index, 'n') for s in chart[til].states
                      if s.finished() and s.name == var]

        return [p for s, start, k in starts for p in paths(s, start, k, expr)]

class EarleyParser(EarleyParser):
    def forest(self, s, kind, chart):
        return self.parse_forest(chart, s) if kind == 'n' else (s, [])

    def parse_forest(self, chart, state):
        pathexprs = self.parse_paths(state.expr, chart, state.s_col.index,
                                     state.e_col.index) if state.expr else []
        return state.name, [[(v, k, chart) for v, k in reversed(pathexpr)]
                            for pathexpr in pathexprs]

class EarleyParser(EarleyParser):
    def parse_on(self, text, start_symbol):
        self._grammar = add_start(self._grammar, start_symbol)
        print_g(self._grammar)

        for alt in self._grammar[start_symbol]:
            cursor, states = self.parse_prefix(text, start_symbol, alt)
            start = next((s for s in states if s.finished()), None)

            if cursor < len(text) or not start:
                #raise SyntaxError("at " + repr(text[cursor:]))
                continue
            forest = self.parse_forest(self.table, start)
            print('weight = ', str(start))
            yield forest
            #for tree in self.extract_trees(forest):
            #    yield tree

class EarleyParser(EarleyParser):
    def extract_a_tree(self, forest_node):
        name, paths = forest_node
        if not paths:
            return (name, [])
        return (name, [self.extract_a_tree(self.forest(*p)) for p in paths[0]])

    def extract_trees(self, forest):
        yield self.extract_a_tree(forest)

class EarleyParser(EarleyParser):
    def extract_trees(self, forest_node):
        name, paths = forest_node
        if not paths:
            yield (name, [])
        results = []
        for path in paths:
            ptrees = [self.extract_trees(self.forest(*p)) for p in path]
            for p in I.product(*ptrees):
                yield (name, p)

class SimpleExtractor:
    def __init__(self, parser, text, start_symbol):
        parser._grammar = add_start(parser._grammar, start_symbol)
        self.parser = parser
        cursor, states = parser.parse_prefix(text, start_symbol, parser._grammar[start_symbol][0])
        start = next((s for s in states if s.finished()), None)
        if cursor < len(text) or not start:
            raise SyntaxError("at " + repr(cursor))
        self.my_forest = parser.parse_forest(parser.table, start)

    def extract_a_node(self, forest_node):
        name, paths = forest_node
        if not paths:
            return ((name, 0, 1), []), (name, [])
        cur_path, i, l = self.choose_path(paths)
        child_nodes = []
        pos_nodes = []
        for s, kind, chart in cur_path:
            f = self.parser.forest(s, kind, chart)
            postree, ntree = self.extract_a_node(f)
            child_nodes.append(ntree)
            pos_nodes.append(postree)

        return ((name, i, l), pos_nodes), (name, child_nodes)

    def choose_path(self, arr):
        l = len(arr)
        i = random.randrange(l)
        res = sorted([(self.cost_of_path(a),a) for a in arr], key=lambda a: a[0])
        return res[0][1], None, None

    def cost_of_path(self, p):
        states = [s for s,kind,chart in p if kind == 'n']
        return sum([s.weight for s in states])

    def extract_a_tree(self):
        pos_tree, parse_tree = self.extract_a_node(self.my_forest)
        return parse_tree

class O:
    def __init__(self, **keys): self.__dict__.update(keys)
    def __repr__(self): return str(self.__dict__)

Options = O(F='|', L='+', V='|', H='-', NL='\n')

def format_newlines(prefix, formatted_node):
    replacement = ''.join([Options.NL, '\n', prefix])
    return formatted_node.replace('\n', replacement)

def format_tree(node, format_node, get_children, prefix=''):
    children = list(get_children(node))
    next_prefix = ''.join([prefix, Options.V, '   '])
    for child in children[:-1]:
        fml = format_newlines(next_prefix, format_node(child))
        yield ''.join([prefix, Options.F, Options.H, Options.H, ' ', fml])
        tree = format_tree(child, format_node, get_children, next_prefix)
        for result in tree:
            yield result
    if children:
        last_prefix = ''.join([prefix, '    '])
        fml = format_newlines(last_prefix, format_node(children[-1]))
        yield ''.join([prefix, Options.L, Options.H, Options.H, ' ', fml])
        tree = format_tree(children[-1], format_node, get_children, last_prefix)
        for result in tree:
            yield result

def format_parsetree(node,
          format_node=lambda x: repr(x[0]),
          get_children=lambda x: x[1]):
    lines = I.chain([format_node(node)], format_tree(node, format_node, get_children), [''],)
    return '\n'.join(lines)

grammar = {
    '<start>': [['<expr>']],
    '<expr>': [
        ['<term>', '+', '<expr>'],
        ['<term>', '-', '<expr>'],
        ['<term>']],
    '<term>': [
        ['<fact>', '*', '<term>'],
        ['<fact>', '/', '<term>'],
        ['<fact>']],
    '<fact>': [
        ['<digits>'],
        ['(','<expr>',')']],
    '<digits>': [
        ['<digit>','<digits>'],
        ['<digit>']],
    '<digit>': [["%s" % str(i)] for i in range(10)],
}
START = '<start>'

# Modifications:
# Each rule gets a weight
# The start gets changed to:
# <$start>  := [0] <start>
#            | [0] <start> <$.+>
# <$.+>     := [1] <$.+> <$.>
#            | [1] <$.>
# Each terminal gets converted to a nonterminal

#ep = EarleyParser(grammar, log=False)
#cursor, columns = ep.parse_prefix('0', START, add_weight(grammar[START][0], 0))
#print(cursor)
#for c in columns:
#    print(c)

myg = EarleyParser(grammar)
inp = 'xz+yz'
print(repr(inp))
x = SimpleExtractor(myg, inp, START)
t = x.extract_a_tree()
print(format_parsetree(t))
#forests = myg.parse_on(inp, START)
#for forest in forests:
#    print('parse:', inp)
#    for v in myg.extract_trees(forest):
#        print(format_parsetree(v))
#        print('||||||||||||||||||\n')


from selenium import webdriver
from pages.quotes_page import QuotesPage

firefox = webdriver.Firefox(executable_path = 'C:\\Users\\Owais Mohammad\\PythonProjects\\geckodriver.exe')
firefox.get('http://quotes.toscrape.com/search.aspx')
page = QuotesPage(firefox)

author = page.ask_for_author()
page.select_author(author_name=author)

tags = page.get_available_tags()
tag = page.ask_for_tag(tags)

page.select_tag(tag_name=tag)

page.search_button.click()

print(page.quotes)


#!/usr/bin/env python
# coding: utf-8

import warnings
warnings.filterwarnings('ignore')

# Qiskit
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit_optimization.algorithms import MinimumEigenOptimizer
from qiskit_optimization import QuadraticProgram

# Dwaves
import dimod
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite

import numpy as np
import pandas as pd
from sympy import *
import re
import os

from qiskit.algorithms.optimizers import COBYLA

################### ########
#Different distributions data generator functions

def create_dir(path, log=False):
    if not os.path.exists(path):
        if log:
            print('The directory', path, 'does not exist and will be created')
        os.makedirs(path)
    else:
        if log:
            print('The directory', path, ' already exists')

#################################### SOLVER

def numpy_for_qubo(qubo, p=None):                      # Classical solver for QUBO
  """
  numpy_for_qubo solves the given QUBO using Numpy library functions
  :param
  qubo: CSG problem instance reduced to the form of qubo.

  return:
  result: An array of binary digits which denotes the solutionn of the input qubo problem
  """
  exact_mes = NumPyMinimumEigensolver()
  exact = MinimumEigenOptimizer(exact_mes)  # using the exact classical numpy minimum eigen solver
  result = exact.solve(qubo)
  return result

def solve_QUBO(linear, quadratic, algo, p=1):
  """
  solve_QUBO is ahigher order function to solve QUBO using the given algo parameter function
  :param
  linear: dictionary of linear coefficient terms in the QUBO formulation of the CSG problem.
  quadratic: dictionary of quadratic coefficient terms in the QUBO formulation of the CSG problem.
  algo: a callback function for qaoa_for_qubo or numpy_for_qubo

  return:
  result: An array of binary digits which denotes the solutionn of the input qubo problem

  """
  keys = list(linear.keys())
  keys.sort(key=natural_keys)
  qubo = QuadraticProgram()
  for key in keys:
    qubo.binary_var(key)                                                             # initialize the binary variables
  qubo.minimize(linear=linear, quadratic=quadratic)                                  # initialize the QUBO maximization problem instance
  op, offset = qubo.to_ising()
  qp=QuadraticProgram()
  qp.from_ising(op, offset, linear=True)
  result = algo(qubo, p)
  return result

###############################################

def natural_keys(text):
  """
  alist.sort(key=natural_keys) sorts in human order
  http://nedbatchelder.com/blog/200712/human_sorting.ht
  For example: Built-in function ['x_8','x_10','x_1'].sort() will sort as ['x_1', 'x_10', 'x_8']
  But using natural_keys as callback function for sort() will sort as ['x_1','x_8','x_10']
  param:
  text: a list of strings ending with numerical characters

  return:
  sorted list in a human way
  """
  return [ atoi(c) for c in re.split(r'(\d+)', text) ]

def atoi(text):
  """
  Function returns the corresponding value of a numerical string as integer datatype
  param:
  text: string conntaining only numerical charcaters

  return:
  integer value corresponding to the input text
  """
  return int(text) if text.isdigit() else text

def exact_solver(linear, quadratic, offset = 0.0):
    """
    Solve Ising hamiltonian or qubo problem instance using dimod API.
    dimod is a shared API for samplers.It provides:
    - classes for quadratic models—such as the binary quadratic model (BQM) class that contains Ising and QUBO models used by samplers such as the D-Wave system—and higher-order (non-quadratic) models.
    - reference examples of samplers and composed samplers.
    - abstract base classes for constructing new samplers and composed samplers.

    :params
    linear: dictionary of linear coefficient terms in the QUBO formulation of the CSG problem.
    quadratic: dictionary of quadratic coefficient terms in the QUBO formulation of the CSG problem.
    offset: Constant energy offset associated with the Binary Quadratic Model.

    :return
    sample_set: Samples and any other data returned by dimod samplers.
    """
    vartype = dimod.BINARY

    bqm = dimod.BinaryQuadraticModel(linear, quadratic, offset, vartype)
    sampler = dimod.ExactSolver()
    sample_set = sampler.sample(bqm)
    return sample_set

def dwave_solver(linear, quadratic, offset = 0.0, runs=1000):
    """
    Solve Ising hamiltonian or qubo problem instance using dimod API for using dwave system.

    :params
    linear: dictionary of linear coefficient terms in the QUBO formulation of the CSG problem.
    quadratic: dictionary of quadratic coefficient terms in the QUBO formulation of the CSG problem.
    runs: Number of repeated executions

    :return
    sample_set: Samples and any other data returned by dimod samplers.
    """

    vartype = dimod.BINARY

    bqm = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype)
    sampler = EmbeddingComposite(DWaveSampler())
    sample_set = sampler.sample(bqm, num_reads=runs)
    return sample_set

def extract_best_result(df):
    """
    A function to fetch the binary string with least energy of the input hamiltonian operator

    :params
    df:

    :return
    x: an array of binary digits specifies the solution of the input problem instance
    fval: value of the operator corresponding to the binary digits in x
    """

    row_min = df[df.energy == df.energy.min()]

    cols = []
    for col in df.columns:
        if 'x_' in col:
            cols.append(col)

    x = []

    for col in cols:
        x.append(row_min.iloc[0][col])

    fval = row_min.energy.iloc[0]
    return x, fval

def from_bin_to_var(x, dictionary):
    """
    function to convert binary string to coalition structure

    :params
    x: an array of binary digits (specifies the solution of the input problem instance)
    dictionary: dictionary with coalitions as keys and coalition values as values (CSG problem instance)

    :return
    solution: list of lists. coalition structure.
    """
    solution = []
    for i in range(len(x)):
        if x[i] == 1:
            print(list(dictionary.keys())[i])
            solution.append(list(dictionary.keys())[i])
    return solution

def create_QUBO(linear_dict, quadratic_dict):
    """
    create a QUBO problem instance using the linear and quadratic coefficients.

    :params
    linear: dictionary of linear coefficient terms in the QUBO formulation of the CSG problem.
    quadratic: dictionary of quadratic coefficient terms in the QUBO formulation of the CSG problem.

    :return
    Object of QuadraticProgram class corresponding to the input linear and quadratic coefficients.
    """
    qubo = QuadraticProgram()

    keys = list(linear_dict.keys())
    keys.sort(key=natural_keys)

    for key in keys:
        qubo.binary_var(key)

    qubo.minimize(linear=linear_dict, quadratic=quadratic_dict)
    return qubo

def from_columns_to_string(df):

    cols = []
    for col in df.columns:
        if 'x_' in col:
            cols.append(col)

    df['x'] = 'x'
    for index, row in df.iterrows():
        x = ''
        for col in cols:
            x = x + str(row[col])
        df.loc[index, 'x'] = x
    return df[['x', 'num_occurrences', 'energy']]

def get_ordered_solution(dictionary):
    """
    Reordering the (key,value) pairs in the dictionary to fetch only the values in order.
    param:
    dictionary: input dictionary.

    return:
    solution: list of values after reordering the dictionary elements.
    """
    sortedDict = dict(sorted(dictionary.items(), key=lambda x: x[0].lower()))
    solution = []
    for k, v in sortedDict.items():
        solution.append(v)

    return solution

def results_from_dwave(sample_set, exact=False):
    """
    Fetch the details of the output_ from D-Wave system (Quantum Annealing).

    :params
    sample_set: Samples and any other data returned by dimod samplers.

    :return
    solution: a list of binary values corresponding to the solution provided by the output_ of D-Wave device.
    fval: The function value (operator value) of the input hamiltonian corresponding to the solution.
    prob: Probability of the solution.
    rank: rank of the solution out of all possible binary arrays.
    time: time taken by the D-Wave device to compute the solution.
    """
    df = sample_set.to_pandas_dataframe()
    row_min = df[df.energy == df.energy.min()]

    cols = []
    for col in df.columns:
        if 'x_' in col:
            cols.append(col)

    cols.sort(key=natural_keys)

    solution = []

    for col in cols:
        solution.append(row_min.iloc[0][col])

    fval = row_min.energy.iloc[0]

    if not exact:
        occ_min_fval = row_min.num_occurrences.to_list()[0]
        occurences = df.num_occurrences.to_list()

        occurences = sorted(occurences, reverse=True)

        time = sample_set.info['timing']['qpu_sampling_time']/1000

        rank = occurences.index(occ_min_fval)+1
        prob = occ_min_fval / sum(df.num_occurrences)
    else:
        rank = 1
        prob = 1
        time = 1

    return solution, fval, prob, rank, time


import torch
import torch.nn as nn
import torch.nn.functional as F
from Pointnet.models.pointnet2_utils import PointNetSetAbstraction,PointNetFeaturePropagation
import numpy as np

class pointSem(nn.Module):
    def __init__(self):
        super(pointSem, self).__init__()
        self.sa = PointNetSetAbstraction(1024, 0.1, 32, 9, [32, 32, 64], False)
        self.sa2 = PointNetSetAbstraction(256, 0.2, 32, 64 + 3, [64, 64, 128], False)
        self.sa3 = PointNetSetAbstraction(64, 0.4, 32, 128 + 3, [128, 128, 256], False)
        self.sa4 = PointNetSetAbstraction(16, 0.8, 32, 256 + 3, [256, 256, 512], False)
        self.fp4 = PointNetFeaturePropagation(768, [256, 256])
        self.fp3 = PointNetFeaturePropagation(384, [256, 256])
        self.fp2 = PointNetFeaturePropagation(320, [256, 128])
        self.fp1 = PointNetFeaturePropagation(128, [128, 128, 128])
        self.conv1 = nn.Conv1d(128, 128, 1)
        self.bn1 = nn.BatchNorm1d(128)
        self.drop1 = nn.Dropout(0.5)
        self.conv = nn.Conv1d(128,16, 1)
        #self.fcx = nn.Linear(1280,512)
        #self.adaptive = nn.AdaptiveAvgPool1d(512)

    def sortit(self,xyz,points):
        print(points.shape, " ", xyz.shape, " ", type(points))
        new_xyz = np.zeros((1,points.shape[2],3))
        new_points = np.zeros((1,points.shape[2],points.shape[1]))
        xyz = xyz.permute(0,2,1).cpu().detach().numpy()
        points = points.permute(0,2,1).cpu().detach().numpy()
        for i,x in enumerate(xyz):
            print(points.shape, " ", x.shape, " ", type(x))
            temp = points[i][np.argsort(x[:,0])].reshape((1,points[1],points[2]))
            new_points = np.append(new_points,temp,axis=0)
            temp = xyz[i][np.argsort(x[:,0])].reshape((1,xyz[1],3))
            new_xyz = np.append(new_xyz,temp,axis=0)
        xyz = torch.tensor(new_xyz).float()
        points = torch.tensor(new_points).float()

        return xyz[1:],permute(0,2,1), points[1:].permute(0,2,1)

    def forward(self, xyz):
        l0_points = xyz
        l0_xyz = xyz[:,:3,:]
        print(l0_points.shape, ' ', l0_xyz.shape)

        l1_xyz, l1_points = self.sa(l0_xyz, l0_points)
        #l1_xyz, l1_points = self.sortit(l1_xyz,l1_points)
        l2_xyz, l2_points = self.sa2(l1_xyz, l1_points)
        #l2_xyz, l2_points = self.sortit(l2_xyz,l2_points)
        l3_xyz, l3_points = self.sa3(l2_xyz, l2_points)
        #l3_xyz, l3_points = self.sortit(l3_xyz,l3_points)
        l4_xyz, l4_points = self.sa4(l3_xyz, l3_points)
        #l4_xyz, l4_points = self.sortit(l4_xyz,l4_points)

        l3_points = self.fp4(l3_xyz, l4_xyz, l3_points, l4_points)
        l2_points = self.fp3(l2_xyz, l3_xyz, l2_points, l3_points)
        l1_points = self.fp2(l1_xyz, l2_xyz, l1_points, l2_points)
        l0_points = self.fp1(l0_xyz, l1_xyz, None, l1_points)

        x = self.drop1(F.relu(self.bn1(self.conv1(l0_points))))
        x = self.conv(x)
        #x = self.fcx(x)
        #x = self.adaptive(x)
        print("hi")
        print(x.shape)
        x = F.log_softmax(x, dim=1)
        x = x.permute(0, 2, 1).squeeze()
        print(x.shape)
        return x.reshape(-1,16*1280) #l3_points.permute(0,2,1)

class get_loss(nn.Module):
    def __init__(self):
        super(get_loss, self).__init__()
    def forward(self, pred, target, trans_feat, weight):
        total_loss = F.nll_loss(pred, target, weight=weight)

        return total_loss

if __name__ == '__main__':
    import  torch
    model = get_model(13)
    xyz = torch.rand(6, 9, 2048)
    (model(xyz))


'''
2021.08.31. Fire! (불!)
https://www.acmicpc.net/problem/4179
'''
from sys import stdin
from collections import deque

stdin = open("../input.txt", "r")

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

r, c = map(int, stdin.readline().rstrip().split())
board = [list(map(str, stdin.readline().rstrip())) for _ in range(r)]
dist = [[-1] * c for _ in range(r)]
fire = [[-1] * c for _ in range(r)]
dist_q, fire_q = deque(), deque()

for i in range(r):
    for j in range(c):
        if board[i][j] == 'J':
            dist_q.append([i, j])
            dist[i][j] = 0
        if board[i][j] == 'F':
            fire_q.append([i, j])
            fire[i][j] = 0

while fire_q:
    cur_x, cur_y = fire_q.popleft()
    for dir in range(4):
        nx, ny = cur_x + dx[dir], cur_y + dy[dir]
        if 0 <= nx < r and 0 <= ny < c:
            if board[nx][ny] == '.' and fire[nx][ny] == -1:
                fire_q.append([nx, ny])
                fire[nx][ny] = fire[cur_x][cur_y] + 1

while dist_q:
    cur_x, cur_y = dist_q.popleft()
    for dir in range(4):
        nx, ny = cur_x + dx[dir], cur_y + dy[dir]
        if not (0 <= nx < r and 0 <= ny < c):
            print(dist[cur_x][cur_y] + 1)
            exit(0)
        if dist[nx][ny] >= 0 or board[nx][ny] == '#':
            continue
        if fire[nx][ny] != -1 and fire[nx][ny] <= dist[cur_x][cur_y] + 1:
            continue
        dist_q.append([nx, ny])
        dist[nx][ny] = dist[cur_x][cur_y] + 1
print("IMPOSSIBLE")


import sys
from cx_Freeze import setup, Executable
from pathlib import Path
import sysconfig
import os

is_64bits = sys.maxsize > 2**32

folder = "exe.{platform}-{version}".format(platform = sysconfig.get_platform(),
                                           version = sysconfig.get_python_version())
buildfolder = Path("build", folder)

# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages" : "Language"}

# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
targetname = None
targetname2 = None
if sys.platform == "win32":
    base = "Win32GUI"
    targetname = "Ticker.exe"
    targetname2 = "Console.exe"

setup(  name = "CPU Ticker",
        version = "2.0",
        #description = "",
        options = {"build_exe": build_exe_options},
        executables = [Executable("gui.py", base=base, targetName=targetname),
                       Executable("console.py", targetName=targetname2)])

if sys.platform == "win32" and os.path.isfile("upx.exe"):
    strbuild = str(buildfolder)
    targets = os.listdir(strbuild)
    targets = filter(lambda x:x.endswith((".pyd", ".exe")), targets)
    targets = " ".join((os.path.join(strbuild, target) for target in targets))
    command = "upx.exe "+targets
    print(command)
    os.system(command)


"""ex02_03.py"""
import random
from datetime import datetime

def creat_words():
    return "linux python robot system network computer service programming".split()

def word_jumble(words):
    random.seed(datetime.now())
    word = random.choice(words)
    jumble = random.sample(word, len(word))
    jumble = ''.join(jumble)
    return word, jumble

def main():
    words = creat_words()
    word, jumble = word_jumble(words)
    print(f"The jumble word is: [{jumble:>15}]")

    guess = input(f"Write your guess: ")
    if guess.lower() == word:
        print(f"Corret! The {jumble} is [{guess:^15}]")
    else:
        print(f"Incorrect! The {jumble} is [{word:<15}]")

if __name__ == '__main__':
    main()


import argparse
import chigger

parser = argparse.ArgumentParser(description='Rotation transform testing.')
parser.add_argument('--rotate', default=[0,0,0], type=int, nargs=3,
                    help='List of rotations to apply.')
parser.add_argument('--name', default='rotate.png', type=str, help='Output filename.')
args = parser.parse_args()

transform = chigger.filters.TransformFilter(rotate=args.rotate)

reader = chigger.exodus.ExodusReader('../input/mug_blocks_out.e')
mug = chigger.exodus.ExodusResult(reader, filters=[transform])

window = chigger.RenderWindow(mug, size=[300,300], test=True)
window.update()
window.write(args.name, antialiasing=5)
window.start()


from setuptools import setup

with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

setup(
    name='RaspberryPiVcgencmd',
    version='1.0.1',
    packages=['RaspberryPiVcgencmd'],
    url='https://github.com/chewett/RaspberryPiVcgencmd',
    license='MIT',
    author='Christopher Hewett',
    author_email='chewett@hotmail.co.uk',
    description='Python binding for the Raspberry Pi Vcgencmd command line executable',
    long_description=long_description,
    long_description_content_type="text/markdown",
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ]
)


import os
import sys
import torch
import torch_neuronx
import argparse
from cv_helper_class import ImgClassificationNet, VisionTransformerNet
from transformers import ViTFeatureExtractor, ViTForImageClassification
from torchvision import models
from common import preprocess_img

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--task", type=str, default="cnn_imgcls",
                        choices=['cnn_imgcls', 'vit_imgcls'])
    parser.add_argument("--cnn_network", type=str, default="RESNET",
                        choices=['VGG', 'RESNET', 'RESNEXT', 'EFFICIENTNET'])
    parser.add_argument("--save_path", type=str, default="neuron_model/resnet")

    parser_args, _ = parser.parse_known_args()
    return parser_args

def get_imgcls_model(args):
    assert(args.cnn_network in ["VGG", "RESNET", "RESNEXT", "EFFICIENTNET"])

    if args.cnn_network == "VGG":
        model_type = "11" # can be 11,11_bn,13,13_bn,16,16_bn,19,19_bn
        assert(model_type in ['11','11_bn','13','13_bn','16','16_bn','19','19_bn'])
        model_name = f"models.vgg{model_type}"
    elif args.cnn_network == "RESNET":
        model_type = 50 # can be 18,34,50,101,152
        assert(model_type in [18,34,50,101,152])
        model_name = f"models.resnet{model_type}"
    elif args.cnn_network == "RESNEXT":
        model_type = "50_32x4d" # can be 50_32x4d,101_32x8d,101_64x4d
        assert(model_type in ['50_32x4d','101_32x8d','101_64x4d'])
        model_name=f"models.resnext{model_type}"
    elif args.cnn_network == "EFFICIENTNET":
        model_type = 0 # can be 0,1,2,3,4,5,6,7
        assert(model_type in range(8))
        model_name = f"models.efficientnet_b{model_type}"

    model_name_eval = eval(model_name)
    model = model_name_eval(pretrained=True)
    net = ImgClassificationNet(model=model, model_name=model_name)
    return net, model, model_name

def get_vit_model():
    model_name = "vit-base-patch16-224"
    model_type = "vit"
    model = ViTForImageClassification.from_pretrained(f"google/{model_name}", torchscript=True)
    net = VisionTransformerNet(model=model, model_name=model_name, model_type=model_type)
    return net, model, model_name

def main(args):

    os.makedirs(args.save_path, exist_ok=True)

    if (args.task == "cnn_imgcls") or (args.task == "vit_imgcls"):
        if args.task == "cnn_imgcls":
            net, model, model_name = get_imgcls_model(args)
        else:
            net, model, model_name = get_vit_model()

    neuron_model_path = os.path.join(args.save_path, f"neuron_{net.model_name}.pt")
    if os.path.exists(neuron_model_path):
        print("=== Load pre-compiled model")
        net.load(neuron_model_path)
    else:
        print("=== Compile model")
        #net.analyze()
        net.compile(save_path=args.save_path)

if __name__ == "__main__":
    main(parse_args())


from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Board
from django.http import HttpResponse
from django.contrib import messages

from .forms import PostForm

def index(request):
  board_list = Board.objects.order_by('-create_date')
  context = {'board_list': board_list}
  return render(request, 'board/board_list.html', context)

def board_zzap(request):
  return render(request, 'board/board_zzap.html')

def detail(request, question_id):
  board_detail = get_object_or_404(Board, pk=question_id)
  context = {'board_detail': board_detail}
  return render(request, 'board/board_detail.html', context)

def notfound(request, exception):
  return render(request, 'not_found.html', status=404)

def board_write(request):
  if request.method == 'POST':
    form = PostForm(request.POST)
    if form.is_valid():
      question = form.save(commit=False)
      question.create_date = timezone.now()
      question.comment = '[]'
      question.writer = request.user.username
      question.view = 0
      question.save()
      return redirect('/board')

  else:
    form = PostForm()
    context = {'form': form}
    return render(request, 'board/board_write.html', context)

def board_modify(request, question_id):
    question = get_object_or_404(Board, pk=question_id)
    if request.method == "POST":
        form = PostForm(request.POST, instance=question)
        if form.is_valid():
            question = form.save(commit=False)
            question.modify_date = timezone.now()
            question.save()
            return redirect(f'/board/{question_id}/', question_id=question.id)
    else:
        form = PostForm(instance=question)

    context = {'form': form}
    return render(request, 'board/board_write.html', context)

def board_delete(request, question_id):
    question = get_object_or_404(Board, pk=question_id)
    question.delete()
    return redirect('/board')


from businessLogic.metrics.metricsFunctions import countByGroup, percentageByGroup
from db.sqlite3.connector import SqliteConnector
import pandas as pd
import datetime
from datetime import timezone
from config import config

def getMetricsPerProject(projectKey):
    dbConnector = SqliteConnector()
    selectedFields = ["Issue.key as issue", "Issue.storyPoints", "IssueType.name as issueType","Status.name as status", "Issue.assigneeName", "Issue.created"]
    joinClauses = [
        {"type":"LEFT", "tableName":"IssueType", "onClause":"Issue.issueTypeId = IssueType.id"},
        {"type":"LEFT", "tableName":"Project", "onClause":"Issue.projectId = Project.id"},
        {"type":"LEFT", "tableName":"Status", "onClause":"Issue.statusId = Status.id"}
    ]
    whereClause = "Project.key = '{}'".format(projectKey)
    statement = dbConnector.queryFromJoinStatement(selectedFields,"Issue",joinClauses,whereClause)

    # load data
    df = pd.read_sql_query(statement, dbConnector.connection)

    # drop data where story points are none
    df = df.drop(df[df.storyPoints == "None"].index)
    df["storyPoints"] = pd.to_numeric(df["storyPoints"])

    # show
    df_status = df.groupby("status").sum()
    print(df_status)

    # parse string to datetime
    df["created"] = pd.to_datetime(df["created"])

    # filter > 2020.1.1
    start = datetime.datetime(year=2020,month=5,day=11).replace(tzinfo=timezone.utc)
    df = df[df["created"] >= start]

    df1 = df.groupby("assigneeName").sum()
    print(df1)
    df2 = df.groupby("issueType").sum()
    print(df2)
    df = df.groupby("status").sum()

    #df = df.groupby("storyPoints").count()
    return df

def findIssuesCreatedBetween(projectKey, startStr, endStr):
    dbConnector = SqliteConnector()
    start = datetime.datetime.strptime(startStr,'%Y-%m-%d').replace(tzinfo=timezone.utc)
    end = datetime.datetime.strptime(endStr,'%Y-%m-%d').replace(tzinfo=timezone.utc)

    selectedFields = ["Issue.key as issue", "Issue.storyPoints", "IssueType.name as issueType","Status.name as status","Issue.statusid", "Issue.assigneeName", "Issue.created", "Issue.updated"]
    joinClauses = [
        {"type":"LEFT", "tableName":"IssueType", "onClause":"Issue.issueTypeId = IssueType.id"},
        {"type":"LEFT", "tableName":"Project", "onClause":"Issue.projectId = Project.id"},
        {"type":"LEFT", "tableName":"Status", "onClause":"Issue.statusId = Status.id"}
    ]
    whereClause = "Project.key = '{}'".format(projectKey)
    statement = dbConnector.queryFromJoinStatement(selectedFields,"Issue",joinClauses,whereClause)

    # load data
    df = pd.read_sql_query(statement, dbConnector.connection)

    df["created"] = pd.to_datetime(df["created"])
    df["updated"] = pd.to_datetime(df["updated"])

    df_created = df[ (df["created"] >= start) & (df["created"]<=end) ]
    print("issue created between those days")
    print("count")
    print(df_created.groupby("status").count())
    print("story points")
    df_created = df_created.drop(df_created[df_created.storyPoints == "None"].index)
    df_created["storyPoints"] = pd.to_numeric(df_created["storyPoints"])
    print(df_created.groupby("status").sum())

    df_updated = df[ (df["updated"] >= start) & (df["updated"]<=end) ]
    print("issue updated between those days")
    print("count")
    print(df_updated.groupby("status").count())
    print("story points")
    df_updated = df_updated.drop(df_updated[df_updated.storyPoints == "None"].index)
    df_updated["storyPoints"] = pd.to_numeric(df_updated["storyPoints"])
    print(df_updated.groupby("status").sum())

def getIssueTypeMetrics():
    dbConnector = SqliteConnector()
    projectKeys = dbConnector.queryTable(["key"], "Project", None)
    # print(projectKeys) # [('PJA',), ('SP',)], the result comes as array of tuple
    if projectKeys is not None:
        for projectKey in projectKeys:
            print("--------------------------------------")
            print("Project: " + projectKey[0])
            print(getMetricsPerProject(projectKey[0]))
            print("--------------------------------------")

def issuesInSprint(sprintId):
    dbConnector = SqliteConnector()
    selectedFields = ["Issue.key as issue", "Issue.storyPoints", "IssueType.name as issueType","Status.name as status","Issue.statusid", "Issue.assigneeName", "Issue.created", "Issue.updated"]
    joinClauses = [
        {"type":"LEFT", "tableName":"IssueType", "onClause":"Issue.issueTypeId = IssueType.id"},
        {"type":"LEFT", "tableName":"Project", "onClause":"Issue.projectId = Project.id"},
        {"type":"LEFT", "tableName":"Status", "onClause":"Issue.statusId = Status.id"},
        {"type":"LEFT", "tableName":"SprintIssueLink", "onClause":"Issue.id = SprintIssueLink.issueId"},
    ]
    whereClause = "SprintIssueLink.sprintId = '{}'".format(sprintId)
    statement = dbConnector.queryFromJoinStatement(selectedFields,"Issue",joinClauses,whereClause)

    # load data
    df = pd.read_sql_query(statement, dbConnector.connection)
    print(df)
    print(df.groupby("status").count())
    df = df.drop(df[df.storyPoints == "None"].index)
    df["storyPoints"] = pd.to_numeric(df["storyPoints"])
    print(df.groupby("status").sum())


import numpy as np
import cupy as cp

def basis_product(flux, basis_arr):
    return cp.tensordot(flux, basis_arr, axes=([[1], [1]]))

class DGFlux:
    def __init__(self, resolution, order, gamma=3.0):
        self.resolution = resolution + 2
        self.order = order
        self.gamma = gamma

        # boundary slices (not necessary in 1D)
        # self.boundary_slices = [(slice(resolution), 0), (resolution, -1)]

        # sound speed check
        self.max_speed = None

    def semi_discrete_rhs(self, variables, grid):  # , max_speeds):
        """
        Calculate the right-hand side of the semi-discrete equation
        """
        # Compute max speed for Lax-Friedrichs penalty term, element-wise
        # self.max_speed = max_speeds
        # Build flux vector
        pressure = (self.gamma - 1.0) * (variables[2, :, :] - 0.5 * variables[1, :, :] ** 2.0 / variables[0, :, :])
        flux0 = variables[1, :, :]
        flux1 = variables[1, :, :] ** 2.0 / variables[0, :, :] + pressure
        flux2 = (variables[2, :, :] + pressure) * variables[1, :, :] / variables[0, :, :]

        # Compute RHSs
        return cp.array([self.flux(variable_d=variables[0, :, :], flux_d=flux0, grid=grid),
                         self.flux(variable_d=variables[1, :, :], flux_d=flux1, grid=grid),
                         self.flux(variable_d=variables[2, :, :], flux_d=flux2, grid=grid)]) * grid.J

    def flux(self, variable_d, flux_d, grid):
        # compute internal flux
        internal = basis_product(flux=flux_d, basis_arr=grid.up)
        # compute numerical flux
        numerical = self.numerical_flux_lf(variable=variable_d, flux=flux_d, basis_arr=grid.xi)

        return internal - numerical

    def numerical_flux_lf(self, variable, flux, basis_arr):
        """
        Implements numerical flux as Lax-Friedrichs flux
        """
        # Allocate
        num_flux = cp.zeros((self.resolution, 2))

        # central flux, left face
        num_flux[:, 0] = -0.5 * (flux[:, 0] + cp.roll(flux[:, -1], shift=1, axis=0))
        # central flux, right face
        num_flux[:, -1] = 0.5 * (flux[:, -1] + cp.roll(flux[:, 0], shift=-1, axis=0))

        # penalty scalar
        # speed_left = cp.amax(cp.array([self.max_speed[:, 0],
        #                                cp.roll(self.max_speed[:, -1],
        #                                        shift=1, axis=0)]),
        #                      axis=0)
        # speed_right = cp.amax(cp.array([self.max_speed[:, -1],
        #                                 cp.roll(self.max_speed[:, 0],
        #                                         shift=-1, axis=0)]),
        #                       axis=0)

        # penalty flux, left face
        # num_flux[:, 0] += -0.5 * cp.multiply(speed_left, variable[:, 0] - cp.roll(variable[:, -1], shift=1, axis=0))
        # num_flux[:, -1] += 0.5 * cp.multiply(speed_right, variable[:, -1] - cp.roll(variable[:, 0], shift=-1, axis=0))

        return basis_product(flux=num_flux, basis_arr=basis_arr)

    def dg_jacobian(self, irk_stages, grid):
        """
        Computes Jacobian of DG system
        """
        # Euler system jacobian
        flux_jacobian = self.flux_jacobian(irk_stages)

        # Compute DG jacobian due to elemental internal fluxes
        dg_jacobian = cp.einsum('ij,klmis->mikjls', grid.up, flux_jacobian)
        dg_jacobian = cp.einsum('abidjs,ag->abigdjs', dg_jacobian, cp.eye(irk_stages.shape[1]))

        # Element boundary fluxes:
        # Jacobian contributions: Left element edge boundary flux
        part1 = cp.einsum('ag,ijas->agijs',
                          cp.eye(irk_stages.shape[1]),
                          flux_jacobian[:, :, :, 0, :])
        dg_jacobian[:, :, :, :, 0, :, :] += 0.5 * cp.einsum('b,agijs->abigjs',
                                                         grid.xi[:, 0],
                                                         part1)
        part1 = cp.roll(cp.einsum('ag,ijas->agijs',
                                  cp.eye(irk_stages.shape[1]),
                                  flux_jacobian[:, :, :, -1, :]),
                        shift=1, axis=0)
        dg_jacobian[:, :, :, :, -1, :, :] += 0.5 * cp.einsum('b,agijs->abigjs',
                                                          grid.xi[:, 0],
                                                          part1)
        # Jacobian contributions: Right element edge boundary flux
        part1 = cp.einsum('ag,ijas->agijs',
                          cp.eye(irk_stages.shape[1]),
                          flux_jacobian[:, :, :, -1])
        dg_jacobian[:, :, :, :, -1, :, :] -= 0.5 * cp.einsum('b,agijs->abigjs',
                                                          grid.xi[:, -1],
                                                          part1)
        part1 = cp.roll(cp.einsum('ag,ijas->agijs',
                                  cp.eye(irk_stages.shape[1]),
                                  flux_jacobian[:, :, :, 0, :]),
                        shift=-1, axis=0)
        dg_jacobian[:, :, :, :, 0, :, :] -= 0.5 * cp.einsum('b,agijs->abigjs',
                                                         grid.xi[:, -1],
                                                         part1)

        return dg_jacobian

    def flux_jacobian(self, variables):
        """
        Computes Euler flux Jacobian
        """
        # Initialize
        flux_jacobian = cp.zeros((variables.shape[0], variables.shape[0],
                                  variables.shape[1], variables.shape[2], variables.shape[3]))
        # Compute pressure and velocity
        velocity = variables[1, :, :, :] / variables[0, :, :, :]
        pressure = (self.gamma - 1.0) * (variables[2, :, :, :] -
                                         0.5 * variables[1, :, :, :] ** 2.0 / variables[0, :, :, :])
        enthalphy = (variables[2, :, :, :] + pressure) / variables[0, :, :, :]
        # Fill elements
        flux_jacobian[0, 1, :, :, :] = 1.0
        flux_jacobian[1, 0, :, :, :] = 0.5 * (self.gamma - 3.0) * (velocity ** 2.0)
        flux_jacobian[1, 1, :, :, :] = (3.0 - self.gamma) * velocity
        flux_jacobian[1, 2, :, :, :] = self.gamma - 1.0
        flux_jacobian[2, 0, :, :, :] = 0.5 * (self.gamma - 1.0) * (velocity ** 3.0) - velocity * enthalphy
        flux_jacobian[2, 1, :, :, :] = enthalphy - (self.gamma - 1.0) * (velocity ** 2.0)
        flux_jacobian[2, 2, :, :, :] = self.gamma * velocity

        return flux_jacobian


# coding=utf-8

#python 2getTrain.py  ./data/5000data.xlsx ./data10_26_750/
from langconv import Converter
import pandas as pd
import csv
import math
import re
import argparse

def rmSymbol(sent):
    return re.sub("|／\n", "", sent)

'''
input : 五個同組的question
output : [[][]
          [][]
          [][]] 10個question pair
'''

class Combination:
    def combine(self, text, n, k):
        res = []
        self.backtrack(text, n, k, res, [], 1)
        return res

    def backtrack(self, text, n, k, res, path, index):
        if len(path) == k:
            res.append(path)
            return
        for i in range(index, n + 1):
            self.backtrack(text, n, k, res, path + [text[i - 1]], i + 1)

if __name__ == '__main__':

    numOfNegSample = 4
    parser = argparse.ArgumentParser()
    parser.add_argument("input_file")
    parser.add_argument("output_directory")
    args = parser.parse_args()

    data = pd.read_excel(args.input_file, sheet_name='測試集', header=0)
    data2 = pd.read_excel(args.input_file, sheet_name='問題', header=0)
    n = len(data)  #5000 測試集內'測試題'與'正確標準問題'
    m = len(data2)  #1000 問題內 '標準問題'
    stdQuestion = data2['標準問題']  #All 標準問題  1000

    #決定negative sample 有多少 ：改成max
    perc = min(999, math.floor(len(stdQuestion) * 0.75))
    print("negative sample number %d" % perc)

    with open(args.output_directory + '/train.csv','w', newline='', encoding="utf8") as tCSV, \
         open(args.output_directory + '/dev.csv','w', newline='', encoding="utf8") as dCSV, \
             open(args.output_directory + '/test.csv','w', newline='', encoding="utf8") as testCSV:

        tCSVW = csv.writer(tCSV, lineterminator='\n')
        dCSVW = csv.writer(dCSV, lineterminator='\n')
        testCSVW = csv.writer(testCSV, lineterminator='\n')

        for i in range(0, n, 5):
            targetQuestion = data['正確標準問題'][i]
            otherQuestion = stdQuestion.loc[stdQuestion != targetQuestion]
            #make sure otherQuestion num == 999
            otherQuestion = otherQuestion.sample(n=perc)

            curGroup = []
            for j in range(5):
                index = i + j
                curGroup.append(data['測試題'][index])
            #create QuestionPair
            combination = Combination()
            curQuestionPairs = combination.combine(curGroup, 5, 2)
            #add postitive Question pair to .csv
            for index, QuestionPair in enumerate(curQuestionPairs):
                if index < 7:
                    tCSVW.writerow([
                        1,
                        rmSymbol(QuestionPair[0]),
                        rmSymbol(QuestionPair[1])
                    ])
                elif 7 <= index and index < 9:
                    dCSVW.writerow([
                        1,
                        rmSymbol(QuestionPair[0]),
                        rmSymbol(QuestionPair[1])
                    ])
                else:
                    #test data[0]為0
                    testCSVW.writerow([
                        0,
                        rmSymbol(QuestionPair[0]),
                        rmSymbol(QuestionPair[1])
                    ])

            #add negative sample to train.csv, dev.csv
            for negativeQuestion in otherQuestion.values:
                tCSVW.writerow(
                    [0,
                     rmSymbol(data['測試題'][i]),
                     rmSymbol(negativeQuestion)])
                dCSVW.writerow(
                    [0,
                     rmSymbol(data['測試題'][i]),
                     rmSymbol(negativeQuestion)])

            #add negative sample to test.csv(999個)，i為當前組index
            for index, row in enumerate(data['測試題']):
                if index != i and index % 5 == 0:
                    testCSVW.writerow([
                        0,
                        rmSymbol(data['測試題'][i + 3]),
                        rmSymbol(data['測試題'][index])
                    ])


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import argparse
import json
import subprocess
import shlex
from common import bcolors

def tidy_json(path):
    try:
        with open(path, 'r') as f:
            parsed = json.load(f)
        with open(path, 'w') as f:
            json.dump(parsed, f, indent=4, sort_keys=True)
        return 0
    except ValueError:
        return 1

def tidy_html(path):
    config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                               ".html-tidy")
    cmd = shlex.split(f'tidy -config "{config_path}" -q "{path}"')
    result = subprocess.run(cmd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)
    if result.returncode == 1:
        return 1
    if result.returncode > 1:
        return 2
    return 0

def tidy_file(path):
    if path.endswith('.json'):
        return tidy_json(path)
    elif path.endswith('.html'):
        return tidy_html(path)

def tidyable_file(path):
    if path.endswith('.json'):
        return True
    if path.endswith('.html'):
        return True
    return False

def tidy_dir(path, level=0, prefix=''):
    prefix_file = prefix + '├── '
    if level == 0:
        print(f'tidy dir {path}')

    result = {
        'warning': [],
        'error': [],
    }

    items = [os.path.join(path, name) for name in os.listdir(path)]
    files = sorted([
        path for path in items if os.path.isfile(path) and tidyable_file(path)
    ])
    dirs = sorted([path for path in items if os.path.isdir(path)])

    for filename in [os.path.basename(path) for path in files]:
        filepath = os.path.join(path, filename)
        tidy = tidy_file(filepath)
        if tidy == 0:
            print(f'{prefix_file}{bcolors.OKGREEN}{filename} ✓{bcolors.ENDC}')
        elif tidy == 1:
            print(f'{prefix_file}{bcolors.WARNING}{filename} ✓{bcolors.ENDC}')
            result['warning'].append(filepath)
        elif tidy > 1:
            print(f'{prefix_file}{bcolors.FAIL}{filename} ✘{bcolors.ENDC}')
            result['error'].append(filepath)

    for dirname in [os.path.basename(path) for path in dirs]:
        print(prefix + '├── ' + dirname)
        subresult = tidy_dir(os.path.join(path, dirname),
                             level=level + 1,
                             prefix=prefix + '│   ')
        result['warning'].extend(subresult['warning'])
        result['error'].extend(subresult['error'])

    return result

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('a')
    args = parser.parse_args()

    result = tidy_dir(args.a)
    if result['error']:
        return 1

    return 0

if __name__ == "__main__":
    sys.exit(main())


from torch.nn.modules.loss import _Loss

def _assert_no_grad(variable):
    assert not variable.requires_grad, \
        "nn criterions don't compute the gradient w.r.t. targets - please " \
        "mark these variables as not requiring gradients"

class DiceLoss(_Loss):
    def __init__(self, size_average=True, reduce=True, num_classes = 2,
                 classweights = [1, 1]):
        super(DiceLoss, self).__init__(size_average)
        self.reduce = reduce
        self.cw = classweights
        self.num_classes = num_classes

    def forward(self, input, target):
        _assert_no_grad(target)

        eps = 0.0000001

        if self.num_classes == 2:
            'Multiclass'

            Closses = 0
            for C in range(input.size(1)):
                Cinput = input[:, C].contiguous()
                target = target.squeeze()

                assert Cinput.size() == target.size(), "Target size different to input size."
                p  = Cinput.view(Cinput.size(0), -1).add(eps).float()
                gt = target.view(target.size(0), -1).add(eps).float()

                if C == 0:
                    gt = 1 - gt
                numerator =  p.mul(gt).sum(1).mul(2)
                denumerator = p.mul(p).sum(1).add(gt.mul(gt).sum(1))
                if C == 0:
                    Closses += self.cw[0]*(1-numerator.div(denumerator))
                else:
                    Closses += self.cw[1]*(1 - numerator.div(denumerator))

            if self.size_average:
                return Closses.mean()
            return Closses.sum()
        'Singleclass'
        assert input.size() == target.size(), "Target size different to input size."
        p  = input.view(input.size(0), -1).add(eps)
        gt = target.view(target.size(0), -1).add(eps)

        numerator =  p.mul(gt).sum(1).mul(2)
        denumerator = p.mul(p).sum(1).add(gt.mul(gt).sum(1))

        if self.size_average:
            return (1-numerator/denumerator).mean()
        return (1-numerator/denumerator).sum()


import gtk
import sys
from xml.dom.minidom import parse

from mi.client.utils import xmlgtk

class t0_xmlgtk(xmlgtk.xmlgtk):
    def __init__(self, uixmldoc, uixml_rootname=None):
        xmlgtk.xmlgtk.__init__(self, uixmldoc, uixml_rootname)
        self.name_map['btn1'].connect('enter-notify-event',
                                      self.show_text,
                                      'DESC BTN1 (AAA)')
        self.name_map['btn1'].connect('leave-notify-event',
                                      self.show_text, '')
        self.name_map['btn2'].connect('enter-notify-event',
                                      self.show_text,
                                      'DESC BTN2 (BBB)')
        self.name_map['btn2'].connect('leave-notify-event',
                                      self.show_text, '')
    def show_text(self, widget, event, data):
        self.name_map['btndesc'].set_text(data)

window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_border_width(4)
window.set_position(gtk.WIN_POS_CENTER)

xml_interface = parse('t0-xmlgtk.xml')

xgobj = t0_xmlgtk(xml_interface)

window.add(xgobj.widget)
window.show_all()

gtk.main()


from server import db, app
from sqlalchemy.exc import IntegrityError, OperationalError

class Document(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    houseId = db.Column(db.Integer(), nullable=False, unique=True)
    documentURL = db.Column(db.String(120))
    province = db.Column(db.String(30))
    description = db.Column(db.String(500))
    name = db.Column(db.String(100))

    def __init__(self, **kwargs):
        """**kwargs firstName, lastName, email, password, phoneNumber"""
        self.houseId = kwargs.get("houseId", "")
        self.documentURL = None
        self.province = kwargs.get("province", "")
        self.description = kwargs.get("description", "")
        self.name = kwargs.get("name", "")

    def insert(self):
        try:
            db.session.add(self)
            db.session.commit()
            db.session.close()
            return True
        except IntegrityError as e:
            print(e)
            db.session.rollback()
            db.session.close()
            return False

    def update(self):
        rows = Document.query.filter(Document.houseId == self.houseId).update(self.toDict(), synchronize_session=False)
        if rows == 1:
            try:
                db.session.commit()
                db.session.close()
                return True
            except OperationalError:
                db.session.rollback()
                db.session.close()
                return False
        return False

    def toDict(self):
        return {
            Document.houseId: self.houseId,
            Document.documentURL: self.documentURL,
            Document.province: self.province,
            Document.description: self.description,
            Document.name: self.name
        }

    def toJson(self):
        return {
            "houseId": self.houseId,
            "documentURL": self.documentURL,
            "province": self.province,
            "description": self.description,
            "name": self.name
        }

    def __repr__(self):
        return "< Document: " + self.documentURL + " >"


from file_clean_up import *
import timeit
from data_model import *
import datetime as dt

RMD = "/Users/jimmyzhong/Desktop/Empty DB for Training.db"
db = DBsqlite(RMD)
golden_address = "/Users/mingyuzhong/Documents/tracker/ReliabilityManagementDB copy.db"
gold = DBsqlite(golden_address)

def test_auto_parse():
    a = RawData()
    # a.settings = {'encode': 'utf-8', 'start_row': 2, 'end_row': -1, 'start_keyword': ' StartTime', 'end_keyword': ' EndTime', 'serial_number_keyword': 'UUT_Serial_Number', 'start_time_indicator': 'start', 'end_time_indicator': 'end', 'separator': ',', 'skip_keywords': [''], 'skip_rows': [''], 'col_name_set': None, 'sn_col': 'UUT_Serial_Number', 'start_time_col': ' StartTime', 'end_time_col': ' EndTime', 'start_col': 0, 'sn_col_candi': [], 'start_time_candi': [], 'end_time_candi': [], 'quotechar': '"'}
    file = "/Users/jimmyzhong/Desktop/seacliff_mot-04_20210526_summary.csv"
    a.settings.update({
        "timestamp_format": '%Y%m%d-%H%M%S',
    })
    # print(timeit.timeit(lambda: a.auto_parse(file), number=1))
    result = a.auto_parse(file)
    print(result)
    # rel_tag = [db.rel_tagging(a[1], a[0]) for a in result[1:]]
    # print (rel_tag)

    # current_time = dt.datetime.now().timestamp()
    # time_str = dt.datetime.now().strftime('%Y%m%d-%H%M%S')
    # print(time_str)

    assert 1 == 1

def test_search_match_in_files():
    assert False

def test_clean_up_file():
    a = RawData()
    a.settings.update(
        {
            "separator": ",",
        }
    )
    file = '/Users/jimmyzhong/Desktop/5385BZ_VID-1_Summary_20210526_G25TC_P_R_MPK.csv'
    result = a.clean_up_file(file)
    print(result)
    assert 1 == 1

def test_concat_matching_files():
    """
    bring starttime and serialnumber to first, all text column to front, all numbers to back
    :return:
    """
    a = RawData()
    a.settings.update(
        {
            "separator": ",",
            "start_time_col": "Start Time",
            "timestamp_format": "%Y/%m/%d %H:%M:%S",
            "sn_col": "Lens Housing Barcode"
        }
    )
    file_list = ['/Users/jimmyzhong/Desktop/5385BZ_VID-1_Summary_20210526_G25TC_P_R_MPK.csv',
            '/Users/jimmyzhong/Desktop/5385BZ_VID-1_Summary_20210526_G25TC_P_R_MPK.csv']
    result = a.concat_matching_files(file_list,db)
    assert 1 == 1

def test_get_timestamp():
    a = RawData()
    time_str = "10/13/2021 14:06"
    format = "%m/%d/%Y %H:%M"
    a = dt.datetime.strptime(time_str, format)
    print (a)


# -*- coding: utf-8 -*-
import scrapy
from xiaosuo.items import XiaosuoItem
from .sort import Cn2An,get_tit_num

class XiaosSpider(scrapy.Spider):
    name = 'xiaos'
    allowed_domains = ['qu.la']
    start_urls = ['http://www.qu.la/paihangbang/']
    novel_list=[]
    def parse(self, response):
        books=response.xpath('.//div[@class="index_toplist mright mbottom"]')
        for book in books:
            link=book.xpath('.//div[2]/div[2]/ul/li[1]')
            for li in link:
                url='http://www.qu.la'+li.xpath('.//a/@href').extract()[0]
                self.novel_list.append(url)
        self.novel_list=list(set(self.novel_list))
        for nov in self.novel_list:
            yield scrapy.Request(nov,callback=self.get_page_url)

    def get_page_url(self,response):

        pages=response.xpath('.//dd/a/@href').extract()
        for url in pages:
            yield scrapy.Request('http://www.qu.la'+url,callback=self.get_text)

    def get_text(self,response):
        item=XiaosuoItem()
        item['bookname'] = response.xpath('.//div[@class="con_top"]/a[2]/text()').extract()[0]

        # 章节名 ,将title单独找出来，为了提取章节中的数字
        title = response.xpath('.//h1/text()').extract()[0]
        item['title'] = title

        #  找到用于排序的id值
        item['order_id'] = Cn2An(get_tit_num(title))

        # 正文部分需要特殊处理
        body = response.xpath('.//div[@id="content"]/text()').extract()

        # 将抓到的body转换成字符串，接着去掉\t之类的排版符号，
        text = ''.join(body).strip().replace('\u3000', '')
        item['body'] = text
        return item


from django import forms
from django.core.validators import MinValueValidator

from .models import Bid, Listing, Comment

class CreateListingForm(forms.ModelForm):
    """
    Form for user to create a new listing.
    Data stored in `Listing` model.
    """
    class Meta:
        model = Listing
        fields = ["title", "description", "starting_bid", "image_url", "category"]
        widgets = {
            "starting_bid": forms.NumberInput(attrs={'step': 0.50}),
        }
        labels = {
            "image_url": "Image URL"
        }
        help_texts = {
            "description": "Provide a short description of your listing",
            "starting_bid": "Enter the minimum bid (in $)",
            "image_url": "(optional) Provide a URL to an image for your listing",
            "category": "Select the category of your listing."
        }

class NewBidForm(forms.ModelForm):
    """
    Form for user to create a new bid for a particular listing.
    Data stored in `Bid` model.
    Ensure any new bid is higher than the current one.
    """
    class Meta:
        model = Bid
        fields = ["bidder", "listing", "price"]
        widgets = {
            "bidder": forms.HiddenInput(),
            "listing": forms.HiddenInput()
        }

    # should min_bid be validated in form or in views??
    def __init__(self, *args, **kwargs):
        # Dynamically validate form to reflect current bid price
        min_bid = kwargs.pop("min_bid")
        super(NewBidForm, self).__init__(*args, **kwargs)
        self.fields["price"].validators = [MinValueValidator(min_bid, message="Enter a bid higher than the current price.")]

class NewCommentForm(forms.ModelForm):
    """
    Form for user to add a new comment for any listing.
    """
    class Meta:
        model = Comment
        fields = ["comment"]


from rest_framework import serializers
from app1.models import ProductosRegistro

class ProductosRegistroSerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductosRegistro
        fields = ['nombre', 'cantidad', 'precio', 'create_at']
        read_only_fields = ('create_at', )

    def validate_nombres(self, value):
        if len(value) < 3:
            raise serializers.ValidationError('Los nombres deben tener al menos 3 caracteres')
        return value

    def validate_cantidad(self, value):
        # Asegúrate de que 'value' sea un entero antes de comparar
        try:
            cantidad = int(value)
        except ValueError:
            raise serializers.ValidationError("La cantidad debe ser un número entero.")

        # Ahora puedes comparar 'cantidad' como un entero
        if cantidad < 0:
            raise serializers.ValidationError("La cantidad debe ser mayor o igual a cero.")

        return cantidad