# -*- coding: utf-8 -*-
"""Main REST like API extension of the BioImageIT original to add pyDetecDiv-specific methods

This file implements the main BioImageIT API with using stateless operation like for a REST API
"""

import os.path

import bioimageit_core.api.request
from bioimageit_core import ConfigAccess
from bioimageit_core.core.exceptions import DataServiceError
from bioimageit_core.core.utils import format_date

class Request(bioimageit_core.api.request.Request):
    """
    A class extending the BioIMageIT Request class in order to add some features without having to modify the original
    code.
    """
    def create_experiment(self, name, author='', date='now', keys=None, destination=''):
        """Create a new experiment

        **Parameters**
        name: str
            Name of the experiment
        author: str
            username of the experiment author
        date: str
            Creation date of the experiment
        keys: list
            List of keys used for the experiment vocabulary
        destination: str
            Destination where the experiment is created. It is a the path of the
            directory where the experiment will be created for local use case
        **Returns**
        Experiment container with the experiment metadata

        """
        if keys is None:
            keys = []
        try:
            if author == '':
                author = ConfigAccess.instance().config['user']['name']
            return self.data_service.create_experiment(name, author, format_date(date),
                                                       keys, destination)
        except DataServiceError as err:
            self.notify_error(str(err))

    def annotate_raw_data_using_regex(self, experiment, keys_, regex):
        """
        Annotate raw dataset of an experiment using the source path name

        :param experiment: the experiment
        :type experiment: Experiment Container
        :param keys_: the annotation keys
        :type keys_: tuple of str
        :param regex: the regular expression defining how to extract the values corresponding to the specified keys
        :type regex: regular expression str
        """
        print(f'Please, wait while annotating raw dataset of {experiment.name}')
        self.data_service.annotate_using_regex(experiment, experiment.raw_dataset,
                                               lambda x: os.path.join(x['source_dir'], x['name']), keys_, regex)
        print('OK')

    def annotate_using_regex(self, experiment, dataset, source, keys_, regex):
        """
        Annotate a dataset of an experiment using a regular expression

        :param experiment: the experiment containing the dataset to annotate
        :type experiment: Experiment Container
        :param dataset: the dataset to annotate
        :type dataset: Dataset Container or DatasetInfo Container
        :param source: a string (column name) or callable returning a string that the regular expression will be
        applied to
        :type source: callable or str
        :param keys_: the annotation keys
        :type keys_: tuple of str
        :param regex: the regular expression defining how to extract the values corresponding to the specified keys
        :type regex: regular expression str
        """
        print(f'Please, wait while annotating dataset {dataset.name}')
        self.data_service.annotate_using_regex(experiment, dataset, source, keys_, regex)
        print('OK')

    def clear_annotation(self, experiment, dataset, key):
        """
        Clear annotations with the specified key in a dataset

        :param experiment: the experiment containing the dataset to update
        :type experiment: Experiment Container
        :param dataset: the dataset
        :type dataset: Dataset Container or DatasetInfo Container
        :param key: the key to remove from the dataset annotations
        :type key: str
        """
        self.data_service.clear_annotation(experiment, dataset, key)

    def import_glob(self, experiment, files_glob, author='',
                    format_='imagetiff', date='now', destination=None, **kwargs):
        """
        Import into an experiment a list of raw data files specified by a glob pattern

        :param experiment: the experiment
        :type experiment: Experiment Container
        :param files_glob: the file path specification
        :type files_glob: str
        :param author: the author's name
        :type author: str
        :param format_: the file format
        :type format_: str
        :param date: the date
        :type date: str
        :param observers: a list of observers to notify progress
        :type observers: list of Observer objects
        """
        # print(f'Please wait while importing data into {experiment.raw_dataset.name} dataset')
        self.data_service.import_glob(experiment, files_glob,
                                      author=author, format_=format_, date=date, observers=None,
                                      destination=destination)
        # print('OK')

    def run(self, job):
        """Run a BioImageIT job

        A BioImageIT job is a run of a processing tool in a database. The data to process are
        selected in the database using a specified request, and the results are automatically
        saved in a new dataset of the database. All the metadata of the job (tool, request,
        parameters) are also saved in the database.
        """
        if job.tool.type == "merge":
            self._run_job_merged(job)
        else:
            self._run_job_sequence(job)
        return job.experiment


def encrypt(text, shift):
    encrypted_text = ""
    for char in text:
        if char.isalpha():
            if char.islower():
                encrypted_text += chr((ord(char) - 97 + shift) % 26 + 97)
            else:
                encrypted_text += chr((ord(char) - 65 + shift) % 26 + 65)
        elif char.isdigit():
            encrypted_text += str((int(char) + shift) % 10)
        else:
            encrypted_text += char
    return encrypted_text

def main():
    repeat = True
    while repeat:
        print("=== Program Enkripsi ===")
        plaintext = input("Masukkan teks: ")
        shift = int(input("Masukkan jumlah pergeseran: "))
        encrypted_text = encrypt(plaintext, shift)
        print("Hasil enkripsi: ", encrypted_text)

        choice = input("Apakah Anda ingin melakukan program lagi? (y/n): ")
        if choice.lower() != "y":
            repeat = False
            print("Terima kasih telah menggunakan program.")

if __name__ == "__main__":
    main()


from odoo.tests.common import users
from odoo.addons.test_mass_mailing.tests import common

class TestLinkTracker(common.TestMassMailCommon):

    def setUp(self):
        super(TestLinkTracker, self).setUp()

        self.link = self.env['link.tracker'].search_or_create({
            'url': 'https://www.example.com'
        })

        self.click = self.env['link.tracker.click'].create({
            'link_id': self.link.id,
            'ip': '100.00.00.00',
            'country_id': self.env.ref('base.fr').id,
        })

    def test_add_link(self):
        code = self.link.code
        self.assertEqual(self.link.count, 1)

        # click from a new IP should create a new entry
        click = self.env['link.tracker.click'].sudo().add_click(
            code,
            ip='100.00.00.01',
            country_code='BEL'
        )
        self.assertEqual(click.ip, '100.00.00.01')
        self.assertEqual(click.country_id, self.env.ref('base.be'))
        self.assertEqual(self.link.count, 2)

    @users('user_marketing')
    def test_add_link_mail_stat(self):
        record = self.env['mailing.test.blacklist'].create({})
        code = self.link.code
        self.assertEqual(self.link.count, 1)
        trace = self.env['mailing.trace'].create({
            'mass_mailing_id': self.mailing_bl.id,
            'model': record._name,
            'res_id': record.id,
        })
        self.assertEqual(trace.trace_status, 'outgoing')
        self.assertFalse(trace.links_click_datetime)

        # click from a new IP should create a new entry and update stat when provided
        click = self.env['link.tracker.click'].sudo().add_click(
            code,
            ip='100.00.00.01',
            country_code='BEL',
            mailing_trace_id=trace.id
        )
        self.assertEqual(self.link.count, 2)
        self.assertEqual(click.mass_mailing_id, self.mailing_bl)
        self.assertTrue(trace.trace_status, 'open')
        self.assertTrue(trace.links_click_datetime)
        self.assertEqual(trace.links_click_ids, click)


def c(hrush):
    if hrush.lower().strip() == 'not ok':
    	print('will you run or stay from the situation?')
    elif hrush.lower().strip() == 'ok':
    	print("will you run or stay from the situation?")

hrush = input("You and youre friend are encoutring youre chrush (type Ok/Not Ok) and (hit enter twice), 'type here--->'  ")
c(hrush)

def stay(run):
	if run.lower().strip() == 'run':
		print('You Lose, game over!')
		exit(0)
	else:
		print('Invalid syntax')

run = input()
stay(run)


import numpy as np
import cv2
from numpy.linalg import inv
import os, sys

WRITE2FILE = True

class img_preprocess(object):
    def __init__(self, f):
        # print("YUV decorator has initialised")
        self.f = f

    def __call__(self, *args, **kwargs):
        print("enter func %s") % self.f.__name__

        self.f(*args, **kwargs)

        print("exit func %s") % self.f.__name__

img_dir = "static/uploads/"

R_Y_mat = np.array([[0.299,0.587,0.114],
                    [-0.14713, -0.28886, 0.436],
                    [0.615, -0.51499, -0.10001]])
Y_R_mat = np.array([[1, 0, 1.13983],
                    [1, -0.39465, -0.58060],
                    [1, 2.03211, 0]])

def RGB2YUV(img):
    return np.einsum('lk,ijl->ijk', R_Y_mat, img)

def YUV2RGB(img):
    return np.einsum('lk,ijl->ijk', Y_R_mat, img)

def subsample_web_api(file):
    img = cv2.imread(os.path.join(img_dir, file))
    img = cv2.resize(img, (512, 512))
    file = file.split('.')[0] + '.jpg'
    cv2.imwrite(os.path.join(img_dir, file), img)

    subsample(img)

def subsample(img):

    img = cv2.cvtColor(img, cv2.COLOR_RGB2YCR_CB)
    # img = RGB2YUV(img)

    if WRITE2FILE:
        cv2.imwrite('static/uploads/temp_Y.jpg',img[:,:,0])
        cv2.imwrite('static/uploads/temp_U.jpg',img[:,:,1])
        cv2.imwrite('static/uploads/temp_V.jpg',img[:,:,2])

    data = np.zeros_like(img, dtype=float)
    data[:] = img

    d1 = chroma_4_2_0_subsampling(data)
    d2 = chroma_4_2_2_subsampling(data)

    img[:] = d1
    # img = YUV2RGB(img)
    img = cv2.cvtColor(img, cv2.COLOR_YCR_CB2RGB)

    if WRITE2FILE:
        cv2.imwrite('static/uploads/temp_4_2_0.jpg',img)

    img[:] = d2
    # img = YUV2RGB(img)
    img = cv2.cvtColor(img, cv2.COLOR_YCR_CB2RGB)

    if WRITE2FILE:
        cv2.imwrite('static/uploads/temp_4_2_2.jpg',img)

    cv2.destroyAllWindows()
    return img

def chroma_4_2_2_subsampling(img):

    height, weight = img.shape[:2]

    # Subsample U by half
    # print img[:,:,1]

    for x in xrange(height):
        for y in xrange(weight):
            img[x, y, 1] = img[x - x % 2, y , 1]

    # Subsample V by zero
    # print img[:,:,2]

    for x in xrange(height):
        for y in xrange(weight):
            img[x, y, 2] = img[x - x % 2, y, 2]

    # print img[:,:,2]
    return img

def chroma_4_2_0_subsampling(img):

    height, weight = img.shape[:2]

    # Subsample U by half
    # print img[:,:,1]

    for x in xrange(height):
        for y in xrange(weight):
            img[x, y, 1] = img[x - x % 2, y - y % 2 , 1]

    # Subsample V by zero
    # print img[:,:,2]

    for x in xrange(height):
        for y in xrange(weight):
            img[x, y, 2] = img[x - x % 2, y - y % 2 , 2]

    # print img[:,:,2]
    return img


import csv
import os
from ...Crawler.Fs import FsPath
from ...Crawler.Fs.Image import Image
from ...Crawler.Fs.Video import Video
from ..Task import Task

