# FileName: dataloader.py (proj1)
# CreateTime: 2020.11.20
# Author: © 王子翊 MF20330086@NJU

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def show_plot(X, Y, Z, title=''):
    """
    Plot 3D surface.

    Args:
        X (np.ndarray): Axis X.(After np.meshgrid or should be a $N \\times N$ array.)
        Y (np.ndarray): Axis Y.(After np.meshgrid or should be a $N \\times N$ array.)
        Z (np.ndarray): Axis Z.(Should be a $N \\times N$ array.)
    """
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.plot_surface(X, Y, Z)
    fig.suptitle(title)
    plt.show()


# Copyright 2019 Xilinx Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import base64
from six import itervalues, next

import cv2
import numpy as np

from vai.dpuv1.rt import xdnn, xdnn_io
from vai.dpuv1.rt.xsnodes.base import XstreamNode, XstreamNodeArgs

class Node(XstreamNode):
    """
    This class implements the Facedetect node. Initializing the class creates
    and starts the node through the loop() method

    Args:
        XstreamNode (XstreamNode): The base class of all nodes

    Returns:
        Facedetect: An instance of the class
    """

    def initialize(self, args):
        self._parser = xdnn.CompilerJsonParser(args['netcfg'])
        self._fpgaRT = xdnn.XDNNFPGAOp(args)
        self._indictnames = args["input_names"]
        self._outdictnames = args["output_names"]

        self._firstInputShape = next(itervalues(self._parser.getInputs()))
        self._meanarr = np.zeros(
            (
                self._firstInputShape[2],
                self._firstInputShape[3],
                self._firstInputShape[1],
            ),
            dtype=np.float32, order='C'
        )

        self.expand_scale_ = 0.0
        self.force_gray_ = False
        self.input_mean_value_ = 128.0
        self.input_scale_ = 1.0
        self.pixel_blob_name_ = 'pixel-prob'
        self.bb_blob_name_ = 'bb-output-tiled'

        self.res_stride_ = 4
        self.det_threshold_ = 0.7
        self.nms_threshold_ = 0.3
        self.input_channels_ = 3

        self._streamIds = [0, 1, 2, 3, 4, 5, 6, 7] # Allow 8 streams

        print("Facedetect: Starting loop")
        self.run()

    # --------------------------------------------------------
    # Fast R-CNN
    # Copyright (c) 2015 Microsoft
    # Licensed under The MIT License [see LICENSE for details]
    # Written by Ross Girshick
    # --------------------------------------------------------
    @staticmethod
    def nms(dets, thresh):
        """
        Implementation of Fast R-CNN using non-maximum supression (nms)

        Args:
            dets ([type]): [description]
            thresh ([type]): [description]

        Returns:
            [type]: [description]
        """
        x1 = dets[:, 0]
        y1 = dets[:, 1]
        x2 = dets[:, 2]
        y2 = dets[:, 3]
        scores = dets[:, 4]

        areas = (x2 - x1 + 1) * (y2 - y1 + 1)
        order = scores.argsort()[::-1]

        keep = []
        while order.size > 0:
            i = order[0]
            keep.append(i)
            xx1 = np.maximum(x1[i], x1[order[1:]])
            yy1 = np.maximum(y1[i], y1[order[1:]])
            xx2 = np.minimum(x2[i], x2[order[1:]])
            yy2 = np.minimum(y2[i], y2[order[1:]])

            w = np.maximum(0.0, xx2 - xx1 + 1)
            h = np.maximum(0.0, yy2 - yy1 + 1)
            inter = w * h
            ovr = inter / (areas[i] + areas[order[1:]] - inter)

            inds = np.where(ovr <= thresh)[0]
            order = order[inds + 1]

        return keep

    def GSTilingLayer_forward(self, bottom, stride):
        stride_sq = stride**2

        input_batch = bottom.shape[0]
        input_channels = bottom.shape[1]
        input_height = bottom.shape[2]
        input_width = bottom.shape[3]

        output_batch = input_batch
        output_channels = input_channels//stride_sq
        output_height = input_height*stride
        output_width = input_width*stride

        top = np.zeros(
            [output_batch, output_channels, output_height, output_width],
            dtype=np.float32
        )

        for n in range(input_batch):
            for ic in range(input_channels):
                off_div = (ic // output_channels) // stride
                off_mod = (ic // output_channels) % stride
                oc = ic % output_channels
                for iy in range(input_height):
                    oy = iy * stride + off_div
                    ox = off_mod - stride
                    top[n,oc,oy,off_mod::stride] = bottom[n,ic,iy,:input_width]

        return top

    def SoftmaxLayer_forward(self, bottom):
        input_batch = bottom.shape[0]
        input_channels = bottom.shape[1]
        input_height = bottom.shape[2]
        input_width = bottom.shape[3]

        top = np.zeros(
            [input_batch, input_channels, input_height, input_width],
            dtype=np.float32
        )

        for n in range(input_batch):

            scale_data = np.zeros([input_height,input_width],dtype=np.float32)
            scale_data = bottom[n,0,...]

            for c in range(1,input_channels):
                scale_data = np.maximum(scale_data, bottom[n, c, ...])

            tmp_bottom = bottom[n, ...] - scale_data
            tmp_bottom = np.exp(tmp_bottom)

            scale_data = np.sum(tmp_bottom, axis=0)
            tmp_bottom = tmp_bottom / scale_data
            top[n] = tmp_bottom

        return top

    # Called for every batch
    def forward(self, bottom):
        top = [0]*len(self._outdictnames)

        indict = {}
        outdict = {}

        for i, n in enumerate(self._indictnames):
            # default to 1 batch
            indict[n] = np.ascontiguousarray(np.expand_dims(bottom[i], 0))

        for i, name in enumerate(self._outdictnames):
            dim = self._parser.getOutputs()[name]
            top[i] = np.empty(dim, dtype=np.float32)
            outdict[name] = top[i]

        # Get a free stream if available
        if self._streamIds:
            streamId = self._streamIds.pop(0)
        else:
            return None

        start_time = time.time()
        # self.fpgaRT.execute(indict, outdict, streamId)
        self._fpgaRT.exec_async(indict, outdict, streamId)
        self._fpgaRT.get_result(streamId)
        end_time = time.time()

        self._streamIds.append(streamId) # Return stream

        return outdict

    def detect(self, image):
        # transpose HWC (0,1,2) to CHW (2,0,1)
        transformed_image = np.transpose(image, (2, 0, 1))

        transformed_image = (transformed_image-self.input_mean_value_)*self.input_scale_
        sz = image.shape

        # Call FPGA
        output = self.forward([transformed_image.astype(np.float32)])

        # Put CPU layers into postprocess
        pixel_conv = output['pixel-conv']
        pixel_conv_tiled = self.GSTilingLayer_forward(pixel_conv, 8)
        prob = self.SoftmaxLayer_forward(pixel_conv_tiled)
        prob = prob[0, 1, ...]

        bb = output['bb-output']
        bb = self.GSTilingLayer_forward(bb, 8)
        bb = bb[0, ...]

        ##import pdb; pdb.set_trace()
        gy = np.arange(0, sz[0], self.res_stride_)
        gx = np.arange(0, sz[1], self.res_stride_)
        gy = gy[0 : bb.shape[1]]
        gx = gx[0 : bb.shape[2]]
        [x, y] = np.meshgrid(gx, gy)

        #print bb.shape[1],len(gy),sz[0],sz[1]
        bb[0, :, :] += x
        bb[2, :, :] += x
        bb[1, :, :] += y
        bb[3, :, :] += y
        bb = np.reshape(bb, (4, -1)).T
        prob = np.reshape(prob, (-1, 1))
        bb = bb[prob.ravel() > self.det_threshold_, :]
        prob = prob[prob.ravel() > self.det_threshold_, :]
        rects = np.hstack((bb, prob))
        keep = self.nms(rects, self.nms_threshold_)
        rects = rects[keep, :]
        rects_expand = []
        for rect in rects:
            rect_expand = []
            rect_w = rect[2] - rect[0]
            rect_h = rect[3] - rect[1]
            rect_expand.append(int(max(0,rect[0]-rect_w*self.expand_scale_)))
            rect_expand.append(int(max(0,rect[1]-rect_h*self.expand_scale_)))
            rect_expand.append(int(min(sz[1],rect[2]+rect_w*self.expand_scale_)))
            rect_expand.append(int(min(sz[0],rect[3]+rect_h*self.expand_scale_)))
            rect_expand.append('face')
            rects_expand.append(rect_expand)

        return rects_expand

    def loop(self, payload):
        (meta, buf) = payload
        meta['callback'] = self._callback

        npimg = np.frombuffer(buf, dtype=getattr(np, meta['dtype']))
        image = np.reshape(npimg, (meta['image_height'], meta['image_width'], meta['image_channels']))

        image_resize = cv2.resize(
            image,
            (320, 320),
            interpolation=cv2.INTER_LINEAR
        )
        if image_resize is not None:
            boxes = self.detect(image_resize)
            meta['boxes'] = boxes
            meta['status'] = 0
            retval, img_str = cv2.imencode(".jpg", image_resize)

            if retval:
                base64_str = base64.b64encode(img_str)
                meta['img'] = base64_str.decode('utf-8')
            else:
                raise NotImplementedError

        # delete objects to decrement obj store refcount
        # -- this is so the object can be auto-deleted,
        #        so we can reuse the id in the put() below
        del buf
        del payload

        self.put(meta)

class Args(XstreamNodeArgs):
    def __init__(self):
        super(Args, self).__init__()

        self.add_start_arg(
            'netcfg',
            "(?): insert description of netcfg"
        )
        self.add_start_arg(
            '_parser',
            "(?): insert description of _parser"
        )
        self.add_start_arg(
            '_indictnames',
            "(str): insert description of _indictnames"
        )
        self.add_start_arg(
            '_outdictnames',
            "(str): insert description of _outdictnames"
        )
        self.add_start_arg(
            'XDNNFPGAOp_args',
            "(?): Not sure which arguments might be needed for the XDNNFPGAOp instance"
        )

        self.add_input_serve_arg(
            'BUFFER',
            "The buffer should contain an image to be parsed with np.dtype"

        )
        self.add_input_serve_arg(
            'dtype',
            "(str): This should be an attribute of np to indicate how to interpret the" +
                "numpy array"
        )
        self.add_input_serve_arg(
            'image_height',
            "(int): Height of the image in pixels"
        )
        self.add_input_serve_arg(
            'image_width',
            "(int): Width of the image in pixels"
        )
        self.add_input_serve_arg(
            'image_channels',
            "(int): Channels in the image (usually should be 3)"
        )

        self.add_output_serve_arg(
            'callback',
            "(str): The meta is updated with the callback value of this node"
        )
        self.add_output_serve_arg(
            'BUFFER',
            "The buffer is emptied"
        )
        self.add_output_serve_arg(
            'status',
            "0 - success"
        )
        self.add_output_serve_arg(
            'boxes',
            "(dict): Detected faces in this format: TBD"
        )
        self.add_output_serve_arg(
            'img',
            "(str): Base64-encoded image URI from the input buffer"
        )


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('clientes', '0001_initial'),
        ('contabilidad', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='cliente',
            name='banco',
            field=models.ForeignKey(to='contabilidad.Bancos'),
        ),
        migrations.AddField(
            model_name='cliente',
            name='tipo_cuenta',
            field=models.ForeignKey(to='contabilidad.TipoCuenta'),
        ),
    ]


import codecs
from numpy import *
import matplotlib.pyplot as plt

def load_data(path):
	"""
	@brief      Loads a data
	@param      path  The path
	@return     data set
	"""
	data_set = list()
	with codecs.open(path) as f:
		for line in f.readlines():
			data = line.strip().split(" ")
			flt_data = list(map(double, data))
			data_set.append(flt_data)
	return data_set

def dist_eucl(vecA, vecB):
	"""
	@brief      the similarity function
	@param      vecA  The vector a
	@param      vecB  The vector b
	@return     the euclidean distance
	"""
	return sqrt(sum(power(vecA - vecB, 2)))

def rand_cent(data_mat, k):
	"""
	@brief      select random centroid
	@param      data_mat  The data matrix
	@param      k
	@return     centroids
	"""
	n = shape(data_mat)[1]
	centroids = mat(zeros((k, n)))
	for j in range(n):
		minJ = min(data_mat[:,j])
		rangeJ = float(max(data_mat[:,j]) - minJ)
		centroids[:,j] = mat(minJ + rangeJ * random.rand(k,1))
	return centroids

def kMeans(data_mat, k, dist = "dist_eucl", create_cent = "rand_cent"):
	"""
	@brief      kMeans algorithm
	@param      data_mat     The data matrix
	@param      k            num of cluster
	@param      dist         The distance funtion
	@param      create_cent  The create centroid function
	@return     the cluster
	"""
	m = shape(data_mat)[0]
	# 初始化点的簇
	cluster_assment = mat(zeros((m, 2)))  # 类别，距离
	# 随机初始化聚类初始点
	centroid = eval(create_cent)(data_mat, k)
	cluster_changed = True
	# 遍历每个点
	while cluster_changed:
		cluster_changed = False
		for i in range(m):
			min_index = -1
			min_dist = inf
			for j in range(k):
				distance = eval(dist)(data_mat[i, :], centroid[j, :])
				if distance < min_dist:
					min_dist = distance
					min_index = j
			if cluster_assment[i, 0] != min_index:
				cluster_changed = True
				cluster_assment[i, :] = min_index, min_dist**2
		# 计算簇中所有点的均值并重新将均值作为质心
		for j in range(k):
			per_data_set = data_mat[nonzero(cluster_assment[:,0].A == j)[0]]
			centroid[j, :] = mean(per_data_set, axis = 0)
	return centroid, cluster_assment

def kmeans_plot_cluster(data_mat, cluster_assment, centroid):
	"""
	@brief      plot cluster and centroid
	@param      data_mat        The data matrix
	@param      cluster_assment  The cluste assment
	@param      centroid        The centroid
	@return
	"""
	plt.figure(figsize=(15, 6), dpi=80)
	plt.subplot(121)
	plt.plot(data_mat[:, 0], data_mat[:, 1], 'o')
	plt.title("source data", fontsize=15)
	plt.subplot(122)
	k = shape(centroid)[0]
	colors = [plt.cm.get_cmap("Spectral")(each) for each in linspace(0, 1, k)]
	for i, col in zip(range(k), colors):
	    per_data_set = data_mat[nonzero(cluster_assment[:,0].A == i)[0]]
	    plt.plot(per_data_set[:, 0], per_data_set[:, 1], 'o', markerfacecolor=tuple(col),
	             markeredgecolor='k', markersize=10)
	for i in range(k):
		plt.plot(centroid[:,0], centroid[:,1], '+', color = 'k', markersize=18)
	plt.title("K-Means Clustering, k = "+str(k), fontsize=15)
	plt.show()

if __name__ == '__main__':
	data_mat = mat(load_data("D:\\大三下\\人工智能基础\\Thecode\\Chapter2\\data\\five_cluster.txt"))
	data_mat = data_mat[:,1:3]

	centroid, cluster_assment = kMeans(data_mat, 5)
	sse = sum(cluster_assment[:,1])
	print("SSE is ", sse)
	kmeans_plot_cluster(data_mat, cluster_assment, centroid)


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:CJR
# 客户端
import socket

client = socket.socket() # 声明 socket 类型，同时生成 socket 连接对象
# <socket.socket fd=496, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0>
# print(client)
client.connect(("localhost", 8967))
# <socket.socket fd=496, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0,
#  laddr=('127.0.0.1', 59049), raddr=('127.0.0.1', 7894)>
# print(client)

while True:
    meg = input(">>:").strip()
    if not meg:
        continue
    client.send(meg.encode("utf-8"))
    data = client.recv(1024) # 设置接收的长度，1024字节 1K
    print("recv:", data.decode())

client.close()


from bot import bot
import datetime
import pytz
from utils.database import execute_database_command
from checks.utils import CheckStatus
from users.models import User

@bot.message_handler(content_types=['sticker'])
def get_sticker_id(message):
    print(message.sticker.file_id)

def remove_markup(chat_id, message_id):
    bot.edit_message_reply_markup(chat_id, message_id=message_id, reply_markup=None)

def get_native_datetime(date, time, timezone):
    return pytz.timezone(timezone).localize(
                datetime.datetime.strptime(f'{date} {time}', "%Y-%m-%d %H:%M"), is_dst=None)

def get_user_naming(user, default):
    user_naming = default
    if user.first_name:
        user_naming = user.first_name
        if user.last_name:
            user_naming = user.first_name + ' ' + user.last_name

    return user_naming

def get_schedule(week_days, time_array, timezone):
    user_date_now = datetime.datetime.now(tz=pytz.timezone(timezone)).date()
    schedule_native = []
    for week_day in week_days:
        if week_day > user_date_now.weekday():
            first_day = user_date_now + datetime.timedelta(week_day - user_date_now.weekday())
        else:
            first_day = user_date_now + datetime.timedelta(7 - user_date_now.weekday() + week_day)

        second_day = first_day + datetime.timedelta(7)
        third_day = second_day + datetime.timedelta(7)

        for time in time_array:
            first_datetime_native, second_datetime_native, third_datetime_native = [
                get_native_datetime(str(day), time, timezone) for day in
                [first_day, second_day, third_day]]

            schedule_native.extend([first_datetime_native, second_datetime_native, third_datetime_native])

    schedule_native.sort()
    schedule_utc = [native_datetime.astimezone(pytz.utc) for native_datetime in schedule_native]
    return schedule_native, schedule_utc

def score_users():
    success_checks = execute_database_command('''SELECT h.user_id, h.fine FROM
        checks c JOIN habits h ON c.habit_id = h.id
        WHERE  c.status=%s;
        ''', (CheckStatus.SUCCESS.name, ))[0]
    for success_check in success_checks:
        u = User.get(success_check[0])
        u.score += success_check[1]
        u.save()

    fail_checks = execute_database_command('''SELECT h.user_id, h.fine FROM
            checks c JOIN habits h ON c.habit_id = h.id
            WHERE  c.status=%s;
            ''', (CheckStatus.FAIL.name,))[0]
    for fail_check in fail_checks:
        u = User.get(fail_check[0])
        u.score -= fail_check[1]
        u.save()

def send_info_to_users():
    users = execute_database_command('SELECT id, first_name, language_code FROM users;')[0]

    for user in users:
        ru_text = f'Привет{", " + user[1] if user[1] else ""}!\n\n' \
                  f'Я решил больше не церемониться. Теперь разговариваю дерзко и на "ты". ' \
                  f'Может, хотя бы это поможет тебе побороть свою лень. ' \
                  f'А ещё я теперь отправляю стикеры.\n\n' \
                  f'Короче, я теперь не унылый стандартный бот.'
        en_text = f'Hello{", " + user[1] if user[1] else ""}!\n\n' \
                  f'I decided to no longer stand on ceremony. Now I speak impertinently. ' \
                  f'Maybe at least it will help you overcome your laziness. ' \
                  f'And now I send stickers.\n\n' \
                  f'In short, I am no longer a dull standard bot.'
        text = ru_text if user[2] == 'ru' else en_text

        try:
            bot.send_message(user[0], text, parse_mode='Markdown')
            bot.send_sticker(user[0], 'CAADAgADcgADE-ZSAdekz3zzPdFUAg')
        except Exception as e:
            print(e)


import collections
import itertools
import os
import re
import random
from glob import glob

from .utils import *

from onmt.utils.logging import logger

RE_SHARD = re.compile(r'([0-9]*)\.([a-z]*)(\.gz)?')

def infinite_iterator(iterator_factory):
    while True:
        yield from iterator_factory()

class TaskEpoch():
    def __init__(self, data_config, task):
        self.data_config = data_config
        self.task = task
        self.indices = set()
        self.files = collections.defaultdict(list)
        self.compressed = False
        self.epoch = 0
        # share_inputs causes this task to use another one's data
        data_task = self.data_config['tasks'][task].get('share_inputs', task)
        self.taskdir = os.path.join(
            self.data_config['meta']['shard']['rootdir'],
            'shards', data_task)
        self.task_type = self.data_config['tasks'][task]['type']
        if self.task_type == 'para':
            self.sides = ('src', 'tgt')
        elif self.task_type == 'mono':
            self.sides = ('mono',)
        else:
            raise Exception('Unrecognized task type "{}"'.format(
                self.task_type))
        # reverse causes roles of src and tgt data to be reversed
        # useful for backtranslation
        # (note that meta src_lang and trg_lang are not modified)
        if self.data_config['meta']['train'].get('reverse', False):
            self.sides = self.sides[::-1]
        self._find_shards()
        logger.info('Shard task "{}" from "{}"'.format(self.task,
                                                       self.taskdir))

    def _find_shards(self):
        for filename in os.listdir(self.taskdir):
            m = RE_SHARD.match(filename)
            if not m:
                continue
            index, suffix, ext = m.groups()
            self.indices.add(index)
            path = os.path.join(self.taskdir, filename)
            self.files[(suffix, index)] = path
            if ext == '.gz':
                self.compressed = True
            elif self.compressed:
                raise Exception('Cannot mix compressed and uncompressed')
        for side in self.sides:
            for index in self.indices:
                if not (side, index) in self.files:
                    raise Exception('Missing shard: {} {}, {}'.format(
                        self.task, side, index))

    def yield_epoch(self):
        self.epoch += 1
        all_shards = []
        for index in self.indices:
            all_shards.append([self.files[(side, index)]
                               for side in self.sides])
        random.shuffle(all_shards)
        yield from all_shards

def debug(stream, prefix='debug'):
    for item in stream:
        print('{}: {}'.format(prefix, item))
        yield item

class ShardIterator():
    def __init__(self, task, files, transforms):
        self.task = task
        self.files = files
        self.transforms = transforms

    def tokenize(self, stream):
        for line in stream:
            yield tuple(line.rstrip('\n').split())

    def transpose(self, streams):
        tpls = list(zip(*streams))
        return tpls

    def transform(self, stream, is_train):
        for tpl in stream:
            for transform in self.transforms:
                tpl = transform.apply(tpl, self.task, is_train)
            if tpl is None:
                # the last transform can filter by returning None
                if not is_train:
                    raise Exception('Cannot filter validation set')
                continue
            yield tpl

    def add_index(self, stream):
        for i, tpl in enumerate(stream):
            yield tpl + (i,)

class TrainShardIterator(ShardIterator):
    def __call__(self, is_train=True):
        fobjs = [open(path, 'r') for path in self.files]
        tokenized = [self.tokenize(stream) for stream in fobjs]
        transposed = self.transpose(tokenized)
        if is_train:
            random.shuffle(transposed)
        for fobj in fobjs:
            fobj.close()
        # transposed = debug(transposed, 'transposed')
        transformed = self.transform(transposed, is_train)
        # transformed = debug(transformed, 'transformed')
        indexed = self.add_index(transformed)
        yield from indexed

class TranslateShardIterator(ShardIterator):
    def __call__(self, is_train=False):
        assert not is_train
        decoded = [self.decode(stream) for stream in self.files]
        tokenized = [self.tokenize(stream) for stream in decoded]
        transposed = self.transpose(tokenized)
        transformed = self.transform(transposed, is_train)
        # transformed = debug(transformed, 'transformed')
        indexed = self.add_index(transformed)
        yield from indexed

    def decode(self, stream):
        for bstr in stream:
            yield bstr.decode("utf-8")

def yield_infinite(task_epoch, task, transforms, is_train):
    for tpl in infinite_iterator(task_epoch.yield_epoch):
        si = TrainShardIterator(task, tpl, transforms)
        yield from si(is_train=is_train)

def yield_once(task_epoch, task, transforms, is_train):
    for tpl in task_epoch.yield_epoch():
        si = TrainShardIterator(task, tpl, transforms)
        yield from si(is_train=is_train)

def yield_translate(files, task, transforms):
    for tpl in files:
        si = TranslateShardIterator(task, tpl, transforms)
        yield from si(is_train=False)

def yield_debug(files, task, transforms, is_train):
    si = TrainShardIterator(task, files, transforms)
    yield from si(is_train=is_train)

class TransformReader():
    def __init__(self, task, transforms):
        self.task = task
        self.transforms = transforms

    def read(self, src_file, side, _dir=None):
        if side != 'src':
            # TODO: make a hacky thing that buffers the joint data
            # and provides access to src and tgt separately via
            # two objects having a read method
            raise Exception("dynamicdata doesn't support tgt")
        files = [(src_file,)]
        stream = yield_translate(files, self.task, self.transforms)
        for (src, idx) in stream:
            yield {'src': src, 'indices': idx}

class MixingWeightSchedule():
    def __init__(self, data_config, keys):
        self.keys = keys
        self.schedule_steps = self._list(
            data_config['meta']['train'].get('mixing_weight_schedule', []))
        self.schedule_steps.append(None)
        self.mixing_weights = {
            key: self._list(data_config['tasks'][key]['weight'],
                            len(self.schedule_steps))
            for key in keys}
        for key in keys:
            if len(self.mixing_weights[key]) != len(self.schedule_steps):
                raise Exception('task "{}" has {} mixing weights,'
                                'expecting {}'.format(
                                key, len(self.mixing_weights[key]),
                                len(self.schedule_steps)))
        self.next_threshold = 0

    def _list(self, val, repeat=None):
        if isinstance(val, int):
            if repeat:
                return [val] * repeat
            else:
                return [val]
        return list(val)

    def __call__(self, i):
        if self.next_threshold is None:
            # no adjustments left
            return None
        if i < self.next_threshold:
            # no adjustment yet
            return None
        new_weights = None
        while self.next_threshold is not None and self.next_threshold <= i:
            self.next_threshold = self.schedule_steps.pop(0)
            new_weights = []
            for key in self.keys:
                new_weights.append(self.mixing_weights[key].pop(0))
        return new_weights

    def min_bucket_size(self):
        sums = []
        for tpl in zip(*self.mixing_weights.values()):
            sums.append(sum(tpl))
        return max(sums)

class TaskMixer():
    def __init__(self, data_config, task_streams, bucket_size=2048):
        self.data_config = data_config
        self.task_streams = task_streams
        self.keys = sorted(self.task_streams.keys())

        self.schedule = MixingWeightSchedule(data_config, self.keys)
        self.current_weights = None
        min_bucket_size = self.schedule.min_bucket_size()
        if bucket_size < min_bucket_size:
            bucket_size = min_bucket_size
            logger.info('increased bucket_size to {}'.format(bucket_size))
        self.bucket_size = bucket_size

    def __call__(self):
        self.maybe_adjust_mix(0)
        mixed = self.mix()
        bucketed = self.bucket(mixed)
        yield from bucketed

    def mix(self):
        # using this while-try-next construction in order to allow
        # self.mixed to be replaced by mix weight schedule while looping
        while True:
            try:
                yield next(self.mixed)
            except StopIteration:
                break

    def bucket(self, stream):
        stream = iter(stream)
        while True:
            bucket = list(itertools.islice(stream, self.bucket_size))
            if len(bucket) == 0:
                break
            yield bucket

    def maybe_adjust_mix(self, i):
        new_weights = self.schedule(i)
        if new_weights is not None:
            self.current_weights = new_weights
            logger.info('*** mb %s set weights to %s',
                        i, list(zip(self.keys, self.current_weights)))
        self.mixed = weighted_roundrobin(
            [self.task_streams[key] for key in self.keys],
            self.current_weights)

def build_mixer(data_config, transforms, is_train=True, bucket_size=1):
    split = 'train' if is_train else 'valid'
    task_epochs = {}
    task_streams = {}
    for task in data_config['tasks']:
        if data_config['tasks'][task]['split'] != split:
            continue
        task_epoch = TaskEpoch(data_config, task)
        if is_train:
            stream = yield_infinite(task_epoch,
                                    task,
                                    transforms[task],
                                    is_train=is_train)
        else:
            # yield validation data only once
            stream = yield_once(task_epoch,
                                task,
                                transforms[task],
                                is_train=is_train)
        task_epochs[task] = task_epoch
        task_streams[task] = stream
    mixer = TaskMixer(data_config, task_streams, bucket_size=bucket_size)
    return mixer, task_epochs


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

from odoo import models, api, _

class ReportAccountAgedPartner(models.AbstractModel):
    _inherit = "account.aged.partner"

    @api.model
    def _lines(self, context, line_id=None):
        sign = -1.0 if self.env.context.get('aged_balance') else 1.0
        lines = []
        results, total, amls = self.env['report.account.report_agedpartnerbalance']._get_partner_move_lines([self._context['account_type']], self._context['date_to'], 'posted', 30)
        for values in results:
            if line_id and values['partner_id'] != line_id:
                continue
            vals = {
                'id': values['partner_id'] and values['partner_id'] or -1,
                'name': values['name'],
                'level': 0 if values['partner_id'] else 2,
                'type': values['partner_id'] and 'partner_id' or 'line',
                'footnotes': context._get_footnotes('partner_id', values['partner_id']),
                'columns': [values['direction'], values['4'], values['3'], values['2'], values['1'], values['0'], values['total']],
                'trust': values['trust'],
                'unfoldable': values['partner_id'] and True or False,
                'unfolded': values['partner_id'] and (values['partner_id'] in context.unfolded_partners.ids) or False,
            }
            vals['columns'] = [self._format(sign * t) for t in vals['columns']]
            vals['columns'].insert(0, '')
            lines.append(vals)
            if values['partner_id'] in context.unfolded_partners.ids:
                for line in amls[values['partner_id']]:
                    aml = line['line']
                    display_name = aml.invoice_id and aml.invoice_id.display_name or ''
                    vals = {
                        'id': aml.id,
                        'name': aml.move_id.name if aml.move_id.name else '/',
                        'move_id': aml.move_id.id,
                        'action': aml.get_model_id_and_name(),
                        'level': 1,
                        'type': 'move_line_id',
                        'footnotes': context._get_footnotes('move_line_id', aml.id),
                        'columns': [line['period'] == 6-i and self._format(sign * line['amount']) or '' for i in range(7)],
                    }
                    vals['columns'].insert(0, display_name)
                    lines.append(vals)
                vals = {
                    'id': values['partner_id'],
                    'type': 'o_account_reports_domain_total',
                    'name': _('Total '),
                    'footnotes': self.env.context['context_id']._get_footnotes('o_account_reports_domain_total', values['partner_id']),
                    'columns': [values['direction'], values['4'], values['3'], values['2'], values['1'], values['0'], values['total']],
                    'level': 1,
                }
                vals['columns'] = [self._format(sign * t) for t in vals['columns']]
                vals['columns'].insert(0, '')
                lines.append(vals)
        if total and not line_id:
            total_line = {
                'id': 0,
                'name': _('Total'),
                'level': 0,
                'type': 'o_account_reports_domain_total',
                'footnotes': context._get_footnotes('o_account_reports_domain_total', 0),
                'columns': [total[6], total[4], total[3], total[2], total[1], total[0], total[5]],
            }
            total_line['columns'] = [self._format(sign * t) for t in total_line['columns']]
            total_line['columns'].insert(0, '')
            lines.append(total_line)
        return lines

class AccountContextAgedReceivable(models.TransientModel):
    _inherit = "account.context.aged.receivable"

    def get_columns_names(self):
        return [_('Invoice Number'), _("Not due on   %s") % self.date_to, _("0 - 30"), _("30 - 60"), _("60 - 90"), _("90 - 120"), _("Older"), _("Total")]

    @api.multi
    def get_columns_types(self):
        return ["text", "number", "number", "number", "number", "number", "number", "number"]

class AccountContextAgedPayable(models.TransientModel):
    _inherit = "account.context.aged.payable"

    def get_report_obj(self):
        return self.env['account.aged.payable']

    def get_columns_names(self):
        return [_('Invoice Number'), _("Not due on   %s") % self.date_to, _("0 - 30"), _("30 - 60"), _("60 - 90"), _("90 - 120"), _("Older"), _("Total")]

    @api.multi
    def get_columns_types(self):
        return ["text", "number", "number", "number", "number", "number", "number", "number"]


#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import argparse
import json
from collections import OrderedDict

import sys

import boto
import boto.ec2
import os
import providers

def main():
    is_cgi = providers.is_cgi()
    working_dir = providers.get_opscode_root()
    scripts_dir = os.path.join(working_dir, 'operation_code', 'toolchain', 'rundeck', 'scripts')
    sys.path.insert(0, scripts_dir)
    import oobe
    import aws
    import utilities

    if is_cgi:
        args, form = providers.parse_default_cgi_vars()
        args['prefix'] = form['prefix'].value
        args['suffix'] = form['suffix'].value
    else:
        parser = argparse.ArgumentParser(description='Get AMIs.')
        providers.setup_default_args(parser)
        parser.add_argument('--prefix', help="Prefix of AMI Names.", default='OOBE_AMAZON_')
        parser.add_argument('--suffix', help="Suffix of AMI Names.", default=r'\d+\.\d+\.\d+_\d+\.\d+\.\d+')
        args = oobe.parse_args(parser)

    oobe.setup_logging(args['app_log_level'], args['other_log_level'], lambda: providers.rundeck_log_file_name(args['project'], args['environment']))
    logger = utilities.get_logger(__name__)
    temp_dir = None
    try:
        logger.info("Using [%s] and [%s]" % (args['prefix'], args['suffix']))
        deployment_config, temp_dir = oobe.setup_deployment_vars(args, working_dir)

        ec2 = boto.ec2.connect_to_region(args['region'])
        values = [];
        for image in aws.list_images(ec2, args['prefix'], args['suffix']):
            values.append({"name": image.name, "value": image.id})
        print("Content-Type: application/json")  # HTML is following
        print("\n")  # blank line, end of headers
        print(json.dumps(values))
    finally:
        oobe.cleanup(temp_dir)

if __name__ == '__main__':
    main()


import unittest

from svmlight import Model

class ModelTestCase(unittest.TestCase):
    def test_construction_creates_invalid_model(self):
        m = Model()
        self.assertRaises(ValueError, m.__getattribute__, 'bias')

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


# coding: utf-8

import unittest

class BidirectionalSearchTest(unittest.TestCase):

    def setUp(self):
        self.size = 3
        self.goal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
        self.panel_list = []

    def testA(self):
        self.panel_list = [5, 4, 2, 6, 7, 0, 8, 1, 3]

        front_puzzle, back_puzzle = bidirectional_search(self.size, self.goal, self.panel_list)

        self.assertTrue(32 >= len(front_puzzle.state_list) + len(back_puzzle.state_list))

    def testB(self):
        self.panel_list = [8, 6, 7, 2, 5, 4, 3, 0, 1]

        front_puzzle, back_puzzle = bidirectional_search(self.size, self.goal, self.panel_list)

        self.assertEqual(32, len(front_puzzle.state_list) + len(back_puzzle.state_list))

    def testC(self):
        self.panel_list = [6, 4, 7, 8, 5, 0, 3, 2, 1]

        front_puzzle, back_puzzle = bidirectional_search(self.size, self.goal, self.panel_list)

        self.assertEqual(32, len(front_puzzle.state_list) + len(back_puzzle.state_list))

class Queue:

    def __init__(self, puzzle):
        self.puzzle_list = []

        self.puzzle_list.append(puzzle)

    def enqueue(self, puzzle):
        self.puzzle_list.append(puzzle)

    def dequeue(self):
        return self.puzzle_list.pop(0)

    def is_empty(self):
        return len(self.puzzle_list) == 0

class Puzzle:

    def __init__(self, panel_list, state_list, size, direction):
        self.panel_list = panel_list
        self.state_list = state_list
        self.state_list.append(panel_list)
        self.size = size
        self.direction = direction

    def gene_next_panel(self, puzzle):
        zero_pos = puzzle.panel_list.index(0)

        col = zero_pos // self.size
        raw = zero_pos % self.size

        def __get_next_panel():
            panel_list = puzzle.panel_list[:]
            n = panel_list[next_pos]
            panel_list[next_pos] = 0
            panel_list[zero_pos] = n
            return panel_list

        if self.size > col + 1:
            next_pos = (col + 1) * self.size + raw
            panel_list = __get_next_panel()
            yield tuple(panel_list)

        if col - 1 >= 0:
            next_pos = (col - 1) * self.size + raw
            panel_list = __get_next_panel()
            yield tuple(panel_list)

        if self.size > raw + 1:
            next_pos = col * self.size + raw + 1
            panel_list = __get_next_panel()
            yield tuple(panel_list)

        if raw - 1 >= 0:
            next_pos = col * self.size + raw - 1
            panel_list = __get_next_panel()
            yield tuple(panel_list)

    def result_print(self):

        for s in self.state_list:
            print(s)

    def back_result_print(self):

        for s in self.state_list[::-1]:
            print(s)

def bidirectional_search(size, goal, panel_list):
    start_puzzle = Puzzle(panel_list, [], size, 'S')
    queue = Queue(start_puzzle)
    goal_puzzle = Puzzle(goal, [], size, 'G')
    queue.enqueue(goal_puzzle)

    checked_dict = {}
    checked_dict[tuple(panel_list)] = start_puzzle
    checked_dict[tuple(goal)] = goal_puzzle

    while queue.is_empty() is False:
        puzzle = queue.dequeue()

        for next_panel in puzzle.gene_next_panel(puzzle):

            if next_panel in checked_dict:
                checked_puzzle = checked_dict[next_panel]

                if checked_puzzle.direction != puzzle.direction:
                    return puzzle, checked_puzzle

            else:
                new_puzzle = Puzzle(list(next_panel), puzzle.state_list[:], size, puzzle.direction)
                checked_dict[next_panel] = new_puzzle
                queue.enqueue(new_puzzle)

if __name__ == '__main__':
    size = 3
    goal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
    panel_list = [5, 4, 2, 6, 7, 0, 8, 1, 3]

    front_puzzle, back_puzzle = bidirectional_search(size, goal, panel_list)

    front_puzzle.result_print()
    back_puzzle.back_result_print()

    unittest.main()


import torch
from torch import nn
from torch import optim
from copy import deepcopy

class BaseModel(nn.Module):
    def __init__(self,sequential=None):
        super(BaseModel,self).__init__()
        self.sequential = sequential

    def forward(self, x):
        if self.sequential:
            out = self.sequential(x)
            return out
        return None

    def predict(self,x_test):
        self.eval()
        y_pred = self(x_test)
        return y_pred

    def predict_dataloader(self,loader):
        self.eval()
        total_loss = 0.0
        acc = 0.0
        for data in test_loader:
            img, y_train = data
            #img = img.view(img.size(0), -1)
            y_pred = self(img)

            loss = self.loss_fn(y_pred, y_train)
            total_loss += loss.data.item()

            _, pred = torch.max(y_pred, 1)
            num_correct = (pred == y_train).sum()
            acc += num_correct.data.item()

        print(total_loss/len(loader),acc/32/len(loader))

    def save(self,path):
        torch.save(self.state_dict(), path)

    def compile(self,optimizer,loss,metrics=None):

        self.optimizer = optimizer(self.parameters(), lr=1e-4)
        self.loss_fn = loss()
        if metrics is not None:
            self.metrics = metrics()

    def fit_dataloader(self,loader):
        num_epochs = 100
        for epoch in range(num_epochs):

            batch_loss = 0.0
            batch_acc = 0.0
            step = 300
            for i,data in enumerate(loader):
                img,y_train = data
                #print('input size:',img.size())
                y_pred = self(img)
                #print(y_pred.size())
                #y_pred = self(img.view(img.size()[0],-1))

                #计算当前批次的准确率（max:返回每列最大的，第二个返回值是对应的下标)
                _, pred = torch.max(y_pred, 1)
                num_correct = (pred == y_train).sum()
                batch_acc += num_correct.data.item()

                # 反向传播
                self.optimizer.zero_grad()
                loss = self.loss_fn(y_pred, y_train)

                #计算当前批次的损失
                batch_loss += loss.data.item()

                loss.backward()
                self.optimizer.step()

                if (i+1) % step == 0:
                    print('Epoch[{}/{}],batch:{}, avg loss: {:.6f},train acc:{:.6f}'
                          .format(epoch + 1, num_epochs,i+1, batch_loss/step,batch_acc/(step*32)))
                    batch_loss = 0.0
                    batch_acc = 0.0

    def fit(self, x_train, y_train):
        # 开始训练
        num_epochs = 1000
        for epoch in range(num_epochs):
            y_pred = self(x_train)
            # 这里顺序不能反，前者是预测值out，后者是target

            # backward
            self.optimizer.zero_grad()
            loss = self.loss_fn(y_pred, y_train)
            loss.backward()
            self.optimizer.step()

            if (epoch + 1) % 20 == 0:
                print('Epoch[{}/{}], loss: {:.6f}'
                      .format(epoch + 1, num_epochs, loss.data.item()))

# 线性模型
class LinearRegression(BaseModel):
    def __init__(self):
        super(LinearRegression, self).__init__()
        self.linear = nn.Linear(1, 1)  # input and output is 1 dimension

    def forward(self, x):
        out = self.linear(x)
        return out

# 定义 Logistic Regression 模型
class Logstic_Regression(BaseModel):
    def __init__(self, in_dim, n_class):
        super(Logstic_Regression, self).__init__()
        self.logstic = nn.Linear(in_dim, n_class)

    def forward(self, x):
        out = self.logstic(x)
        return out

class MLP(BaseModel):
    def __init__(self,n_input,n_hidden_1,n_hidden_2,n_output):
        super(MLP,self).__init__()
        self.layer1 = nn.Linear(n_input,n_hidden_1)
        self.layer2 = nn.Linear(n_hidden_1,n_hidden_2)
        self.layer3 = nn.Linear(n_hidden_2,n_output)

    def forward(self, x):
        out =  self.layer1(x)
        out = self.layer2(out)
        out = self.layer3(out)
        return out

# 定义 Convolution Network 模型
class Cnn(BaseModel):
    def __init__(self, in_dim, n_class):
        super(Cnn, self).__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(in_dim, 6, 3, stride=1, padding=1),
            nn.ReLU(True),
            nn.MaxPool2d(2, 2),
            nn.Conv2d(6, 16, 5, stride=1, padding=0),
            nn.ReLU(True), nn.MaxPool2d(2, 2))

        self.fc = nn.Sequential(
            nn.Linear(400, 120), nn.Linear(120, 84), nn.Linear(84, n_class))

    def forward(self, x):
        out = self.conv(x)
        out = out.view(out.size(0), -1)
        out = self.fc(out)
        return out

