import logging

import azure.functions as func
# from Utils import ReadTagContainer,UpdateTagContainer, DeleteTagContainer, CreateTagContainer
# from EncryptionDecryption import encrypt_message,decrypt_message
import json
import time
from geopy.distance import geodesic
import os, sys

from os.path import dirname, join, abspath
sys.path.insert(0, abspath(join(dirname(__file__), '..')))

from Utils import ReadTagContainer,UpdateTagContainer, DeleteTagContainer, CreateTagContainer

def main(req: func.HttpRequest) -> func.HttpResponse:
    response_message = "Nothing happened."
    try:
        try:
            req_body = req.get_json()
        except Exception:
            req_body = req.form
        # response_message = EncryptValuesOfDictionary(req_body)
        # print("thi is obj" + str(response_message))
        # response_message = DecryptValuesOfDictionary(response_message)
        # print("thi is obj" + str(response_message))
        # return func.HttpResponse(body=str(response_message))
        submittedid = str(req_body.get('uidtid')) if 'uidtid' in req_body else ""
        submittedcode = str(req_body.get('code')) if 'code' in req_body else ""
        # ip = str(req_body.get('ip')) if 'ip' in req_body else ""
        ip = req.headers['x-forwarded-for'] if 'x-forwarded-for' in req.headers else ""

        logging.info("--------------- IP is: " + ip + "---------------")
        action = str(req_body.get('action')).lower() if 'action' in req_body else ""
        scannedby = str(req_body.get('user')) if 'user' in req_body else ""
        LatLocation = req_body.get('Lat') if 'Lat' in req_body else ""
        LonLocation = req_body.get('Lon') if 'Lon' in req_body else ""
        distance = req_body.get('distance') if 'distance' in req_body else ""
        description = req_body.get('description') if 'description' in req_body else ""

        if submittedid and submittedcode:
            id = "--RFID:" + submittedid + "--CODE:" + submittedcode + "--"
        elif submittedid == "" and submittedcode:
            id = "--CODE:" + submittedcode + "--"
        elif submittedcode == "" and submittedid:
            id = "--RFID:" + submittedid
        else:
            id = ""

        #filter junk out
        id = id.replace("\t","")
        id = id.replace("\n","")
        id = id.replace("\"","")
        ip = ip.replace("\t","")
        ip = ip.replace("\n","")
        ip = ip.replace("\"","")
        action = action.replace("\t","")
        action = action.replace("\n","")
        action = action.replace("\"","")
        scannedby = scannedby.replace("\t","")
        scannedby = scannedby.replace("\n","")
        scannedby = scannedby.replace("\"","")
        LatLocation = LatLocation.replace("\t","")
        LatLocation = LatLocation.replace("\n","")
        LatLocation = LatLocation.replace("\"","")
        LonLocation = LonLocation.replace("\t","")
        LonLocation = LonLocation.replace("\n","")
        LonLocation = LonLocation.replace("\"","")
        description = description.replace("\t","")
        description = description.replace("\n","")
        description = description.replace("\"","")

        # if action is enroll new record
        if action and action == "enroll":
            tag_obj = {}
            tag_obj['id'] = id
            tag_obj['status'] = 'enrolled'
            tag_obj['clientid'] = scannedby
            tag_obj['isDeleted'] = 0
            tag_obj['description'] = description
            scan = {}
            scan["id"] = 0
            scan['scannedby'] = scannedby
            scan['datetime'] = str(int(round(time.time() * 1000)))
            scan['ip'] = ip
            scan['LatLocation'] = LatLocation
            scan['LonLocation'] = LonLocation
            scan['distance'] = distance
            scan['mph'] = 0
            scans_array = list()
            scans_array.append(scan)
            tag_obj["scans"] = scans_array
            already_obj = ReadTagContainer(id)
            if already_obj and "status" in already_obj and already_obj["status"] == "assigned":
                response_message = "Enrollment error as object has already assigned status"
            elif already_obj:
                tag_obj["id"] = already_obj["id"]
                response = UpdateTagContainer(tag_obj)
                if response:
                    response_message = "Enrolled "+ id
                else:
                    response_message = "Enrollment error"
            else:
                response = CreateTagContainer(tag_obj)
                if response:
                    response_message = "Enrolled "+ id
                else:
                    response_message = "Enrollment error"

        # if action is void delete db record
        elif action and action == "void":
            response = DeleteTagContainer(id)
            if response:
                response_message = "deleted "+ id
            else:
                response_message = "Error, can't delete the record."

        # read record and add scan
        elif action and action == "checkinverify":
            tag_obj = ReadTagContainer(id)
            if tag_obj and "status" in tag_obj and tag_obj["status"] == "assigned":
                response_message = "Enrollment error as object has already assigned status"
            elif not tag_obj:
                response_message = "No Record"
            else:
                already_scans = list(tag_obj["scans"])
                last_scans = already_scans[len(tag_obj["scans"])-1]
                scan = {}
                scan["id"] = len(already_scans)
                scan['scannedby'] = scannedby
                scan['datetime'] = str(int(round(time.time() * 1000)))
                scan['ip'] = ip
                scan['LatLocation'] = LatLocation
                scan['LonLocation'] = LonLocation
                scan['distance'] = distance
                scan['mph'] = 0
                #compute distance from last scan
                speed = 0
                scan['distance'] = geodesic((last_scans['LatLocation'],last_scans['LonLocation']), (scan['LatLocation'],scan['LonLocation'])).miles
                if scan['distance'] <= 0:
                    scan['distance'] = 0.001
                #compute time from last scan
                timeinhours = round(((int(scan['datetime']) - int(last_scans['datetime']))/1000)/3600,32)
                if timeinhours <= 0:
                    timeinhours = 0.001
                #compute speed one must travel to get between both points in the given time
                speedmph = round(int(scan['distance'])/timeinhours,32)
                #speed = (int(scan['distance'])/((int(scan['datetime']) - int(last_scans['datetime']))/1000)/3600)
                # if speed is greater than 90 it is considered counterfiet
                if speedmph >= 90:
                    response_message = "counterfeit " + str(speedmph) + " mph"
                        #response_message = response_message + " \ndistance from last scan is " + str(scan['distance']) + " miles, which would need to travel at " + str(speedmph) + " mph.\n>90mph, so failed"
                        # update db record by new scand adding data
                elif speedmph < 90:
                    response_message = "Verified OK if product scanned matches the registered description, which is: \n\n" + tag_obj['description'] + "\n\nOpportunity to put photo of item here?"
                    response_message = response_message + " \ntime from last scan is " + str(timeinhours) + " (hrs)\ndistance from last scan is " + str(scan['distance']) + " miles, which would need to travel at " + str(speedmph) + " mph.\n<90mph, so approved"
                    #response_message = response_message + "

"
                scan['mph'] = speedmph
                already_scans.append(scan)
                tag_obj["scans"] = already_scans
                UpdateTagContainer(tag_obj)
    except Exception as ex:
        response_message = "An unhandled error occured: " + str(ex)

    #response_message = response_message + "

Go Back"
    #response_message = ""+response_message+""
    return func.HttpResponse(body=response_message)


# -*- encoding: utf-8 -*-
'''
Current module: pyrunner.p_applog

Rough version history:
v1.0    Original version to use
v2.0    define some normal functions for this module which act as Log Center
********************************************************************
    @AUTHOR:  Administrator-Bruce Luo(罗科峰)
    MAIL:    lkf20031988@163.com
    RCS:      rock4.common.p_applog,v 2.0 2017年2月7日
    FROM:     2015年4月14日
********************************************************************

======================================================================

Provide a package for the log

'''

import os,logging

class AppLog():
    ''' record the logs with your preference  '''
    def __init__(self,logger_name,level = "debug",filename = None,hand2screen = False,strf = ""):
        '''Initial a AppLog instance.
        Sample usage:
            AppLog("bruce_luo")
        '''
        self.logger=self.__getAppLogger(logger_name)
        self.level_list=["NOTSET","DEBUG","INFO","WARNING","ERROR","CRITICAL"]

        if strf:
            self.format_str = strf
        else:
            self.format_str = '#%(asctime)s  %(filename)s[line:%(lineno)-4d] %(levelname)-8s:%(message)s'

        self.__set_basic_config(level.upper(), filename)
        if hand2screen:
            self.__handle2screen(level.upper())

    def tolog(self,str_value,level = 'debug'):
        getattr(self.logger,level.lower())(str_value)

    def __set_format_str(self,strf):
        ''' define a format for logging . notice that you should use this after logging obj created if need
        Sample usage:
            test = AppLog()
            test.set_format_str(r'[line:%(lineno)-4d]#%(levelname)-8s: #%(filename)-20s->%(message)s')
            test.set_format_str(r'#%(asctime)s  %(filename)s[line:%(lineno)-4d] %(levelname)-8s:%(message)s')
        '''
        self.format_str = strf

    def __set_basic_config(self,lev,filename=None):
        ''' Will not save log if filename is None
        Sample usage:
            set_basic_config("DEBUG","d:/auto/buffer/sample.log")
            set_basic_config("DEBUG","sample.log")
            set_basic_config("DEBUG")
        '''
        lev_up = lev.upper()

        if filename:
            file_abs_path = os.path.abspath(os.path.dirname(filename))
            if not os.path.isdir(file_abs_path):
                raise Exception("\n\tp_applog.py exception 1.0: invalid filename '%s'." %(filename))

        if lev_up in self.level_list:
            logging.basicConfig(level=getattr(logging, lev_up),filename=filename,filemode='w',format=self.format_str)
        else:
            raise Exception("\n\tp_applog.py exception 1.1: invalid level '%s'." %(lev))

    def __handle2screen(self,lev):
        '''Call this function to output logs to screen. Only save log if not call this function
        Sample usage:
            handle2screen("INFO",False)
            handle2screen("INFO")
            handle2screen()
        '''
        if self.logger.handlers:
            return
        lev_up=lev.upper()

        if lev_up in self.level_list:
            self.console = logging.StreamHandler()
            self.console.setLevel(getattr(logging, lev_up))
        else:
            raise Exception("\n\tp_applog.py exception 2.0: invalid level '%s'." %(lev))

        self.formatter = logging.Formatter(self.format_str)
        self.console.setFormatter(self.formatter)

        self.logger.addHandler(self.console)

    def __getAppLogger(self,logger_name):
        '''return the named logger if it exists, creating it with the name if the logger not exists
        Sample usage:
            getAppLogger("bruce_luo")
        '''
        return logging.getLogger(logger_name)

def usage_Applog():
    log=AppLog("test",level = "info",filename = "D:/auto/buffer/test.log",hand2screen = True)

    log.tolog("debug msg")
    log.tolog("info msg",level = "info")
    log.tolog("warning msg",level = "warning")
    log.tolog("error msg",level = "error")
    log.tolog("critical msg",level = "critical")

if __name__=="__main__":
    usage_Applog()


# -*- coding: utf-8 -*-
"""
Created on Fri Sep  6 11:21:35 2019

@author: tascheib
"""

import pandas as pd
import numpy as np
from sklearn.preprocessing import Imputer
data = {'Name': ['John','Paul', np.NaN, 'Wale', 'Mary', 'Carli', 'Steve'],
        'Age': [21,23,np.nan,19,25,np.nan,15],
        'Sex': ['M',np.nan,np.nan,'M','F','F','M'],
        'Goals': [5,10,np.nan,19,5,0,7],
        'Assists': [7,4,np.nan,9,7,6,4],
        'Value': [55,84,np.nan,90,63,15,46]}
df=pd.DataFrame(data, columns =['Name','Age','Sex',
                                'Goals', 'Assists', 'Value'])
values = df[["Age","Goals","Assists","Value"]].values
imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0, verbose = 0, copy = True)
transformed_values = imputer.fit_transform(values)
df_new = pd.DataFrame(transformed_values, columns =['Age','Goals', 'Assists', 'Value'])
print(df_new)
df_new


'''
Created on Nov 13, 2014

@author: mikael
'''
from scripts_inhibition import effect_conns

scale=1
kw={'n_rows':11,
        'n_cols':24,
        'w':72*17.6*2/3./2.54*scale,
        'h':150*scale,
        'fontsize':7*scale,
        'frame_hight_y':0.5,
        'frame_hight_x':0.7,
        'title_fontsize':7*scale,
        'gs_builder':effect_conns.gs_builder_conn2}