class SubmissionSheet(Task):
    """
    A task to create a cvs file for client deliveries.
    """

    def __init__(self, *args, **kwargs):
        """
        Create a SubmissionSheet.
        """
        super(SubmissionSheet, self).__init__(*args, **kwargs)

        self.__rows = {}
        self.__deliveryData = {}
        self.__clientDeliveryPath = ""

    def _perform(self):
        """
        Perform the task.
        """
        jsonCrawler = self.crawlers()[0]
        self.__getDeliveryData(jsonCrawler)
        if self.option('mergeMattes'):
            self.__findMattes()

        self.__columnLabels = list(map(lambda x: x[0], self.option("_columns")))

        internalDeliveryFolder = os.path.dirname(jsonCrawler.var('filePath'))
        self.__clientDeliveryPath = os.path.join(internalDeliveryFolder, jsonCrawler.var('name'))
        crawler = FsPath.createFromPath(self.__clientDeliveryPath)
        # Add rows for all images found first, so the resolution and other info is added in priority
        for crawler in crawler.glob(filterTypes=[Image]):
            self.__setRow(crawler)
        # Add rows for all videos next, so if images were already written, it'll just update the extensions, otherwise
        # it'll add the full video info
        for crawler in crawler.glob(filterTypes=[Video]):
            self.__setRow(crawler)

        self.__writeSpreadsheet()
        if self.option("includeLogFile"):
            self.__writeLogFile()

        return []

    def __getDeliveryData(self, jsonCrawler):
        """
        Get the delivery data stored in a json file in the parent folder of the client delivery folder.
        """
        self.__deliveryData = jsonCrawler.contents()

    def __findMattes(self):
        """
        Look for delivery data tagged as mattes and set their name on their matching internalVersion entry.
        """
        mattes = {}
        toDelete = []
        for name in self.__deliveryData:
            if not self.__deliveryData[name].get('isMatte', 0):
                continue
            internalVersion = self.__deliveryData[name].get('internalVersion')
            mattes[internalVersion] = name
            toDelete.append(name)
        for name in self.__deliveryData:
            internalVersion = self.__deliveryData[name].get('internalVersion')
            self.__deliveryData[name]['matteName'] = mattes.get(internalVersion, '')
        # Remove mattes from dictionary so they don't get added on their own line in the spreadsheet
        for name in toDelete:
            del self.__deliveryData[name]

    def __setRow(self, crawler):
        """
        Get the data expected to be in a spreadsheet row for the given file crawler.
        """
        name = crawler.var("name")

        isProxy = (name.endswith("_h264") or name.endswith("_prores"))
        if isProxy and not self.option('includeProxies'):
            return

        shortName = name if not isProxy else "_".join(name.split("_")[:-1])
        if self.option('mergeMattes') and shortName not in self.__deliveryData:
            return

        if shortName not in self.__rows:
            self.__addRow(shortName, crawler)
        else:
            self.__updateRow(shortName, crawler)

    def __addRow(self, name, crawler):

        self.__rows[name] = {}
        for label, fieldName in self.option("_columns"):
            # Deal with fields that require custom processing
            if fieldName == "name":
                self.__rows[name][label] = name

            elif fieldName == "clientStatus":
                vars = {"sg_status_list": self.__deliveryData[name].get('sg_status_list')}
                self.__rows[name][label] = self.templateOption('clientStatus', vars=vars)

            else:
                self.__rows[name][label] = self.__getFieldValue(name, fieldName, crawler)

    def __updateRow(self, name, crawler):

        for label, fieldName in self.option("_columns"):
            if fieldName == "clientFileType":
                currentExt = self.__rows[name].get(label)
                extName = self.__getFieldValue(name, fieldName, crawler)
                if extName not in currentExt.split(","):
                    self.__rows[name][label] = "{},{}".format(currentExt, extName)

    def __getFieldValue(self, name, fieldName, crawler):
        # Look for a value in the delivery data first
        if fieldName in self.__deliveryData[name]:
            return self.__deliveryData[name].get(fieldName)
        # Next, it could be a task option
        elif fieldName in self.optionNames():
            return self.templateOption(fieldName, crawler=crawler)
        # Finally, the value would be in the crawler
        elif fieldName in crawler.varNames():
            return crawler.var(fieldName)

    def __writeSpreadsheet(self):
        """
        Write a cvs file at the target path.
        """
        targetPath = os.path.join(self.__clientDeliveryPath, "{}.csv".format(self.crawlers()[0].var('name')))
        with open(targetPath, 'w') as csvfile:
            writer = csv.DictWriter(csvfile, fieldnames=self.__columnLabels)
            writer.writeheader()
            for rowName in sorted(self.__rows):
                writer.writerow(self.__rows[rowName])

    def __writeLogFile(self):
        name = os.path.basename(self.__clientDeliveryPath)
        logFile = os.path.join(self.__clientDeliveryPath, "{}_log.txt".format(name))
        os.system("cd {0};ls -1R > {1}".format(self.__clientDeliveryPath, logFile))

# registering task
Task.register(
    'submissionSheet',
    SubmissionSheet
)


# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def pairSum(self, head: Optional[ListNode]) -> int:
        # step1: reverse the 2nd half of the linked list in place (已知)
        #       1.1 find the miidle (two pointer)
        #       1.2 reverse it
        # step2: traverse and find the sum

        # step 1.1
        slow = head
        fast = head

        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next

        # step 1.2 now, slow is at the end of 1st half
        prev = None
        curr = slow

        while curr:
            temp = curr.next
            curr.next = prev
            # update pointers
            prev = curr
            curr = temp

        # step 2
        first = head
        last = prev
        maxSum = -1
        while last:
            if first.val + last.val > maxSum:
                maxSum = first.val + last.val

            first = first.next
            last = last.next

        return maxSum


import torch
from torch import nn, Tensor
from torch.nn import functional as F

import numpy as np
import math
from typing import Optional, Dict, Tuple, Union, Sequence

from layers.conv_layer import ConvBlock

from .transformer import TransformerEncoder, LinearAttnFFN

class MobileViTBlock(nn.Module):
    """
    This class defines the `MobileViT block <https://arxiv.org/abs/2110.02178?context=cs.LG>`_

    Args:
        opts: command line arguments
        in_features (int): :math:`C_{in}` from an expected input of size :math:`(N, C_{in}, H, W)`
        transformer_dim (int): Input dimension to the transformer unit
        ffn_dim (int): Dimension of the FFN block
        n_transformer_blocks (Optional[int]): Number of transformer blocks. Default: 2
        head_dim (Optional[int]): Head dimension in the multi-head attention. Default: 32
        attn_dropout (Optional[float]): Dropout in multi-head attention. Default: 0.0
        dropout (Optional[float]): Dropout rate. Default: 0.0
        ffn_dropout (Optional[float]): Dropout between FFN layers in transformer. Default: 0.0
        patch_h (Optional[int]): Patch height for unfolding operation. Default: 8
        patch_w (Optional[int]): Patch width for unfolding operation. Default: 8
        transformer_norm_layer (Optional[str]): Normalization layer in the transformer block. Default: layer_norm
        conv_ksize (Optional[int]): Kernel size to learn local representations in MobileViT block. Default: 3
        dilation (Optional[int]): Dilation rate in convolutions. Default: 1
        no_fusion (Optional[bool]): Do not combine the input and output feature maps. Default: False
    """

    def __init__(
        self,
        in_features: int,
        transformer_dim: int,
        ffn_dim: int,
        n_transformer_blocks: Optional[int] = 2,
        head_dim: Optional[int] = 32,
        attn_dropout: Optional[float] = 0.0,
        dropout: Optional[int] = 0.0,
        ffn_dropout: Optional[int] = 0.0,
        patch_h: Optional[int] = 8,
        patch_w: Optional[int] = 8,
        transformer_norm_layer: Optional[str] = "layer_norm",
        conv_ksize: Optional[int] = 3,
        dilation: Optional[int] = 1,
        no_fusion: Optional[bool] = False,
    ) -> None:
        conv_3x3_in = ConvBlock(
            in_features=in_features,
            out_features=in_features,
            kernel_size=conv_ksize,
            stride=1,
            use_norm=True,
            dilation=dilation,
        )
        conv_1x1_in = ConvBlock(
            in_features=in_features,
            out_features=transformer_dim,
            kernel_size=1,
            stride=1,
            use_norm=False,
        )

        conv_1x1_out = ConvBlock(
            in_features=transformer_dim,
            out_features=in_features,
            kernel_size=1,
            stride=1,
            use_norm=True,
        )
        conv_3x3_out = None
        if not no_fusion:
            conv_3x3_out = ConvBlock(
                in_features=2 * in_features,
                out_features=in_features,
                kernel_size=conv_ksize,
                stride=1,
                use_norm=True,
            )
        super().__init__()
        self.local_rep = nn.Sequential()
        self.local_rep.add_module(name="conv_3x3", module=conv_3x3_in)
        self.local_rep.add_module(name="conv_1x1", module=conv_1x1_in)

        assert transformer_dim % head_dim == 0
        num_heads = transformer_dim // head_dim

        global_rep = [
            TransformerEncoder(
                embed_dim=transformer_dim,
                ffn_latent_dim=ffn_dim,
                num_heads=num_heads,
                attn_dropout=attn_dropout,
                dropout=dropout,
                ffn_dropout=ffn_dropout,
                transformer_norm_layer=transformer_norm_layer,
            )
            for _ in range(n_transformer_blocks)
        ]
        global_rep.append(
            nn.BatchNorm1d(transformer_dim)
        )
        self.global_rep = nn.Sequential(*global_rep)

        self.conv_proj = conv_1x1_out

        self.fusion = conv_3x3_out

        self.patch_h = patch_h
        self.patch_w = patch_w
        self.patch_area = self.patch_w * self.patch_h

        self.cnn_in_dim = in_features
        self.cnn_out_dim = transformer_dim
        self.n_heads = num_heads
        self.ffn_dim = ffn_dim
        self.dropout = dropout
        self.attn_dropout = attn_dropout
        self.ffn_dropout = ffn_dropout
        self.dilation = dilation
        self.n_blocks = n_transformer_blocks
        self.conv_ksize = conv_ksize

    def unfolding(self, feature_map: Tensor) -> Tuple[Tensor, Dict]:
        patch_w, patch_h = self.patch_w, self.patch_h
        patch_area = int(patch_w * patch_h)
        batch_size, in_features, orig_h, orig_w = feature_map.shape

        new_h = int(math.ceil(orig_h / self.patch_h) * self.patch_h)
        new_w = int(math.ceil(orig_w / self.patch_w) * self.patch_w)

        interpolate = False
        if new_w != orig_w or new_h != orig_h:
            # Note: Padding can be done, but then it needs to be handled in attention function.
            feature_map = F.interpolate(
                feature_map, size=(new_h, new_w), mode="bilinear", align_corners=False
            )
            interpolate = True

        # number of patches along width and height
        num_patch_w = new_w // patch_w  # n_w
        num_patch_h = new_h // patch_h  # n_h
        num_patches = num_patch_h * num_patch_w  # N

        # [B, C, H, W] --> [B * C * n_h, p_h, n_w, p_w]
        reshaped_fm = feature_map.reshape(
            batch_size * in_features * num_patch_h, patch_h, num_patch_w, patch_w
        )
        # [B * C * n_h, p_h, n_w, p_w] --> [B * C * n_h, n_w, p_h, p_w]
        transposed_fm = reshaped_fm.transpose(1, 2)
        # [B * C * n_h, n_w, p_h, p_w] --> [B, C, N, P] where P = p_h * p_w and N = n_h * n_w
        reshaped_fm = transposed_fm.reshape(
            batch_size, in_features, num_patches, patch_area
        )
        # [B, C, N, P] --> [B, P, N, C]
        transposed_fm = reshaped_fm.transpose(1, 3)
        # [B, P, N, C] --> [BP, N, C]
        patches = transposed_fm.reshape(batch_size * patch_area, num_patches, -1)

        info_dict = {
            "orig_size": (orig_h, orig_w),
            "batch_size": batch_size,
            "interpolate": interpolate,
            "total_patches": num_patches,
            "num_patches_w": num_patch_w,
            "num_patches_h": num_patch_h,
        }

        return patches, info_dict

    def folding(self, patches: Tensor, info_dict: Dict) -> Tensor:
        n_dim = patches.dim()
        assert n_dim == 3, "Tensor should be of shape BPxNxC. Got: {}".format(
            patches.shape
        )
        # [BP, N, C] --> [B, P, N, C]
        patches = patches.contiguous().view(
            info_dict["batch_size"], self.patch_area, info_dict["total_patches"], -1
        )

        batch_size, pixels, num_patches, channels = patches.size()
        num_patch_h = info_dict["num_patches_h"]
        num_patch_w = info_dict["num_patches_w"]

        # [B, P, N, C] --> [B, C, N, P]
        patches = patches.transpose(1, 3)

        # [B, C, N, P] --> [B*C*n_h, n_w, p_h, p_w]
        feature_map = patches.reshape(
            batch_size * channels * num_patch_h, num_patch_w, self.patch_h, self.patch_w
        )
        # [B*C*n_h, n_w, p_h, p_w] --> [B*C*n_h, p_h, n_w, p_w]
        feature_map = feature_map.transpose(1, 2)
        # [B*C*n_h, p_h, n_w, p_w] --> [B, C, H, W]
        feature_map = feature_map.reshape(
            batch_size, channels, num_patch_h * self.patch_h, num_patch_w * self.patch_w
        )
        if info_dict["interpolate"]:
            feature_map = F.interpolate(
                feature_map,
                size=info_dict["orig_size"],
                mode="bilinear",
                align_corners=False,
            )
        return feature_map

    def forward_spatial(self, x: Tensor) -> Tensor:
        res = x

        fm = self.local_rep(x)

        # convert feature map to patches
        patches, info_dict = self.unfolding(fm)

        # learn global representations
        for transformer_layer in self.global_rep:
            patches = transformer_layer(patches)

        # [B x Patch x Patches x C] --> [B x C x Patches x Patch]
        fm = self.folding(patches=patches, info_dict=info_dict)

        fm = self.conv_proj(fm)

        if self.fusion is not None:
            fm = self.fusion(torch.cat((res, fm), dim=1))
        return fm

    def forward_temporal(
        self, x: Tensor, x_prev: Optional[Tensor] = None
    ) -> Union[Tensor, Tuple[Tensor, Tensor]]:

        res = x
        fm = self.local_rep(x)

        # convert feature map to patches
        patches, info_dict = self.unfolding(fm)

        # learn global representations
        for global_layer in self.global_rep:
            if isinstance(global_layer, TransformerEncoder):
                patches = global_layer(x=patches, x_prev=x_prev)
            else:
                patches = global_layer(patches)

        # [B x Patch x Patches x C] --> [B x C x Patches x Patch]
        fm = self.folding(patches=patches, info_dict=info_dict)

        fm = self.conv_proj(fm)

        if self.fusion is not None:
            fm = self.fusion(torch.cat((res, fm), dim=1))
        return fm, patches

    def forward(
        self, x: Union[Tensor, Tuple[Tensor]], *args, **kwargs
    ) -> Union[Tensor, Tuple[Tensor, Tensor]]:
        if isinstance(x, Tuple) and len(x) == 2:
            # for spatio-temporal MobileViT
            return self.forward_temporal(x=x[0], x_prev=x[1])
        elif isinstance(x, Tensor):
            # For image data
            return self.forward_spatial(x)
        else:
            raise NotImplementedError