# 定义 Recurrent Network - LSTM模型
class Lstm(BaseModel):
    def __init__(self, in_dim, hidden_dim, n_layer, n_class):
        super(Lstm, self).__init__()
        self.n_layer = n_layer
        self.hidden_dim = hidden_dim
        self.lstm = nn.LSTM(in_dim, hidden_dim, n_layer, batch_first=True)
        self.classifier = nn.Linear(28*hidden_dim, n_class)

    def forward(self, x):
        out, _ = self.lstm(x)
        #print(type(out),out.size())
        out = out[:, -1, :] #这里直接把（32，28，128） => (32,128)，直接扔掉？
        #out = out.view(32,-1) view操作竟然不行
        #print(out.size())
        out = self.classifier(out)
        return out

import numpy as np
def test_linear2():
    seq = nn.Sequential(
        nn.Linear(1,1)
    )
    model = BaseModel(seq)
    model.compile(optimizer=optim.SGD, loss=nn.MSELoss)
    x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
                        [9.779], [6.182], [7.59], [2.167], [7.042],
                        [10.791], [5.313], [7.997], [3.1]])

    y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
                        [3.366], [2.596], [2.53], [1.221], [2.827],
                        [3.465], [1.65], [2.904], [1.3]])

    model.fit(torch.Tensor(x_train), torch.Tensor(y_train))
    y_pred = model.predict(torch.Tensor(x_train))

    data = y_pred.data

    import matplotlib.pyplot as plt
    plt.plot(x_train, y_pred.data.numpy(), label='Fitting Line')
    plt.show()