kwargs={'data_path':('/home/mikael/results/papers/inhibition/network/'
                    +'milner/simulate_beta_ZZZ_conn_effect_perturb_final/'),
        'from_diks':0,
        'script_name':(__file__.split('/')[-1][0:-3]+'/data'),
        'exclude':['M1', 'M2', 'FS', 'ST','SN',
                   'M1_SN', 'M2_GI','ST_SN', 'FS_FS', 'FS_M1', 'FS_M2',
                   'GI_SN', 'M1_M1', 'M1_M2', 'M2_M1', 'M2_M2',
                   'GI_ST'],

        'do_plots':['firing_rate'],

        'fontsize_x':7*scale,
        'fontsize_y':7*scale,
        'separate_M1_M2':False,

        'clim_raw':[[0,40], [0, 1]],
        'clim_gradient':[[-25, 25], [-0.6, 0.6]],

        'kwargs_fig':kw,
        'fr_label':'Hz',
        'coher_label':'Coherence',
        'title':'Activation (beta)',
        'title_flipped':True,
        'title_ax':3,
        'title_posy':0.9,

        'conn_fig_title_fontsize':7*scale,
        'top_lables_fontsize':7*scale,
        'top_labels_show':True}

obj=effect_conns.Main(**kwargs)
obj.do()


# -*- coding: utf-8 -*-
from mxnet import image
import matplotlib.pyplot as plt
from mxnet import nd
import utils
from mxnet import nd
import sys

sys.path.append('..')
import utils

img = image.imdecode(open('cat.png', 'rb').read())
plt.imshow(img.asnumpy())

# plt.show()

# 图片增广避免过拟合

def apply(img, aug, n=3):
    _, figs = plt.subplots(n, n, figsize=(8, 8))
    for i in range(n):
        for j in range(n):
            # 转成 float,一是因为 aug 需要 float 类型数据来方便做变化。
            # 二是这里会有一次 copy 操作,因为有些 aug 直接通过改写输入
            # (而不是新建输出)获取性能的提升
            x = img.astype('float32')
            # 有些 aug 不保证输入是合法值,所以做一次 clip
            y = aug(x).clip(0, 254)
            # 显示浮点图片时 imshow 要求输入在 [0,1] 之间
            figs[i][j].imshow(y.asnumpy() / 255.0)
            figs[i][j].axes.get_xaxis().set_visible(False)
            figs[i][j].axes.get_xaxis().set_visible(False)
    plt.show()

# 以.5 的概率做翻转
aug1 = image.HorizontalFlipAug(.5)
# 随机裁剪一个块 200 x 200 的区域
aug2 = image.RandomCropAug([200, 200])
# 随机裁剪,要求保留至少 0.1 的区域,随机⻓宽比在.5 和 2 之间。
# 最后将结果 resize 到 200x200
aug3 = image.RandomSizedCropAug((200, 200), .1, (.5, 2))
# 随机将亮度增加或者减小在 0-50% 间的一个量
aug4 = image.BrightnessJitterAug(.5)
# 随机色调变化
aug5 = image.HueJitterAug(.5)

# apply(img, aug5)

def apply_aug_list(img, augs):
    for f in augs:
        img = f(img)
    return img

train_augs = [
    image.HorizontalFlipAug(.5),
    image.RandomCropAug((28, 28))
]
test_augs = [
    image.CenterCropAug((28, 28))
]

from mxnet import gluon
from mxnet import nd
import sys

sys.path.append('..')
import utils

def get_transform(augs):
    def transform(data, label):
        # data: sample x height x width x channel
        # label: sample
        data = data.astype('float32')
        if augs is not None:
            data = apply_aug_list(data, augs)
        data = nd.transpose(data, (2, 0, 1)) / 255
        return data, label.astype('float32')

    return transform

def get_data(batch_size, train_augs, test_augs=None):
    cifar10_train = gluon.data.vision.CIFAR10(
        train=True, transform=get_transform(train_augs))
    cifar10_test = gluon.data.vision.CIFAR10(
        train=False, transform=get_transform(test_augs))
    train_data = gluon.data.DataLoader(
        cifar10_train, batch_size, shuffle=True)
    test_data = gluon.data.DataLoader(
        cifar10_test, batch_size, shuffle=False)
    return (train_data, test_data)

train_data, _ = get_data(36, train_augs)
for imgs, _ in train_data:

    utils.show_images(imgs, 6)
    break

# 定义模型
from mxnet.gluon import nn

# ResNet 18 的hybrid版本
class Residual(nn.HybridBlock):
    def __init__(self, channels, same_shape=True, **kwargs):
        super(Residual, self).__init__(**kwargs)
        self.same_shape = same_shape
        strides = 1 if same_shape else 2
        self.conv1 = nn.Conv2D(channels, kernel_size=3, padding=1,
                               strides=strides)
        self.bn1 = nn.BatchNorm()
        self.conv2 = nn.Conv2D(channels, kernel_size=3, padding=1)
        self.bn2 = nn.BatchNorm()
        if not same_shape:
            self.conv3 = nn.Conv2D(channels, kernel_size=1,
                                   strides=strides)

    def hybrid_forward(self, F, x):
        out = F.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        if not self.same_shape:
            x = self.conv3(x)
        return F.relu(out + x)

def resnet_18(num_classes):
    net = nn.HybridSequential()
    with net.name_scope():
        net.add(
            nn.BatchNorm(),
            nn.Conv2D(64, kernel_size=3, strides=1),
            nn.MaxPool2D(pool_size=3, strides=2),
            Residual(64),
            Residual(64),
            Residual(128, same_shape=False),
            Residual(128),
            Residual(256, same_shape=False),
            Residual(256),
            nn.AvgPool2D(pool_size=3),
            nn.Dense(num_classes)
        )
    return net

from mxnet import init

def train(train_augs, test_augs, learning_rate=.1):
    batch_size = 32
    num_epochs = 10
    ctx = utils.try_gpu()
    loss = gluon.loss.SoftmaxCrossEntropyLoss()
    train_data, test_data = get_data(
        batch_size, train_augs, test_augs)
    net = resnet_18(10)
    net.initialize(ctx=ctx, init=init.Xavier())
    net.hybridize()
    trainer = gluon.Trainer(net.collect_params(),
                            'sgd', {'learning_rate': learning_rate})
    utils.train(
        train_data, test_data, net, loss, trainer, ctx, num_epochs, batch_size)

train(train_augs, test_augs)


"""
  @Author       : liujianhan
  @Date         : 21/3/19 11:06
  @Project      : leetcode_in_python
  @FileName     : 1603.设计停车系统.py
  @Description  : 请你给一个停车场设计一个停车系统。停车场总共有三种不同大小的车位：大，中和小，每种尺寸分别有固定数目的车位。
    请你实现 ParkingSystem 类：
    ParkingSystem(int big, int medium, int small) 初始化 ParkingSystem 类，三个参数分别对应每种停车位的数目。
    bool addCar(int carType) 检查是否有 carType 对应的停车位。 carType 有三种类型：大，中，小，分别用数字 1， 2 和 3 表示。
    一辆车只能停在  carType 对应尺寸的停车位中。如果没有空车位，请返回 false ，否则将该车停入车位并返回 true 。

    示例 1：
    输入：
    ["ParkingSystem", "addCar", "addCar", "addCar", "addCar"]
    [[1, 1, 0], [1], [2], [3], [1]]
    输出：
    [null, true, true, false, false]

    解释：
    ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
    parkingSystem.addCar(1); // 返回 true ，因为有 1 个空的大车位
    parkingSystem.addCar(2); // 返回 true ，因为有 1 个空的中车位
    parkingSystem.addCar(3); // 返回 false ，因为没有空的小车位
    parkingSystem.addCar(1); // 返回 false ，因为没有空的大车位，唯一一个大车位已经被占据了

    提示：
    0 <= big, medium, small <= 1000
    carType 取值为 1， 2 或 3
    最多会调用 addCar 函数 1000 次
"""

class ParkingSystem:

    def __init__(self, big: int, medium: int, small: int):
        self.cargo = {
            1: big,
            2: medium,
            3: small
        }

    def addCar(self, carType: int) -> bool:
        if self.cargo.get(carType):
            self.cargo[carType] -= 1
            return True
        return False

if __name__ == '__main__':
    p = ParkingSystem(1, 1, 0)
    print(p.addCar(1))
    print(p.addCar(2))
    print(p.addCar(3))
    print(p.addCar(1))


# ทำข้อมูลให้เป็น มาตรฐาน 0 -> 1
import uuid

from sklearn.preprocessing import StandardScaler as Sta
from dumpfile import IO

class Sta_:
    def __init__(self,X,pathfile,dump = 1):
        self.X = X
        self.pathfile = pathfile
        self.dump = dump
    def sta(self):  # StandardScaler

        sta_ = Sta()
        sta_.fit(self.X)
        xy_sta = sta_.transform(self.X)
        stapath = str(uuid.uuid4())
        # save ไฟล์ model
        if self.dump == 1:
            IO.add_model_wait_dump(stapath,sta_,self.pathfile)
        return xy_sta, stapath


from __future__ import division

import os
import numpy as np
import nibabel as nib

def normalize_img(img):
    mean = np.mean(img)
    std = np.std(img)
    img -= mean
    img /= std
    return img

def get_2d_patches(input_fold, output_fold, drop_class, file_name):
    """
    Generating 2d patches based on 3d input images.
    :param input_fold: string. Path to the folder with two other folders: images and masks.
                            In turn raw 3d images and masks are stored respectively.
    :param output_fold: string. Path to the output folder with numpy files of images and masks.
                             Inside output folder train and test folder will be generated storing their
                             images and masks respectively.
    :param drop_class: list of integers. List of classes that will be reasigned to background (class 0).
    :param file_name:
    :return: tuple with 4 numpy files. 1.train images, 2.train masks, 3.test images, 4.test masks.
    """

    assert os.path.isdir(input_fold)
    dirs = sorted(os.listdir(os.path.join(input_fold)))

    image_list = []
    segm_list = []
    # For each image (1,2,3,4,5)
    for dir in dirs:

        # Load the Flair image
        flair_img = nib.load(os.path.join(input_fold, dir+'/FLAIR.nii.gz'))
        flair_numpy = flair_img.get_fdata()
        flair_numpy = np.nan_to_num(flair_numpy)
        flair_numpy = flair_numpy.astype('float32')
        flair_numpy = normalize_img(flair_numpy)
        flair_numpy = flair_numpy[..., np.newaxis]

        # Load the Regularized T1 images
        reg_t1_img = nib.load(os.path.join(input_fold, dir + '/reg_T1.nii.gz'))
        reg_t1_numpy = reg_t1_img.get_fdata()
        reg_t1_numpy = np.nan_to_num(reg_t1_numpy)
        reg_t1_numpy = reg_t1_numpy.astype('float32')
        reg_t1_numpy = normalize_img(reg_t1_numpy)
        reg_t1_numpy = reg_t1_numpy[..., np.newaxis]

        # ir_img = nib.load(os.path.join(input_fold, dir + '/IR.nii.gz'))
        # ir_numpy = ir_img.get_fdata()
        # ir_numpy = np.nan_to_num(ir_numpy)
        # ir_numpy = ir_numpy.astype('float32')

        # Concatenate Flair and Numpy
        image_numpy = np.concatenate((flair_numpy, reg_t1_numpy), axis=3)

        # Load the segmentation Maps
        segm_img = nib.load(os.path.join(input_fold, dir + '/segm.nii.gz'))
        segm_numpy = segm_img.get_fdata()
        segm_numpy = np.nan_to_num(segm_numpy)
        segm_numpy = segm_numpy.astype('float32')

        # Drop classes 9,10
        for elem in drop_class:
            segm_numpy[segm_numpy == elem] = 0

        # layer = each channel
        for layer in range(image_numpy.shape[2]):
            patch_img = image_numpy[:, :, layer]
            patch_mask = segm_numpy[:, :, layer]
            patch_mask = np.reshape(patch_mask, (patch_mask.shape[0], patch_mask.shape[1], 1))
            image_list.append(patch_img)
            segm_list.append(patch_mask)

    # 240 values = 48 Channels * 5 subjects/images
    # Image List = (Number, Width, Height, Channels=2)
    image_list = np.array(image_list, dtype='float32')
    segm_list = np.array(segm_list, dtype='float32')
    np.save(os.path.join(output_fold + 'X_'+ file_name + '.npy'), image_list)
    np.save(os.path.join(output_fold + 'Y_' + file_name + '.npy'), segm_list)