class MobileViTBlockv2(nn.Module):
    """
    This class defines the `MobileViTv2 <https://arxiv.org/abs/2206.02680>`_ block

    Args:
        opts: command line arguments
        in_features (int): :math:`C_{in}` from an expected input of size :math:`(N, C_{in}, H, W)`
        attn_unit_dim (int): Input dimension to the attention unit
        ffn_multiplier (int): Expand the input dimensions by this factor in FFN. Default is 2.
        n_attn_blocks (Optional[int]): Number of attention units. Default: 2
        attn_dropout (Optional[float]): Dropout in multi-head attention. Default: 0.0
        dropout (Optional[float]): Dropout rate. Default: 0.0
        ffn_dropout (Optional[float]): Dropout between FFN layers in transformer. Default: 0.0
        patch_h (Optional[int]): Patch height for unfolding operation. Default: 8
        patch_w (Optional[int]): Patch width for unfolding operation. Default: 8
        conv_ksize (Optional[int]): Kernel size to learn local representations in MobileViT block. Default: 3
        dilation (Optional[int]): Dilation rate in convolutions. Default: 1
        attn_norm_layer (Optional[str]): Normalization layer in the attention block. Default: layer_norm_2d
    """

    def __init__(
        self,
        in_features: int,
        attn_unit_dim: int,
        ffn_multiplier: Optional[Union[Sequence[Union[int, float]], int, float]] = 2.0,
        n_attn_blocks: Optional[int] = 2,
        attn_dropout: Optional[float] = 0.0,
        dropout: Optional[float] = 0.0,
        ffn_dropout: Optional[float] = 0.0,
        patch_h: Optional[int] = 8,
        patch_w: Optional[int] = 8,
        conv_ksize: Optional[int] = 3,
        dilation: Optional[int] = 1,
    ) -> None:
        cnn_out_dim = attn_unit_dim

        conv_3x3_in = ConvBlock(
            in_features=in_features,
            out_features=in_features,
            kernel_size=conv_ksize,
            stride=1,
            use_norm=True,
            dilation=dilation,
            groups=in_features,
        )
        conv_1x1_in = ConvBlock(
            in_features=in_features,
            out_features=cnn_out_dim,
            kernel_size=1,
            stride=1,
            use_norm=False,
        )

        super(MobileViTBlockv2, self).__init__()
        self.local_rep = nn.Sequential(conv_3x3_in, conv_1x1_in)

        self.global_rep, attn_unit_dim = self._build_attn_layer(
            d_model=attn_unit_dim,
            ffn_mult=ffn_multiplier,
            n_layers=n_attn_blocks,
            attn_dropout=attn_dropout,
            dropout=dropout,
            ffn_dropout=ffn_dropout,
        )

        self.conv_proj = ConvBlock(
            in_features=cnn_out_dim,
            out_features=in_features,
            kernel_size=1,
            stride=1,
            use_norm=True,
        )

        self.patch_h = patch_h
        self.patch_w = patch_w
        self.patch_area = self.patch_w * self.patch_h

        self.cnn_in_dim = in_features
        self.cnn_out_dim = cnn_out_dim
        self.transformer_in_dim = attn_unit_dim
        self.dropout = dropout
        self.attn_dropout = attn_dropout
        self.ffn_dropout = ffn_dropout
        self.n_blocks = n_attn_blocks
        self.conv_ksize = conv_ksize

    def _compute_unfolding_weights(self) -> Tensor:
        # [P_h * P_w, P_h * P_w]
        weights = torch.eye(self.patch_h * self.patch_w, dtype=torch.float)
        # [P_h * P_w, P_h * P_w] --> [P_h * P_w, 1, P_h, P_w]
        weights = weights.reshape(
            (self.patch_h * self.patch_w, 1, self.patch_h, self.patch_w)
        )
        # [P_h * P_w, 1, P_h, P_w] --> [P_h * P_w * C, 1, P_h, P_w]
        weights = weights.repeat(self.cnn_out_dim, 1, 1, 1)
        return weights

    def _build_attn_layer(
        self,
        d_model: int,
        ffn_mult: Union[Sequence, int, float],
        n_layers: int,
        attn_dropout: float,
        dropout: float,
        ffn_dropout: float,
    ) -> Tuple[nn.Module, int]:

        if isinstance(ffn_mult, Sequence) and len(ffn_mult) == 2:
            ffn_dims = (
                np.linspace(ffn_mult[0], ffn_mult[1], n_layers, dtype=float) * d_model
            )
        elif isinstance(ffn_mult, Sequence) and len(ffn_mult) == 1:
            ffn_dims = [ffn_mult[0] * d_model] * n_layers
        elif isinstance(ffn_mult, (int, float)):
            ffn_dims = [ffn_mult * d_model] * n_layers
        else:
            raise NotImplementedError

        # ensure that dims are multiple of 16
        ffn_dims = [int((d // 16) * 16) for d in ffn_dims]

        global_rep = [
            LinearAttnFFN(
                embed_dim=d_model,
                ffn_latent_dim=ffn_dims[block_idx],
                attn_dropout=attn_dropout,
                dropout=dropout,
                ffn_dropout=ffn_dropout,
            )
            for block_idx in range(n_layers)
        ]
        global_rep.append(
            nn.BatchNorm2d(d_model)
        )

        return nn.Sequential(*global_rep), d_model

    def unfolding(self, feature_map: Tensor) -> Tuple[Tensor, Tuple[int, int]]:

        batch_size, in_features, img_h, img_w = feature_map.shape

        # [B, C, H, W] --> [B, C, P, N]
        patches = F.unfold(
            feature_map,
            kernel_size=(self.patch_h, self.patch_w),
            stride=(self.patch_h, self.patch_w),
        )
        patches = patches.reshape(
            batch_size, in_features, self.patch_h * self.patch_w, -1
        )

        return patches, (img_h, img_w)

    def folding(self, patches: Tensor, output_size: Tuple[int, int]) -> Tensor:
        batch_size, in_dim, patch_size, n_patches = patches.shape

        # [B, C, P, N]
        patches = patches.reshape(batch_size, in_dim * patch_size, n_patches)

        feature_map = F.fold(
            patches,
            output_size=output_size,
            kernel_size=(self.patch_h, self.patch_w),
            stride=(self.patch_h, self.patch_w),
        )

        return feature_map

    def resize_input_if_needed(self, x):
        batch_size, in_features, orig_h, orig_w = x.shape
        if orig_h % self.patch_h != 0 or orig_w % self.patch_w != 0:
            new_h = int(math.ceil(orig_h / self.patch_h) * self.patch_h)
            new_w = int(math.ceil(orig_w / self.patch_w) * self.patch_w)
            x = F.interpolate(
                x, size=(new_h, new_w), mode="bilinear", align_corners=True
            )
        return x

    def forward_spatial(self, x: Tensor, *args, **kwargs) -> Tensor:
        x = self.resize_input_if_needed(x)

        fm = self.local_rep(x)

        # convert feature map to patches
        patches, output_size = self.unfolding(fm)

        # learn global representations on all patches
        patches = self.global_rep(patches)

        # [B x Patch x Patches x C] --> [B x C x Patches x Patch]
        fm = self.folding(patches=patches, output_size=output_size)
        fm = self.conv_proj(fm)

        return fm

    def forward_temporal(
        self, x: Tensor, x_prev: Tensor, *args, **kwargs
    ) -> Union[Tensor, Tuple[Tensor, Tensor]]:
        x = self.resize_input_if_needed(x)

        fm = self.local_rep(x)

        patches, output_size = self.unfolding(fm)

        # learn global representations
        for global_layer in self.global_rep:
            if isinstance(global_layer, LinearAttnFFN):
                patches = global_layer(x=patches, x_prev=x_prev)
            else:
                patches = global_layer(patches)

        # [B x Patch x Patches x C] --> [B x C x Patches x Patch]
        fm = self.folding(patches=patches, output_size=output_size)
        fm = self.conv_proj(fm)

        return fm, patches

    def forward(
        self, x: Union[Tensor, Tuple[Tensor]], *args, **kwargs
    ) -> Union[Tensor, Tuple[Tensor, Tensor]]:
        if isinstance(x, Tuple) and len(x) == 2:
            # for spatio-temporal data (e.g., videos)
            return self.forward_temporal(x=x[0], x_prev=x[1])
        elif isinstance(x, Tensor):
            # for image data
            return self.forward_spatial(x)
        else:
            raise NotImplementedError


# coding: utf-8
from django.utils.translation       import ugettext_lazy as _
from django.db                      import models
__all__ = ('Log', 'LOG_EXCEPTION','LOG_WARNING','LOG_NOTICE','LOG_STRING')

import datetime

LOG_EXCEPTION = 1
LOG_WARNING = 2
LOG_NOTICE = 3
LOG_STRING = 4

LOG_TYPE = (
    (LOG_EXCEPTION, _('LOG_EXCEPTION')),
    (LOG_WARNING, _('LOG_WARNING')),
    (LOG_NOTICE, _('LOG_NOTICE')),
    (LOG_STRING, _('LOG_STRING')),
)

#Log
class Log(models.Model):
    #date
    date = models.DateTimeField(verbose_name=_(u'date'))
    #type
    type = models.PositiveIntegerField(choices = LOG_TYPE, default=LOG_EXCEPTION, verbose_name=_(u'type'))
    #subject
    subject = models.CharField(max_length=255, verbose_name=_(u'subject'), blank=True)
    #content
    content = models.TextField(verbose_name=_(u'content'), blank=True)

    __unicode__ = lambda self: self.subject

    class Meta():
        verbose_name=_(u'Log')
        verbose_name_plural=_(u'Log')
        ordering = ('-date',)

    def save(self):
        if not self.id:
            self.date = datetime.datetime.today()
        super(Log, self).save()


import os
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse, JSONResponse
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.middleware.cors import CORSMiddleware
from typing import Any
from pydantic import BaseModel
import json

# additional packages
from openai.embeddings_utils import get_embedding
import openai
import pinecone

pinecone.init(api_key=os.environ["PINECONE_API_KEY"],
              environment=os.environ["PINECONE_ENVIRONMENT"]
              )
index = pinecone.Index("huberman-podcast-1")

openai.api_key = os.environ["OPENAI_API_KEY"]

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://chat.openai.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class Query(BaseModel):
    text: str

@app.post("/query", summary="Search for any health related information within the podcast episodes of Andrew Huberman's podcast.")
async def query(query: Query) -> Any:
    text = query.text
    embedding = get_embedding(text, engine='text-embedding-ada-002')

    res = index.query([embedding], top_k=10, include_metadata=True)

    i = 0
    chosen_docs = []
    tokens = 0
    while tokens < 800 and len(res['matches']) > i:
        match = res['matches'][i]
        if int(match['metadata']['tokens']) + tokens > 800:
            break
        chosen_docs.append({
            'content': match['metadata']['content'],
            'episode': match['metadata']['episode'],
        })
        tokens += int(match['metadata']['tokens'])

    return chosen_docs

@app.get("/image")
async def image():
    image_path = os.path.join(os.path.dirname(__file__), "./huberman_lab_podcast_image.jpeg")
    if not os.path.exists(image_path):
        raise HTTPException(status_code=404, detail="Image not found")
    return FileResponse(image_path)

@app.get("/.well-known/ai-plugin.json", include_in_schema=False)
async def ai_plugin_json():
    json_path = os.path.join(os.path.dirname(__file__), "ai-plugin.json")
    if not os.path.exists(json_path):
        raise HTTPException(status_code=404, detail="ai-plugin.json not found")
    with open(json_path, "r") as json_file:
        data = json.load(json_file)
    return JSONResponse(content=data)

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        title="Custom title",
        version="2.5.0",
        description="This is a very custom OpenAPI schema",
        routes=app.routes,
    )
    app.openapi_schema = openapi_schema
    return app.openapi_schema

app.openapi = custom_openapi

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8080)


"""
Game Template

Attributes:
    g (TYPE): Description
"""

import pygame as pg # rename for fast typing
import random
from settings import *

class Game:

	"""Summary

	Attributes:
	    all_sprites (TYPE): Description
	    clock (TYPE): Description
	    playing (bool): Description
	    running (bool): Description
	    screen (TYPE): Description
	"""

	def __init__(self):
		"""initialize game window, etc
		"""
		pg.init()
		pg.mixer.init()
		self.screen = pg.display.set_mode((WIDTH, HEIGHT))
		pg.display.set_caption("My Game")
		self.clock = pg.time.Clock()
		self.running = True

	def new(self):
		"""Start a New Game
		"""
		self.all_sprites = pg.sprite.Group()

	def run(self):
		"""Game Loop
		"""
		self.playing = True
		while  self.playing:
			self.clock.tick(FPS) # keep looping at the right speed
			self.events()
			self.update()
			self.draw()

	def update(self):
		"""Game Loop - Update
		"""
		self.all_sprites.update()

	def events(self):
		"""Game Loop - events
		"""
		for event in pg.event.get():
			#check for closing window
			if (event.type == pg.QUIT) or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE):
				if self.playing:
					self.playing = False
				self.running = False

	def draw(self):
		"""Game Loop - draw
		"""
		self.screen.fill(BLACK)
		self.all_sprites.draw(self.screen)
		pg.display.flip() # after drawing everything, flip the display

	def show_start_screen(self):
		"""game splash/start screen
		"""
		print("game start")
		pass

	def show_go_screen(self):
		"""game over/continue screen
		"""
		print("game end")
		pass