def test_linear():
    model = LinearRegression()
    model.compile(optimizer=optim.SGD,loss=nn.MSELoss)

    x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
                        [9.779], [6.182], [7.59], [2.167], [7.042],
                        [10.791], [5.313], [7.997], [3.1]])

    y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
                        [3.366], [2.596], [2.53], [1.221], [2.827],
                        [3.465], [1.65], [2.904], [1.3]])

    model.fit(torch.Tensor(x_train),torch.Tensor(y_train))
    y_pred = model.predict(torch.Tensor(x_train))

    data = y_pred.data

    import matplotlib.pyplot as plt
    plt.plot(x_train, y_pred.data.numpy(), label='Fitting Line')
    plt.show()

    model.save('./mymodel.pth')

def test_logistic(loader):
    model = Logstic_Regression(28 * 28, 10)  # 图片大小是28x28
    model.compile(optimizer=optim.SGD,loss=nn.CrossEntropyLoss)
    model.fit_dataloader(loader)

def test_MLP(loader,test_loader):
    model = MLP(28*28,300,100,10)
    model.compile(optimizer=optim.SGD,loss=nn.CrossEntropyLoss)
    model.fit_dataloader(loader)
    model.predict_dataloader(test_loader)

def test_cnn(loader,test_loader):
    model = Cnn(1,10)
    model.compile(optimizer=optim.SGD, loss=nn.CrossEntropyLoss)
    model.fit_dataloader(loader)
    model.predict_dataloader(test_loader)