def get_2d_patches_unannotated(input_fold, output_fold, file_name):
    """
    Generating 2d patches based on 3d input images.
    Args:
        input_fold: string. Path to the folder with two other folders: images and masks.
                            In turn raw 3d images and masks are stored respectively.
        drop_class: list of integers. List of classes that will be reasigned to background (class 0).
        flair: boolean. True when flair images are used, False in opposite case.
        t1: boolean. True when t1 images are used, False in opposite case.
        ir: boolean. Ture when t1 images are used, Flase in opposite case.
        normilize_per_case: boolean. True when each image per case (3d image) is normilized, False if not.
        test_imgs:  string. Name of the image which is selected for testing among all images.
        output_fold: string. Path to the output folder with numpy files of images and masks.
                             Inside output folder train and test folder will be generated storing their
                             images and masks respectively.
    Returns:
        tuple with 4 numpy files. 1.train images, 2.train masks, 3.test images, 4.test masks.
    """

    assert os.path.isdir(input_fold)
    dirs = sorted(os.listdir(os.path.join(input_fold)))

    image_list = []
    # We have 20 unannotated samples
    for dir in dirs:

        flair_img = nib.load(os.path.join(input_fold, dir + '/FLAIR.nii.gz'))
        flair_numpy = flair_img.get_fdata()
        flair_numpy = np.nan_to_num(flair_numpy)
        flair_numpy = flair_numpy.astype('float32')
        flair_numpy = normalize_img(flair_numpy)
        flair_numpy = flair_numpy[..., np.newaxis]

        t1_img = nib.load(os.path.join(input_fold, dir + '/T1.nii.gz'))
        t1_numpy = t1_img.get_fdata()
        t1_numpy = np.nan_to_num(t1_numpy)
        t1_numpy = t1_numpy.astype('float32')
        t1_numpy = normalize_img(t1_numpy)
        t1_numpy = t1_numpy[..., np.newaxis]

        # ir_img = nib.load(os.path.join(input_fold, dir + '/IR.nii.gz'))
        # ir_numpy = ir_img.get_fdata()
        # ir_numpy = np.nan_to_num(ir_numpy)
        # ir_numpy = ir_numpy.astype('float32')

        image_numpy = np.concatenate((flair_numpy, t1_numpy), axis=3)

        for layer in range(image_numpy.shape[2]):
            patch_img = image_numpy[:, :, layer]
            image_list.append(patch_img)

    image_list = np.array(image_list, dtype='float32')
    np.save(os.path.join(output_fold + 'train_x_' + file_name + '.npy'), image_list[0:288])
    np.save(os.path.join(output_fold + 'val_x_' + file_name + '.npy'), image_list[288:336])

# def save_complete_data(dirpath, file_name):
#
#     train_x = np.load(dirpath + 'train/X_train.npy')
#     train_x_unannotated = np.load(dirpath + 'unannotated/X_unannotated.npy')
#
#     # Create single numpy array for annotated and unannotated data
#     train_x_total = np.concatenate((train_x, train_x_unannotated), axis=0)
#     train_y_total = np.concatenate((np.ones(len(train_x)), np.zeros(len(train_x_unannotated))), axis=0)
#
#     np.save(os.path.join(dirpath + 'X_' + file_name + '.npy'), train_x_total)
#     np.save(os.path.join(dirpath + 'Y_' + file_name + '.npy'), train_y_total)

def main():

    input_dir_train = os.path.join(os.getcwd(), 'data/mr_brains/raw/train/')
    output_dir_train = os.path.join(os.getcwd(), 'data/mr_brains/numpy/train/')

    input_dir_val = os.path.join(os.getcwd(), 'data/mr_brains/raw/val/')
    output_dir_val = os.path.join(os.getcwd(), 'data/mr_brains/numpy/val/')

    input_dir_test = os.path.join(os.getcwd(), 'data/mr_brains/raw/test/')
    output_dir_test = os.path.join(os.getcwd(), 'data/mr_brains/numpy/test/')

    input_dir_unannotated = os.path.join(os.getcwd(), 'data/mr_brains/raw/unannotated/')
    output_dir_unannotated = os.path.join(os.getcwd(), 'data/mr_brains/numpy/unannotated/')

    dirpath = os.path.join(os.getcwd(), 'data/mr_brains/numpy/')

    # Train
    get_2d_patches(input_fold=input_dir_train, drop_class=[9,10],
                   output_fold=output_dir_train, file_name='train')
    # Val
    get_2d_patches(input_fold=input_dir_val, drop_class=[9, 10],
                    output_fold=output_dir_val, file_name='val')

    # Test
    get_2d_patches(input_fold=input_dir_test, drop_class=[9, 10],
                   output_fold=output_dir_test, file_name='test')

    # Unannotated
    get_2d_patches_unannotated(input_fold=input_dir_unannotated,
                   output_fold=output_dir_unannotated, file_name='unannotated')

    #save_complete_data(dirpath=dirpath, file_name='total')

if __name__ == '__main__':
    main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import numpy as np
import pickle
import json
import csv
import pandas as pd

from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LassoCV,Lasso
from sklearn.linear_model import LogisticRegressionCV,LogisticRegression
from matplotlib import pyplot as plt
from sklearn.multiclass import OneVsRestClassifier
import scipy

#from sklearn.metrics import confusion_matrix
#from sklearn.metrics import accuracy_score
#from sklearn.metrics import precision_score
#from sklearn.metrics import recall_score
import sklearn.metrics as metrics

from nysol.mining.cPredict import cPredict

class classo(object):
	def __init__(self,x_df,y_df,standardize=False):
		print("##MSG: initializing model ...")

		if len(y_df.columns)!=1:
			raise BaseException("##ERROR: DataFrame of y variable must be one column data")
		# nullデータチェック
		for i,isnull in enumerate(x_df.isnull().any()):
			if isnull:
				raise BaseException("##ERROR: null data found in field '%s'"%(x_df.columns[i]))
		for i,isnull in enumerate(y_df.isnull().any()):
			if isnull:
				raise BaseException("##ERROR: null data found in field '%s'"%(y_df.columns[i]))

		self.y_name=y_df.columns[0]
		self.labels=y_df[self.y_name].cat.categories.to_list()
		self.y=y_df.values.reshape((-1,))

		self.x_names=x_df.columns.to_list()
		self.x=x_df.values.reshape((-1,len(x_df.columns)))

		# standardize x variables
		if standardize:
			self.scaler = StandardScaler()
			self.scaler.fit(self.x)
			self.x_trans=self.scaler.transform(self.x)
		else:
			self.scaler = None
			self.x_trans=self.x

		self.mse_chart = None
		self.coef_chart= None

	def build(self,l1_ratio=1.0,cv=10,Cs=40,max_iter=100):
		print("##MSG: building model ...")
		self.penalty="elasticnet"
		self.l1_ratio=l1_ratio
		self.cv=cv
		self.Cs=Cs
		self.max_iter=max_iter
		# https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegressionCV.html#sklearn.linear_model.LogisticRegressionCV
		self.model = LogisticRegressionCV(penalty=self.penalty,l1_ratios=[self.l1_ratio],cv=self.cv,Cs=self.Cs,solver="saga",random_state=0, max_iter=self.max_iter,multi_class='multinomial')
		self.model.fit(self.x_trans, self.y)
		self.score=self.model.score(self.x_trans, self.y)
		#print(self.model.coef_)
		#print(self.model.intercept_)
		#print(self.model.predict(self.x_trans))
		#print(self.y)

		# 回帰係数
		self.coef=[]
		self.coef.append(["class","x","coef"])
		if len(self.labels)==2:
			cnos=[0]
		else:
			cnos=range(len(self.labels))
		for c in cnos:
			self.coef.append([str(self.labels[c]),"intercept",float(self.model.intercept_[c])])
			for i in range(len(self.x_names)):
				self.coef.append([str(self.labels[c]),self.x_names[i],float(self.model.coef_[c][i])])

		# 最適λ
		self.opt_lambda=[]
		self.opt_lambda.append(["class","lambda"])
		for c in cnos:
			#self.opt_lambda.append([str(self.labels[c]),float(self.model.C_[c])])
			self.opt_lambda.append([self.labels[c],float(self.model.C_[c])])

		self.visualize()

	def predict(self,x_df):
		print("##MSG: predicting ...")
		x=x_df.values.reshape((-1,len(x_df.columns)))
		if self.scaler is None:
			x_trans=x
		else:
			x_trans=self.scaler.transform(x)

		y_pred=self.model.predict(x_trans) # [0 0 0 0 0 0 0 ...] # pred class表
		y_prob=self.model.predict_proba(x_trans) # sample * class prob 表
		# [[9.86925146e-01 1.30748490e-02 5.13506829e-09]
		#  [9.81685740e-01 1.83142489e-02 1.10697584e-08]...

		# y_prob等のclassの出力順
		orderedLabels=self.model.classes_

		# id込みのDataFrameに変換
		y_pred=pd.DataFrame(y_pred)
		y_pred.index=x_df.index.to_list()
		y_pred.columns=["y_predicted"]

		y_prob=pd.DataFrame(y_prob)
		y_prob.index=x_df.index.to_list()
		names=[]
		for c in orderedLabels:
			names.append("prob_"+str(c))
		y_prob.columns=names

		pred=cPredict(y_pred,y_prob,orderedLabels)

		return pred

	def load(modelF):
		print("##MSG: loading model ...")
		with open(modelF, 'rb') as fpr:
			model = pickle.load(fpr)
		return model

	def save(self,oPath):
		print("##MSG: saving model ...")
		os.makedirs(oPath,exist_ok=True)
		oFile="%s/model.sav"%(oPath)
		with open(oFile, 'wb') as fpw:
			pickle.dump(self, fpw)

		json_dump = json.dumps(self.coef, ensure_ascii=False, indent=2)
		with open("%s/coef.json"%(oPath),"bw") as f:
			f.write(json_dump.encode("utf-8"))
		with open("%s/coef.csv"%(oPath),"w") as f:
			writer = csv.writer(f)
			for row in self.coef:
				writer.writerow(row)

		json_dump = json.dumps(self.opt_lambda, ensure_ascii=False, indent=2)
		with open("%s/opt_lambda.json"%(oPath),"bw") as f:
			f.write(json_dump.encode("utf-8"))

		if self.mse_chart:
			self.mse_chart.savefig("%s/mse.png"%(oPath))
		if self.coef_chart:
			self.coef_chart.savefig("%s/coef.png"%(oPath))

	def visualize(self):
		##### visualization
		m_log_alphas = self.model.Cs_ # lambda path (x axis)

		# MSE path chart
		clsSize=len(self.model.scores_)
		#print(clsSize)
		fig, axs = plt.subplots(nrows=clsSize, figsize=(10,6*clsSize))
		if axs.__class__.__name__=="AxesSubplot": # binary classの場合はここに引っかかる
			axs=[axs]

		i=0
		for key,scores in self.model.scores_.items():
			#print(key,scores.shape)
			#print(key,scores.mean(axis=0).shape)
			#print(i)
			#axs[i] = plt.gca()
			axs[i].plot(m_log_alphas, scores.mean(axis=0), linewidth=2)
			axs[i].errorbar(m_log_alphas, scores.mean(axis=0), yerr = scores.std(axis=0), capsize=2, fmt='o', markersize=1, ecolor='black', markeredgecolor = "black", color='w')
			axs[i].set_xscale('log') # set_xlimより前に実行must
			axs[i].set_xlim(axs[i].get_xlim()[::-1])  # reverse axis
			axs[i].set_title('Mean square error: class='+str(key))
			axs[i].set_xlabel('-log(alpha)')
			i+=1
		self.mse_chart=fig

		# coefficient path chart
		coefs=[]
		for c in reversed(self.model.Cs_):
			model = LogisticRegression(penalty=self.penalty,l1_ratio=self.l1_ratio,C=c, solver="saga",random_state=0, max_iter=self.max_iter, multi_class='multinomial')

			#model.fit(self.scaler.transform(self.x), self.y)
			model.fit(self.x, self.y)
			coefs.append(model.coef_[0])
		#print("coef.shape",coefs[0].shape)
		#print("alpha.shape",m_log_alphas.shape)

		fig=plt.figure()
		ax = plt.gca()
		ax.plot(m_log_alphas, coefs)
		ax.set_xscale('log')
		ax.set_xlim(ax.get_xlim()[::-1])  # reverse axis
		plt.xlabel('-log(alpha)')
		plt.ylabel('weights')
		plt.title('Lasso coefficients as a function of the regularization')
		plt.axis('tight')
		self.coef_chart=fig