g = Game() # instance of game object
g.show_start_screen()
while g.running:
	g.new()
	g.run()
	g.show_go_screen()

pg.quit()


import time

from selenium.webdriver.common.by import By

from Tools.function import BaseDriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class Sortable(BaseDriver):

    interaction_icon = "//*[name()='path' and contains(@d,'M880 112H1')]"
    sortable_module = "//span[contains(text(),'Sortable')]"
    header = "//div[contains(text(),'Sortable')]"

    grid = "//a[@id='demo-tab-grid']"
    one = "//div[@class='create-grid']//div[@class='list-group-item list-group-item-action'][normalize-space()='One']"
    nine = "//div[contains(text(),'Nine')]"
    eight = "//div[normalize-space()='Eight']"
    four = "//div[@class='create-grid']//div[@class='list-group-item list-group-item-action'][normalize-space()='Four']"

    list = "//a[@id='demo-tab-list']"
    two = "//body/div[@id='app']/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[1]/div[2]"
    six = "//body/div[@id='app']/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[1]/div[6]"
    three = "//body/div[@id='app']/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[1]/div[2]"
    five = "//body/div[@id='app']/div[1]/div[1]/div[2]/div[2]/div[2]/div[1]/div[1]/div[1]/div[4]"

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

    def test_open_interaction_icon(self):
        wait = WebDriverWait(self.driver, 10)
        wait.until(EC.presence_of_element_located((By.XPATH, self.interaction_icon)))
        wait.until(EC.element_to_be_clickable((By.XPATH, self.interaction_icon)))
        self.find(self.interaction_icon).click()

    def test_open_sortable_module(self):
        self.find(self.sortable_module).click()

    def test_header(self):
        headers = self.find(self.header).text
        assert "Sortable" in headers
        self.driver.save_screenshot(self.ss_url_interaction + "Sortable Header.png")

    def test_grid(self):
        self.find(self.grid).click()

    def test_one_move_to_nine(self):
        move_one = self.find(self.one)
        move_nine = self.find(self.nine)

        action = ActionChains(self.driver)
        action.click_and_hold(move_one).move_to_element(move_nine).release().perform()
        time.sleep(2)
        self.driver.save_screenshot(self.ss_url_interaction + "Grid Type Move One to Nine Position.png")

    def test_four_move_to_eight(self):
        move_four = self.find(self.four)
        move_eight = self.find(self.eight)

        action = ActionChains(self.driver)
        action.click_and_hold(move_four).move_to_element(move_eight).release().perform()
        time.sleep(2)
        self.driver.save_screenshot(self.ss_url_interaction + "Grid Type Move four to eight Position.png")

    def test_list(self):
        self.find(self.list).click()

    def test_two_move_to_six(self):
        move_two = self.find(self.two)
        move_six = self.find(self.six)

        action = ActionChains(self.driver)
        action.click_and_hold(move_two).move_to_element(move_six).release().perform()
        time.sleep(2)
        self.driver.save_screenshot(self.ss_url_interaction + "List Type Move Two to six Position.png")

    def test_three_move_to_five(self):
        move_three = self.find(self.three)
        move_five = self.find(self.five)

        action = ActionChains(self.driver)
        action.click_and_hold(move_three).move_to_element(move_five).release().perform()
        time.sleep(2)
        self.driver.save_screenshot(self.ss_url_interaction + "List Type Move Three to Five Position.png")


from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.uix.screenmanager import Screen,ScreenManager
from kivymd.uix.dialog import MDDialog
from kivymd.uix.button import MDFlatButton
from kivy.storage.jsonstore import JsonStore
from kivymd.uix.picker import MDDatePicker

helpstr = '''
ScreenManager:
    WelcomeScreen:
    UsernameScreen:
    DOB:
    MainScreen:

<WelcomeScreen>:
    name : 'welcomescreen'
    MDLabel:
        text:'Welcome Screen'
        font_style: 'H2'
        halign: 'center'
        pos_hint: {'center_y':0.65}
    MDFloatingActionButton:
        icon:'android'
        md_bg_color:app.theme_cls.primary_color
        user_font_size : '60sp'
        pos_hint: {'center_x':0.5,'center_y':0.32}
        on_press:
            root.manager.current = 'usernamescreen'
            root.manager.transition.direction = 'left'

    MDProgressBar:
        value:30
        pos_hint:{'center_y' : 0.02}
<UsernameScreen>
    name:'usernamescreen'
    MDFloatingActionButton:
        icon: 'arrow-left'
        md_bg_color:app.theme_cls.primary_color
        pos_hint: {'center_x':0.1,'center_y':0.1}
        user_font_size : '45sp'
        on_press:
            root.manager.current = 'welcomescreen'
            root.manager.transition.direction = 'right'
    MDFloatingActionButton:
        id:disabled_button
        disabled: True
        icon: 'arrow-right'
        md_bg_color:app.theme_cls.primary_color
        pos_hint: {'center_x':0.9,'center_y':0.1}
        user_font_size : '45sp'
        on_press:
            root.manager.current = 'dob'
            root.manager.transition.direction = 'left'
    MDProgressBar:
        value:60
        pos_hint: {'center_y':0.02}

    MDLabel:
        text:'Username'
        font_style: 'H2'
        halign: 'center'
        pos_hint : {'center_y':0.85}

    MDTextField:
        id:username_text_fied
        pos_hint: {'center_x':0.5,'center_y':0.6}
        size_hint: (0.7,0.1)
        hint_text : 'username'
        helper_text: 'Required'
        helper_text_mode: 'on_error'
        icon_right: 'account'
        icon_right_color: app.theme_cls.primary_color
        required : True

    MDFloatingActionButton:
        icon:'account-plus'
        md_bg_color:app.theme_cls.primary_color
        pos_hint: {'center_x':0.5,'center_y':0.35}
        user_font_size: '50sp'
        on_press: app.check_username()

<DOB>:
    name:'dob'
    MDLabel:
        text:'Date of Birth'
        font_style: 'H2'
        halign: 'center'
        pos_hint: {'center_y':0.75}

    MDRaisedButton:
        id:date_picker
        text:'Date Picker'
        user_font_size : '70sp'
        pos_hint : {'center_x':0.5,'center_y':0.6}
        on_press:
            app.show_date_picker()

    MDFloatingActionButton:
        icon:'arrow-left'
        md_bg_color:app.theme_cls.primary_color
        pos_hint: {'center_x':0.1,'center_y':0.1}
        user_font_size: '45sp'
        on_press: root.manager.current = 'usernamescreen'
    MDFloatingActionButton:
        id: second_disabled
        disabled: True
        icon:'arrow-right'
        md_bg_color:app.theme_cls.primary_color
        pos_hint: {'center_x':0.9,'center_y':0.1}
        user_font_size: '45sp'
        on_press: root.manager.current = 'mainscreen'

<MainScreen>:
    name : 'mainscreen'
    MDLabel:
        id:profile_name
        text:'main screen'
        font_style : 'H2'
        halign : 'center'
        pos_hint : {'center_y':0.7}

'''
class WelcomeScreen(Screen):
    pass
class UsernameScreen(Screen):
    pass
class DOB(Screen):
    pass
class MainScreen(Screen):
    pass