def test_lstm(loader,test_loader):
    model = Lstm(28, 128, 2, 10)  # 图片大小是28x28
    model.compile(optimizer=optim.Adam, loss=nn.CrossEntropyLoss)
    model.fit_dataloader(loader)
    model.predict_dataloader(test_loader)

class LstmTrans(object):
    def __call__(self, pic):
        out = pic.squeeze(0)# 1x28x28 =>28x28,把channel压缩掉
        return out

    def __repr__(self):
        return self.__class__.__name__ + '()'

class Trans(object):
    def __call__(self, pic):
        #print('pic:',pic.size())
        out = pic.view(-1)
        #print('out',out.size())
        return out

    def __repr__(self):
        return self.__class__.__name__ + '()'

if __name__ == '__main__':
    from torchvision import datasets,transforms
    from torch.utils.data import DataLoader

    composed = transforms.Compose([transforms.ToTensor(),
                                  LstmTrans()])

    train_dataset = datasets.MNIST(
        root='./data', train=True, transform=composed, download=True)

    test_dataset = datasets.MNIST(
        root='./data', train=False, transform=composed)

    train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
    test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)

    #test_linear()
    #test_MLP(train_loader,test_loader)
    #test_cnn(train_loader,test_loader)
    test_lstm(train_loader,test_loader)