if __name__ == '__main__':
	import dataset as ds
	def senario1():
		config={}
		config["type"]="table"
		config["vars"]=[
			["id","id",{}],
			["n1","numeric",{}],
			["n2","numeric",{}],
			["n3","numeric",{}],
			["n4","numeric",{}],
			["d1","dummy",{"dummy_na":True,"drop_first":True,"dtype":float}],
			["d2","dummy",{}],
			["d3","dummy",{}],
			["i1","dummy",{}],
			["i2","dummy",{}],
			["class","class",{}]
		]
		data=ds.mkTable(config,"./data/crx2.csv")
		data=data.dropna()
		y=ds.cut(data,["class"])
		x=ds.cut(data,["class"],reverse=True)
		ds.show(x)
		ds.show(y)

		model=classo(x,y)
		model.build()
		model.save("xxclasso_model_crx")

		pred=model.predict(x)
		pred.evaluate(y)
		#print(pred.y_pred)
		#print(pred.y_true)
		#print(pred.y)
		#print(pred.stats)
		#print(pred.charts)
		#pred.charts["true_pred_scatter"].savefig("xxa.png")
		#pred.charts["roc_chart"]
		#pred.charts["confusion_matrix_plot"]
		#plt.show()
		pred.save("xxclasso_pred_crx")

		model=classo.load("xxclasso_model_crx/model.sav")
		pred=model.predict(x)
		pred.evaluate(y)
		pred.save("xxclasso_pred_crx2")

	def iris():
		from sklearn.datasets import load_iris
		iris = load_iris()
		config={}
		config["type"]="table"
		config["vars"]=[
			["sepal length","numeric",{}],
			["sepal width" ,"numeric",{}],
			["petal lengt" ,"numeric",{}],
			["petal width" ,"numeric",{}]
		]
		x=ds.mkTable(config,iris.data)

		config={}
		config["type"]="table"
		config["vars"]=[
			["species","category",{}]
		]
		y=ds.mkTable(config,iris.target)
		ds.show(x)
		ds.show(y)

		model=classo(x,y)
		# build(self,l1_ratio=1.0,cv=10,Cs=40,max_iter=100)
		model.build(max_iter=10000)
		model.save("xxclasso_model_iris")

		pred=model.predict(x)
		pred.evaluate(y)
		pred.save("xxclasso_pred_iris")

		model=classo.load("xxclasso_model_iris/model.sav")
		pred=model.predict(x)
		pred.evaluate(y)
		pred.save("xxclasso_pred_iris2")

	senario1()
	#iris()


import Classes

"""
    Stores the video of the request to the cache with the
    minimum latency
"""
def storeVidCache(request, endpoints, videos, caches):

    # Find endpoint
    for element in endpoints:
        if (element.ID == request.endpointID):
            endpoint = element
            break

    # Find endpoint
    video = videos[request.videoID]

    # Store the video to the closest cache
    for cacheID in [x[0] for x in endpoint.caches]:
        if video.ID in caches[cacheID].videosstored:
            break

        # Since endpoint.caches are sorted, we store the video to the first
        # cache where it fits
        if caches[cacheID].cursize <= video.MB:
            caches[cacheID].cursize -= video.MB
            caches[cacheID].videosstored.append(video.ID)
            break


import pandas as pd
import teradatasql as t
import math
import string

class upload_to_tera:
    """
    Uploading large dataframes to tera

    """

    def __init__(self, df, q, table_name):
        """
        ARGS:
        df - dataframe
        q - string - query
        table_name - string

        example format:
        q = Insert into d_digital_data.blabla values (?, ?, ?, ?)
        table_name = d_digital_data.blabla
        """
        self.df = df
        self.q = q
        self.table_name = table_name
        alphabet_string = string.ascii_lowercase
        self.alphabet_list = list(alphabet_string)+list(alphabet_string)+list(alphabet_string)+list(alphabet_string)+list(alphabet_string)
        self.upload_how_many_rows_we_want_main()

    def stack(self):
        return self.alphabet_list.pop()

    def upload_how_many_rows_we_want_main(self):
        """
        uploading large dataframes to tera

        ARGS:
        df - dataframe
        q - string - query
        table_name - string

        example format:
        q = Insert into d_digital_data.blabla values (?, ?, ?, ?)
        table_name = d_digital_data.blabla

        Return:
        nan
        """
        l = self.uploade_how_many_rows_we_want(self.df, self.q, self.table_name)
        if len(l)==0:
            print("done")
        else:
            # union all tables
            with t.connect('{"host":"tdprd","logmech":"krb5"}') as con:
                with con.cursor() as cur:
                    q_union = "sel * from {0}".format(l[0])
                    for item in l[1:]:
                        q_union +=" union all sel * from {0}".format(item)

                    q_final = """insert into {0}
                    {1}
                    """.format(self.table_name, q_union)
                    cur.execute(q_final)
                    for item in l:
                        cur.execute("drop table {0}".format(item))
                    print('done')

    def uploade_how_many_rows_we_want(self, df, q, table_name, l=[]):
        """
        A recursion that will divide our data into several parts and upload them to tera.

        ARGS:
        df - dataframe
        q - string - query
        table_name - string
        l - list - keep empty

        example format:
        q = Insert into d_digital_data.blabla values (?, ?, ?, ?)
        table_name = d_digital_data.blabla

        Return:
        nan
        """
        print("len of rows: " + str(len(df)))
        try:
            with t.connect('{"host":"tdprd","logmech":"krb5"}') as con:
                with con.cursor() as cur:
                    cur.execute(q, df.values.tolist())
        except Exception as ex:
            if "batch request" in str(ex):
                with t.connect('{"host":"tdprd","logmech":"krb5"}') as con:
                    with con.cursor() as cur:
                        # create new tables in tera
                        create_statment = cur.execute("show table " + table_name).fetchall()[0]
                        create_statment = create_statment[0].replace('\r', '\n')
                        a = self.stack()
                        b = self.stack()
                        print(a)
                        print(b)
                        table_name1 = table_name + a
                        table_name2 = table_name + b
                        create_statment1 = create_statment.replace(table_name, table_name1)
                        create_statment2 = create_statment.replace(table_name, table_name2)
                        cur.execute(create_statment1)
                        cur.execute(create_statment2)

                        # usally, tera upload some of the data before crashing.
                        # we dont want duplicates.
                        cur.execute("delete {0}".format(table_name))

                        # split the data to 2 dataframes
                        len_data = math.ceil(len(df)/2)
                        df1 = df.iloc[:len_data]
                        df2 = df.iloc[len_data:]

                        # replace query
                        q1 = q.replace(table_name, table_name1)
                        q2 = q.replace(table_name, table_name2)

                        l1 = self.uploade_how_many_rows_we_want(df1, q1, table_name1, l + [table_name1])
                        l2 = self.uploade_how_many_rows_we_want(df2, q2, table_name2, l + [table_name2])
                        l = l+l1+l2

            else:
                print (ex)
                raise error

        return l


import time
import requests
import board
import busio
import asyncio
import threading
import urllib.request
import RPi.GPIO as GPIO
import os
import subprocess
from subprocess import Popen
from pathlib import Path
import pygame

time.sleep(60.0)
os.environ["DISPLAY"] = ":0"
pygame.display.init()
#game = pygame.display.set_mode((200,300))
game = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
#game = pygame.display.set_mode((0,0),0,32,pygame.NOFRAME)
#game = pygame.display.set_mode((0,0),pygame.NOFRAME)
pygame.display.set_caption('picture')
img = pygame.image.load('/home/pi/Downloads/hnd/5.jpg')
img = pygame.transform.scale(img,(400,300))
white =(255,255,255)

GPIO.setup(26, GPIO.IN) # señal entrada
GPIO.setup(11, GPIO.OUT) #señal apagado entrada
GPIO.setup(13, GPIO.IN) #persona en entrada

GPIO.setup(6, GPIO.OUT) #señal apagado salida
GPIO.setup(5, GPIO.IN) #señal salida(arduino2)
GPIO.setup(19, GPIO.IN)#persona salida

GPIO.setup(10, GPIO.OUT) #apagado señal oportunidad
GPIO.setup(9, GPIO.IN) #señal oportunidad
oportunidad = GPIO.input(9)

GPIO.setup(6, GPIO.OUT)
GPIO.output(6,GPIO.HIGH)
time.sleep(0.5)
GPIO.setup(6, GPIO.OUT)
GPIO.output(6,GPIO.LOW)
señalSalida = GPIO.input(5)
personaSalida = GPIO.input(19)

GPIO.setup(11, GPIO.OUT)
GPIO.output(11,GPIO.HIGH)
time.sleep(0.5)
GPIO.setup(11, GPIO.OUT)
GPIO.output(11,GPIO.LOW)
personaEntrada = GPIO.input(13)
señalEntrada = GPIO.input(26)

def PostOport():
    url= 'http://143.198.132.112/smarthh/novaspost_oportunidades.php'
    status_code = 200
    try:
        status_code = requests.get(url, timeout = 10)

    except requests.exceptions.ConnectTimeout:
        #print ('time out')
        status_code = 3
    except requests.exceptions.ConnectionError:
        #print ('error de conexion')
        status_code = 3

    if status_code == 200:
        query = {'lat':'45','lon':'180'}
        response = requests.post('http://143.198.132.112/smarthh/novaspost_oportunidades.php',data = {'foo2':'bar2'})
        #print (response.text)
    else:
        pass

def PostEfect():

    url= 'http://143.198.132.112/smarthh/novaspost_efectivo.php'
    status_code = 200
    try:
        status_code = requests.get(url, timeout = 5)
        status_code.raise_for_status()
    except requests.exceptions.ConnectTimeout:
        #print ('time out')
        status_code = 3
    except requests.exceptions.ConnectionError:
       # print ('error de conexion')
        status_code = 3

    if status_code == 200:
        query = {'lat':'45','lon':'180'}
        response = requests.post('http://143.198.132.112/smarthh/novaspost_efectivo.php',data = {'foo2':'bar2'})
        #print (response.text)
    else:
        pass
        #print ('no fue posible entrar')
    #print("lavado de manos")

def apagarbomba():
    GPIO.output(10,GPIO.HIGH)
    time.sleep(0.4)
    GPIO.output(10,GPIO.LOW)
    time.sleep(0.1)

def apagarentrada():
    global k
    GPIO.setup(26, GPIO.IN)
    señalEntrada = GPIO.input(26)
    while(señalEntrada == 1):
        GPIO.setup(26, GPIO.IN)
        señalEntrada = GPIO.input(26)
        GPIO.setup(5, GPIO.IN)
        señalSalida = GPIO.input(5)
        GPIO.setup(6, GPIO.OUT)
        GPIO.output(6,GPIO.HIGH)
        time.sleep(0.1)
        GPIO.setup(6, GPIO.OUT)
        GPIO.output(6,GPIO.LOW)
        time.sleep(0.1)
    k = 1

def apagarsalida():

    GPIO.setup(5, GPIO.IN)
    señalSalida = GPIO.input(5)
    global l
    while(señalSalida == 1):
        GPIO.setup(5, GPIO.IN)
        señalSalida = GPIO.input(5)
        GPIO.setup(11, GPIO.OUT)
        GPIO.output(11,GPIO.HIGH)
        time.sleep(0.1)
        GPIO.setup(11, GPIO.OUT)
        GPIO.output(11,GPIO.LOW)
        time.sleep(0.1)
    l = 1

def screen():
	global screen_status
	url= 'http://143.198.132.112/smarthh/pantalla.php'
	status_code = 200
	try:
		status_code = requests.get(url,timeout = 10)
		#print(status_code)

	except requests.exceptions.ConnectTimeout:
		status_code = 3
	except requests.exceptions.ConnectionError:
		status_code = 3
	if status_code == 200 or "[200]":
		query = {'lat':'45','lon':'180'}
		r = requests.post('http://143.198.132.112/smarthh/pantalla.php')
		screen_status = r.text
		#print(r.text)
		#print('request realizado')
	else:print('no hubo request')