sm = ScreenManager()
sm.add_widget(WelcomeScreen(name = 'welcomescreen'))
sm.add_widget(UsernameScreen(name = 'usernamescreen'))
sm.add_widget(DOB(name = 'dob'))
sm.add_widget(MainScreen(name = 'main_screen'))
class NewApp(MDApp):
    def build(self):
        self.strng = Builder.load_string(helpstr)
        return self.strng

    def check_username(self):
        self.username_text = self.strng.get_screen('usernamescreen').ids.username_text_fied.text
        username_check_false = True
        try:
            int(self.username_text)
        except:
            username_check_false = False
        if username_check_false or self.username_text.split() == []:
                cancel_btn_username_dialogue = MDFlatButton(text='Retry',on_release = self.close_username_dialogue)
                self.dialog = MDDialog(title = 'Invalid Username',text = "Please input a valid username",size_hint = (0.7,0.2),buttons = [cancel_btn_username_dialogue])
                self.dialog.open()

        else:
            self.strng.get_screen('usernamescreen').ids.disabled_button.disabled = False

    def close_username_dialogue(self,obj):
        self.dialog.dismiss()

    def show_date_picker(self):
        date_dialog = MDDatePicker(callback = self.get_date,year = 1999,month = 1,day =1,)
        date_dialog.open()
    def get_date(self,date):
        self.dob = date
        self.strng.get_screen('dob').ids.date_picker.text = str(self.dob)
        self.strng.get_screen('dob').ids.second_disabled.disabled = False

        #Storing of DATA
        self.store.put('UserInfo',name = self.username_text,dob = str(self.dob))
        self.username_changer()

    def username_changer(self):
        self.strng.get_screen('mainscreen').ids.profile_name.text = f"Welcome {self.store.get('UserInfo')['name']}"

    def on_start(self):
        self.store = JsonStore("userProfile.json")
        try:
            if self.store.get('UserInfo')['name'] != "":
                self.username_changer()
                self.strng.get_screen('mainscreen').manager.current = 'mainscreen'

        except KeyError:
            self.strng.get_screen('welcomescreen').manager.current = 'welcomescreen'

NewApp().run()


from django import forms
from .models import Note
from .models import Task
from .models import Content
from .models import Music
from django.contrib.auth.models import User

class NoteForm(forms.ModelForm):

    class Meta:
        model = Note
        fields = ('title', 'text',)

class TaskForm(forms.ModelForm):

    class Meta:
        model = Task
        fields = ('task_title', 'description', 'end_date')

class ContentForm(forms.ModelForm):
    content_file = forms.FileField(required=True)
    class Meta:
        model = Content
        fields = ('file_name', 'content_file')

class MusicForm(forms.ModelForm):

    class Meta:
        model = Music
        fields = ('song_title', 'author')


# Blackjack Capstone Project

import random

cards = [
    ("A", 11),
    ("2", 2),
    ("3", 3),
    ("4", 4),
    ("5", 5),
    ("6", 6),
    ("7", 7),
    ("8", 8),
    ("9", 9),
    ("10", 10),
    ("J", 10),
    ("Q", 10),
    ("K", 10),
]

def choose_cards():
    return random.choice(cards)

def get_cards(hand):
    return [card[0] for card in hand]

def evaluate_winner(player_hand, computer_hand):
    player_score = 0
    computer_score = 0
    for card in player_hand:
        player_score += card[1]
    for card in computer_hand:
        computer_score += card[1]
    print(player_score, computer_score)
    if player_score > 21 or player_score < computer_score:
        return "You lose!"
    elif player_score == computer_score:
        return "It's a tie!"
    return "You win!"

# Draw player and computer hand
player_hand = []
computer_hand = []
for i in range(2):
    player_hand.append(choose_cards())
    computer_hand.append(choose_cards())

# Display Cards
print("Your cards:", get_cards(player_hand))
print("Computer's first card:", get_cards(computer_hand)[0])

# Ask if the player would like to get another card
choice = input("Type 'y' to get another card, type 'n' to pass: ")
if choice == "y":
    player_hand.append(choose_cards())

# Display final hand
print("Your final hand:", get_cards(player_hand))
print("Computer's final hand:", get_cards(computer_hand))

print(evaluate_winner(player_hand, computer_hand))


from turtle import *

def draw_triangle(turt, length):
    for i in range(3):
        turt.fd(length)
        turt.lt(120)

def pentagon(turt, length):
    for i in range(5):
        turt.fd(length)
        t.rt(72)

def draw_triangle_star(turt, count, angle):
    if count <= 0:
        return None
    else:
        pentagon(turt, 100)
        turt.rt(angle)
        draw_triangle_star(turt, count - 1, angle)

t = Turtle()
t.speed(0)
triangles = 20
draw_triangle_star(t, triangles, 360 / triangles)

done()


import requests as req
import json
import pandas as pd