class Solution(object):
    def twoSum(self, n):
        """
        :type n: int
        :rtype: List[float]
        """
        minVal = n
        maxVal = n*6
        prob = [0] * (n+1)
        prob[0] = 1
        for i in range(1,n+1):
            prob[i] = prob[i-1] * (n-i+1) / i
        res = []
        base = (1/6) ** n
        res.append(1)
        for i in range(1, maxVal + 1 - minVal):
            curRes = 0
            if ((i-1) % 5 == 0):
                left = (i-1) // 5 + 1
                right = n  if i > n else i
                for j in range(left, right + 1):
                    curRes += prob[j]
            else:
                if i < n:
                    curRes += prob[i]
                    curRes += res[-1]
                else:
                    curRes = res[-1]
            res.append(curRes)
        for i in range(len(res)):
            res[i] *= base
        return res
'''
一直想用概率的方法求出来
但是一直都不行，好难算
发现人家是用dp来做的
好气
'''
a = Solution()
print(a.twoSum(2))
print("Done")


"""
eklogi Response Utilities

This module contains utility functions for constructing JSON API responses.
"""
import json
import time
import traceback

from flask import Response, request

def response(data, *, success=True, status=200, response_time=None):
    """
    Generates a JSON response given a serializable data object.

    The data object is serialized to JSON to represent the data of the response.

    :param data: the data object to be serialized
    :param success: the flag for whether the response is a success
    :param status: the http response code
    :param response_time the response time
    :return: a JSON response
    """
    # is True may seem redundant, but allows for truthy values to always be
    # serialized to a bool
    req = {'method': request.method,
           'path': request.path,
           'args': request.args,
           'timestamp': int(time.time()),
           'status': status}
    if response_time:
        req['response_time'] = response_time
    res = {'success': success is True,
           'request': req,
           'data': data}
    return Response(response=json.dumps(res, indent=2, separators=(',', ': ')),
                    status=status,
                    mimetype='application/json')

def error_response(error, *, message=None, status=500):
    """
    Generates an error JSON response given an error object.

    The http response code defaults to '500' to represent internal server error.

    Any caught client errors, e.g. malformed requests, should specify the accurate response code.

    :param error: the error object
    :param message: the error message
    :param status: the http response code
    :return: an error JSON response
    """
    res = {'error': type(error).__name__ if isinstance(
        error, BaseException) else error,
           'message': message or ''}
    return response(res, success=False, status=status)

def apply(f):
    """
    Applies a function to return a result that can be returned as a JSON response.

    All errors are caught and returned within a JSON error response.

    :param f: the function to apply
    :return: a success response if no error occurred during applying f, otherwise an error response
    """
    try:
        begin = time.time()
        data = f()
        diff = time.time() - begin
        diff_str = "{}s".format(int(diff)) if int(diff) else \
            "{}ms".format(int(diff * 1000)) if int(diff * 1000) else \
                "{}ns".format(int(diff * 1000000))
        return response(data, response_time=diff_str)
    except Exception as e:  # pylint: disable=broad-except
        traceback.print_exc()
        return error_response(e)


from os import makedirs
from os.path import join
from os.path import exists

import sys
import logging
from rainbow_logging_handler import RainbowLoggingHandler

def configure_logging(name, base=None):
    log = logging.getLogger()
    log.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s %(name)-38s %(levelname)-7s - %(message)s")

    #ch = logging.StreamHandler(sys.stderr)
    ch = RainbowLoggingHandler(sys.stderr, color_name=('red', 'black', True))
    ch.setFormatter(formatter)
    log.addHandler(ch)

    if base is not None:
        fh = logging.handlers.RotatingFileHandler(
                join(base, '%s.log' % name),
                maxBytes=(262144),
                backupCount=10)

        fh.setFormatter(formatter)
        log.addHandler(fh)


from django.conf.urls import url

from App import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(\d+)/$', views.index, name='index1'),
    url(r'^post/$',views.manage_post,name='post'),
    url(r'^add/(\w+)/$',views.add_post,name='add'),
    url(r'^one/$',views.one2one,name='one'),

]


#! /usr/bin/env python3

import sys

filename = sys.argv[1]

from collections import Counter

count = 0

hexamers_5 = Counter()
hexamers_3 = Counter()

for line in open(filename):
    line = line.rstrip()

    if count == 0:
       count += 1

    elif count == 1:
       seq = line
       count += 1

    elif count == 2:
       count += 1

    elif count == 3:
       count = 0

       hexamer_5 = seq[0:6]
       hexamer_3 = seq[-6:]
       hexamers_5[hexamer_5] += 1
       hexamers_3[hexamer_3] += 1

for hexamer, count in hexamers_5.most_common(1):
    print("The most common hexamer at 5':", hexamer, count)

for hexamer, count in hexamers_3.most_common(1):
    print("The most common hexamer at 3':", hexamer, count)


# -*- coding: utf-8 -*-
"""
Created on Fri Sep 25 08:08:58 2020

@author: seelc
"""
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn import tree
from sklearn.metrics import accuracy_score

df = pd.read_csv("C:\\Users\\seelc\\OneDrive\\Desktop\\Projects\\Titanic Kaggle\\train.csv")

#First cleaning up the age column, if their age is empty set equal to the median age
df['Age'] = df['Age'].fillna(df['Age'].median())

#Cleaning up the cabin column. If there is no cabin listed set equal to zero
df['Cabin'] = df['Cabin'].fillna("None")

ticket_int = df['Ticket'].copy().rename("ticket_int")
ticket_str = df['Ticket'].copy().rename("ticket_str")

#Splitting ticket into two columns one with the integer and one with the string
for index, value in ticket_int.items():
    value = value.split(" ")
    print(value)
    print(len(value))
    if len(value) == 1:
        ticket_str[index] = 0
        ticket_int[index] = value[0]
    elif len(value) == 2:
        ticket_int[index] = value[1]
        ticket_str[index] = value[0]

df = pd.concat([df, ticket_int, ticket_str], axis = 1, sort = False)

'''Visualization'''
fig, axes = plt.subplots(2,2)

axes[0,0].scatter(df['Pclass'], df['Fare'],c = df['Survived'])
axes[0,0].set_title('Ticket cost and Class')
axes[0,0].set_xlabel('PClass')
axes[0,0].set_ylabel('Ticket Cost')

axes[0,1].scatter(df['Age'], df['Sex'], c = df['Survived'])
axes[0,1].set_title('Gender and Age')
axes[0,1].set_xlabel('Age')
axes[0,1].set_ylabel('Gender')

axes[1,0].scatter(df['PassengerId'], df['Parch'], c = df['Survived'])
axes[1,0].set_title('Children and Survival Rate')
axes[1,0].set_xlabel('Passeger ID')
axes[1,0].set_ylabel('Number of Children')

fig.tight_layout()
plt.show()

'''First decision tree with minimum sized dataframe'''
first_df = df[["Sex", "Pclass", "Age", "Fare", "Survived"]].copy()

#First encoding categorical variables
label_encoder = LabelEncoder()
first_df["Sex"] = label_encoder.fit_transform(first_df["Sex"])

#No scaling required in decision tree, splitting data into train and test
x_train, x_test, y_train, y_test = train_test_split(first_df[["Sex", "Pclass", "Age", "Fare"]],
                                                    first_df["Survived"], test_size = 0.2, random_state = 42)

first_tree = DecisionTreeClassifier(max_depth = 3)
first_predictor= first_tree.fit(x_train, y_train)

#Predicting outcomes on test and train sets
test_prediction = first_predictor.predict(x_test)
train_prediction = first_predictor.predict(x_train)

#Visualizing results
fig = plt.figure(figsize=(25,20))
tree.plot_tree(first_predictor)

#Determining the model accuracy
test_score = accuracy_score(y_test, test_prediction)
train_score = accuracy_score(y_train, train_prediction)
print("Test Accuracy: ", test_score)
print("Train Accuracy: ", train_score)


# Databricks notebook source
# MAGIC
# MAGIC %md
# MAGIC ## Example 2-1 M&M Count

# COMMAND ----------

from pyspark.sql.functions import *

mnm_file = "/databricks-datasets/learning-spark-v2/mnm_dataset.csv"

# COMMAND ----------

# MAGIC %md
# MAGIC ### Read from the CSV and infer the schema

# COMMAND ----------

mnm_df = (spark
          .read
          .format("csv")
          .option("header", "true")
          .option("inferSchema", "true")
          .load(mnm_file))

display(mnm_df)

# COMMAND ----------

# MAGIC %md
# MAGIC ### Aggregate count of all colors and groupBy state and color, orderBy descending order

# COMMAND ----------

count_mnm_df = (mnm_df
                .select("State", "Color", "Count")
                .groupBy("State", "Color")
                .agg(count("Count").alias("Total"))
                .orderBy("Total", ascending=False))

count_mnm_df.show(n=60, truncate=False)
print("Total Rows = %d" % (count_mnm_df.count()))

# COMMAND ----------

# MAGIC %md
# MAGIC ### Find the aggregate count for California by filtering on State

# COMMAND ----------

ca_count_mnm_df = (mnm_df.filter(mnm_df.State == "CA")
                   .select("State", "Color", "Count")
                   #.where(mnm_df.State == "CA")
                   .groupBy("State", "Color")
                   .agg(count("Count").alias("Total"),sum("Count").alias("Sum") )
                   .orderBy("Total", ascending=False))

ca_count_mnm_df.show(n=10, truncate=False)

# COMMAND ----------


import serial
import _winreg as winreg
import itertools
import time

def enumerate_serial_ports():
    """ Uses the Win32 registry to return a iterator of serial
        (COM) ports existing on this computer.
    """

    path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
    try:
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
    except WindowsError:
        raise IterationError

    for i in itertools.count():
        try:
            val = winreg.EnumValue(key, i)
            yield (str(val[1]), str(val[0]))
        except EnvironmentError:
            break

def main():

    comPorts=[]
    for i in enumerate_serial_ports():
        comPorts.append(i)

    for i in comPorts:
        print(i)

    com= comPorts[0]

    com= com[0]
    ser = serial.Serial(
                port= com,
                baudrate=115200,
                bytesize=serial.EIGHTBITS,
                timeout=3  )
    while(True):

        ser.flush()
        line="-";
        while 'A' not in line:
            line= ser.readline()
            line.strip();
            print('Looking for A')
            print(line)

        ser.write('list\0')
        time.sleep(1)
        line= ser.readline();
        while(line != "end\n"):
            print(line)
            line= ser.readline()

if __name__ == '__main__':
    main()


"""Provides iTrack reporting functions"""
import functools
from datetime import datetime, timedelta