def imagen(j):
    if(j == 1):
        img = pygame.image.load('/home/pi/Downloads/hnd/2.jpg')
        img = pygame.transform.rotate(img,-90)
        img = pygame.transform.scale(img,(720,600))
    elif(j == 2):
        img = pygame.image.load('/home/pi/Downloads/hnd/3.jpg')
        img = pygame.transform.rotate(img,-90)
        img = pygame.transform.scale(img,(720,600))
    else:
        img = pygame.image.load('/home/pi/Downloads/hnd/5.jpg')
        img = pygame.transform.rotate(img,-90)
        img = pygame.transform.scale(img,(720,600))

    game.blit(img,(0,0))

def start_img():
    j = 0
    crash = False
    while not crash:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN:
                    pygame.quit()
                    crash = True
                elif event.key == pygame.K_RIGHT:
                    j = 1
                elif event.key == pygame.K_LEFT:
                    j = 2
            #print('dentro del for')

        game.fill(white)
        imagen(j)
        pygame.display.update()

flag = 1
video = Path("/home/pi/Downloads/hnd/camalion.mp4")
video2 = Path("/home/pi/Downloads/AnimatedSF.mp4")
global a
os.environ['DISPLAY']= ":0"
global screen_status
screen_status = ''
a = 'no video'
flag = 1
print("Iniciando...")
i = 1

s = threading.Thread(target = start_img)
s.start()

while True:

    GPIO.setup(26, GPIO.IN)
    señalEntrada = GPIO.input(26)
    GPIO.setup(5, GPIO.IN)
    señalSalida = GPIO.input(5)
    #print("señal entrada:")
    #print(señalEntrada)
    #print("señal salida:")
    #print(señalSalida)

    if(señalEntrada == 1):
        GPIO.setup(13, GPIO.IN)
        personaEntrada = GPIO.input(13)
        GPIO.setup(19, GPIO.IN)
        personaSalida = GPIO.input(19)
        oportunidad = GPIO.input(9)
        #print("alguien en la puerta")
         #print(personaEntrada)
        if(oportunidad == 1):
            flag = 1;
        else:
            flag = 0;
        while(personaEntrada == 1 or personaSalida == 1):
            personaEntrada = GPIO.input(13)
            personaSalida = GPIO.input(19)
            #print("alguien en la puerta")
            #print(personaEntrada)

        if(flag ==1):
            b = threading.Thread(target = apagarbomba)
            b.start()
            e = threading.Thread(target = PostEfect)
            e.start()
            f = threading.Thread(target = PostOport)
            f.start()
            #print('realizar peticion http oportunidad con lavado de manos')
        else:
            b = threading.Thread(target = apagarbomba)
            b.start()
            f = threading.Thread(target = PostOport)
            f.start()
            #i = ventana(i)

            #print('realizar peticion http oportunidad sin lavado de manos')

        greenflag = 1
        global k
        global l
        k = 0
        l = 0
        while(k == 0):

            if(greenflag ==1):
                es = threading.Thread(target = apagarentrada)
                es.start()
                greenflag = 0
                #print("valor de k es:")
                #print(k)
            else:
                pass

        greenflag = 1
        #print(k)

        while(l == 0):

            if(greenflag ==1):
                ec = threading.Thread(target = apagarsalida)
                ec.start()
                greenflag = 0

            else:
                pass
        greenflag = 1

  #############################################################
        #print("apagando... entrada")
        #print("señal apagada")
        i = i + 1
        #print(i)

    elif (señalSalida == 1):

        GPIO.setup(13, GPIO.IN)
        personaEntrada = GPIO.input(13)
        GPIO.setup(19, GPIO.IN)
        personaSalida = GPIO.input(19)
        while(personaEntrada == 1 or personaSalida == 1):
            personaEntrada = GPIO.input(13)
            personaSalida = GPIO.input(19)
            #print("alguien en la puerta")
            #print(personaEntrada)

        greenflag = 1

        k = 0
        l = 0

        while(l == 0):

            if(greenflag ==1):
                er = threading.Thread(target = apagarsalida)
                er.start()
                greenflag = 0

            else:
                pass
        greenflag = 1

        while(k == 0):

            if(greenflag ==1):
                ee = threading.Thread(target = apagarentrada)
                ee.start()
                greenflag = 0
                #print("valor de k es:")
                #print(k)
            else:
                pass

        greenflag = 1
        #print(k)

        #print("salida")

    else:

        GPIO.output(6,GPIO.LOW)
        GPIO.setup(11, GPIO.OUT)
        GPIO.output(11,GPIO.LOW)
        #print("no hay nadie")


from load_sample import load_sample_file
from validate_output import validate_json

def transform():
    input_json = load_sample_file()
    createdAt = input_json['createdAt']
    createdBy = input_json['createdBy']
    id = input_json['id']
    name = input_json['name']
    owner = input_json['owner']
    lookerId = input_json['workspaceItems'][0]['options']['lookerId']
    output_json = {'createdAt': createdAt, 'createdBy': createdBy, 'id': id, 'lookerId': lookerId, 'name': name, 'owner': owner}

    if (validate_json(output_json)):
        print("The transformed object conforms to the schema.")
    else:
        print("Object \n {} \n does not conform to the given schema.")


import boto3
import json
from inspect import getmembers
from optparse import OptionParser
from bson import json_util
import datetime

client = boto3.client('macie2',region_name='us-east-1')
my_list=list()
paginator = client.get_paginator('list_findings')
index=1
for finding in paginator.paginate(maxResults=50):
    for findingid in finding['findingIds']:
        a=my_list.append(findingid)
        a=findingid

for i in my_list:
    response = client.get_findings(findingIds=[i])
    print(response)
    def datetime_handler(x):
        if isinstance(x, datetime.datetime):
            return x.isoformat()
        raise TypeError("Unknown type")
    json.dumps(response, default=datetime_handler)
    with open("sample.json", "a") as json_file:
        print(response)
        json.dump(response,json_file,indent=4,default=datetime_handler)


#!/usr/bin/env python3

"""
    Newton Circles
    ==============

    But not really.

    But in the end it should still be OK for running the code, right?

"""

import numpy as np
import matplotlib.pyplot as pltlib
import matplotlib.patches as ptchs

class newtonCircles:
    def __init__(self, n = 2, growth_factor = .6, random_color = True):
        self._NOI = n
        self._figsize = (16, 9)
        self._gf = growth_factor
        self._r = 1.
        self._rc = random_color

    def draw_circle(self, center = None, radius = 1., axes = None, use_patches = False, random_color = True):
        if center is None:
            center = [0., 0.]

        if random_color:
            col = np.random.randint(256, size=3) / 255.
        else:
            col = [1., 0.5, 0.]

        phi = 2 * np.pi * np.linspace(0, 1, 100)
        sphi = np.sin(phi)
        cphi = np.cos(phi)

        if axes == None:
            if use_patches:
                ptchs.Circle((center[0], center[1]), radius, edgecolor=None, facecolor = col)
            else:
                pltlib.plot(center[0] + radius * cphi, center[1] + radius * sphi, lw = 2, color = col)
        else:
            if use_patches:
                circ = ptchs.Circle((center[0], center[1]), radius, edgecolor=None, facecolor = col)
                axes.add_patch(circ)
            else:
                axes.plot(center[0] + radius * cphi, center[1] + radius * sphi, lw = 2, color = col)

    def draw_single_y(self):
        fig = pltlib.figure(figsize = self._figsize)
        ax = fig.add_subplot(111, aspect = 'equal')

        ax.axis('off')

        for ii in range(self._NOI):
            r = self._r * self._gf ** ii
            c = (0., r)
            self.draw_circle(c, r, ax)

        pltlib.savefig("plts/single_y.png")

    def draw_double_y(self):
        fig = pltlib.figure(figsize = self._figsize)
        ax = fig.add_subplot(111, aspect = 'equal')

        ax.axis('off')

        for ii in range(self._NOI):
            r = self._r * self._gf ** ii
            c_u = (0., r)
            c_d = (0., -r)
            self.draw_circle(c_u, r, ax)
            self.draw_circle(c_d, r, ax)

        pltlib.savefig("plts/double_y.png")

    def draw_m_outward(self, m = 2, save_frames = False):
        theta = 2 * np.pi / m

        fig = pltlib.figure(figsize = self._figsize)
        ax = fig.add_subplot(111, aspect = 'equal')

        r_lim = 2 * self._r + 2 * self._r / (1 - self._gf)
        ax.set_xlim((-r_lim, r_lim))
        ax.set_ylim((-r_lim, r_lim))
        ax.axis('off')

        self.draw_circle(radius = self._r / self._gf, axes = ax, use_patches = True)
        if save_frames:
            pltlib.savefig("plts/frames/00000.png")

        cum_r = 0.

        for ii in range(self._NOI):
            r = self._r * self._gf ** ii

            for mm in range(m):
                c = ((2 * cum_r + r + self._r / self._gf) * np.cos(theta * mm), (2 * cum_r + r + self._r / self._gf) * np.sin(theta * mm))

                self.draw_circle(c, r, ax, True)
                if save_frames:
                    print("Savig outward frame {:d} of {:d}...".format(mm + ii * m + 1, m * self._NOI))
                    pltlib.savefig("plts/frames/{:05d}.png".format(mm + ii * m + 1))

            cum_r += r

        pltlib.savefig("plts/n{:d}_m{:d}_gf{:.1f}_outward.png".format(self._NOI, m, self._gf))

    def draw_m_fractal(self, m = 4, save_frames = False, overlay = False, random_color = False):
        theta = 2 * np.pi / m

        prev_r = 0.
        prev_c = [[0., 0.]]

        if overlay:
            fig = pltlib.figure(figsize = self._figsize)
            ax = fig.add_subplot(111, aspect = 'equal')

            r_lim = 2 * self._r + 2 * self._r / (1 - self._gf)
            ax.set_xlim((-r_lim, r_lim))
            ax.set_ylim((-r_lim, r_lim))
            ax.axis('off')

        for ii in range(self._NOI):
            if not overlay:
                fig = pltlib.figure(figsize = self._figsize)
                ax = fig.add_subplot(111, aspect = 'equal')

                r_lim = 2 * self._r + 2 * self._r / (1 - self._gf)
                ax.set_xlim((-r_lim, r_lim))
                ax.set_ylim((-r_lim, r_lim))
                ax.axis('off')

            r = self._r * self._gf ** ii
            new_c_list = []
            for old_c_list in prev_c:
                all_centers = old_c_list

                for mm in range(m):

                    c = [all_centers[0] + (r / self._gf + r) * np.cos(theta * mm), all_centers[1] + (r / self._gf + r) * np.sin(theta * mm)]
                    new_c_list.append(c)

                    self.draw_circle(tuple(c), r, ax, True, random_color)

                prev_c = new_c_list

            if save_frames:
                print("Savig fractal frame {:d} of {:d}...".format(ii + 1, self._NOI))
                pltlib.savefig("plts/frames/{:05d}.png".format(ii))

            if not ii == self._NOI - 1 and not overlay:
                pltlib.close(fig)

        pltlib.savefig("plts/n{:d}_m{:d}_gf{:.1f}_fractal.png".format(self._NOI, m, self._gf))

    def draw_m_inward(self, m = 2):
        theta = 2 * np.pi / m

        fig = pltlib.figure(figsize = self._figsize)
        ax = fig.add_subplot(111, aspect = 'equal')

        ax.axis('off')

        self.draw_circle(radius = self._r, axes = ax)

        for ii in range(1, self._NOI):
            r = self._r * self._gf ** ii
            c = (0., r)
            self.draw_circle(c, r, ax)

        pltlib.savefig("plts/m{:d}_inward.png".format(m))

if __name__ == "__main__":

    tester = newtonCircles(3, 0.5)
    # tester.draw_single_y()
    # tester.draw_double_y()
    # tester.draw_m_outward(m = 4, save_frames = True)
    tester.draw_m_fractal(m = 4, save_frames = False, overlay = False, random_color = True)

    pltlib.show()


#DSA-Assgn-4
'''
Created on Mar 13, 2019

@author: vijay.pal01
'''

class Player:
    def __init__(self,name,experience):
        self.__name=name
        self.__experience=experience

    def get_name(self):
        return self.__name

    def get_experience(self):
        return self.__experience

    def __str__(self):
        return(self.__name+" "+(str)(self.__experience))