headers = {'User-Agent': 'Mozilla/4.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
my_r = req.get('https://dominospizza.ru/find_dominos?st=del', headers=headers)

s = my_r.text
s = s[s.find('"geo":') + len('"geo":'):]
brackets = 1
r = 0
for i in range(1, len(s)):
    if brackets == 0:
        r = i
        break
    if s[i] == '{':
        brackets += 1
    elif s[i] == '}':
        brackets -= 1
j = json.loads(s[:r])
data = []
for i in j['cities']:
    data.append([i['longitude'], i['lattitude']])
data = pd.DataFrame(data, columns=['lon', 'lat'])
data.to_csv('dominos.csv')


import cv2
import numpy as np

drawing = False
mode = True
start = (-1, -1)

def mouse_event(event, x, y, flags, param):
    global start, drawing, mode
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        start = (x, y)
    elif event == cv2.EVENT_MOUSEMOVE:
        if drawing:
            if mode:
                cv2.rectangle(img, start, (x, y), (255, 0, 0), 1)
            else:
                cv2.circle(img, (x, y), 5, (0, 0, 255), -1)
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        if mode:
            cv2.rectangle(img, start, (x, y), (255, 0, 0), 1)
        else:
            cv2.circle(img, (x, y), 5, (0, 0, 255), -1)

img = np.zeros((512, 512, 3), np.uint8)
cv2.namedWindow("img")
cv2.setMouseCallback('img', mouse_event)

while True:
    cv2.imshow("img", img)
    if cv2.waitKey(1) == ord('m'):
        mode = not mode
    elif cv2.waitKey(1) == 27:
        break


#!/usr/bin/env python
# -------------------------------------------------------------------
# File Name : create_dataset_events.py
# Creation Date : 05-12-2016
# Last Modified : Fri Jan  6 15:04:54 2017
# Author: Thibaut Perol <tperol@g.harvard.edu>
# -------------------------------------------------------------------
"""Creates tfrecords dataset of events trace and their cluster_ids.
This is done by loading a dir of .mseed and one catalog with the
time stamps of the events and their cluster_id
e.g.,
./bin/preprocess/create_dataset_events.py \
--stream_dir data/streams \
--catalog data/50_clusters/catalog_with_cluster_ids.csv\
--output_dir data/50_clusters/tfrecords
"""

import os
import numpy as np
from quakenet.data_pipeline import DataWriter
import tensorflow as tf
from obspy.core import read
from quakenet.data_io import load_catalog
from obspy.core.utcdatetime import UTCDateTime
from openquake.hazardlib.geo.geodetic import distance
import fnmatch
import json
import argparse
import config as config
import utils
import random

#def preprocess_stream(stream):
#    stream = stream.detrend('constant')
#    return stream.normalize()

def main(_):
    print("[tfrecords negatives] Converting .mseed files into tfrecords...")
    print("[tfrecords negatives] Input directory: "+os.path.join(dataset_dir, cfg.mseed_noise_dir))
    print("[tfrecords negatives] Output directory: "+os.path.join(output_dir, cfg.output_tfrecords_dir_negatives))
    print("[tfrecords negatives] File pattern: "+args.pattern)

    stream_files = [file for file in os.listdir(os.path.join(dataset_dir, cfg.mseed_noise_dir)) if
                    fnmatch.fnmatch(file, args.pattern)]

    print("[tfrecords negatives] Matching files: "+str(len(stream_files)))

    # Divide training and validation datasets
    random.seed(cfg.random_seed)
    random.shuffle(stream_files)

    if cfg.balance:
        stream_files_positives = [file for file in os.listdir(os.path.join(dataset_dir, cfg.mseed_event_dir)) if
                    fnmatch.fnmatch(file, args.pattern)]
        total_positives = len(stream_files_positives)
        stream_files = stream_files[0:total_positives]
        print ("[tfrecords negatives] \033[93m WARNING!!\033[0m Balancing dataset, only "+str(len(stream_files))+" negatives used.")

    total_negatives = len(stream_files)
    stream_files_train = stream_files[:int(0.8*total_negatives)-1]
    stream_files_validation = stream_files[int(0.8*total_negatives):]

    # Create dir to store tfrecords
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    write(stream_files_train, "train")
    write(stream_files_validation, "test")

def write(stream_files, subfolder):

    if not os.path.exists(os.path.join(output_dir, subfolder)):
        os.makedirs(os.path.join(output_dir, subfolder))

    if not os.path.exists(os.path.join(os.path.join(output_dir, subfolder), cfg.output_tfrecords_dir_negatives)):
        os.makedirs(os.path.join(os.path.join(output_dir, subfolder), cfg.output_tfrecords_dir_negatives))

    # Write event waveforms and cluster_id in .tfrecords
    output_name = output_name = args.file_name
    output_path = os.path.join(os.path.join(os.path.join(output_dir, subfolder), cfg.output_tfrecords_dir_negatives), output_name)
    writer = DataWriter(output_path)
    for stream_file in stream_files:
        stream_path = os.path.join(os.path.join(dataset_dir, cfg.mseed_noise_dir), stream_file)
        #print "[tfrecords negatives] Loading Stream {}".format(stream_file)
        st_event = read(stream_path)
        #print '[tfrecords negatives] Preprocessing stream'

        #filtrem
        if cfg.filterfreq:
            st_event = utils.filter_stream(st_event)

        #Select only the specified channels
        st_event_select = utils.select_components(st_event, cfg)

        #cluster_id = filtered_catalog.cluster_id.values[event_n]
        cluster_id = -1 #We work with only one location for the moment (cluster id = 0)
        n_traces = len(st_event_select)
        if utils.check_stream(st_event_select, cfg):
            #print("[tfrecords negatives] Writing sample with dimensions "+str(cfg.WINDOW_SIZE)+"x"+str(st_event[0].stats.sampling_rate)+"x"+str(n_traces))
            # Write tfrecords
            writer.write(st_event_select, cluster_id)

    # Cleanup writer
    print("[tfrecords negatives] Number of windows written={}".format(writer._written))
    writer.close()

if __name__ == "__main__":
    print ("\033[92m******************** STEP 3/5. PREPROCESSING STEP 3/3. NEGATIVE TRAINING WINDOWS -> TFRECORDS *******************\033[0m ")
    parser = argparse.ArgumentParser()
    parser.add_argument("--config_file_path",type=str,default=None,
                        help="path to .ini file with all the parameters")
    parser.add_argument("--prep_data_dir",type=str, required=True)
    parser.add_argument("--pattern",type=str, default="*.mseed")
    parser.add_argument("--tfrecords_dir",type=str, required=True)
    parser.add_argument("--component_N",type=int, default=argparse.SUPPRESS) #Optional, we will use the value from the config file
    parser.add_argument("--component_E",type=int, default=argparse.SUPPRESS) #Optional, we will use the value from the config file
    parser.add_argument("--file_name",type=str, default="negatives.tfrecords")
    parser.add_argument("--window_size", type=int, required=True)
    parser.add_argument("--debug",type=int, default=argparse.SUPPRESS) #Optional, we will use the value from the config file
    parser.add_argument("--balance",type=int, default=argparse.SUPPRESS) #Optional, we will use the value from the config file

    #parser.add_argument("--redirect_stdout_stderr",type=bool, default=False)

    args = parser.parse_args()
    cfg = config.Config(args)

    dataset_dir = args.prep_data_dir
    output_dir = args.tfrecords_dir

    tf.app.run()


'''
Created on 08.12.2012

@author: Artur
'''
import math

class Interpolator(object):

    def __init__(self,scalingFactorX = 1,scalingFactorY = 1, maximalNumberOfInterPoints = 10, resolution = 1):
        self.maxInterPt = maximalNumberOfInterPoints;
        self.resolution = resolution;
        self.lastPoint = None
        self.scalingX = scalingFactorX;
        self.scalingY = scalingFactorY;

    def interpolate(self,point):
        point = [point[0]*self.scalingX,point[1]*self.scalingY]
        if(self.lastPoint != None):
            distance = math.sqrt(0. + (self.lastPoint[0] - point[0])**2 + (self.lastPoint[1] - point[1])**2)
            if (distance/self.resolution >= self.maxInterPt - 1):
                resolution = distance/(self.maxInterPt -1)
            else:
                resolution = self.resolution
            directionVec = [(point[0]-self.lastPoint[0])* resolution/distance,(point[1]-self.lastPoint[1])*resolution/distance]
            interPoints = [None]*int(distance/resolution)
            actPoint = self.lastPoint;
            for i in range(int(distance/resolution)):
                actPoint = [int(self.lastPoint[0] + directionVec[0]*i),int(self.lastPoint[1] + directionVec[1]*i)]
                interPoints[i] = actPoint;
            self.lastPoint = point;
            interPoints.append(point)
            return interPoints
        else:
            self.lastPoint = point
            return [point]


import os
import zipfile
import rarfile
import shutil
def extract(dir):  #将rar,zip文件解压到dir

  for root,dirs,files in os.walk(dir):
    for file in files:  #所有文件都尝试解压
      cur_cd=os.getcwd()
      os.chdir(root)
      cmd="7z e \"%s\"" %(file)
      os.system(cmd)
      os.chdir(cur_cd)
  for root,dirs,files in os.walk(dir): #删除空文件夹
    for d in dirs:
      os.system("rmdir \"%s\\%s\"" %(root,d))
"""
(1)读取rar将文件解压到 rar文件夹。
(2)枚举文件夹，将子文件放入根文件。
"""
dir=input("要解压的目录")
stuList=extract(dir)
#print(stuList)

VB作业/解压目录.py


from tkinter import *
import time
from random import randint

root = Tk()
root.title("MATRIX")
root.geometry("1000x500")
root.configure(bg="black")
label = Label(root,text="The Matrix",bg="#000000",fg="#09ff00",font=("Algerian",40))
label.pack()

canvas = Canvas(root,height=500,width=1000, highlightthickness=0,highlightbackground="black")
canvas.configure(bg="black")
canvas.pack()

# Start with first three characters of Japanese Katakana syllabary
# Works like 0x30a0 - 0x30a9,0x30b0 - 0x30b9 upto g
#c3 = chr(0x30a0)
#c = chr(0x30a0 + randint(0,97))
#print(c)
#x,y =100,100
#label = canvas.create_text(100,100,text=c, fill="#09ff00",font=("arial black",20))
def choose(n):
	c = chr(0x30a0 + randint(0,97))
	canvas.itemconfig(n,text=c)

def draw(i):
	c = chr(0x30a0 + randint(0,97))
	x,y =randint(0,1000),randint(0,10)
	canvas.create_text(x,y,text=c, fill="#09ff00",font=("arial black",20))

	for j in range(100):
		choose(j)
		canvas.move(j,0,15)
		time.sleep(0.0001)
		root.update()
for i in range(100):
	draw(i)

root.mainloop()


# coding:utf-8
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
from keras.models import Sequential, load_model, Input, Model
from keras.layers import Dense, LSTM, Activation, BatchNormalization, Dropout, LocallyConnected1D, \
    GaussianNoise
from keras.layers.core import *
from keras.layers.recurrent import LSTM
from keras.models import *
from datetime import datetime, timedelta
from keras.engine import Layer
import time
import keras.backend as K
from keras import initializers
from keras.optimizers import SGD, RMSprop, Adam
from keras.utils import get_custom_objects
from config import tickets,output_path, use_today, today, model_path,output_path_flask
from evaluate import eval
from pandas.plotting import register_matplotlib_converters
from keras.layers import Dense, Lambda, dot, Activation, concatenate
from keras.layers import Multiply
import os
import re

register_matplotlib_converters()

# 导入数据
df = pd.read_csv((output_path + 'presult' + '.csv'))  # 读入股票数据
df = df.fillna(0)
df = df[df['date'] >= '2014-01-01']

data = df.loc[:, list(tickets.keys())]
x_date = df.loc[:, 'date'].values

normalize_data = data.values
# normalize_data = (data - np.mean(data)) / np.std(data)  # 标准化
# normalize_data = normalize_data[:, np.newaxis]  # 增加维度

# 生成训练集
# 设置常量
time_step = 30  # 时间步
rnn_unit = 128  # hidden layer units
input_size = 28  # 输入层维度
output_size = 28  # 输出层维度
time_window = 3  # 计算loss时使用未来均值的时间窗口
predict_time_interval = 30  # 预测的时间长度
empty_time = 0  # 预测时间绘图前补充的长度
# 评价收益方式
# profit_type = 'weight'  表示使用增值比例
profit_type = 'value'  # 表示使用增值数值
# profit_type = 'weight'
# train_type 表示训练的模式
train_type = 'evaluate'  # 使用训练值训练
# train_type='all' 使用全部值训练
# train_type = 'all'

data_x, data_y = [], []  # 训练集
for i in range(len(normalize_data) - time_step - time_window):
    x = normalize_data[i:i + time_step]
    # 使用均值差作为预测标准
    # 加入0.003的交易税率
    if profit_type == 'weight':
        y = ((0.01 + np.mean(normalize_data[i + time_step:i + time_step + time_window], axis=0)) / (0.01 + np.mean(
            normalize_data[i + time_step - time_window:i + time_step], axis=0))) - 1.0015
    else:
        y = np.sum(normalize_data[i + time_step: i + time_step + time_window], axis=0) - np.sum(
            normalize_data[i + time_step - time_window:i + time_step], axis=0)

    data_x.append(x)  # 将数组转化成列表
    data_y.append(y)

data_x = np.array(data_x)
data_y = np.array(data_y)
data_x = data_x.reshape((-1, time_step, input_size))
data_y = data_y.reshape((-1, output_size))
if train_type == 'evaluate':
    train_x = data_x[:-predict_time_interval]
    train_y = data_y[:-predict_time_interval]
else:
    train_x = data_x[:]
    train_y = data_y[:]

# 测试集
data_test_x, data_test_y = [], []
for i in range(len(normalize_data) - time_step):
    x = normalize_data[i:i + time_step]
    # 预测标准使用y真实值
    y = normalize_data[i + time_step]
    data_test_x.append(x)  # 将数组转化成列表
    data_test_y.append(y)

data_test_x = np.array(data_test_x)
data_test_y = np.array(data_test_y)

test_x = data_test_x[-predict_time_interval:]
test_y = data_test_y[-predict_time_interval:]

print(train_x.shape, train_y.shape, test_x.shape, test_y.shape)

# 使用happynoom描述的网络模型
# 评价函数，使用y值*仓位表示
def risk_estimation(y_true, y_pred):
    return -K.sum(y_true * y_pred)

class ReLU(Layer):
    """Rectified Linear Unit."""

    def __init__(self, alpha=0.0, max_value=None, **kwargs):
        super(ReLU, self).__init__(**kwargs)
        self.supports_masking = True
        self.alpha = alpha
        self.max_value = max_value

    def call(self, inputs):
        return K.relu(inputs, alpha=self.alpha, max_value=self.max_value)

    def get_config(self):
        config = {'alpha': self.alpha, 'max_value': self.max_value}
        base_config = super(ReLU, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

class SeqModel:
    # 使用happynoom描述的网络模型
    def __init__(self, input_shape=None, learning_rate=0.005, n_layers=2, n_hidden=8, rate_dropout=0.2,
                 loss=risk_estimation):
        self.input_shape = input_shape
        self.learning_rate = learning_rate
        self.n_layers = n_layers
        self.n_hidden = n_hidden
        self.rate_dropout = rate_dropout
        self.loss = loss
        self.model = None

    def attention_3d_block(self, inputs):
        input_dim = int(inputs.shape[2])
        a = Permute((2, 1))(inputs)
        a = Reshape((input_dim, time_step))(a)
        a = Dense(time_step, activation='softmax')(a)
        # single_attention_vector
        # a = Lambda(lambda x: K.mean(x, axis=1), name='dim_reduction')(a)
        # a = RepeatVector(input_dim)(a)
        a_probs = Permute((2, 1), name='attention_vec')(a)
        output_attention_mul = Multiply()([inputs, a_probs])
        return output_attention_mul

    def lstmModel(self):
        self.model = Sequential()
        self.model.add(GaussianNoise(stddev=0.01, input_shape=self.input_shape))
        for i in range(0, self.n_layers - 1):
            self.model.add(LSTM(self.n_hidden * 4, return_sequences=True, activation='tanh',
                                recurrent_activation='tanh', kernel_initializer='glorot_uniform',
                                recurrent_initializer='orthogonal', bias_initializer='zeros',
                                dropout=self.rate_dropout, recurrent_dropout=self.rate_dropout))

        self.model.add(LSTM(self.n_hidden, return_sequences=False, activation='softsign',
                            recurrent_activation='hard_sigmoid', kernel_initializer='glorot_uniform',
                            recurrent_initializer='orthogonal', bias_initializer='zeros',
                            dropout=self.rate_dropout, recurrent_dropout=self.rate_dropout))

        self.model.add(Dense(output_size, kernel_initializer=initializers.glorot_uniform()))
        self.model.add(BatchNormalization(axis=-1, beta_initializer='ones'))
        self.model.add(ReLU(alpha=0.0, max_value=1.0))
        opt = RMSprop(lr=self.learning_rate)
        self.model.compile(loss=self.loss, optimizer=opt, metrics=['accuracy'])
        self.model.summary()
        return self.model

    def lstmAttentionModel(self):
        K.clear_session()  # 清除之前的模型，省得压满内存
        inputs = Input(shape=(time_step, input_size,))
        attention_mul = self.attention_3d_block(inputs)
        for i in range(0, self.n_layers - 1):
            attention_mul = LSTM(self.n_hidden * 4, return_sequences=True, activation='tanh',
                                 recurrent_activation='hard_sigmoid', kernel_initializer='glorot_uniform',
                                 recurrent_initializer='orthogonal', bias_initializer='zeros',
                                 dropout=self.rate_dropout, recurrent_dropout=self.rate_dropout)(attention_mul)
        attention_mul = LSTM(self.n_hidden, return_sequences=False, activation='tanh',
                             recurrent_activation='hard_sigmoid', kernel_initializer='glorot_uniform',
                             recurrent_initializer='orthogonal', bias_initializer='zeros',
                             dropout=self.rate_dropout, recurrent_dropout=self.rate_dropout)(attention_mul)
        attention_mul = Dense(output_size, kernel_initializer=initializers.glorot_uniform())(attention_mul)
        attention_mul = BatchNormalization(axis=-1, beta_initializer='ones')(attention_mul)
        outputs = ReLU(alpha=0.0, max_value=1.0)(attention_mul)
        self.model = Model(input=[inputs], output=outputs)
        opt = RMSprop(lr=self.learning_rate)
        self.model.compile(loss=self.loss, optimizer=opt, metrics=['accuracy'])
        self.model.summary()
        return self.model

    def train(self):
        # fit network
        history = self.model.fit(train_x, train_y, epochs=500, batch_size=2048, verbose=1, shuffle=True,
                                 validation_data=(test_x, test_y))
        # plot history
        plt.plot(history.history['loss'], label='train')
        plt.legend()
        plt.show()

    def save(self, path=model_path, type='evaluate'):
        if type == 'evaluate':
            file = 'lstm_evaluate_' + timestamp + '.h5'
        else:
            file = 'lstm_' + timestamp + '.h5'
        self.model.save(path + file)

    def load(self, path=model_path, type='evaluate', version='lastest'):
        file_names = os.listdir(path)
        model_files = []
        eval_files = []
        if version == 'lastest':
            for file in file_names:
                if re.search('eval', file) is not None:
                    eval_files.append(file)
                else:
                    model_files.append(file)
            if type == 'evaluate':
                eval_files.sort(reverse=True)
                model_name = eval_files[0]
            else:
                model_files.sort(reverse=True)
                model_name = model_files[0]
            print(model_name, 'has loaded')
            self.model = load_model(path + model_name, custom_objects={'risk_estimation': risk_estimation})
        else:
            self.model = load_model(path + version, custom_objects={'risk_estimation': risk_estimation})

    def predict(self, test):
        predict = []
        for sample_index in range(test.shape[0]):
            test_data = test[sample_index].reshape(1, time_step, input_size)
            prev = self.model.predict(test_data)
            predict.append(prev)
        return np.array(predict)

get_custom_objects().update({'ReLU': ReLU})
model = SeqModel(input_shape=(time_step, input_size), loss=risk_estimation)
net = model.lstmModel()

timestamp = str(int(time.time()))
# model.load(type=train_type, version='lstm_1583287513.h5') # fixed_models
# model.load(type=train_type, version='lstm.h5')  # fixed_models
# model.load(type=train_type, version='lstm_1583488295.h5')
# model.load(type=train_type)
# 训练模型
model.train()
# 储存模型
model.save(type=train_type)
# 读入模型
# model.load(type=train_type)
# 预测

predict = model.predict(test_x)
predict = predict.reshape(-1, output_size)
# 评价函数
eval(predict, df)

predict_df = pd.DataFrame(predict)
predict_df.columns = list(df.columns[1:].values.astype(str))
dim_date = x_date[-predict_time_interval - empty_time:]

predict_df['date'] = dim_date
predict_df.set_index('date', drop=True, inplace=True)
print(predict_df)

# 涨5个点线
test_1 = np.copy(test_x)
test_1[-1][-1, :] = test_1[-1][-1, :] + 0.02

predict_1 = model.predict(test_1)
predict_1 = predict_1.reshape(-1, output_size)
predict_df_1 = pd.DataFrame(predict_1)
predict_df_1.columns = list(df.columns[1:].values.astype(str))
predict_df_1['date'] = dim_date
predict_df_1.set_index('date', drop=True, inplace=True)

# 跌5个点线
test_2 = np.copy(test_x)
test_2[-1][-1, :] = test_2[-1][-1, :] - 0.05
predict_2 = model.predict(test_2)
predict_2 = predict_2.reshape(-1, output_size)
predict_df_2 = pd.DataFrame(predict_2)
predict_df_2.columns = list(df.columns[1:].values.astype(str))
predict_df_2['date'] = dim_date
predict_df_2.set_index('date', drop=True, inplace=True)

# 画图使用
history = data_test_y[-predict_time_interval - empty_time:-predict_time_interval, :].reshape(-1, output_size)
val = data_test_y[-predict_time_interval:, :].reshape(-1, output_size)
eval_seq = np.vstack((history, val))

history_pad = 0.5 * np.ones((history.shape[0], history.shape[1]))
prev_seq = np.vstack((history_pad, predict))
prev_seq_1 = np.vstack((history_pad, predict_1))
prev_seq_2 = np.vstack((history_pad, predict_2))

# 计算时间轴
dim_date = x_date[-predict_time_interval - empty_time:]
xs = [datetime.strptime(d, '%Y-%m-%d').date() for d in dim_date]
print("xs:", len(xs))
xs1 = [(datetime.strptime(d, '%Y-%m-%d')).date() for d in dim_date]

# 绘图
rcParams.update({'font.size': 16, 'font.family': 'serif'})
fig_num = 7
num = int(output_size / fig_num)
for i in range(fig_num):
    fig = plt.figure(figsize=(20, 40))
    output_name_list = []
    for im_num in range(i * num, (i + 1) * num):
        index = im_num
        ax1 = fig.add_subplot(num, 1, im_num - i * num + 1)
        ax1.set_ylabel(data.columns[index])
        output_name_list.append(data.columns[index])
        l1 = ax1.plot(xs, eval_seq[:, index], color='red')[0]

        ax2 = ax1.twinx()
        l3 = ax2.plot(xs1, prev_seq_1[:, index], color='blue')[0]
        l4 = ax2.plot(xs1, prev_seq_2[:, index], color='yellow')[0]
        l2 = ax2.plot(xs1, prev_seq[:, index], color='green')[0]
        ax2.set_ylabel('predict')
        fig.legend([l1, l2, l3, l4], ['real price', 'buy predict', '+0.05', '-0.05'], loc='upper right')
        plt.gcf().autofmt_xdate()
    output_name = '_'.join(output_name_list)
    plt.savefig(output_path + '{}.png'.format(output_name))
    plt.savefig(output_path_flask + '{}.png'.format(output_name))
    plt.show()


#!/bin/python3

import sys

prime_pre = [0 for i in range(100001)]
sieve = [0 for i in range(100001)]
for i in range(2, 100000):
    if sieve[i] == 0:
        prime_pre[i] = prime_pre[i-1]+1
        #primes.append(i)
        for j in range(i, 100001, i):
            sieve[j] = i
    else:
        prime_pre[i] = prime_pre[i-1]

g = int(input().strip())
for a0 in range(g):
    n = int(input().strip())
    print("MJ" if prime_pre[n]%2 == 0 else "Zolfa")


"""
    Main module for setting up and running tests using dpytest.
    Handles configuration of a bot, and setup of the discord environment
"""

import sys
import asyncio
import logging
import discord
import typing
from termcolor import colored
import nest_asyncio
nest_asyncio.apply()
from . import backend as back, callbacks
from .utils import embed_eq

class RunnerConfig(typing.NamedTuple):
    """
        Exposed discord test configuration
        Contains the current client, and lists of faked objects
    """

    client: discord.Client
    guilds: typing.List[discord.Guild]
    channels: typing.List[discord.abc.GuildChannel]
    members: typing.List[discord.Member]

log = logging.getLogger("discord.ext.tests")
_cur_config: typing.Optional[RunnerConfig] = None
sent_queue = asyncio.queues.Queue()
error_queue = asyncio.queues.Queue()

def require_config(func):
    def wrapper(*args, **kwargs):
        if _cur_config is None:
            log.error("Attempted to make call before runner configured")
            raise RuntimeError(f"Configure runner before calling {func.__name__}")
        return func(*args, **kwargs)
    wrapper.__wrapped__ = func
    return wrapper

async def run_all_events():
    """
        Ensure that all dpy related coroutines have completed or been cancelled
    """
    # print("run_all_events called")
    while True:
        if sys.version_info[1] >= 7:
            pending = asyncio.all_tasks()
        else:
            pending = asyncio.Task.all_tasks()
        if not any(map(lambda x: x._coro.__name__ == "_run_event" and not (x.done() or x.cancelled()) , pending)):
            break
        # print("e")
        for task in pending:
            # print(59)
            if task._coro.__name__ == "_run_event" and not (task.done() or task.cancelled()):
                # print(60)
                # print("task is", task)
                await task
                # loop = asyncio.get_event_loop()
                # loop.run_until_complete(task)
                # loop.close()
                # print(61)

async def finish_on_command_error():
    """
        Ensure that all dpy related coroutines have completed or been cancelled
    """
    if sys.version_info[1] >= 7:
        pending = filter(lambda x: x._coro.__name__ == "_run_event", asyncio.all_tasks())
    else:
        pending = filter(lambda x: x._coro.__name__ == "_run_event", asyncio.Task.all_tasks())
    for task in pending:
        if not (task.done() or task.cancelled()):
            await task

def verify_message(text=None, equals=True, contains=False, peek=False, assert_nothing=False):
    """
        Assert that a message was sent with the given text, or that a message was sent that *doesn't* match the
        given text

    :param text: Text to match, or None to match anything
    :param equals: Whether to negate the check
    :param assert_nothing: Whether to assert that nothing was sent at all
    """
    if text is None:
        equals = not equals
    if assert_nothing:
        assert sent_queue.qsize() == 0, f"A message was not meant to be sent but this message was sent {sent_queue.get_nowait().content}"
        return

    try:
        message = sent_queue.get_nowait()
        if peek:
            messages = [message]
            while not sent_queue.empty():
                tmp_message = sent_queue.get_nowait()
                messages.append(tmp_message)
            for tmp_message in messages:
                sent_queue.put_nowait(tmp_message)
        if equals:
            if contains:
                assert text in message.content,f"Didn't find expected text. Expected {text} to be in {message.content}"
            else:
                assert message.content == text, f"Didn't find expected text. Expected {text}, found {message.content}"
        else:
            if contains:
                assert text not in message.content, f"Found unexpected text. Expected something not containing {text}"
            else:
                assert message.content != text, f"Found unexpected text. Expected something not matching {text}"
    except asyncio.QueueEmpty:
        raise AssertionError("No message returned by command")

def get_message(peek=False):
    """
        Allow the user to retrieve a message sent by the bot

    :param peek: do not remove the message from the queue of messages
    :return:
    """
    message = sent_queue.get_nowait()
    if peek:
        messages = [message]
        while not sent_queue.empty():
            tmp_message = sent_queue.get_nowait()
            messages.append(tmp_message)
        for tmp_message in messages:
            sent_queue.put_nowait(tmp_message)
    return message

def verify_embed(embed=None, allow_text=False, equals=True, peek=False,assert_nothing=False):
    """
        Assert that a message was sent containing an embed, or that a message was sent not
        containing an embed

    :param embed: Embed to compare against
    :param allow_text: Whether non-embed text is allowed
    :param equals: Whether to invert the assertion
    :param assert_nothing: Whether to assert that no message was sent
    """
    if embed is None:
        equals = not equals
    if assert_nothing:
        assert sent_queue.qsize() == 0, f"A message was not meant to be sent but this message was sent {sent_queue.get_nowait().content}"
        return

    try:
        message = sent_queue.get_nowait()
        if not allow_text:
            assert message.content is None
        if peek:
            messages = [message]
            while not sent_queue.empty():
                tmp_message = sent_queue.get_nowait()
                messages.append(tmp_message)
            for tmp_message in messages:
                sent_queue.put_nowait(tmp_message)
        emb = None
        if len(message.embeds) > 0:
            emb = message.embeds[0]
        if equals:
            assert embed_eq(emb, embed), "Didn't find expected embed"
        else:
            assert not embed_eq(emb, embed), "Found unexpected embed"
    except asyncio.QueueEmpty:
        raise AssertionError("No message returned by command")

def get_embed(peek=False):
    """
        Allow the user to retrieve an embed in a message sent by the bot

    :param peek: do not remove the message from the queue of messages
    :return:
    """
    message = sent_queue.get_nowait()
    if peek:
        messages = [message]
        while not sent_queue.empty():
            tmp_message = sent_queue.get_nowait()
            messages.insert(0,tmp_message)
        for tmp_message in messages:
            sent_queue.put_nowait(tmp_message)
    return message.embeds[0]

def verify_file(file=None, allow_text=False, equals=True, assert_nothing=False):
    if file is None:
        equals = not equals
    if assert_nothing:
        assert sent_queue.qsize() == 0, f"A message was not meant to be sent but this message was sent {sent_queue.get_nowait().content}"

    try:
        message = sent_queue.get_nowait()
        if not allow_text:
            assert message.content is None

        attach = None
        if len(message.attachments) > 0:
            attach = message.attachments[0]
        if equals:
            assert attach == file, "Didn't find expected file"
        else:
            assert attach != file, "Found unexpected file"
    except asyncio.QueueEmpty:
        raise AssertionError("No message returned by command")

def verify_activity(activity=None, equals=True):
    if activity is None:
        equals = not equals
    me = _cur_config.guilds[0].me

    me_act = me.activity
    if isinstance(activity, discord.Activity):
        activity = (activity.name, activity.url, activity.type)
    if isinstance(me_act, discord.Activity):
        me_act = (me_act.name, me_act.url, me_act.type)

    if equals:
        assert me_act == activity, "Didn't find expected activity"
    else:
        assert me_act != activity, "Found unexpected activity"

async def empty_queue():
    await run_all_events()
    while not sent_queue.empty():
        await sent_queue.get()
    while not error_queue.empty():
        await error_queue.get()

async def message_callback(message):
    await sent_queue.put(message)

async def error_callback(ctx, error):
    await error_queue.put((ctx, error))

async def create_role_callback(guild, role, reason=None):
    roles = [role] + guild.roles
    if role.position == -1:
        for r in roles:
            if r.position != 0:
                r.position += 1
        role.position = 1
    back.update_guild(guild, roles=roles)

async def move_role_callback(guild, role, positions, reason=None):
    for pair in positions:
        guild._roles[pair["id"]].position = pair["position"]

async def add_role_callback(member, role, reason=None):
    roles = [role] + [x for x in member.roles if x.id != member.guild.id]
    back.update_member(member, roles=roles)

async def remove_role_callback(member, role, reason=None):
    roles = [x for x in member.roles if x != role and x.id != member.guild.id]
    back.update_member(member, roles=roles)

@require_config
async def message(content, channel=0, member=0):
    if isinstance(channel, int):
        channel = _cur_config.channels[channel]
    if isinstance(member, int):
        member = _cur_config.members[member]
    # print("_cur_config.members is", _cur_config.members)
    # print("in require_config.message member is", member)
    mes = back.make_message(content, member, channel)
    # print("before run_all_events")
    await run_all_events()
    #await
    # print(" after run_all_events")

    if not error_queue.empty():
        err = await error_queue.get()
        raise err[1]

    return mes

@require_config
async def set_permission_overrides(target, channel, overrides=None, **kwars):
    if kwars:
        if overrides:
            raise ValueError("either overrides parameter or kwargs")
        else:
            overrides = discord.PermissionOverwrite(**kwars)

    if isinstance(target, int):
        target = _cur_config.members[target]
    if isinstance(channel, int):
        channel = _cur_config.channels[channel]

    if not isinstance(channel, discord.abc.GuildChannel):
        raise TypeError(f"channel '{channel}' must be a abc.GuildChannel, not '{type(channel)}''")
    if not isinstance(target, (discord.abc.User, discord.Role)):
        raise TypeError(f"target '{target}' must be a abc.User or Role, not '{type(target)}''")

    back.update_text_channel(channel, target, overrides)

@require_config
async def add_role(member, role):
    if isinstance(member, int):
        member = _cur_config.members[member]
    if not isinstance(role, discord.Role):
        raise TypeError("Role argument must be of type discord.Role")

    roles = [role] + [x for x in member.roles if x.id != member.guild.id]
    back.update_member(member, roles=roles)

@require_config
async def remove_role(member, role):
    if isinstance(member, int):
        member = _cur_config.members[member]
    if not isinstance(role, discord.Role):
        raise TypeError("Role argument must be of type discord.Role")

    roles = [x for x in member.roles if x.id != role.id and x.id != member.guild.id]
    back.update_member(member, roles=roles)

@require_config
async def member_join(guild=0, user=None, *, name=None, discrim=None):
    # print(colored("member joined called bruh momment right here","red"))
    import random
    if isinstance(guild, int):
        guild = _cur_config.guilds[guild]
    # print("member join called")
    if user is None:
        if name is None:
            name = "TestUser"
        if discrim is None:
            discrim = random.randint(1, 9999)
        user = back.make_user("TestUser", discrim)
    member = back.make_member(user, guild)
    return member

def get_config():
    return _cur_config

def configure(client, num_guilds=1, num_channels=1, num_members=1):
    global _cur_config

    if not isinstance(client, discord.Client):
        raise TypeError("Runner client must be an instance of discord.Client")
    if isinstance(client, discord.AutoShardedClient):
        raise TypeError("Sharded clients not yet supported")

    back.configure(client)

    # Wrap on_error so errors will be reported
    old_error = None
    if hasattr(client, "on_command_error"):
        old_error = client.on_command_error

    async def on_command_error(ctx, error):
        try:
            if old_error:
                await old_error(ctx, error)
        finally:
            await error_queue.put((ctx, error))

    on_command_error.__old__ = old_error
    client.on_command_error = on_command_error

    # Configure global callbacks
    callbacks.set_callback(message_callback, "send_message")
    callbacks.set_callback(create_role_callback, "create_role")
    callbacks.set_callback(move_role_callback, "move_role")
    callbacks.set_callback(add_role_callback, "add_role")
    callbacks.set_callback(remove_role_callback, "remove_role")

    back.get_state().stop_dispatch()

    guilds = []
    for num in range(num_guilds):
        guild = back.make_guild(f"Test Guild {num}")
        guilds.append(guild)

    channels = []
    members = []
    for guild in guilds:
        for num in range(num_channels):
            channel = back.make_text_channel(f"Channel_{num}", guild)
            channels.append(channel)
        for num in range(num_members):
            user = back.make_user(f"TestUser{str(num)}", f"{num+1:04}")
            member = back.make_member(user, guild, nick=user.name + f"_{str(num)}_nick")
            members.append(member)
            # print("members is", members, "runner 395")
        back.make_member(back.get_state().user, guild)

    back.get_state().start_dispatch()

    _cur_config = RunnerConfig(client, guilds, channels, members)


import sys

# sys.setrecursionlimit(10**4)
# from sys import stdin
# readline = stdin.readline
sr=lambda: input()
ir=lambda: int(sr())
lr=lambda: list(map(int, sr().split()))

import bisect

from sys import stdout

inf=10**18
mod=10**9+7
# mod = 998244353
# len(bin(n)) - bin(n).rfind("1") - 1

import random

if __name__=='__main__':
    n = ir()
    a = lr()
    b = lr()
    x_min = 1
    x_max = 1000
    for i in range(n):
        x_min = max(x_min, a[i])
        x_max = min(x_max, b[i])
    print(max(0,x_max-x_min+1))


# PART 1 ----------------------
with open('input1.txt') as f:
    datas = f.readlines()

larger_counter = 0
previous_data = None
for index, data in enumerate(datas):
    if index > 0:
        previous_data = int(datas[index - 1])
        if int(data) > previous_data:
            larger_counter += 1

larger_counter = 0
previous_data = int(datas[0])
for data in datas:
    if int(data) > previous_data:
        larger_counter += 1
    previous_data = int(data)

print("Depth measurement increases", larger_counter, "time")

# PART 2 ----------------------
previous_sum = None
larger_counter_sum = 0
for index, data in enumerate(datas):
    if index >= 2:
        a = int(datas[index - 2])
        b = int(datas[index - 1])
        c = int(datas[index])
        sum = a + b + c

        if previous_sum is not None:
            if sum > previous_sum:
                larger_counter_sum += 1
        previous_sum = int(sum)

print("Depth measurement increases", larger_counter_sum, "time")


#!/usr/bin/python
# -*- coding:utf-8 -*-
from flask import render_template, request, redirect, url_for, jsonify, current_app
from flask_login import login_user, logout_user, current_user

from app.libs.logger import CmsLogger
from app.libs.redprint import Redprint
from app.models.auth_user import AuthUser
from app.models.conf import Conf

__author__ = 'justin.郑'

api = Redprint('login')
mdb = globals()['AuthUser']
db_conf = globals()['Conf']

@api.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user_find = mdb.query.filter_by(username=request.form.get('username')).first()
        if user_find and user_find.check_password(request.form.get('password')):
            # remember=True 记住我 功能
            login_user(user_find)
            # next = request.args.get('next')
            # if not next or not next.startswith('/'):
            #     next = url_for('admin.index')
            # return redirect(next)
            # CmsLogger('info').info('ID：%s 账号：%s 登录系统' % (user_find.id, user_find.username))
            return jsonify({"status": 200})
        else:
            return jsonify({"status": 401, "msg": "账号或密码错误,请重新输入"})

    if request.method == 'GET':
        find = db_conf.query.filter_by(id=1).first()
        return render_template('admin/login/login.html', find=find, version=current_app.config['VERSION_ADMIN'])

@api.route('/logout')
def logout():
    CmsLogger('info').info('ID：%s 账号：%s 退出系统' % (current_user.id, current_user.username))
    logout_user()
    return redirect(url_for('admin.index'))

@api.route('/test')
def test():
    CmsLogger('info').info('测试logger')
    return 'abc'


"""
将华氏温度转换为摄氏温度
F = 1.8C + 32

Version: 0.1
Author: zz
"""

def transfer(c = 1.0):
    f = 1.8 * c + 32
    return f
c = float(input('please input c: '))
print('F = '+str(transfer(c))+' when C = '+ str(c))
quit()


import gc
from torch.utils.data import DataLoader
import torch.optim as optim
from tqdm.auto import tqdm
import numpy as np
import torch
import torch.nn
import sys
import os

from losses import bce_weighted_dice_loss

dtype = torch.cuda.FloatTensor

def train(model, model_name, save_dir, train_dataloader, val_dataloader, criterion, optimizer, epochs=100, gpu_id=0):
    gc.collect()
    torch.cuda.empty_cache()

    best_weights = None
    best_loss = sys.maxsize

    train_loss = []
    val_loss = []

    # Model name format:
    # model_name, patch_size, dataset, lr, epoch
    model_name = f'{model_name}_{str(epochs)}'

    pbar = tqdm(total=epochs, desc='Training')
    for epoch in range(epochs):
        # Train
        model.train()
        running_loss = 0

        for inputs, labels in train_dataloader:
            gc.collect()
            torch.cuda.empty_cache()
            # Move data to GPU
            inputs = torch.unsqueeze(torch.tensor(inputs.type(dtype).cuda(device=gpu_id)), axis=1)
            labels = torch.unsqueeze(torch.tensor(labels.type(dtype).cuda(device=gpu_id)), axis=1)
            optimizer.zero_grad()
            # Run model
            outputs = model.forward(inputs)

            loss = criterion(outputs, labels).cuda(device=gpu_id)

            loss.backward()

            running_loss += loss.item()
            optimizer.step()

        train_epoch_loss = running_loss / len(train_dataloader)
        train_loss.append(train_epoch_loss)

        # Val
        model.eval()
        running_loss = 0
        with torch.no_grad():
            for inputs, labels in val_dataloader:
                gc.collect()
                torch.cuda.empty_cache()
                # Move data to GPU
                inputs = torch.unsqueeze(torch.tensor(inputs.type(dtype).cuda(device=gpu_id)), axis=1)
                labels = torch.unsqueeze(torch.tensor(labels.type(dtype).cuda(device=gpu_id)), axis=1)
                # Run model
                outputs = model.forward(inputs)

                loss = criterion(outputs, labels).cuda(device=gpu_id)
                running_loss += loss.item()
        val_epoch_loss = running_loss / len(val_dataloader)
        val_loss.append(val_epoch_loss)

        # Keep track of best weights
        if val_epoch_loss < best_loss:
            best_loss = val_epoch_loss
            best_weights = model.state_dict()

        pbar.set_postfix({'TL': train_epoch_loss, 'VL': val_epoch_loss, 'BV': best_loss})
        pbar.update(1)
    # Save weights
    torch.save(best_weights, os.path.join(save_dir, f'{model_name}_best_loss.npz'))
    torch.save(model.state_dict(), os.path.join(save_dir, f'{model_name}_last_epoch.npz'))
    return model, train_loss, val_loss


# 16529 - 股票
n = int(input())
prices = list(map(float, input().split()))
r = 1
min_ = prices[0]
max_ = prices[0]
for i, p in enumerate(prices):
    if p > max_:
        max_ = p
        r = max(r, max_/min_)
    if p < min_:
        min_ = p
        max_ = p
print('{:.2f}'.format(100*r))