import numpy as np
import pandas as pd
from pandas.tseries.offsets import BDay
import matplotlib.pyplot as plt
import seaborn as sns

from . import api
from ..utils.recipes import const, bool2int
from ..auth import BasicAuth

sns.set(style='white')
sns.set_palette(sns.color_palette("Paired"))

AUTH = BasicAuth.from_env('ITRACK')
SERVER = ('itrack.barco.com', 443)
TODAY = datetime.today().date()
LAST_YEAR = TODAY - timedelta(days=356)
BLUE, DARK_BLUE, GREEN, DARK_GREEN, RED, DARK_RED = sns.color_palette()
MARKERS = ['D', '*', 'o', 'v', '^', '<', '>', '1', '2', '3', '4', 's', 'p',
           ',', 'h', 'H', '+', 'x', '.', 'd']

def add_metadata(data, config, pqm=True, experience=True):
    """
    Adds PQM and Experience metadata to `data`.

    Parameters
    ----------
    data -- pandas.DataFrame
    config -- dict
        Mapping with the PQM configuration
    pqm, experience -- bool
        Flags indicating whether or not to add the respective column
    """
    df = data.copy()
    if pqm:
        df['PQM'] = df.project.map(lambda x: config.get(x, 'Other'))
    if experience:
        df['Experience'] = df.project.map(
            lambda x: config.get(x, 'Other-').split('-')[0]
        )
    return df

def add_measures(data):
    """
    Adds the measures columns to `data`.

    Parameters
    ----------
    data -- pandas.DataFrame
    """

    def _busday(start, end, n=1):
        def _inner(df):
            return ((df[start].fillna(TODAY) + BDay(n) >= df[end].fillna(TODAY))
                    .map(bool2int))
        return _inner

    measures = ('N', 'FRT_10', 'TRT_20')
    funcs = (const(1), _busday('created', 'investigated', n=10),
             _busday('created', 'closuredate', n=20))

    df = data.copy().assign(
        **{k: func for k, func in zip(measures, funcs)}
    )

    # these measures make no sense for the recent dates --> clear these
    for measure, n in zip(measures[1:], (10, 20)):
        df.loc[df.created >= TODAY - BDay(n), measure] = np.nan

    return df

def calculate_trend(data, start=LAST_YEAR):
    """
    Calculates trend measures for `data`.

    Parameters
    ----------
    data -- pandas.DataFrame
    """
    def _timeseries(data, x='created', y='N', agg='sum', freq='B'):
        return (data.rename(columns={x:'DT'}).set_index('DT').sort_index()
                .resample(freq)[y].agg(agg).fillna(0))

    return pd.DataFrame(dict(
        created=_timeseries(data),
        resolved=_timeseries(data, x='closuredate'),
        FRT_10=_timeseries(data, y='FRT_10', agg='mean'),
        TRT_20=_timeseries(data, y='TRT_20', agg='mean')
    ))[start:]

def load(config, start=LAST_YEAR):
    """
    Returns the active and hist aspect of the iTrack report.

    Parameters
    ----------
    config -- dict
        Mapping with a 'pqms' key with the project to PQM mapping
    """

    # load the history
    JQL = 'filter=26769 and (created > {0:%Y-%m-%d} or closed > {0:%Y-%m-%d})'
    jql = JQL.format(start)
    hist = api.search(
        jql, auth=AUTH, server=SERVER
    ).pipe(add_metadata, config['pqms']).pipe(add_measures)

    # load the active
    active = api.search(
        'filter=27347', auth=AUTH, server=SERVER
    ).pipe(add_metadata, config['pqms'])

    return active, hist

def pyplot(title=None, xlabel=None, ylabel=None, legend=True):
    """
    Decorator factory adding formatting matplotlib Axes returned from decorated
    function.

    Parameters
    ----------
    title -- Unicode
        the title to add to the Axes
    xlabel -- Unicode
        the label of the X-axis of the Axes
    ylabel -- Unicode
        the label of the Y-axis of the Axes
    legend -- bool
        whether or not to show the legend
    """
    def _decorator(func):
        @functools.wraps(func)
        def _wrapper(*args, **kwargs):
            ax = func(*args, **kwargs)
            if title is not None:
                ax.set_title(title, loc='left')
            if xlabel is not None:
                ax.set_xlabel(xlabel)
            if ylabel is not None:
                ax.set_ylabel(ylabel)
            if legend:
                ax.legend(loc='best', fancybox=True, framealpha=0.5)
            sns.despine(ax=ax)
            return ax
        return _wrapper
    return _decorator

@pyplot(
    title='Age vs. Idle (active)',
    xlabel='Age (BD)', ylabel='Idle (BD)'
)
def age_vs_idle_scatter(data, ax):
    """
    Plots Age vs. Idle of `data` on Axes `ax`.

    Parameters
    ----------
    data -- pandas.DataFrame
    ax -- matplotlib.axes.Axes
    """
    groups = data.groupby('status')
    kws = dict(alpha=0.9, ls='')
    for lbl, grp, m in zip(*zip(*groups), MARKERS):
        ax.plot(grp.age, grp.idle, label=lbl, marker=m, **kws)
    return ax

@pyplot(
    title='Priority vs. Severity (active)',
    ylabel='Tickets'
)
def priority_vs_severity_bars(data, ax):
    """
    Plots priority vs. severity of `data` on Axes `ax`.

    Parameters
    ----------
    data -- pandas.DataFrame
    ax -- matplotlib.axes.Axes
    """
    data.copy().assign(N=1).groupby(
        ['priority', 'severity']
    ).N.sum().unstack().plot.bar(stacked=True, ax=ax)
    return ax

@pyplot(
    title='Status (active)', legend=False
)
def status_pie(data, ax, n=4):
    """
    Plots status pie chart of `data` on Axes `ax`.

    Parameters
    ----------
    data -- pandas.DataFrame
    ax -- matplotlib.axes.Axes
    """
    ys = data.status.value_counts()
    selected = ys.nlargest(n)
    other = sum(v for k, v in ys.items() if k not in selected.index.tolist())
    items = list(selected.items()) + [('Other', other)] if other > 0 else list(selected.items())
    labels, sizes = zip(*items)
    ax.pie(sizes, labels=labels, autopct='%1.0f%%', shadow=True)
    return ax

@pyplot(
    title='PQM (active)', legend=False
)
def pqm_pie(data, ax, n=4):
    """
    Plots PQM pie chart of `data` on Axes `ax`.

    Parameters
    ----------
    data -- pandas.DataFrame
    ax -- matplotlib.axes.Axes
    """
    ys = data.PQM.value_counts()
    selected = ys.nlargest(n)
    other = sum(v for k, v in ys.items() if k not in selected.index.tolist())
    items = list(selected.items()) + [('Other', other)] if other > 0 else list(selected.items())
    labels, sizes = zip(*items)
    ax.pie(sizes, labels=labels, autopct='%1.0f%%', shadow=True)
    return ax

@pyplot(
    title='Created vs. Resolved (CUMUL)',
    ylabel='Tickets'
)
def created_vs_resolved_cumul(data, ax):
    """
    Plots created vs. resolved (cumulative) of `data` on Axes `ax`.

    Parameters
    ----------
    data -- pandas.DataFrame
    ax -- matplotlib.axes.Axes
    """
    columns = ('created', 'resolved')
    x = data.index
    ys = [data[col].cumsum() for col in columns]
    for y, lbl, color in zip(ys, ['Created', 'Resolved'], [RED, GREEN]):
        ax.plot(x, y, label=lbl, color=color)
    y1, y2 = ys
    ax.fill_between(x, y1, y2, where=y1 >= y2, facecolor=RED, alpha=0.1)
    ax.fill_between(x, y2, y1, where=y2 >= y1, facecolor=GREEN, alpha=0.1)
    return ax

@pyplot(
    title='Unresolved (CUMUL)',
    ylabel='Tickets'
)
def unresolved_cumul(data, ax):
    """
    Plots unresolved (cumulative) of `data` on Axes `ax`.

    Parameters
    ----------
    data -- pandas.DataFrame
    ax -- matplotlib.axes.Axes
    """
    x = data.index
    y = data.created.cumsum() - data.resolved.cumsum()
    ax.plot(x, y, label='$\Delta$ Unresolved', color=BLUE)
    return ax

@pyplot(
    title='Created vs. Resolved (7MA)',
    ylabel='Tickets'
)
def created_vs_resolved_rolling(data, ax):
    """
    Plots created vs. resolved (7MA) of `data` on Axes `ax`.

    Parameters
    ----------
    data -- pandas.DataFrame
    ax -- matplotlib.axes.Axes
    """
    columns = ('created', 'resolved')
    x = data.index
    ys = [data[col].rolling(7).mean() for col in columns]
    for y, lbl, color in zip(ys, ['Created', 'Resolved'], [RED, GREEN]):
        ax.plot(x, y, label=lbl, color=color)
    y1, y2 = ys
    ax.fill_between(x, y1, y2, where=y1 >= y2, facecolor=RED, alpha=0.1)
    ax.fill_between(x, y2, y1, where=y2 >= y1, facecolor=GREEN, alpha=0.1)
    return ax

@pyplot(
    title='Responsiveness (7MA)',
    ylabel='Percentage'
)
def responsiveness_rolling(data, ax):
    """
    Plots responsiveness (7MA) of `data` on Axes `ax`.

    Parameters
    ----------
    data -- pandas.DataFrame
    ax -- matplotlib.axes.Axes
    """
    columns = ('FRT_10', 'TRT_20', 'created')
    x = data.index
    y1, y2, total = [data[col].rolling(7).mean() for col in columns]
    y1.loc[TODAY - pd.tseries.offsets.BDay(10):] = np.nan
    y2.loc[TODAY - pd.tseries.offsets.BDay(20):] = np.nan
    ax.plot(x, y1 * 100 / total, label='% Investigated < 10BD', color=BLUE, ls='--')
    ax.plot(x, y2 * 100 / total, label='% Resolved < 20BD', color=BLUE)
    ax.set_ylim([0, 100])
    return ax

def plot(active, trend, options):

    fig = plt.figure(figsize=(11, 11))
    fig.suptitle(options['name'])

    grid_specs = [(0, 0, 3, 1), (1, 0, 3, 1), (2, 0, 3, 1), (3, 0, 3, 1),
                  (0, 3, 3, 1), (1, 3, 3, 1), (2, 3, 3, 1), (3, 3, 3, 1),]

    axes = [plt.subplot2grid((4, 5), (x, y), colspan=c, rowspan=r)
            for x, y, c, r in grid_specs]

    created_vs_resolved_cumul(trend, axes[0])
    unresolved_cumul(trend, axes[1])
    created_vs_resolved_rolling(trend, axes[2])
    responsiveness_rolling(trend, axes[3])
    age_vs_idle_scatter(active, axes[4])
    status_pie(active, axes[5])
    priority_vs_severity_bars(active, axes[6])
    pqm_pie(active, axes[7])

    plt.tight_layout()
    fig.subplots_adjust(bottom=0.1, top=0.9)

    created = int(trend.created.sum())
    resolved = int(trend.resolved.sum())
    high = len(active.query('severity == "S1" | priority == "P1"'))
    total = len(active)

    txt1 = r'Trend: {:d} created and {:d} resolved in last 356 days'.format(
        created, resolved
    )
    fig.text(0.5, 0.04, txt1, horizontalalignment='center')
    txt2 = r'Active: {:d} total and {:d} P1/S1'.format(total, high)
    fig.text(0.5, 0, txt2, horizontalalignment='center')

    return fig


#!/usr/bin/env python3