#Implement Game class here
class Game:
    def __init__(self,players_list):
        self.__players_list = players_list
    def sort_players_based_on_experience(self):
        for i in range(0,len(self.__players_list)):
            for j in range(i+1,len(self.__players_list)):
                if(self.__players_list[i].get_experience()<
                   self.__players_list[j].get_experience()):
                    temp=self.__players_list[i]
                    self.__players_list[i]=self.__players_list[j]
                    self.__players_list[j]=temp
    def shift_player_to_new_position(self,
                                     old_index_position,
                                     new_index_position):
        p1= self.__players_list[old_index_position]
        self.__players_list.pop(old_index_position)
        self.__players_list.insert(new_index_position, p1)

    def display_player_details(self):
        player_list =[]
        for i in self.__players_list:
            player_list.append(i.get_name()+':'+i.get_experience())
        if(len(players_list)==0):
            return None
        return player_list

player1=Player("Dhoni",15)
player2=Player("Virat",10)
player3=Player("Rohit",12)
player4=Player("Raina",11)
player5=Player("Jadeja",13)
player6=Player("Ishant",9)
player7=Player("Shikhar",8)
player8=Player("Axar",7.5)
player9=Player("Ashwin",6)
player10=Player("Stuart",7)
player11=Player("Bhuvneshwar",5)
#Add different values to the list and test the program
players_list=[player1,player2,player3,player4,player5,player6,player7,player8,player9,player10,player11]
#Create object of Game class, invoke the methods and test your program


# -*- coding: utf-8 -*-
"""
Created on Wed Oct 10 12:03:29 2018

Miscellaneous helper functions

@author: tangk
"""
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from scipy.stats import spearmanr, pearsonr

#%% easy numbers
def is_all_nan(data):
    """ data is in the form of an array
     return if all elements in data are np.nan"""
    return np.all(np.isnan(data))

def to_numpy(data):
    if isinstance(data,pd.core.frame.Series):
        return data.values
    elif isinstance(data,(tuple,list)):
        return np.array(data)

def r2(x,y):
    """ x and y are Series or array-like
    Returns the R2 value between x and y """
    i = np.logical_not(np.logical_or(np.isnan(x),np.isnan(y)))
    x = x[i]
    y = y[i]

    lr = LinearRegression()
    x, y = to_numpy(x), to_numpy(y)

    lr.fit(x.reshape(-1,1),y.reshape(-1,1))
    r2 = lr.score(x.reshape(-1,1),y.reshape(-1,1))
    return r2

def rho(x,y):
    """returns the spearman rank-order correlation coefficient"""
    i = np.logical_not(np.logical_or(np.isnan(x),np.isnan(y)))
    x = x[i]
    y = y[i]

    x, y = to_numpy(x), to_numpy(y)
    rho, p = spearmanr(x,y)
    return rho

def corr(x,y):
    """returns the pearson correlation coefficient"""
    i = np.logical_not(np.logical_or(np.isnan(x),np.isnan(y)))
    x = x[i]
    y = y[i]

    x, y = to_numpy(x), to_numpy(y)
    r, p = pearsonr(x,y)
    return r

#%% matching things
def ordered_intersect(l1,l2):
    """Ordered intersection of two iterables. Keeps the order of l1"""
    return [i for i in l1 if i in l2]

def arg_ordered_intersect(l1,l2):
    """Returns indices of l1 for which elements at those indices are also in l2"""
    return [i for i in range(len(l1)) if l1[i] in l2]

# fix this later
def partial_ordered_intersect(l1,l2):
    """Ordered intersection of two iterables. Keeps the order of l1.
    If elements of l1 are not in l2, they are omitted from the returned list.
    If elements of of l2 are not in l1, they are included at the end of the
    returned list in the order of l2."""
    l2 = list(l2)
    out = []
    for l in l1:
        if l in l2:
            out.append(l)
            l2.remove(l)
    out.extend(l2)
    return out

#%%
def condense_df(df, thresh=0.05, thresh_type='upper_bound', axis=0):
    """
    df = condense(df)
    Condenses a dataframe by removing either rows or columns where all elements
    do not meet a certain criterion. The criterion is defined by thresh_type:
        upper_bound: thresh is a number. filters out all rows/columns where values are greater than upper_bound
        lower_bound: thresh is a number. filters out all rows/columns where values are lower than lower_bound
        between: thresh is a list of length 2. filters out all rows/columns where values are not between the lower and upper values in thresh.
        outside: thresh is a list of length 2. filters out all rows/columns where values are between the lower and upper values in thresh.
    axis=0 removes rows. axis=1 removes columns
    """
    df = df.dropna(axis=0, how='all').dropna(axis=1, how='all')
    if thresh_type=='upper_bound':
        drop = (df > thresh).all(axis=1-axis)
    elif thresh_type=='lower_bound':
        drop = (df < thresh).all(axis=1-axis)
    elif thresh_type=='between':
        drop = ((df < min(thresh)) | (df > max(thresh))).all(axis=1-axis)
    elif thresh_type=='outside':
        drop = ((df > min(thresh)) & (df < max(thresh))).all(axis=1-axis)
    drop = drop[drop].index
    return df.drop(drop, axis=axis)

# implemented in dfxtend table
#def query_list(dataframe,column,qlist):
#    """ queries a dataframe by whether column contains qlist """
#    return dataframe[dataframe[column].isin(qlist)]

# implemented in dfxtend chdata
#def re_cutoff(chdata,cutoff):
#    """ cut off the time series at a different place
#    the re cutoff must be shorter than the chdata """
#    return chdata.applymap(lambda x: x[cutoff])


from asyncio import get_event_loop
from collections import OrderedDict, deque
from copy import deepcopy
from dataclasses import dataclass, field
from datetime import datetime
from time import time as timestamp
from typing import Tuple, List, Dict, Set, Optional, Deque, TYPE_CHECKING

from autobahn.exception import Disconnected

from config import MAX_COOKIES_PER_IP, BAN_TIME, CHANNEL_SETUP_INVENTORY_COUNT, ENABLE_OBJECTS
from .objects import get_random_object
from .objects.inventory import UserInventory
from .state_users import User
from .tools import encode_json, OrderedDequeDict

if TYPE_CHECKING:
    from .client import LoultServerProtocol

class Channel:

    def __init__(self, channel_name, state):
        self.name = channel_name
        self.loult_state = state
        self.clients: Set['LoultServerProtocol'] = set()
        self.users: Dict[str, User] = OrderedDict()
        self.backlog: List = []
        # this is used to track how many cookies we have per connected IP in that channel
        self.ip_cookies_tracker: Dict[str, Set[bytes]] = dict()
        self.inventory = UserInventory()
        # filling the channel's inventory with some random items
        if ENABLE_OBJECTS:
            from .objects import SantasSack
            for _ in range(3):
                self.inventory.add(SantasSack())
            for _ in range(CHANNEL_SETUP_INVENTORY_COUNT):
                self.inventory.add(get_random_object())

    def _signal_user_connect(self, client, user: User):
        client.send_json(type='connect', date=timestamp() * 1000, **user.info)

    def _signal_user_disconnect(self, client, user: User):
        client.send_json(type='disconnect', date=timestamp() * 1000,
                         userid=user.user_id)

    def broadcast(self, binary_payload=None, **kwargs):
        msg = encode_json(kwargs)
        for client in self.clients:
            try:
                if kwargs:  # in case there is no "text" message to be broadcasted
                    client.sendMessage(msg)
                if binary_payload:
                    client.send_binary(binary_payload)
            except Disconnected:
                client.sendClose(code=4000, reason="Something went wrong, closing connection")

    def get_userlist(self):
        return OrderedDict([(user_id, deepcopy(user.info))
                            for user_id, user in self.users.items()])

    def update_userlist(self):
        userlist = self.get_userlist()
        for user_id in self.users.keys():
            my_userlist = deepcopy(userlist)
            my_userlist[user_id]['params']['you'] = True
            for client in self.users[user_id].clients:
                client.send_json(type='userlist', users=list(my_userlist.values()))

    def channel_leave(self, client, user: User):
        try:
            self.users[user.user_id].clients.remove(client)

            # if the user is not connected anymore, we signal its disconnect to the others
            if len(self.users[user.user_id].clients) < 1:
                self.clients.discard(client)
                del self.users[user.user_id]

                # removing the client/user's cookie from the ip-cookie tracker
                self.ip_cookies_tracker[client.ip].remove(client.cookie)

                for client in self.clients:
                    self._signal_user_disconnect(client, user)

                # if no one's connected, we delete the channel from the register
                if not self.clients:
                    del self.loult_state.chans[self.name]
        except KeyError:
            pass

    def user_connect(self, new_user: User, client):
        if client.ip in self.ip_cookies_tracker:
            if client.cookie not in self.ip_cookies_tracker[client.ip]:
                if len(self.ip_cookies_tracker[client.ip]) >= MAX_COOKIES_PER_IP:
                    from .client import UnauthorizedCookie
                    raise UnauthorizedCookie()
                else:
                    self.ip_cookies_tracker[client.ip].add(client.cookie)
        else:
            self.ip_cookies_tracker[client.ip] = {client.cookie}

        if self.loult_state.is_shadowbanned(cookie=new_user.cookie_hash,
                                            ip=client.ip):
            new_user.state.is_shadowbanned = True

        if new_user.user_id not in self.users:
            for other_client in self.clients:
                if other_client != client:
                    self._signal_user_connect(other_client, new_user)
            self.users[new_user.user_id] = new_user
            return new_user
        else:
            self.users[new_user.user_id].clients.append(client)
            return self.users[new_user.user_id]  # returning an already existing instance of the user

    def log_to_backlog(self, user_id, msg: str, kind='msg'):
        # creating new entry
        info = {
            'user': self.users[user_id].info['params'],
            'msg': msg,
            'userid': user_id,
            'date': timestamp() * 1000,
            'type': kind,
        }

        # adding it to list and removing oldest entry
        self.backlog.append(info)
        self.backlog = self.backlog[-10:]
        return info

    def get_user_by_name(self, pokemon_name: str, order=0) -> (int, User):

        for user_id, user in self.users.items():
            if user.poke_params.pokename.lower() == pokemon_name.lower():
                if order <= 0:
                    return user_id, user
                else:
                    order -= 1

        return None, None

    def disconnect_all_clients(self, user_id=None, ip=None):
        """Either disconnects all clients for a user, or for an ip"""
        if user_id is not None:
            pass

        if ip is not None:
            pass

@dataclass(frozen=True)
class UserIdentity:
    cookie: str = None
    ip: str = None

@dataclass
class IdentitiesTracker:
    cookies: Set[str] = field(default_factory=set)
    ips: Set[str] = field(default_factory=set)

    def __contains__(self, item: UserIdentity):
        if item.cookie is not None:
            if item.cookie in self.cookies:
                return True
        if item.ip is not None:
            if item.ip in self.ips:
                return True
        return False

    def add(self, item: UserIdentity):
        if item.cookie is not None:
            self.cookies.add(item.cookie)
        if item.ip is not None:
            self.ips.add(item.ip)

    def remove(self, item: UserIdentity):
        if item.cookie is not None:
            self.cookies.remove(item.cookie)
        if item.ip is not None:
            self.ips.remove(item.ip)

@dataclass
class ConnectionEvent:
    cookie: str
    ip: str
    channel: str
    time: datetime

class IdentitiesBacklog:

    def __init__(self):
        self.backlog: Deque[ConnectionEvent] = deque(maxlen=1000)
        self.ip_last_login = OrderedDequeDict()

    def log_connection(self, cookie: str, ip: str, channel: str):
        self.backlog.append(ConnectionEvent(cookie=cookie, ip=ip,
                                            channel=channel, time=datetime.now()))
        self.ip_last_login[ip] = datetime.now()

    def get_cookie_ips(self, cookie: str):
        return set(conn.ip for conn in self.backlog if conn.cookie == cookie)

    def get_ip_cookies(self, ip: str):
        return set(conn.cookie for conn in self.backlog if conn.ip == ip)

    def get_cookie_channels(self, cookie: str):
        return set(conn.channel for conn in self.backlog if conn.cookie == cookie)

    def ip_backlog(self):
        return set(conn.ip for conn in self.backlog)