# Leon: Hero 273 -- A game made for a 48-hour game jam.
# Copyright (C) 2014 JT-Dev

# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:

# 1. The above copyright notice and this permission notice shall be included in
#    all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import pygame

import g
import utils
import constants
import sys

class TitleScreen(object):
	class Button(object):
		#0 Button Not Down
		#1 Button Down

		def __init__(self, pos, image_up, image_down, main, screen):
			self.image_up = image_up
			self.image_down = image_down
			self.rect = pygame.Rect(pos, self.image_up.get_rect().size)

			self.main = main
			self.screen = screen
			self.state = 0

		def clicked(self):
			if not self.screen:
				pygame.quit()
				sys.exit()

			self.main.running = False
			g.screen = self.screen

		def draw(self, surface):
			if self.state:
				surface.blit(self.image_down, self.rect)
			else:
				surface.blit(self.image_up, self.rect)

	def __init__(self, loader):
		self.background = loader.load("sprites/logo.png","image").convert_alpha()
		self.background = pygame.transform.scale(self.background, (constants.SCREEN_WIDTH // 2, constants.SCREEN_HEIGHT // 2))

		self.music = loader.load("sounds/titlescreen/music.ogg", "sound")
		self.music.play(loops=-1)

		g.deaths = 0

		self.running = True
		self.buttons = []

		play_button = self.Button((10, 100),
			loader.load("sprites/buttons/play_up.png", "image").convert_alpha(),
			loader.load("sprites/buttons/play_down.png", "image").convert_alpha(),
			self, g.screen_map["info"]
		)

		credit_button = self.Button((10, 155),
			loader.load("sprites/buttons/credits_up.png", "image").convert_alpha(),
			loader.load("sprites/buttons/credits_down.png", "image").convert_alpha(),
			self, g.screen_map["credit"]
		)

		quit_button = self.Button((10, 210),
			loader.load("sprites/buttons/quit_up.png", "image").convert_alpha(),
			loader.load("sprites/buttons/quit_down.png", "image").convert_alpha(),
			self, None
		)

		self.buttons.append(play_button)
		self.buttons.append(credit_button)
		self.buttons.append(quit_button)

	def update(self, inputmanager):
		clicked = False

		for button in self.buttons:
			if not inputmanager.click_pos:
				break

			if button.rect.collidepoint(inputmanager.click_pos):
				if inputmanager.click_state:
					button.state = 1
				else:
					clicked = True
					button.clicked()
			elif button.state:
				button.state = 0

		if clicked:
			self.music.stop()
			inputmanager.reset()

	def draw(self, surface):
		x = (constants.SCREEN_WIDTH - self.background.get_width()) // 2
		y = (constants.SCREEN_HEIGHT - self.background.get_height()) // 2

		surface.blit(self.background, (x, y))

		for button in self.buttons:
			button.draw(surface)

	def peek(self):
		return not self.running


import pandas as pd

from flask import (
    Flask,
    render_template,
    jsonify)

from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# The database URI
app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///wine_review.sqlite"

db = SQLAlchemy(app)

# Create database tables
@app.before_first_request
def setup():
    # Recreate database each time for demo
    #db.drop_all()
    db.create_all()

@app.route("/")
def home():

    # Find data
    review_data = SQLAlchemy.db.wine_review.find_one()
    print(review_data)
    # return template and data
    return render_template("index.html", review_data = review_data)

if __name__ == '__main__':
    app.run(debug=True)


import torchvision
from torch.utils.data import random_split, DataLoader
from pytorch_lightning import LightningDataModule
import typing as tp

class CelebaDataModule(LightningDataModule):

    def __init__(
            self,
            data_dir: str = "celeba",
            image_shape: int = (128, 128),
            batch_size: int = 32,
            num_workers: int = 32,
            validation_len: tp.Union[int, float] = 500,
            attributes: tp.List[str] = ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Male', 'Young'],
            **kwargs
    ):
        self.transforms = torchvision.transforms.Compose([
            torchvision.transforms.Resize(image_shape),
            torchvision.transforms.ToTensor(),
            torchvision.transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
        ])
        attrs = '5_o_Clock_Shadow ' \
                'Arched_Eyebrows ' \
                'Attractive ' \
                'Bags_Under_Eyes ' \
                'Bald ' \
                'Bangs ' \
                'Big_Lips ' \
                'Big_Nose ' \
                'Black_Hair ' \
                'Blond_Hair ' \
                'Blurry ' \
                'Brown_Hair ' \
                'Bushy_Eyebrows ' \
                'Chubby ' \
                'Double_Chin ' \
                'Eyeglasses ' \
                'Goatee ' \
                'Gray_Hair ' \
                'Heavy_Makeup ' \
                'High_Cheekbones ' \
                'Male ' \
                'Mouth_Slightly_Open ' \
                'Mustache ' \
                'Narrow_Eyes ' \
                'No_Beard ' \
                'Oval_Face ' \
                'Pale_Skin ' \
                'Pointy_Nose ' \
                'Receding_Hairline ' \
                'Rosy_Cheeks ' \
                'Sideburns ' \
                'Smiling ' \
                'Straight_Hair ' \
                'Wavy_Hair ' \
                'Wearing_Earrings ' \
                'Wearing_Hat ' \
                'Wearing_Lipstick ' \
                'Wearing_Necklace ' \
                'Wearing_Necktie ' \
                'Young'
        attr2index = {j: i for i, j in enumerate(attrs.split())}
        self.attributes = attributes
        self.label_subset_indices = [attr2index[j] for j in self.attributes]
        super().__init__()
        self.data_dir = data_dir
        self.batch_size = batch_size
        self.num_workers = num_workers
        self.validation_len = validation_len
        self.image_shape = image_shape

    def target_transform(self, label):
        return label[self.label_subset_indices]

    def setup(self, stage=None):
        self.celeba = torchvision.datasets.CelebA(self.data_dir, target_type='attr', transform=self.transforms,
                                                  target_transform=self.target_transform, download=True)
        if isinstance(self.validation_len, float):
            self.validation_len = int(self.validation_len * len(self.celeba))
        self.train_dataset, self.val_dataset = random_split(self.celeba,
                                                            lengths=[len(self.celeba) - self.validation_len,
                                                                self.validation_len])

    def train_dataloader(self):
        return DataLoader(self.train_dataset, self.batch_size, shuffle=True,
                          num_workers=self.num_workers)

    def val_dataloader(self):
        return DataLoader(self.val_dataset, self.batch_size, shuffle=False,
                          num_workers=self.num_workers)

    # def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]:
    #     pass


"""

This module contains functions needed to evaluate post selection
p-values for non polyhedral selection procedures through a variety of means.

These p-values appear for the group LASSO global null test as well as the nuclear norm
p-value test.

They are described in the `Kac Rice`_ paper.

.. _Kac Rice: http://arxiv.org/abs/1308.3020
.. _Spacings: http://arxiv.org/abs/1401.3889
.. _post selection LASSO: http://arxiv.org/abs/1311.6238

"""

import numpy as np
from scipy.stats import chi

from scipy.stats import norm as ndist, truncnorm
from scipy.integrate import quad

from mpmath import mp
mp.dps = 80

def norm_q(prob):
    r"""
    A multi-precision calculation of the
    standard normal quantile function:

    .. math::

       \int_{-\infty}^{q(p)} \frac{e^{-z^2/2}}{\sqrt{2\pi}} \; dz = p

    where $p$ is `prob`.

    Parameters
    ----------

    prob : float

    Returns
    -------

    quantile : float

    """
    return np.array(mp.erfinv(2*prob-1)*mp.sqrt(2))

def norm_pdf(observed):
    r"""
    A multi-precision calculation of the
    standard normal density function:

    .. math::

       \frac{e^{-T^2/2}}{\sqrt{2\pi}}

    where `T` is observed.

    Parameters
    ----------

    observed : float

    Returns
    -------

    density : float

    """
    return np.array(mp.npdf(observed))

def norm_interval(lower, upper):
    r"""
    A multiprecision evaluation of

    .. math::

        \Phi(U) - \Phi(L)

    Parameters
    ----------

    lower : float
        The lower limit $L$

    upper : float
        The upper limit $U$

    """
    if lower > 0 and upper > 0:
        return mp.ncdf(-lower) - mp.ncdf(-upper)
    else:
        return mp.ncdf(upper) - mp.ncdf(lower)

def truncnorm_cdf(observed, lower, upper):
    r"""
    Compute the truncated normal
    distribution function.

    .. math::

        \frac{\Phi(U) - \Phi(T)}{\Phi(U) - \Phi(L)}

    where $T$ is `observed`, $L$ is `lower_bound` and $U$ is `upper_bound`.

    Parameters
    ----------

    observed : float

    lower : float

    upper : float

    Returns
    -------

    P : float

    """
    x, a, b = observed, lower, upper

    x = max(x, a)
    x = min(x, b)

    if a > 0 and b > 0:
        Fx, Fa, Fb = mp.ncdf(-x), mp.ncdf(-a), mp.ncdf(-b)
        return float( ( Fa - Fx ) / ( Fa - Fb ) )
    else:
        Fx, Fa, Fb = mp.ncdf(x), mp.ncdf(a), mp.ncdf(b)
        return float( ( Fx - Fa ) / ( Fb - Fa ) )

def chi_pvalue(observed, lower_bound, upper_bound, sd, df, method='MC', nsim=1000):
    r"""

    Compute a truncated $\chi$ p-value based on the
    conditional survival function.

    Parameters
    ----------

    observed : float

    lower_bound : float

    upper_bound : float

    sd : float
        Standard deviation.

    df : float
        Degrees of freedom.

    method: string
        One of ['MC', 'cdf', 'sf']

    Returns
    -------

    pvalue : float

    Notes
    -----

    Let $T$ be `observed`, $L$ be `lower_bound` and $U$ be `upper_bound`,
    and $\sigma$ be `sd`.
    The p-value, for $L \leq T \leq U$ is

    .. math::

         \frac{P(\chi^2_k / \sigma^2 \geq T^2) - P(\chi^2_k / \sigma^2 \geq U^2)}
         {P(\chi^2_k / \sigma^2 \geq L^2) - P(\chi^2_k / \sigma^2 \geq U^2)}

    It can be computed using `scipy.stats.chi` either its `cdf` (distribution
    function) or `sf` (survival function) or evaluated
    by Monte Carlo if method is `MC`.

    """

    L, T, U = lower_bound, observed, upper_bound # shorthand

    if method == 'cdf':
        pval = ((chi.cdf(U / sd, df) - chi.cdf(T / sd, df)) /
                (chi.cdf(U / sd, df) - chi.cdf(L / sd, df)))
    elif method == 'sf':
        pval = ((chi.sf(U / sd, df) - chi.sf(T / sd, df)) /
                (chi.sf(U / sd, df) - chi.sf(L / sd, df)))
    elif method == 'MC':
        if df == 1:
            H = []
        else:
            H = [0]*(df-1)
        pval = general_pvalue(T / sd, L / sd, U / sd, H, nsim=nsim)
    else:
        raise ValueError('method should be one of ["cdf", "sf", "MC"]')
    if pval == 1: # the distribution functions may have failed -- use MC
        pval = general_pvalue(T / sd, L / sd, U / sd, H, nsim=50000)
    if pval > 1:
        pval = 1
    return pval

def gauss_poly(lower_bound, upper_bound, curvature, nsim=100):
    r"""
    Computes the integral of a polynomial times the
    standard Gaussian density over an interval.

    Introduced in `Kac Rice`_, display (33) of v2.

    Parameters
    ----------

    lower_bound : float

    upper_bound : float

    curvature : np.array
        A diagonal matrix related to curvature.
        It is assumed that `curvature + lower_bound I` is non-negative definite.

    nsim : int
        How many draws from $N(0,1)$ should we use?

    Returns
    -------

    integral : float

    Notes
    -----

    The return value is a Monte Carlo estimate of

    .. math::

        \int_{L}^{U} \det(\Lambda + z I)
        \frac{e^{-z^2/2\sigma^2}}{\sqrt{2\pi\sigma^2}} \, dz

    where $L$ is `lower_bound`, $U$ is `upper_bound` and $\Lambda$ is the
    diagonal matrix `curvature`.

    """

    T, H = lower_bound, curvature
    Z = np.fabs(np.random.standard_normal(nsim))
    keep = Z < upper_bound - T
    proportion = keep.sum() * 1. / nsim
    Z = Z[keep]
    if H != []:
        HT = H + T
        exponent = np.log(np.fabs(np.add.outer(Z, HT))).sum(1) - T*Z - T**2/2.
    else:
        exponent = - T*Z - T**2/2.
    C = exponent.max()

    return np.exp(exponent - C).mean() * proportion, C

def general_pvalue(observed, lower_bound, upper_bound, curvature, nsim=100):

    r"""
    Computes the integral of a polynomial times the
    standard Gaussian density over an interval.

    Introduced in `Kac Rice`_, display (35) of v2.

    Parameters
    ----------

    observed : float

    lower_bound : float

    upper_bound : float

    curvature : np.array
        A diagonal matrix related to curvature.
        It is assumed that `curvature + lower_bound I` is non-negative definite.

    nsim : int
        How many draws from $N(0,1)$ should we use?

    Returns
    -------

    integral : float

    Notes
    -----

    The return value is a Monte Carlo estimate of

    .. math::

        \frac{\int_{T}^{U} \det(\Lambda + z I)
        \frac{e^{-z^2/2\sigma^2}}{\sqrt{2\pi\sigma^2}} \, dz}
        {\int_{L}^{U} \det(\Lambda + z I)
        \frac{e^{-z^2/2\sigma^2}}{\sqrt{2\pi\sigma^2}} \, dz}

    where $T$ is `observed`, $L$ is `lower_bound`,
    $U$ is `upper_bound` and $\Lambda$ is the
    diagonal matrix `curvature`.

    """

    exponent_1, C1 = gauss_poly(observed, upper_bound, curvature, nsim=nsim)
    exponent_2, C2 = gauss_poly(lower_bound, upper_bound, curvature, nsim=nsim)

    return np.exp(C1-C2) * exponent_1 / exponent_2

class SelectionInterval(object):
    """
    Compute a selection interval for
    a Gaussian truncated to an interval.
    """

    def __init__(self, lower_bound, observed, upper_bound, sigma):
        self.lower_bound, self.observed, self.upper_bound, self.sigma = lower_bound, observed, upper_bound, sigma

    def pivot(self, exp):
        L, obs, U, sd = self.lower_bound, self.observed, self.upper_bound, self.sigma
        return truncnorm_cdf((obs-exp)/sd, (L-exp)/sd, (U-exp)/sd)

    def conf_int(self, lb, ub, alpha=0.05):
        F = lambda exp: self.pivot(exp)
        L = _find_root(F, 1.0 - 0.5 * alpha, lb, ub)
        U = _find_root(F, 0.5 * alpha, L, ub)
        return L, U

def _find_root(f, y, lb, ub, tol=1e-6):
    """
    searches for solution to f(x) = y in (lb, ub), where
    f is a monotone decreasing function
    """

    # make sure solution is in range
    a, b   = lb, ub
    fa, fb = f(a), f(b)

    # assume a < b
    if fa > y and fb > y:
        while fb > y :
            b, fb = b + (b-a), f(b + (b-a))
    elif fa < y and fb < y:
        while fa < y :
            a, fa = a - (b-a), f(a - (b-a))

    # determine the necessary number of iterations
    max_iter = int( np.ceil( ( np.log(tol) - np.log(b-a) ) / np.log(0.5) ) )

    # bisect (slow but sure) until solution is obtained
    for _ in xrange(max_iter):
        c, fc  = (a+b)/2, f((a+b)/2)
        if fc > y: a = c
        elif fc < y: b = c

    return c


"""
    Author:Hemanth Kumar Veeranki
    Nick:Harry7

    This File is one of modules written for the game Donkey Kong

"""

import pygame
from random import randint as rand

"""

Map values for
1. Coins -   2
2. Fireball- 5
3. Ladders - 3
4. Walls and Floors - 1

"""

__author__="Hemanth Kumar Veeranki"
__version__ = "1.0.1"
__maintainer__ = "Hemanth Kumar Veeranki"
__email__ = "hemanth.veeranki@students.iiit.ac.in"
__status__ = "Development"

class Fireball:

    """ This Class basically deals with all tasks of Fireballs """

    def __init__(self):

        """
        This is default constructor. It initialises all variable
        1.Xpos contains x co-ordinates of fireballs similarly the Ypos has heights
        2.side determines which side the fireball has to move
        """

        self.Xpos=[]
        self.Ypos=[]
        self.side=[]
        self.infall=[]
        self.image=pygame.image.load('fireball.jpg')
        self.image=pygame.transform.scale(self.image,(15,20))
        self.rect=self.image.get_rect()
    def checkWall(self,Map,x,y):
        return Map[y][x]==1
    def Makefireballs(self,Map,xpos,ypos):

        """

        This Functions generates a fireball from monkey
        It takes the Map,Xpos,Ypos variables of Board class's instance created

        """

        if(Map[ypos][xpos]==0):
            Map[ypos][xpos]=5
            self.Xpos.append(xpos)
            self.Ypos.append(ypos)
            self.side.append(1)
            self.infall.append(0)

    def DrawFireball(self,Map,display):

        """

        This Functions Draws Fireballs to the display
        It takes Map variable of Board class instance created and display surface as variables

        """

        x=15
        y=20
        for k in xrange(len(self.Xpos)):
            j=self.Xpos[k]
            i=self.Ypos[k]
            if Map[i][j]>=5 and Map[i][j]!=100:
                    rect=self.rect
                    rect=rect.move((j*x,i*y))
                    display.blit(self.image,rect)

    def move(self,game):

        """

         This function takes care of moving fireballs and eliminating them if they go to the end
         It takes instance of Board class created in main_game file

        """

        # We store indices of fireballs came to the end in this variable
        marked=[]
        for i in range(len(self.Xpos)):

            x=self.Xpos[i]
            y=self.Ypos[i]
            s=self.side[i]
            #Instead of making its value as 5 we add 5 and when removing we subtract 5 so as to  take care of fireball coming onto other objects
            game.Map[y][x]-=5

            #This decides the probability of going down the ladder or getting down through end of floor

            p=rand(0,1)

            # Taking care of Ladders and getting down through a ladder
            if self.infall[i]==1:
                y+=1
                if game.Map[y+1][x]!=0:
                    self.infall[i]=0
            elif p==1 and  game.Map[y+1][x]==3:
                y+=1
                if self.checkWall(game.Map,x,y):
                    y-=1
            elif game.Map[y][x]==3 and game.Map[y+1][x]!=1:
                y+=1
                if self.checkWall(game.Map,x,y):
                    y-=1

            elif game.Map[y-1][x]==3 and game.Map[y+1][x]==3:
                y+=1
                if self.checkWall(game.Map,x,y):
                    y-=1
            elif y==28:
                    x-=1
                    if x==1:
                        game.Map[y][x]-=5
                        marked.append(i)
            elif self.side[i]==1:

                # Dealing with normal moovment on floor
                x+=1
                if self.checkWall(game.Map,x,y):
                    self.side[i]=0
                    x-=2
            else:

                # Dealing with normal moovment on floor

                x-=1
                if self.checkWall(game.Map,x,y):
                    x+=2
                    self.side[i]=1

            if self.infall[i]!=1 and game.Map[y][x]==0 and game.Map[y+1][x]==0:
                self.infall[i]=1
            game.Map[y][x]+=5

            self.Xpos[i]=x
            self.Ypos[i]=y

            marked.sort()
            j=0
        # Eliminating the ones which reached the end

        for i in marked:
                self.Xpos.pop(i-j)
                self.Ypos.pop(i-j)
                self.side.pop(i-j)
                j+=1

        #Same as above


#載入LineBot所需要的套件
from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import *

import re
import mongodb

app = Flask(__name__)

# 必須放上自己的Channel Access Token
line_bot_api = LineBotApi('ebe0/QaFkSufFT7V8JzKU67yo1s9zK6ujgFzPeEftnZ/F0j3AGesJZuedpHmDtCapJF+f3dMZmtT3weqtVzU73ic1kumQTJAVKHkF+Nz3fNvxPbLXr14cNhS6IcWC2JRGVMfTCNcHplz3nJrcoysbwdB04t89/1O/w1cDnyilFU=')
# 必須放上自己的Channel Secret
handler = WebhookHandler('30c48e179824500fb837c06a79dbc750')

line_bot_api.push_message('Ub72a3a6d716f44d30d2ec6be9a5c0c5e', TextSendMessage(text='你可以開始了'))

# 監聽所有來自 /callback 的 Post Request
@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        abort(400)

    return 'OK'
'''
#訊息傳遞區塊
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    message = TextSendMessage(text=event.message.text)
    line_bot_api.reply_message(event.reply_token,message)
'''

#訊息傳遞區塊
@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    ### 抓到顧客的資料 ###
    profile = line_bot_api.get_profile(event.source.user_id)
    uid = profile.user_id #使用者ID
    usespeak=str(event.message.text) #使用者講的話
    line_bot_api.push_message(uid, TextSendMessage(usespeak))
    if re.match('[0-9]{4}[<>][0-9]',usespeak): # 先判斷是否是使用者要用來存股票的
        line_bot_api.push_message(uid, TextSendMessage('測試儲存'))
        mongodb.write_user_stock_fountion(stock=usespeak[0:4], bs=usespeak[4:5], price=usespeak[5:])
        line_bot_api.push_message(uid, TextSendMessage(usespeak[0:4]+'已經儲存成功'))
        return 0

    elif re.match('刪除[0-9]{4}',usespeak): # 刪除存在資料庫裡面的股票
        mongodb.delete_user_stock_fountion(stock=usespeak[2:])
        line_bot_api.push_message(uid, TextSendMessage(usespeak+'已經刪除成功'))
        return 0

#主程式
import os
if __name__ == "__main__":
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)


# -*- coding: utf-8 -*-
#
from .surface_base import SurfaceBase

class Rectangle(SurfaceBase):
    """
    Creates a rectangle.

    x0 : array-like[3]
         The 3 first expressions define the lower-left corner.
    a : float
        Rectangle width.
    b : float
        Rectangle height.
    corner_radius : float
        Defines a radius to round the rectangle corners.
    char_length : float
        Characteristic length of the mesh elements of this polygon.
    """

    def __init__(self, x0, a, b, corner_radius=None, char_length=None):
        super(Rectangle, self).__init__()

        assert len(x0) == 3

        self.x0 = x0
        self.a = a
        self.b = b
        self.corner_radius = corner_radius
        self.char_length = char_length

        args = list(x0) + [a, b]
        if corner_radius is not None:
            args.append(corner_radius)

        args = ", ".join(["{}".format(arg) for arg in args])

        self.code = "\n".join(
            [
                "{} = news;".format(self.id),
                "Rectangle({}) = {{{}}};".format(self.id, args),
            ]
            + self.char_length_code(char_length)
        )
        return