class LoultServerState:

    def __init__(self):
        self.chans: Dict[str, Channel] = {}
        self.id_backlog = IdentitiesBacklog()
        self.banned: IdentitiesTracker = IdentitiesTracker()
        self.shadowbanned: IdentitiesTracker = IdentitiesTracker()
        self.trashed: IdentitiesTracker = IdentitiesTracker()

    def channel_connect(self, client, user_cookie: str, channel_name: str) -> Tuple[Channel, User]:
        # if the channel doesn't exist, we instanciate it and add it to the channel dict
        if channel_name not in self.chans:
            self.chans[channel_name] = Channel(channel_name, self)
        channel_obj = self.chans[channel_name]
        channel_obj.clients.add(client)
        self.id_backlog.log_connection(user_cookie, client.ip, channel_name)
        return channel_obj, channel_obj.user_connect(User(user_cookie, channel_name, client), client)

    def apply_ban(self, cookie: Optional[str] = None, ip: Optional[str] = None,
                  ban_type: str = "ban",  # ban, shadowban or trash
                  duration: int = BAN_TIME * 60  # in seconds
                  ):
        identity = UserIdentity(cookie=cookie, ip=ip)
        if ban_type == "shadowban":
            tracker = self.shadowbanned
        elif ban_type == "trash":
            tracker = self.trashed
        else:
            tracker = self.banned
        if identity in tracker:
            return
        tracker.add(identity)
        loop = get_event_loop()
        loop.call_later(duration, tracker.remove, identity)

    def remove_ban(self, cookie: Optional[str] = None, ip: Optional[str] = None,
                   ban_type: str = "ban",  # ban, shadowban or trash
                   ):
        identity = UserIdentity(cookie=cookie, ip=ip)
        if ban_type == "shadowban":
            tracker = self.shadowbanned
        elif ban_type == "trash":
            tracker = self.trashed
        else:
            tracker = self.banned
        if identity in tracker:
            return
        tracker.remove(identity)

    def is_banned(self, cookie: Optional[str] = None, ip: Optional[str] = None):
        return UserIdentity(cookie=cookie, ip=ip) in self.banned

    def is_shadowbanned(self, cookie: Optional[str] = None, ip: Optional[str] = None):
        return UserIdentity(cookie=cookie, ip=ip) in self.shadowbanned

    def is_trashed(self, cookie: Optional[str] = None, ip: Optional[str] = None):
        return UserIdentity(cookie=cookie, ip=ip) in self.trashed


from modules.wordnikapi import wordApi
from requests import get
from pathlib import Path

word = 'cat'

res = wordApi.getAudio(word, useCanonical=True, limit=1)
assert res, 'null getAudio result'
assert len(res) == 1, 'getAudio size should be 1'

# prints attributes of audio result
print(res[0].__dict__)

url = res[0].fileUrl
name = res[0].word

def music(url, name):
    path = Path().absolute().joinpath('data')
    file_name = path.joinpath(str(name) + ".wav")
    with open(file_name, 'wb') as file:
        response = get(url)
        file.write(response.content)

music(url, name)


from random import randint
from collections import Counter

sides = []
times = int(input(
    "Please type in how many times you want to flip the coin"))

def coin_flip():
    return randint(1, 2)

for x in range(times):
    sides.append(coin_flip())
sides = Counter(sides)
for x in sides:
    if x == 2:
        print(f"{sides[x]} Heads")
    elif x == 1:
        print(f"{sides[x]} Tails")


from sklearn.decomposition import PCA
import numpy as np
import time
from Pipeline.Utilities.CBASS_U_PhaseRandomize1D import PhaseRandomize1D

def AddPhaseRandomizedSignal(sREC, sOPTION):
    '''
     Part of L1 of the bout pipeline. Creates surrogate LFP having the same
     covariance matrix and the same spectral density as sREC.db2LFP.

     Input -------------------------------------------------------------------

     sREC:         a structure requiring the following fields:
                   -.db2LFP a (channel x time sample) matrix containing the
                   signal (i.e. time series) of interest.
                   -.inSampleRate a positive number representing the sample
                   rate of the time series.
     inSeed        (optional) a non negative integer used to seed the random
                   number generator.

     Output ------------------------------------------------------------------

     sREC          the input structure with the additonal subfield:
                   -.db2LFP_Rnd a (channel x time sample) matrix of the same
                   size as sREC.db2LFP containing a phase randomized signal
                   having the same spectral density and the same covariance
                   matrix as sREC.db2LFP.
    '''

    verbose = sOPTION.blVerbose
    start_time = time.time()

    # Decomposes the LFP into orthogonal principal components
    pca = PCA(random_state = 1949,n_components=sREC.db2LFP.shape[0])
    db2LFP_Rnd = pca.fit_transform(sREC.db2LFP.T)
    if verbose: print("-- PCA: {}s seconds ---".format(time.time() - start_time))
    # if verbose: print('db2LFP_Rnd.shape: ',db2LFP_Rnd.shape)
    # if verbose: print('db2LFP_Rnd[:5,:5]: ',db2LFP_Rnd[:5,:5])

    # Randomizes the phase of each principal component
    start_phase = time.time()
    db2LFP_Rnd = PhaseRandomize1D(db2LFP_Rnd, sOPTION, inDim = 0)
    if verbose: print("-- Randomize1D: {}s seconds ---".format(time.time() - start_phase))
    # if verbose: print('(randomized) db2LFP_Rnd[:5,:5]: ',db2LFP_Rnd[:5,:5])

    # Recomposes the signal and stores it in the output structure
    sREC.db2LFP_Rnd = pca.transform(db2LFP_Rnd).T

    return sREC


#Agenda Telefonica
#V0.1 por Bertulfo Rincon

import modulos

modulos.bienvenidos()

opcion = input("> ")

print("has seleccionado la opcion",opcion)

if opcion == "1":
   modulos.escribir()

elif opcion == "2":
    print("Dime cuantos registros quieres ver")
    registros = input("> ")
    registrosnumero = int(registros)
    modulos.listar((registrosnumero+1))

else:
    modulos.mierror()


class method_config():

    SCRIPT_LIBRARY = [
        "developer",
        "combat_fighter",
        "nz_training",
        "iron_ore_mining",
        "fish_cooking",
        "fletching_training",
        "herb_cleaning",
        "marrentill_tar",
        "sapphire_ring_crafting",
        "death_rune_buy",
    ];

    ABOUT_SCRIPT = [
        "Developer Tools by Suirdna",
        "Experimental Realtime Detection Combat Script by Suirdna",
        "Nightmare Zone Combat training Script",
        "Al Kharid Iron Ore mining Script",
        "Eurthorpe Fish cooking Script",
        "Bow fletching Script",
        "Herb cleaning Script",
        "Marrentill Tar making Script",
        "Sapphire Ring crafting Script",
        "Death Rune making Money Script",
    ];


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

import os

import numpy as np

from geomdl import NURBS
from geomdl import exchange
from geomdl import tessellate
from geomdl import compatibility
from geomdl import utilities
from geomdl import helpers
from geomdl import operations
from geomdl.visualization import VisPlotly

import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection

from misc_routines import NURBS_connectivity_arrays_2D
from misc_routines import exportar_triangulacion_parametrico

#--input data--------------------------------
#prefix='infinite_plate'
#prefix='cuadrado2'
prefix='cuadrado'
#prefix='biquadratic_bspline'
delta_u = 0.05
delta_v = 0.05
density_refinement_u = 2
density_refinement_v = 2
nptx = 11
npty = 21
#--------------------------------------------

# Fix file path
#os.chdir(os.path.dirname(os.path.realpath(__file__)))

# Create a BSpline surface instance
surf = NURBS.Surface()

# Import smesh file (contains ctrlpts,knotvectors,degree)
imported = exchange.import_smesh("./ctrlpts_data/"+prefix+"_smesh.dat")
surf = imported[0]

# Refines the knot vector on the v-direction of a surface
operations.refine_knotvector(surf,[density_refinement_u,density_refinement_v])

# Set evaluation delta
surf.delta_u = delta_u
surf.delta_v = delta_v

# Evaluate surface
surf.evaluate()

# ''''''''''''''''''''''''''''''''''''''''''''''''''
# puntos de control (distintos formatos)
w         = surf.weights    # weight
ctrlpts   = surf.ctrlpts    # unweighted ctrlpts
ctrlpts2d = surf.ctrlpts2d  # weighted ctrlpts array
ctrlptsw  = surf.ctrlptsw   # weighted ctrls

# variables relevantes: numero de puntos de control (u y v)
size_u = surf.ctrlpts_size_u
size_v = surf.ctrlpts_size_v
# orden de Bspline/NURBS
degree_u = surf.degree_u
degree_v = surf.degree_v
# vector 'knot'
knotvector_u = surf.knotvector_u
knotvector_v = surf.knotvector_v

# ''''''''''''''''''''''''''''''''''''''''''''''''''

#----------------------------------------------

# crear malla de nodos en el espacio parametrico (u,v)
unod = np.linspace(0.0,1.0,nptx)
vnod = np.linspace(0.0,1.0,npty)

#coordenadas en espacio parametrico
nodes=[]
for j in range(npty):
	for i in range(nptx):
		nodes.append([unod[i],vnod[j]])

# transformacion lineal al espacio fisico (x,y)
N=[] ; M=[] ; span_u=[] ; span_v=[]
for uknot in unod: # function base direccion u
	span_u.append(helpers.find_span_linear(degree_u,knotvector_u,size_u,uknot))
	#span_u.append(helpers.find_span_binsearch(degree_u,knotvector_u,size_u,uknot))
	N.append(helpers.basis_function(degree_u,knotvector_u,span,uknot))
for vknot in vnod: # ... direccion v
	span_v.append(helpers.find_span_linear(degree_v,knotvector_v,size_v,vknot))
	#span_v.append(helpers.find_span_binsearch(degree_v,knotvector_v,size_v,vknot))
	M.append(helpers.basis_function(degree_v,knotvector_v,span,vknot))

#coordenadas en espacio fisico
coord = [] ; shapef = []
for j in range(npty):
	for i in range(nptx):

		aux_phi = [[0 for col in range(degree_v+1)] for row in range(degree_u+1)]
		aux_coord = [[0 for col in range(degree_v+1)] for row in range(degree_u+1)]
		aux_sum = [ 0 for row in range(3) ]

		# vector auxiliar que contiene los puntos de control no nulos
		uspan = N[i][0]
		vspan = M[j][0]
		aux_coord = []
		aux_udir = ctrlpts2d[uspan-degree_u:uspan+1]
		for aux_vdir in aux_udir:
			aux_coord.append(aux_vdir[vspan-degree_v:vspan+1])

		# vector auxiliar que contiene la funcion de forma 2d
		for jj in range(degree_v+1):
			for ii in range(degree_u+1):
				aux_phi[ii][jj] = N[i][1][ii] * M[j][1][jj]

		# calculo vector posicion en coordenadas fisica x,y
		for jj in range(degree_v+1):
			for ii in range(degree_u+1):
				aux_sum[0]=aux_sum[0]+aux_coord[ii][jj][0]*aux_phi[ii][jj]
				aux_sum[1]=aux_sum[1]+aux_coord[ii][jj][1]*aux_phi[ii][jj]
				aux_sum[2]=aux_sum[2]+aux_coord[ii][jj][2]*aux_phi[ii][jj]

		coord.append(aux_sum)
		shapef.append(aux_phi)

# triangulacion delaunay
from scipy.spatial import Delaunay
tri = Delaunay(nodes)

# grafico de la triangulacion en el espacio parametrico y fisico
x=[] ; y=[]
for i in range(len(coord)):
	x.append(coord[i][0])
	y.append(coord[i][1])
plt.triplot(x,y,tri.simplices.copy())
plt.plot(x,y,'o')
plt.show()
#--
u=[] ; v=[]
for i in range(len(nodes)):
	u.append(nodes[i][0])
	v.append(nodes[i][1])
plt.triplot(u,v,tri.simplices.copy())
plt.plot(u,v,'o')
plt.show()
#--

# graficar funcion de forma
shapef_list=[]
for shp in shapef:
	aux=[]
	for sh in shp:
		for s in sh:
			aux.append(s)
	shapef_list.append(tuple(aux)) #transforma el arreglo 2D shapef a un
		#arreglo 1D para facilitar la exportacion. CUIDADO CON EL ORDEN!

# exportar malla
filename='NURBS_mesh.dat'
f=open(filename,'w')
#--
fmtstr="%e "
fmtstr=((degree_u+1)*(degree_v+1))*fmtstr
fmtstr=fmtstr+'\n'
#--
f.write("%d %d\n"%(size_u,size_v))
for shape in shapef_list:
	f.write(fmtstr%(shape))
f.close()

# exportar funcion de forma
filename='NURBS_shapef.dat'
f=open(filename,'w')
#--
fmtstr="%e "
fmtstr=((degree_u+1)*(degree_v+1))*fmtstr
fmtstr=fmtstr+'\n'
#--
f.write("%d %d\n"%(size_u,size_v))
for shape in shapef_list:
	f.write(fmtstr%(shape))
f.close()

#exportar_triangulacion_parametrico('hola',vertices,triangles,ctrlpts)

# Plot the control point grid and the evaluated surface
vis_comp = VisPlotly.VisSurface()
surf.vis = vis_comp
surf.render()

# Good to have something here to put a breakpoint
pass

##--triangulacion espacio fisico--
#triangulation_xy = Delaunay(list(zip(x,y)))
#triangulation_uv = Delaunay(list(zip(u,v)))

## Export 'surf' data
#exchange.export_smesh( surf , file_name='./ctrlpt_data/CTRLPTSW_smesh.dat' )
#exchange.export_txt( surf, './ctrlpt_data/CTRLPTSW.dat', two_dimensional=True)

##exportar triangulacion
#prefix='infinite_plate'

#f=open(prefix+'_nodes.txt','w')
#for pts in ctrlptsw:
#	f.write('%e %e\n'%(pts[0],pts[1]))
#f.close()

#f=open(prefix+'_elements.txt','w')
#for triang in triangulation_xy.simplices:
#	f.write('%d %d %d\n'%(triang[0],triang[1],triang[2]))
#f.close()

##--plotear triangulacion--
#fig = plt.figure(figsize=(4,4))
#ax = fig.add_subplot(111)
#ax.scatter(u,v)	#vertices
#plt.triplot(u, v, triangulation_uv.simplices)
#plt.show()
#plt.cla()   # Clear axis
#plt.clf()   # Clear figure
#plt.close() # Close a figure window

#vertices,triangles = utilities.make_triangle_mesh(ctrlpts,size_u,size_v)

## exportar teselacion en espacio parametrico
#prefix = 'infinite_plate_parametric'
#f=open(prefix+'_elements.txt','w') # exportar a archivo
#elem=[] ; contador=0
#for triangle in triangles:
#	if ( any(contador==skipval for skipval in uv_skip) ):
#		continue
#	contador = contador + 1
#	elem.append(triangle.vertex_ids) #element
#	f.write('%d %d %d\n'%(elem[-1][0],elem[-1][1],elem[-1][2]))
#f.close()

#---------------------------------------------------------------

##--espacio parametrico--
#fig,ax = plt.subplots()
#ax.scatter(u,v)	#vertices
#patches = []
#for vertex in elem:
#	tvert = []
#	for pt in vertex:
#		tvert.append([u[pt-1],v[pt-1]]) #forma el triangulo
#	patches.append( Polygon(np.array(tvert),True) ) #crea poligono
#p = PatchCollection(patches, alpha=0.4)
#colors = 10*np.random.rand(len(patches))
#p.set_array(np.array(colors))
#ax.add_collection(p) #triangulos
#plt.show()
#plt.cla()   # Clear axis
#plt.clf()   # Clear figure
#plt.close() # Close a figure window

#--espacio fisico--
#fig,ax = plt.subplots()
#ax.scatter(x,y)	#vertices
#triangulation = Delaunay(list(zip(x,y)))

#plt.triplot(x, y, triangulation.simplices)
#plt.plot(points[:,0], points[:,1], 'o')
#plt.show()

#patches = []
#for vertex in elem:
#	tvert = []
#	for pt in vertex:
#		tvert.append([u[pt-1],v[pt-1]]) #forma el triangulo
#	patches.append( Polygon(np.array(tvert),True) ) #crea poligono
#p = PatchCollection(patches, alpha=0.4)
#colors = 10*np.random.rand(len(patches))
#p.set_array(np.array(colors))
#ax.add_collection(p) #triangulos
#plt.show()
#plt.cla()   # Clear axis
#plt.clf()   # Clear figure
#plt.close() # Close a figure window

##----------------------------------------------------

## exportar datos para rutina table_delaunay
## (triangulacion espacio fisico)
#x=[];y=[] # xy_coord (physical coordinates -> weighted)
#for vertex in vertices:
#	x.append(vertex.x)
#	y.append(vertex.y)
#prefix = 'infinite_plate'
#f=open(prefix+'_nodes.txt','w') # exportar a archivo
#aux_list = [] ; xy_skip = []
#for i in range(len(x)):
#	#--evita exportar puntos repetidos--
#	if ( any( (x[i],y[i]) == aux for aux in aux_list ) ):
#		xy_skip.append(i)
#		continue
#	aux_list.append( (x[i],y[i]) )
#	#----------------------------------
#	f.write('%e %e\n' % (x[i],y[i]) )
#f.close()

## exportar datos para rutina table_delaunay
## (triangulacion espacio parametrico)
#u=[];v=[] # uv_coord (parameter coordinates -> weighted)
#for vertex in vertices:
#	u.append(vertex.u)
#	v.append(vertex.v)
#prefix = 'infinite_plate_parametric'
#f=open(prefix+'_nodes.txt','w') # exportar a archivo
#aux_list = [] ; uv_skip = []
#for i in range(len(u)):
#	#--evita exportar puntos repetidos--
#	if ( any( (u[i],v[i]) == aux for aux in aux_list ) ):
#		uv_skip.append(i)
#		continue
#	aux_list.append( (u[i],v[i]) )
#	#----------------------------------
#	f.write('%e %e\n' % (u[i],v[i]) )
#f.close()

##----------------------------------------------------

## Plot the control point grid and the evaluated surface
#vis_comp = VisPlotly.VisSurface()
#surf.vis = vis_comp
#surf.render()

## Good to have something here to put a breakpoint
#pass


import debug_toolbar
from django.contrib import admin
from django.urls import path, include
from blog.views import *

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', Home.as_view(), name='home'),
    path('category/<str:slug>/', PostsByCategory.as_view(), name='category'),
    path('get_post/<slug:slug>/', post_detail, name='single'),
    path('tag/<str:slug>/', PostByTag.as_view(), name='tag'),
    path('search/', Search.as_view(), name='search'),
    path('register/', user_register, name='register'),
    path('logout/', user_logout, name='logout'),
    path('login/', user_login, name='login'),
    path('like/<int:pk>', LikeView, name='like_comment'),
    path('__debug__/', include(debug_toolbar.urls)),
    path('ckeditor/', include('ckeditor_uploader.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


# -*- coding:UTF-8 -*-
import requests
import time
from lxml import etree
from tqdm import tqdm
import re
import threading

class MeiZiSpider():
    '''妹子爬虫'''
    def __init__(self):
        self.url = 'https://www.mzitu.com/'
        self.page_url = []
        self.page_photo_link = [] # 主图链接
        self.photo_name = [] # 主图名称
        self.photo_url = [] # 图片链接

    def _headers(self,word):
        '''配置请求头'''
        headers = {
            'accept-encoding':'gzip, deflate, br',
            'accept-language': 'zh-CN,zh;q=0.9',
            'referer': 'https://www.mzitu.com/' + word,
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36'
        }
        return headers

    def _get_page(self,word):
        '''获取对应栏总页数'''
        r = requests.get(self.url + word,headers=self._headers(word))
        html = etree.HTML(r.text)
        page = html.xpath('//a[@class="page-numbers"][4]/text()')
        # page = html.xpath('//a[@class="page-numbers"][1]/text()')
        return page

    def _get_page_link(self,word):
        '''使用获取到的pages来构造页码'''
        pages = self._get_page(word)
        for page in range(1, int(pages[0])+1):
            temp = self.url + word + str(page)
            self.page_url.append(temp)
        return self.page_url

    def _get_page_photo_link(self,word):
        '''获取每页中妹纸图的链接地址'''
        self._get_page_link(word)
        for url in tqdm(self.page_url):
            time.sleep(1)
            r = requests.get(url, headers=self._headers(word))
            try:
                if r.status_code == 200:
                    html = etree.HTML(r.text)
                    page_photo_link = html.xpath('//*[@id="pins"]//span/a/@href')
                    photo_name = html.xpath('//*[@id="pins"]//span/a/text()')
                    self.page_photo_link.extend(page_photo_link)
                    self.photo_name.extend(photo_name)
            except:
                pass

    def _get_simple_group_photo_page(self,word):
        '''获取一组妹子图片的页数'''
        self._get_page_photo_link(word)
        pages = []
        for url in tqdm(self.page_photo_link):
            time.sleep(1)
            r = requests.get(url, headers=self._headers(word))
            try:
                if r.status_code == 200:
                    html = etree.HTML(r.text)
                    page = html.xpath('//div[@class="pagenavi"]/a[5]/span/text()')
                    pages.extend(page)
            except:
                pass
        return pages

    def _get_photo_link(self,word):
        '''构造每张图的请求地址'''
        pages = self._get_simple_group_photo_page(word)
        for url in self.page_photo_link:
            for page in tqdm(range(1, int(pages[self.page_photo_link.index(url)])+1)):
                temp = url + '/' +str(page)
                self.photo_url.append(temp)
        return self.photo_url

    def save_photo(self,more_url):
        for url in tqdm(more_url):
            index = more_url.index(url) + 1
            pattern = re.compile(r'\d{6,10}')
            page_photo_id_s = re.findall(pattern, url)
            page_photo_id = page_photo_id_s[0]
            k_word =  page_photo_id + '/' + str(index)
            try:
                r = requests.get(url, headers=self._headers(k_word))
                html = etree.HTML(r.text)
                photo_link = html.xpath('//*[@class="main-image"]//img/@src')
                filename = photo_link[0][-9:]
                with open(filename,'wb') as f:
                    time.sleep(1)
                    r = requests.get(photo_link[0], headers=self._headers(k_word))
                    f.write(r.content)
            except:
                pass

    def mult_threading(self, word):
        full_url = self._get_photo_link(word)
        left = len(full_url) // 4
        mid = len(full_url) // 2
        right = len(full_url) * 3 // 4
        t1 = threading.Thread(target=self.save_photo, args=(full_url[0:left],))
        t2 = threading.Thread(target=self.save_photo, args=(full_url[left:mid],))
        t3 = threading.Thread(target=self.save_photo, args=(full_url[mid:right],))
        t4 = threading.Thread(target=self.save_photo, args=(full_url[right:-1],))
        new_list = [t1, t2, t3, t4]
        for i in new_list:
            i.start()
        for j in new_list:
            j.join()

    def run(self, num):
        if num == '1':
            self.mult_threading('xinggan/')
        elif num == '2':
            self.mult_threading('japan/')
        elif num == '3':
            self.mult_threading('taiwan/')
        elif num == '4':
            self.mult_threading('mm/')
        else:
            pass

if __name__ == '__main__':
    mz = MeiZiSpider()
    msg = input('输入你想抓取的类型：1.性感妹子；2.日本妹子；3.台湾妹子；4.清纯妹子，输入对应序号即可！\n')
    mz.run(msg)


# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

from os import path
from poort import Request
from poort.utils import FileStorage
from utils import get_environ
from utils import HERE

class TestRequest(object):
    def test_base(self):
        environ = get_environ('base')
        request = Request(environ)

        assert request.as_dict() == {
            'host': 'localhost:8000',
            'path': '/',
            'method': 'GET',
            'ssl': False,

            'ip_address': '127.0.0.1',

            'accept_type': ('text/html,application/xhtml+xml,application/xml;'
                            'q=0.9,image/webp,*/*;q=0.8'),
            'content_type': '',

            'want_json': False,
            'want_html': True,

            'query': {},
            'form': {},
            'files': {},
            'cookies': {},
            'json': None,

            'params': {},
        }

    def test_cookie(self):
        environ = get_environ('cookie-get')
        request = Request(environ)

        assert request.get_cookie('some-cookie') == 'test'

    def test_post(self):
        environ = get_environ('multipart-post')
        request = Request(environ)

        with open(path.join(HERE, 'environs', 'attachment.txt')) as stream:
            attachment = FileStorage(stream, 'attachment.txt', 'attachment',
                                     'text/plain')

            assert request.query == {
                'id': '12',
            }
            assert request.form == {
                'color': ['red', 'green', 'blue'],
                'name': 'poort',
            }
            assert request.files == {
                'attachment': attachment,
            }

            assert request.params == {
                'color': ['red', 'green', 'blue'],
                'name': 'poort',
                'id': '12',
                'attachment': attachment,
            }

    def test_json(self):
        environ = get_environ('json-post')
        request = Request(environ)

        assert request.params == {
            'color': ['red', 'green', 'blue'],
        }

    def test_json_invalid(self):
        environ = get_environ('json-invalid-post')
        request = Request(environ)

        assert request.json is None