import os

import openai
from flask import Flask, redirect, render_template, request, url_for, jsonify

app = Flask(__name__)
openai.api_key = os.getenv("OPENAI_API_KEY")

@app.route("/", methods=("GET", "POST"))
def index():
    if request.method == "GET":
        query_parameters = request.args
        if query_parameters.get("prompt"):
            prompt = query_parameters.get("prompt")
            response = openai.Completion.create(
                model="text-davinci-003",
                prompt=prompt,
                temperature=0.6,
                max_tokens=4000-int(len(prompt)/5),
            )
            return jsonify(response.choices[0].text)
        return jsonify('No prompt provided')
    return jsonify('ChatGPT API')


"""
返回与给定先序遍历 preorder 相匹配的二叉搜索树（binary search tree）的根结点。
"""
from leetcode.utils import *
from typing import *

class Solution:
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        if len(preorder) == 0:
            return None
        root = TreeNode(preorder[0])
        for num in preorder[1:]:
            self.insert(root, num)
        return root

    def insert(self, root, val):
        ptr = root
        while ptr:
            if val < ptr.val:
                if ptr.left is None:
                    ptr.left = TreeNode(val)
                    return
                ptr = ptr.left
            elif val > ptr.val:
                if ptr.right is None:
                    ptr.right = TreeNode(val)
                    return
                ptr = ptr.right


# Description: This short script exchanges lines for a "standard_b.lib" file
# necessary for Curves+ input. It exchanges (using python list indexing), from
# 10 lines, 2 <--> 3, and then 2 <--> 9. But it needs to this for all sets of 10
# lines.
# Author: Angel-Emilio Villegas Sanchez
#Last Updated: 07/05/21

import sys

if len(sys.argv) == 2 :
    r_file = open(sys.argv[1],'r')
    lines = list(line.strip() for line in r_file)

    # Exchange the lines. Not necessary to alocate extra memory, so I'll just have
    # one counter.
    for sec in range(2,len(str)-1,10):
        third = sec+1
        lines[sec],lines[third] = lines[third],lines[sec]
        ninth = sec + 7
        lines[sec],lines[ninth] = lines[ninth],lines[sec]

    for lin in lines:
        print(lin)


import sys
sys.stdin = open('input.txt')

def pre_order(node):
    if node != 0:
        left1, right1 = tree[node][1], tree[node][2]

        print(chr(node+64), end='')
        pre_order(left1)
        pre_order(right1)

def in_order(node):
    if node != 0:
        left1, right1 = tree[node][1], tree[node][2]
        in_order(left1)
        print(chr(node + 64), end='')
        in_order(right1)

def post_order(node):
    if node != 0:
        left1, right1 = tree[node][1], tree[node][2]
        post_order(left1)
        post_order(right1)
        print(chr(node + 64), end='')

N = int(input())

tree = [[0, 0, 0] for _ in range(N+1)]
for _ in range(N):
    current, left, right = input().split()
    current = ord(current) - 64
    left = ord(left) - 64
    right = ord(right) - 64
    if 1<=left<=27:
        tree[current][1] = left
        tree[left][0] = current
    if 1<=right<=27:
        tree[current][2] = right
        tree[right][0] = current

pre_order(1)
print()
in_order(1)
print()
post_order(1)


def End(result: list):
    Ending(result[0], result[1])
    return

# Method use for taking the initial config
def Ending(config: dir, wave: str):
    if(config["visible"] or config["save"]):
        if(config["orientation"] == "1"):
            for i in range(len(wave)):
                wave[i] = wave[i][::-1]
            result = WriteVertical(config, wave)
        if(config["orientation"] == "2"):
            result = WriteOrizontal(config, wave, config["level"]-1, -1)
        if(config["orientation"] == "3"):
            result = WriteVertical(config, wave)
        if(config["orientation"] == "4"):
            result = WriteOrizontal(config, wave, 0, config["level"])

        if(config["visible"]):
            print(result)
        if(config["save"]):
            file = open(config["save"][0], config["save"][1])
            file.write(result)
            file.close()

    return

def WriteVertical(config, wave):
    result = ""
    for s in wave:
        result += s + "\n"
    return result

def WriteOrizontal(config, wave, start, end):
    result = ""
    while(start != end):
        for s in wave:
            result += s[start]
        result += "\n"
        if(start < end):
            start += 1
        else:
            start -= 1
    return result


'''Smoothing/Blurring is done when an img has a lot of noise such as camera sensors,lighting issues,etc'''

import cv2 as cv
import numpy as np

img = cv.imread('Resources/Photos/cats.jpg')
cv.imshow('Original', img)

# 1.) Averaging - Each pixel is replaced by the average value of all pixels in the kernel window i.e. for a 3*3 kernel the centre pixel will be replaced by avg of other 8 surrounding pixels
average = cv.blur(img, (3,3)) #will implement averaging blur with a kernel of3*3. Increasing kernel size will increase blur
cv.imshow('Average Blur', average)

# 2.) GaussianBlur - similar to averaging operation but the surrounding pixels given a weight so weighted avg calculated. It gives less blurring than Averaging Blur but is more natural.
gauss = cv.GaussianBlur(img, (3,3), 0)   #0 is s.d. in x direction
cv.imshow('Gaussian Blurred', gauss)

# 3.) Median Blur - Instead of averaging it replaces pixel with median of its surrounding.
# It provided more blur than above two methods and  is effective to reduce SALT&PEPPER NOISE.
# It is not effective with higher kernel sizes such as 5*5 or 7*7
median = cv.medianBlur(img, 3) # kernel size is just 3 as automaticallly understands 3*3
cv.imshow('Median Blur', median)

# 4.) Bilateral Blurring - most effective blurring
#other blurring methods dont see if they are removing edges or not but Bilateral blurring does blurring but RETAINS edges as well
bilateral = cv.bilateralFilter(img, 10, 20, 20) #10 is diamter of neighborhood, 20 is sigma color (higher value indicates more colors in neighborhood), 20 is sigma space (higher value means pixel farther from centre will influence blurring more)
cv.imshow('Bilateral blurring', bilateral)

cv.waitKey(0)


#!/usr/bin/python3
import os
import tempfile
import argparse

def query_db(row):

    if not row:
        row = 'FirstName'

    sql = f".open /home/jared/chinook.db\nSELECT {row} FROM employees;"
    os.system(f'echo "{sql}" | /usr/bin/sqlite3')

    print("Done!")

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--row", help="Row to query")
    args = parser.parse_args()

    query_db(args.row)


"""Contains example scripts presenting various activation functions characteristics."""
import os

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

import inspect
from typing import Dict, Type

import NaiveNeurals.MLP.activation_functions as functions_module

def plot_characteristics():
    """Plots various activation functions characteristics"""
    functions: Dict[str, Type[functions_module.ActivationFunction]] = {}
    for _, obj in inspect.getmembers(functions_module):
        if obj == functions_module.ActivationFunction:
            continue
        if inspect.isclass(obj) and issubclass(obj, functions_module.ActivationFunction):
            functions[obj.label] = obj

    plot_marks = ['m-', 'k-', 'r--', 'b-', 'c-']
    colors = ['magenta', 'black', 'red', 'blue', 'cyan']
    f1 = plt.figure()
    ax1 = f1.add_subplot(111)
    legend_handlers = []
    for fn_label, fn in functions.items():
        if fn_label == 'lin':
            x_vals = np.linspace(-1, 1, 21)
        elif fn_label == 'softplus':
            x_vals = np.linspace(-2, 2, 21)
        else:
            x_vals = np.linspace(-4, 4, 101)
        plot_label = mpatches.Patch(color=colors.pop(), label=fn_label)
        legend_handlers.append(plot_label)
        ax1.plot(x_vals, fn.function(x_vals), plot_marks.pop())

    plt.legend(handles=legend_handlers)
    plt.savefig(os.path.abspath(os.path.dirname(__file__)) + '/../docs/graphs/activation_functions.png')
    plt.show()

if __name__ == '__main__':
    plot_characteristics()


def read_graph(vertex_number, edge_number):
    graph = [[] for i in range(vertex_number)]
    for i in range(edge_number):
        v1, v2, w = map(int, input().split())
        graph[v1].append((v2, w))
        graph[v2].append((v1, w))
    return graph

def prim(graph):
    spanning_vertexes = {0}
    tree = []
    for i in range(len(graph) - 1):
        min_length = float('+inf')
        for vertex in spanning_vertexes:
            for neighbour, weight in graph[vertex]:
                if neighbour not in spanning_vertexes and weight < min_length:
                    cur_v, cur_e, min_length = neighbour, (vertex, neighbour), weight
        spanning_vertexes.add(cur_v)
        tree.append(cur_e)
    return tree

vertex_number, edge_number = tuple(map(int, input().split()))
result = prim(read_graph(vertex_number, edge_number))
print(result)


from toxi.geom import Vec3D

W = H = 500
FPS = 30.0
DURATION = 2
N_FRAMES = DURATION * FPS
N_SAMPLES = 4
BG_COLOR = color(72,45,87)
MAIN_COLOR = color(0)
RECORD = True

COLOR1 = color(234,236,198)
COLOR2 = color(53,31,57)
COLOR3 = color(199,211,182)
COLOR4 = color(165,187,163)
PALETTE = [COLOR1, COLOR2, COLOR3, COLOR4]

CENTRAL, BOTTOM_OPEN, TOP_OPEN, BOTTOM_CLOSE, TOP_CLOSE, NONE = range(6)

class Particle(object):
    def __init__(self, x, y, w, h, col, ptype, direction):
        self.x = x
        self.y = y
        self.z = 0
        self.width, self.height = w, h
        self.color = col
        self.type = ptype
        self.direction = direction

    def display(self, t, is_shadow=False):
        inverse = False

        if self.type == CENTRAL:
            pos = Vec3D(self.x, self.y, self.z)
            a = Vec3D(0, 0, 0).add(pos)
            b = Vec3D(self.width - 5, 0, 0).add(pos)
            c = Vec3D(self.width - 5, (self.height - 5), 0).add(pos)
            d = Vec3D(0, (self.height - 5), 0).add(pos)
            for v in [a, b, c, d]:
                v.addSelf(Vec3D(0, self.direction * self.height * t, 0))
        elif self.type == TOP_OPEN:
            pos = Vec3D(self.x, self.y, self.z)
            a = Vec3D(0, 0, 0).add(pos)
            b = Vec3D(self.width - 5, 0, 0).add(pos)
            c = Vec3D(self.width - 5, self.height - 5, 0).rotateX(-PI * (1 - t)).add(pos)
            d = Vec3D(0, self.height - 5, 0).rotateX(-PI * (1 - t)).add(pos)
            for v in [a, b, c, d]:
                v.addSelf(Vec3D(0, self.direction * self.height * t - 5 * (1 - t), 0))
            if t < 0.46: inverse = True
        elif self.type == BOTTOM_OPEN:
            pos = Vec3D(self.x, self.y + self.height, self.z)
            a = Vec3D(0, 0, 0).add(pos)
            b = Vec3D(self.width - 5, 0, 0).add(pos)
            c = Vec3D(self.width - 5, self.height - 5, 0).rotateX(-PI * t).add(pos)
            d = Vec3D(0, self.height - 5, 0).rotateX(-PI * t).add(pos)
            for v in [a, b, c, d]:
                v.addSelf(Vec3D(0, self.direction * (self.height - 5) * t, 0))
            if t > 0.46: inverse = True
        elif self.type == BOTTOM_CLOSE:
            pos = Vec3D(self.x, self.y + self.height, self.z)
            a = Vec3D(0, 0, 0).add(pos)
            b = Vec3D(self.width - 5, 0, 0).add(pos)
            c = Vec3D(self.width - 5, self.height - 5, 0).rotateX(-PI * (1 - t)).add(pos)
            d = Vec3D(0, self.height - 5, 0).rotateX(-PI * (1 - t)).add(pos)
            for v in [a, b, c, d]:
                v.addSelf(Vec3D(0, self.direction * self.height * t - 5 * (1 - t), 0))
            if t < 0.53: inverse = True
        elif self.type == TOP_CLOSE:
            pos = Vec3D(self.x, self.y, self.z)
            a = Vec3D(0, -self.height + 5, 0).rotateX(PI * (1 - t)).add(pos)
            b = Vec3D(self.width - 5, -self.height + 5, 0).rotateX(PI * (1 - t)).add(pos)
            c = Vec3D(self.width - 5, 0, 0).add(pos)
            d = Vec3D(0, 0, 0).add(pos)
            for v in [a, b, c, d]:
                v.addSelf(Vec3D(0, self.direction * self.height * t - 5 * t, 0))
            if t < 0.54: inverse = True

        if is_shadow:
            color2 = color(25)
            color3 = color(25)
            color4 = color(25)
        else:
            color2 = COLOR2
            color3 = COLOR3
            color4 = COLOR4

        noStroke()
        if not inverse:
            fill(color3)
            beginShape()
            vertex(a.x(), a.y(), a.z())
            vertex(b.x(), b.y(), b.z())
            vertex(c.x(), c.y(), c.z())
            endShape(CLOSE)

            fill(color4)
            beginShape()
            vertex(a.x(), a.y(), a.z())
            vertex(d.x(), d.y(), d.z())
            vertex(c.x(), c.y(), c.z())
            endShape(CLOSE)
        else:
            fill(color3)
            beginShape()
            vertex(b.x(), b.y(), b.z())
            vertex(c.x(), c.y(), c.z())
            vertex(d.x(), d.y(), d.z())
            endShape(CLOSE)

            fill(color4)
            beginShape()
            vertex(a.x(), a.y(), a.z())
            vertex(b.x(), b.y(), b.z())
            vertex(d.x(), d.y(), d.z())
            endShape(CLOSE)

        noFill()
        stroke(color2)
        beginShape()
        vertex(a.x(), a.y(), a.z())
        vertex(b.x(), b.y(), b.z())
        vertex(c.x(), c.y(), c.z())
        vertex(d.x(), d.y(), d.z())
        endShape(CLOSE)

def draw_(t):
    background(COLOR1)

    strokeWeight(2)
    for particle in particles:
        particle.display(t, is_shadow=True)

    filter(BLUR, 4)

    for particle in particles:
        particle.display(t)

def setup():
    global particles

    size(W, H, P3D)
    frameRate(FPS)

    particles = []
    r = 150
    w = h = 10
    gap = 2 * r / float(w)
    for i in range(w):
        for j in range(h):
            x = (i - w / 2 + 0.15) * gap + width / 2
            y = (j - h / 2 + 0.5 * (i % 2) - 0.25) * gap + height / 2
            if j == 0 and i % 2:
                ptype = BOTTOM_CLOSE
            elif j == h-1 and i % 2:
                ptype = TOP_OPEN
            elif j == 0 and not i % 2:
                ptype = BOTTOM_OPEN
            elif j == h-1 and not i % 2:
                ptype = TOP_CLOSE
            else:
                ptype = CENTRAL
            p1 = Particle(x, y, gap, gap, COLOR3, ptype, -(2 * (i % 2) - 1))
            p2 = Particle(x, y, gap, gap, COLOR3, ptype, -(2 * (i % 2) - 1))
            particles.append(p2)

def draw():
    if not RECORD:
        t = (frameCount / float(N_FRAMES)) % 1.0
        draw_(t)
    elif N_SAMPLES <= 1:
        t = (frameCount / float(N_FRAMES)) % 1.0
        draw_(t)
        if frameCount <= N_FRAMES:
            saveFrame('gif/####.gif')
        else:
            exit()
    else:
        result = [[0, 0, 0] for i in range(W * H)]
        for sample in range(N_SAMPLES):
            t = (frameCount + sample / float(N_SAMPLES)) / N_FRAMES
            draw_(t)
            loadPixels()
            for i, pix in enumerate(pixels):
                result[i][0] += red(pix)
                result[i][1] += green(pix)
                result[i][2] += blue(pix)
        loadPixels()
        for i, rgb in enumerate(result):
            pixels[i] = color(rgb[0] / N_SAMPLES, rgb[1] / N_SAMPLES, rgb[2] / N_SAMPLES)
        updatePixels()
        if frameCount <= N_FRAMES:
            saveFrame('gif/####.gif')
        else:
            exit()


import cv2
import numpy as np
from PIL import Image
import os

path = 'dataset'

recogniser = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

def getImagesAndLabels(path):

    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    #it should be for f in ... maybe
    #it joins one or more path components intelligently. So basically an array of paths is created.
    #Each path is of type "path/f" where path is defined above and f is in os.listdir(path)
    #it returns a string which represents the concatenated path components.
    #os.listdir() method in python is used to get the list of all files and directories in the
    #specified directory.
    #Basically this code stores the paths of all files in the dataset folder in the imagePaths variable
    facesamples = []
    ids = []

    for imagePath in imagePaths:
        PIL_img = Image.open(imagePath).convert('L')
        #Returns a converted copy of this image
        # Syntax: Image.convert(mode=None, matrix=None, dither=None, palette=0, colors=256)
        # for grayscale the mode is 'L'
        img_numpy = np.array(PIL_img, 'uint8')#converting the image into a numpy array

        id = int(os.path.split(imagePath)[-1].split(".")[1])
        #os.path.split splits the path into head and tail and returns a list containing these.
        #the tail is basically the filename in the path and is the last object in the returned list
        #-1 is used to access this last string. now this string is split into multiple strings by
        #a delimmiter '.' and then the first element of this list is accessed.

        faces = detector.detectMultiScale(img_numpy)
        #default scalefactor and minneighbours for this are 1.1 and 3.

        for (x, y, w, h) in faces:
            facesamples.append(img_numpy[y:y+h, x:x+w])
            ids.append(id)

        return facesamples, ids

print("\n [INFO] Training faces.....")

faces, ids = getImagesAndLabels(path)
recogniser.train(faces, np.array(ids))

recogniser.write('trainer/trainer.yml')

print("\n [INFO] {0} faces trained.".format(len(np.unique(ids))))


__author__ = 'xuxiaoye'
from django.conf.urls import url
from . import views

urlpatterns = [
    # Json APIs
    url(r'^jsonResult$', views.jsonResult, name='jsonResult'),
    url(r'^api\/login$', views.apiLogin, name='apiLogin'),
    url(r'^rs$', views.rs, name='rs'),
    # End of Json APIs
    # Wechat backend
    url(r'^weixin$', views.weixin, name='weixin'),
    # End of Wechat backend
    # Common process
    url(r'^back$', views.back, name='back'),
    url(r'^logoff$', views.logoff, name='logoff'),
    # End of Common process
    # Application pages
    url(r'^app1\_1$', views.app1_1, name='app1_1'),
    url(r'^app1\_2$', views.app1_2, name='app1_2'),
    url(r'^app2\_1$', views.app2_1, name='app2_1'),
    # End of Application pages
    # Ajax
    url(r'^ajax$', views.ajax, name='ajax'),
    # End of Ajax
    # Default home page
    url(r'^.*$', views.index, name='index'),
    # End of Default home page
]


import torch
import torchvision
import torch.nn as nn

def get_vgg16():
    vgg16 = torchvision.models.vgg16(pretrained=False)
    weight = vgg16.features[0].weight.clone()
    vgg16.features[0] = nn.Conv2d(1, 64, kernel_size=(3, 3), stride=(1, 1), padding=1)
    with torch.no_grad():
        vgg16.features[0].weight[:, 0] = weight[:, 0]
    vgg16.classifier[6] = nn.Linear(in_features=4096, out_features=4, bias=True)
    return vgg16

def get_resnet50():
    resnet50 = torchvision.models.resnet50(pretrained=False)
    weight = resnet50.conv1.weight.clone()
    resnet50.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=3)
    with torch.no_grad():
        resnet50.conv1.weight[:, 0] = weight[:, 0]
    resnet50.fc = nn.Linear(in_features=2048, out_features=4, bias=True)
    return resnet50

def get_squeezenet():
    squeezenet = torchvision.models.squeezenet1_0(pretrained=False)
    weight = squeezenet.features[0].weight.clone()
    squeezenet.features[0] = nn.Conv2d(1, 96, kernel_size=(7, 7), stride=(1, 1), padding=1)
    with torch.no_grad():
        squeezenet.features[0].weight[:, 0] = weight[:, 0]
    squeezenet.classifier[1] = nn.Conv2d(512, 4, kernel_size=(1, 1), stride=(1, 1))
    return squeezenet

def get_resnext():
    resnext = torchvision.models.resnext50_32x4d(pretrained=False)
    weight = resnext.conv1.weight.clone()
    resnext.conv1 = nn.Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=3)
    with torch.no_grad():
        resnext.conv1.weight[:, 0] = weight[:, 0]
    resnext.fc = nn.Linear(2048, 4, bias=True)
    return resnext

def get_densenet():
    densenet = torchvision.models.densenet161(pretrained=False)
    weight = densenet.features.conv0.weight.clone()
    densenet.features.conv0 = nn.Conv2d(1, 96, kernel_size=(7, 7), stride=(2, 2), padding=3)
    with torch.no_grad():
        densenet.features.conv0.weight[:, 0] = weight[:, 0]
    densenet.classifier = nn.Linear(2208, 4, bias=True)
    return densenet

def count_parameters(model):
        return sum(p.numel() for p in model.parameters() if p.requires_grad)


"""
return square submatrix that sums to the higest value

this solution is O(l^3) where l is the length of one side of the matrix
 *technically O(longer_side * shorter_side ^ 2)

first we use DP to build a way to get sums of squares in constant time (O(l^2))

then we go through each element and try all valid squares starting from there (O(l^3))

once we find the max subarray, slice it out and return
"""

class DpSum(object):
    def __init__(self, arr):
        self.arr = arr
        self.height = len(arr)
        self.width = len(arr[0])
        self.memo = [[0 for i in range(len(row))] for row in arr]
        self.populate_memo(arr)

    def __str__(self):
        arrstr = self.stringify_arr_rows(self.arr)
        memostr = self.stringify_arr_rows(self.memo)

        rows = ['{} <|> {}'.format(a, m) for a, m in zip(arrstr, memostr)]

        rows.append('array <' + '-' * 30 + '> memo')

        return '\n'.join(rows)

    def stringify_arr_rows(self, arr):
        return [''.join([str(i).center(5) for i in row]) for row in arr]

    def print_arr(self, arr):
        print('\n'.join(self.stringify_arr_rows(arr)))

    def populate_memo(self, arr):
        for r in range(self.height):
            for c in range(self.width):
                self.memo[r][c] = self.get_memo(r-1, c) + \
                self.get_memo(r, c-1) - \
                self.get_memo(r-1, c-1) + \
                arr[r][c]

    def get_memo(self, r, c):
        if r < 0 or r > self.height or c < 0 or c > self.width:
            return 0
        return self.memo[r][c]

    def sum(self, r1, c1, r2, c2, do_print=False):
        assert(r1 < r2 and c1 < c2)
        r1 -= 1
        c1 -= 1
        if do_print:
            print('sum ({}, {} - {}, {})'.format(r1+1, c1+1, r2, c2), self.get_memo(r2, c2), self.get_memo(r1, c2), self.get_memo(r2, c1), self.get_memo(r1, c1))
        return self.get_memo(r2, c2) - \
            self.get_memo(r1, c2) - \
            self.get_memo(r2, c1) + \
            self.get_memo(r1, c1)

    def square(self, r, c, length):
        r2 = r + length
        c2 = c + length
        if r2 >= self.height or c2 >= self.width:
            return None
        return self.sum(r, c, r2, c2)

    def max_square(self):
        max_sum = -9999999
        max_square = (-1, -1, -1)
        for r in range(self.height):
            for c in range(self.width):
                length = 1
                while r + length < self.height and c + length < self.width:
                    total = self.square(r, c, length)
                    if total > max_sum:
                        max_sum = total
                        max_square = (r, c, length)
                    length += 1
        return max_square

    def subarray(self, r1, c1, r2, c2):
        return [[i for i in row[c1:c2+1]] for row in self.arr[r1:r2+1]]

    def max_subarray(self):
        square = self.max_square()
        return self.subarray(square[0], square[1], square[0] + square[2], square[1] + square[2])

test_arr = [
    [-1, 2, 6, -8, 9],
    [6, 1, 3, -4, 5],
    [-9, 2, 5, 6, -4],
    [5, 8, 4, -7, 8],
    [2, 5, 3, 2, 6]
]

test_arr_2 = [
    [1, -2, 4],
    [-7, 5, 6],
    [-2, -12, 3]
]

test_arrays = [test_arr, test_arr_2]

if __name__ == '__main__':
    for a in test_arrays:
        dp = DpSum(a)
        print('-'*50)
        print(dp)
        print('-'*50)
        dp.print_arr(dp.max_subarray())


import numpy as mypy
import threading
import time
import random

import socket as mysoc
#import client

def reverseString(strz):
  if strz == "\n" or strz == "":
    client.globalBoolVar = False
    return

  #remove '\n'
  if strz[len(strz)-1] == '\n':
    str1 = strz[0:len(strz)-1]

  chars = list(str1)
  for i in range(len(str1)//2):
    tmp = chars[i]
    chars[i] = chars[len(str1)-i-1]
    chars[len(str1)-i-1] = tmp

  outputStr = ''.join(chars)
  return outputStr

def server():
    try:
        ss=mysoc.socket(mysoc.AF_INET, mysoc.SOCK_STREAM)
        print("[S]: Server socket created")
    except mysoc.error as err:
        print('{} \n'.format("socket open error ",err))
    server_binding=('',50004)
    ss.bind(server_binding)
    ss.listen(1)
    host=mysoc.gethostname()
    print("[S]: Server host name is: ",host)
    localhost_ip=(mysoc.gethostbyname(host))
    print("[S]: Server IP address is  ",localhost_ip)
    csockid,addr=ss.accept()
    print ("[S]: Got a connection request from a client at", addr)
    #send a intro  message to the client.
    msg="Welcome to CS 352"
    csockid.send(msg.encode('utf-8'))

#Q2 - recv string
    while client.globalBoolVar == True:

      stringIN = csockid.recv(1024).decode('utf-8')
      if stringIN == "":
        break
      else:
        print("[S]: Receive request from the connect client: ", stringIN[0:len(stringIN)-1])
        stringOut002 = reverseString(stringIN)
        csockid.send(stringOut002.encode('utf-8'))

   # Close the server socket
    ss.close()
    exit()

t1 = threading.Thread(name='server', target=server)
print("SERVER START")
t1.start()
time.sleep(random.random()*5)
#t2 = threading.Thread(name='client', target=client.client)
#print("CLIENT START")
#t2.start()

input("Hit ENTER  to exit")

exit()


# 导入操作系统库
import os
# 更改工作目录
os.chdir(r"D:\softwares\applied statistics\pythoncodelearning\chap1\sourcecode")
# 导入基础计算库
import numpy as np
# 导入绘图库
import matplotlib.pyplot as plt
# 导入Lasso模型
from sklearn.linear_model import MultiTaskLasso, Lasso
# 导入绘图库中的字体管理包
from matplotlib import font_manager
# 实现中文字符正常显示
font = font_manager.FontProperties(fname=r"C:\Windows\Fonts\SimKai.ttf")
# 使用seaborn风格绘图
plt.style.use("seaborn-v0_8")
# 设置样本量，维度，回归模型中y的维度（响应变量的多元回归）
n_samples, n_features, n_tasks = 100, 30, 40
# 显著变量的个数
n_relevant_features = 5
# 初始化真实系数，是一个矩阵
coef = np.zeros((n_tasks, n_features))
# 时刻
times = np.linspace(0, 2 * np.pi, n_tasks)
# 设置随机数种子
np.random.seed(10)
# 生成真实系数
for k in range(n_relevant_features):
    coef[:, k] = np.sin(
        (1.0 + np.random.randn(1)) * times + 3 * np.random.randn(1)
    )
# 生成X
X = np.random.randn(n_samples, n_features)
# 生成Y
Y = np.dot(X, coef.T) + np.random.randn(n_samples, n_tasks)
print("查看多元响应变量Y的情况：", Y[:5, :2], sep="\n")
# 建立Lasso模型，分别对Y的每一个分量做，提取系数
coef_lasso_ = np.array(
    [
        Lasso(alpha=0.5).fit(X, y).coef_ for y in Y.T
    ]
)
# 建立MultiLasso模型，提取系数
coef_multi_task_lasso_ = MultiTaskLasso(alpha=1.0).fit(X, Y).coef_
# 开始绘图
fig, axs = plt.subplots(nrows=1, ncols=2, figsize=(8, 5))
# 用于展示稀疏二维数组的图形
axs[0].spy(coef_lasso_)
axs[0].set_xlabel("Feature")
axs[0].set_ylabel("Time (or Task)")
axs[0].text(10, 5, "Lasso")
axs[1].spy(coef_multi_task_lasso_)
axs[1].set_xlabel("Feature")
axs[1].set_ylabel("Time (or Task)")
axs[1].text(10, 5, "MultiTaskLasso")
fig.suptitle("Coefficient non-zero location")
plt.show()
fig.savefig("../codeimage/code15.pdf")
# 绘制第一个特征前的系数
feature_to_plot = 0
# 开始绘图
fig1, ax = plt.subplots(figsize=(6,6), tight_layout=True)
# 绘制coef的线图
ax.plot(
    coef[:, feature_to_plot],
    color="seagreen",
    linewidth=2,
    label="Ground truth"
)
# 绘制coef_lass0的线图
ax.plot(
    coef_lasso_[:, feature_to_plot],
    color="cornflowerblue",
    linewidth=2,
    label="Lasso"
)
# 绘制coef_task_lasso的线图
ax.plot(
    coef_multi_task_lasso_[:, feature_to_plot],
    color="gold",
    linewidth=2,
    label="MultiTaskLasso",
)
# 显示图例
ax.legend(loc="best")
# 设置纵轴范围
ax.set_ylim([-1.1, 1.1])
plt.show()
fig1.savefig("../codeimage/code16.pdf")


import numpy as np
import matplotlib.pyplot as plt
import os
import pandas as pd
import csv

### NOTE: Need to make filepaths for the laptop now ###

def lagrange(X):
    '''
    Function for creating Lagrange basis functions.
    Inputs
    ------
    X: array-like. The elements nodal x-locations.
    Returns
    -------
    List of basis functions and a list of their derivatives. This function supports linear
    and quadratic basis functions.
    '''
    deg = len(X)-1
    if deg == 1:
        x0 = X[0]
        x1 = X[1]
        x = np.linspace(x0,x1)
        phi0 = (x-x1)/(x0-x1)
        phi1 = (x-x0)/(x1-x0)
        dphi0 = 1/(x0-x1)
        dphi1 = 1/(x1-x0)
        return [phi0, phi1], [dphi0*np.ones_like(x), dphi1*np.ones_like(x)], x
    elif deg ==2:
        x0, x1, x2 = X
        x = np.linspace(x0,x2)
        phi0 = (x-x1)*(x-x2)/((x0-x1)*(x0-x2))
        phi1 = (x-x0)*(x-x2)/((x1-x0)*(x1-x2))
        phi2 = (x-x0)*(x-x1)/((x2-x0)*(x2-x1))
        dphi0 = (2*x-x1-x2)/((x0-x1)*(x0-x2))
        dphi1 = (2*x-x0-x2)/((x1-x0)*(x1-x2))
        dphi2 = (2*x-x0-x1)/((x2-x0)*(x2-x1))
        return [phi0, phi1, phi2], [dphi0, dphi1, dphi2], x
    else:
        raise ValueError('Currently supporting only first or second order Lagrange basis functions.')

# def read_nodes(file):
#     path = os.getcwd()
#     if 'mattjwilliams' in path:
#         path = '/Users/mattjwilliams/Documents/PythonStuff/FEM/GangLi/Chapter4/HeatTransfer/ProgramFiles'
#     node_df = pd.read_csv(os.path.join(path,file),delimiter=' ')
#     return node_df

def read_file(file):
    path = os.getcwd()
    if 'mattjwilliams' in path:
        path = '/Users/mattjwilliams/Documents/PythonStuff/FEM/GangLi/Chapter4/HeatTransfer/ProgramFiles'
    else:
        path = '/Users/mattwilliams/Documents/PythonProjects/FEM/GangLi/IntroToFEM/Chapter4/HeatTransfer/ProgramFiles'
    df = pd.read_csv(os.path.join(path,file),delimiter=' ')
    return df

def mesher1D(xstart,xend,n_elements,deg=1):
    if deg == 1:
        n_nodes = n_elements + 1
        dx = (xend-xstart)/(n_elements)
        elements = np.arange(0,n_elements,dtype='int8')
        arr = np.zeros((n_elements,deg+2),dtype='object')
        node1 = np.arange(xstart,xend,dx)
        node2 = np.arange(xstart+dx,xend+dx,dx)
        arr[:,0] = elements
        arr[:,1] = node1
        arr[:,2] = node2
    else:
        n_nodes = 2*n_elements + 1
        dx = (xend-xstart)/(n_elements)
        elements = np.arange(0,n_elements,dtype='int8')
        arr = np.zeros((n_elements,deg+2),dtype='object')
        node1 = np.arange(xstart,xend,dx)
        node2 = np.arange(xstart+dx/2,xend+dx/2,dx)
        node3 = np.arange(xstart+dx,xend+dx,dx)
        arr[:,0] = elements
        arr[:,1] = node1
        arr[:,2] = node2
        arr[:,3] = node3
    path = os.getcwd()
    if 'mattjwilliams' in path:
        path = '/Users/mattjwilliams/Documents/PythonStuff/FEM/GangLi/Chapter4/HeatTransfer/ProgramFiles'
    else:
        path = '/Users/mattwilliams/Documents/PythonProjects/FEM/GangLi/IntroToFEM/Chapter4/HeatTransfer/ProgramFiles'
    fname = 'nodes.txt'
    if deg == 1:
        headers = ['element','node0','node1']
    else:
        headers = ['element','node0','node1','node2']
    with open(os.path.join(path,fname),'w',newline='') as f:
        mywriter = csv.writer(f,delimiter=' ')
        mywriter.writerow(headers)
        mywriter.writerows(arr)
    return None

def element_indexer(n_elements,deg):
    arr = np.zeros((n_elements,deg+2),dtype='int8')
    arr[:,0] = np.arange(n_elements)
    if deg == 1:
        arr[:,1] = np.arange(0,n_elements,deg)
        arr[:,2] = np.arange(1,n_elements+1,deg)
        headers = ['element','node0','node1']
    else:
        n_nodes = 2*n_elements + 1
        arr[:,1] = np.arange(0,n_nodes-1,deg)
        arr[:,2] = np.arange(1,n_nodes,deg)
        arr[:,3] = np.arange(2,n_nodes+1,deg)
        headers = ['element','node0','node1','node2']

    path = os.getcwd()
    if 'mattjwilliams' in path:
        path = '/Users/mattjwilliams/Documents/PythonStuff/FEM/GangLi/Chapter4/HeatTransfer/ProgramFiles'
    else:
        path = '/Users/mattwilliams/Documents/PythonProjects/FEM/GangLi/IntroToFEM/Chapter4/HeatTransfer/ProgramFiles'
    fname = 'elements.txt'
    with open(os.path.join(path,fname),'w',newline='') as f:
        mywriter = csv.writer(f,delimiter=' ')
        mywriter.writerow(headers)
        mywriter.writerows(arr)
    return None

def global_nodes(xstart,xend,n_elements,deg=1):
    if deg == 1:
        n_nodes = n_elements + 1
    else:
        n_nodes = 2*n_elements + 1
    arr = np.zeros((n_nodes,2),dtype='object')
    arr[:,0] = np.arange(n_nodes)
    dx = (xend-xstart)/(n_nodes-1)
    arr[:,1] = np.arange(xstart,xend+dx,dx)
    path = os.getcwd()
    if 'mattjwilliams' in path:
        path = '/Users/mattjwilliams/Documents/PythonStuff/FEM/GangLi/Chapter4/HeatTransfer/ProgramFiles'
    else:
        path = '/Users/mattwilliams/Documents/PythonProjects/FEM/GangLi/IntroToFEM/Chapter4/HeatTransfer/ProgramFiles'
    fname = 'global_nodes.txt'
    headers = ['global node','x location']
    with open(os.path.join(path,fname),'w',newline='') as f:
        mywriter = csv.writer(f,delimiter=' ')
        mywriter.writerow(headers)
        mywriter.writerows(arr)
    return None

def boundary_conditions(n_elements,bcs,deg=1):
    '''
    Boundary conditions passed as a list:
    Left end type, left end value, right end type, right end value

    Type 1 == Dirichlet, Type 2 == Neumann or flux
    '''
    type1, val1, type2, val2 = bcs
    if deg == 1:
        n_nodes = n_elements + 1
    else:
        n_nodes = 2*n_elements + 1
    arr = np.zeros((n_nodes,3),dtype='object')
    arr[:,0] = np.arange(n_nodes)
    arr[0,1] = type1
    arr[0,2] = val1
    arr[-1,1] = type2
    arr[-1,2] = val2
    path = os.getcwd()
    if 'mattjwilliams' in path:
        path = '/Users/mattjwilliams/Documents/PythonStuff/FEM/GangLi/Chapter4/HeatTransfer/ProgramFiles'
    else:
        path = '/Users/mattwilliams/Documents/PythonProjects/FEM/GangLi/IntroToFEM/Chapter4/HeatTransfer/ProgramFiles'
    fname = 'bcs.txt'
    headers = ['global node','type','value']
    with open(os.path.join(path,fname),'w',newline='') as f:
        mywriter = csv.writer(f,delimiter=' ')
        mywriter.writerow(headers)
        mywriter.writerows(arr)
    return None

def properties(n_elements,k1,k2):
    arr = np.zeros((n_elements,2),dtype='object')
    if n_elements%2 != 0:
        arr[:n_elements//2+1,1] = k1
        arr[n_elements//2+1:,1] = k2
        arr[:,0] = np.arange(n_elements)
    else:
        arr[:n_elements//2,1] = k1
        arr[n_elements//2:,1] = k2
        arr[:,0] = np.arange(n_elements)
    path = os.getcwd()
    if 'mattjwilliams' in path:
        path = '/Users/mattjwilliams/Documents/PythonStuff/FEM/GangLi/Chapter4/HeatTransfer/ProgramFiles'
    else:
        path = '/Users/mattwilliams/Documents/PythonProjects/FEM/GangLi/IntroToFEM/Chapter4/HeatTransfer/ProgramFiles'
    fname = 'elprops.txt'
    headers = ['element','kcond']
    with open(os.path.join(path,fname),'w',newline='') as f:
        mywriter = csv.writer(f,delimiter=' ')
        mywriter.writerow(headers)
        mywriter.writerows(arr)
    return None

if __name__ == '__main__':
    ### PREPROCESSING SECTION ###
    # rod is 100 cm long.
    xleft = 0.0
    xright = 100.0
    n_elements = 8
    # degree of basis functions
    deg = 2
    # set my local working directory for retrieving and saving program files
    path = os.getcwd()
    if 'mattjwilliams' in path:
        path = '/Users/mattjwilliams/Documents/PythonStuff/FEM/GangLi/Chapter4/HeatTransfer/ProgramFiles'
    else:
        path = '/Users/mattwilliams/Documents/PythonProjects/FEM/GangLi/IntroToFEM/Chapter4/HeatTransfer/ProgramFiles'
    fnames = ['nodes.txt','elements.txt','global_nodes.txt','bcs.txt','elprops.txt','globals.txt']
    # run functions that create the files containing the mesh information
    mesher1D(xleft,xright,n_elements,deg)
    element_indexer(n_elements,deg)
    global_nodes(xleft,xright,n_elements,deg)
    boundary_conditions(n_elements,[2,0.1,1,0.0],deg)
    properties(n_elements,0.92,0.12)
    # load information from program files into dataframes
    df_dict = {}
    df_names = ['df_nodes','df_elems','df_glob_nodes','df_bcs','df_elprops','df_globals']
    for fname, df_name in zip(fnames,df_names):
        df_dict[df_name] = read_file(fname)

    ### MAIN LOOP ###
    n_nodes = n_elements*deg + 1
    K = np.zeros((n_nodes,n_nodes))
    F = np.zeros(n_nodes)
    Tenv, r, kconv = df_dict['df_globals'].iloc[0]
    for e in range(n_elements):
        node_locs = df_dict['df_nodes'].iloc[e,1:]
        N, Nx, xelem = lagrange(node_locs)
        kcond = df_dict['df_elprops'].iloc[e]['kcond']
        n = len(Nx)
        k = np.zeros((n,n))
        f = np.zeros(n)
        for row in range(n):
            I = 2*kconv*Tenv/r*N[row]
            f[row] = np.trapz(I,x=xelem)
            for col in range(n):
                # This currently only has the first integral on the LHS
                I1 = Nx[row]*Nx[col]*kcond
                I2 = 2*kconv/r*N[row]*N[col]
                k[row,col] = np.trapz(I1,x=xelem) + np.trapz(I2,x=xelem)
        glob_nodes = df_dict['df_elems'].iloc[e,1:]
        for i,row in enumerate(glob_nodes):
            F[row] += f[i]
            for j,col in enumerate(glob_nodes):
                K[row,col] += k[i,j]
    for i in range(n_nodes):
        bc_type = df_dict['df_bcs'].iloc[i]['type']
        if bc_type == 2:
            F[i] += df_dict['df_bcs'].iloc[i]['value']
        if bc_type == 1:
            penalty = abs(K[i,i]+1)*1e7
            K[i,i] = penalty
            F[i] = df_dict['df_bcs'].iloc[i]['value']*penalty
    ### END MAIN LOOP ###

    ### SOLUTION AND POST PROCESSING ###
    temps = np.linalg.solve(K,F)

    sol = []
    xvals = []
    for e in range(n_elements):
        node_locs = df_dict['df_nodes'].iloc[e,1:]
        N, Nx, xelem = lagrange(node_locs)
        val_arr = np.zeros_like(xelem)
        xvals.append(xelem)
        for i in range(deg+1):
            val_arr += N[i]*temps[deg*e+i]
        sol.append(val_arr)

sol_temps = np.stack(sol).flatten()
sol_xvals = np.stack(xvals).flatten()
plt.plot(sol_xvals,sol_temps)
plt.grid()
plt.xlim(sol_xvals[0],sol_xvals[-1])
plt.ylim(0,30)
plt.xlabel('Distance along bar (cm)')
plt.ylabel('Temperature ($^oC$)')
plt.title(f'FEM Solution with {n_elements} Elements and Degree {deg} Interpolants')
plt.show()


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

def reverseList(head):
    arr = []
    while head:
        a = head.val
        res.insert(0, a)
        head = head.next
    print(arr)
    res = ListNode()
    for el in arr:
        res.val = el
        res.next = ListNode()


# -*- coding: utf-8 -*-
"""
===============================================================================
Script 'fig-pupil-voc'
===============================================================================

This script plots pupil size & significance tests for the vocoder experiment.
"""
# @author: Dan McCloy (drmccloy@uw.edu)
# Created on Fri Sep 25 11:15:34 2015
# License: BSD (3-clause)

import yaml
import os.path as op
import numpy as np
import matplotlib.pyplot as plt
from pandas import DataFrame
from matplotlib.colors import colorConverter as cc
from scipy.stats import distributions
from mne.stats import spatio_temporal_cluster_1samp_test, ttest_1samp_no_p
from convenience_functions import (box_off, use_font, tick_label_size,
                                   hatch_between, read_data)
from functools import partial

# mostly rcParams stuff
plt.ioff()
use_font('source')
tick_label_size(10)

# flags
plot_stderr = True
plot_signif = True
show_pval = False
savefig = True
use_deconv = True
only_perfect = False

# file I/O
work_dir = '..'
out_dir = op.join(work_dir, 'results')
voc_file = op.join(work_dir, 'voc_data.npz')
perfect_filename = '-perfect' if only_perfect else ''
vv = np.load(voc_file)
data_deconv, t_fit, subjects = vv['fits_struct'], vv['t_fit'], vv['subjects']
data_zscore, fs, kernel = vv['zscores_struct'], vv['fs'], vv['kernel']
'''
data_zscore.shape
16,   40,      2,          2,            2,         6550
subj  trials   200/600gap  maint/switch  10/20chan  samples
(similar for data_deconv, with fewer samples along last dimension)
'''

# params
stim_times = np.array([0, 0.5, 1.5, 2.0, 2.5, 3.0])  # gap not included (yet)
stim_dur = 0.47  # really 0.5, but leave a tiny gap to visually distinguish
t_kernel_peak = np.where(kernel == kernel.max())[0][0] / float(fs)
t_min, t_max = -0.5, 6. - t_kernel_peak
t_zs = t_min + np.arange(data_zscore.shape[-1]) / float(fs)
stat_fun = partial(ttest_1samp_no_p, sigma=1e-3)

# colors
cue, msk, blu, red = '0.75', '0.75', '#332288', '#cc6677'
signifcol = '0.9'
axiscol = '0.8'
tickcol = '0.8'
axislabcol = '0.3'
ticklabcol = '0.5'

# get behavioral data
if only_perfect:
    path = op.join(work_dir, 'data-behavioral', 'voc-behdata-longform.tsv')
    beh_data = read_data(path, parse_presses=False)
    beh_data['perfect'] = np.logical_and(beh_data['misses'] == 0,
                                         beh_data['false_alarms'] == 0)
    cols = ['subj', 'gap_len', 'attn', 'voc_chan']
    beh_data = beh_data.sort_values(by=cols)
    dims = [len(beh_data[c].unique()) for c in cols]
    dims.insert(1, -1)
    perfect_ix = beh_data['perfect'].reshape(dims)
    voc_10_ix = (beh_data['voc_chan'] == 10).reshape(dims)
    voc_20_ix = (beh_data['voc_chan'] == 20).reshape(dims)
    gap_200_ix = (beh_data['gap_len'] == 'short').reshape(dims)
    gap_600_ix = (beh_data['gap_len'] == 'long').reshape(dims)
    maint_ix = (beh_data['attn'] == 'maint.').reshape(dims)
    switch_ix = (beh_data['attn'] == 'switch').reshape(dims)

# set up figure
fig, axs = plt.subplots(3, 1, figsize=(3, 6.5))
xlim = [t_min, t_max]

times = [t_fit] if use_deconv else [t_zs]
datas = [data_deconv] if use_deconv else [data_zscore]
for t, data in zip(times, datas):
    # collapse across trials and experimental contrasts
    # axis 1 is trials, 2 is gap dur, 3 is maint/switch, 4 is num voc channels
    chan_10_vs_20 = np.nanmean(data, axis=(1, 2, 3))
    gap_200_vs_600 = np.nanmean(data, axis=(1, 3, 4))
    maint_vs_switch = np.nanmean(data, axis=(1, 2, 4))
    # if only analyzing trials with perfect behavioral response, recompute
    # the per-subject mean pupil resp. by condition using only those trials
    # (a bit awkward because of potentially unequal counts)
    if only_perfect:
        # temporarily set these to infinite values (to check later that they
        # got properly re-assigned)
        chan_10_vs_20 = np.full_like(chan_10_vs_20, np.inf)
        gap_200_vs_600 = np.full_like(gap_200_vs_600, np.inf)
        maint_vs_switch = np.full_like(maint_vs_switch, np.inf)
        # keep track of how many correct trials per condition
        n_perfect_trials = dict()
        for ix, subj in enumerate(subjects):
            sj = np.zeros_like(perfect_ix)
            sj[ix] = True
            v10 = np.logical_and(perfect_ix, voc_10_ix)
            v20 = np.logical_and(perfect_ix, voc_20_ix)
            g2 = np.logical_and(perfect_ix, gap_200_ix)
            g6 = np.logical_and(perfect_ix, gap_600_ix)
            mn = np.logical_and(perfect_ix, maint_ix)
            sw = np.logical_and(perfect_ix, switch_ix)
            chan_10_vs_20[ix] = np.array([np.nanmean(data[sj & v10], axis=0),
                                          np.nanmean(data[sj & v20], axis=0)])
            gap_200_vs_600[ix] = np.array([np.nanmean(data[sj & g2], axis=0),
                                           np.nanmean(data[sj & g6], axis=0)])
            maint_vs_switch[ix] = np.array([np.nanmean(data[sj & mn], axis=0),
                                            np.nanmean(data[sj & sw], axis=0)])
            # bookkeeping for n_perfect_trials
            conds = dict()
            conds['voc'] = {10: np.logical_and(v10, sj).sum(),
                            20: np.logical_and(v20, sj).sum()}
            conds['gap'] = {200: np.logical_and(g2, sj).sum(),
                            600: np.logical_and(g6, sj).sum()}
            conds['attn'] = {'maint': np.logical_and(mn, sj).sum(),
                             'switch': np.logical_and(sw, sj).sum()}
            n_perfect_trials[subj] = conds
        assert np.all(np.isfinite(chan_10_vs_20))
        assert np.all(np.isfinite(gap_200_vs_600))
        assert np.all(np.isfinite(maint_vs_switch))

    # axis limits
    ymax = np.max(np.mean(np.nanmean(data, axis=1), axis=0))  # ceil
    ymax = 10 ** np.trunc(np.log10(ymax)) if ymax < 1 else np.ceil(ymax)
    ylim = [-0.6 * ymax, ymax]
    # y values for stim timecourse diagram
    stim_ymin = ymax * -0.45
    stim_ymax = ymax * -0.3
    for jj, (contrast, ax) in enumerate(zip([chan_10_vs_20, gap_200_vs_600,
                                             maint_vs_switch], axs)):
        # within-subject difference between conditions
        contr_diff = (contrast[:, 1, :] - contrast[:, 0, :])[:, :, np.newaxis]
        # collapse across subjects (only for plotting, not stats)
        contr_std = np.std(contrast, axis=0) / np.sqrt(len(contrast) - 1)
        contr_mean = np.mean(contrast, axis=0)
        # vars for trial timecourse
        gaps = [[0.6, 0.6], [0.2, 0.6], [0.6, 0.6]][jj]
        labels = [['10 band', '20 band'], ['short gap', 'long gap'],
                  ['maintain', 'switch']][jj]
        colors = [[cue, cue], [cue, cue], [blu, red]][jj]
        # plot curves
        for kk, (cond, se) in enumerate(zip(contr_mean, contr_std)):
            col = colors[kk]
            linecol = [blu, red][kk]
            tcol = cc.to_rgb(linecol) + (0.4,)  # add alpha channel
            tcol_hex = '#' + ''.join('%02x' % int(x * 255) for x in tcol)
            zord = [2, 0][kk]
            # plot standard error bands
            if plot_stderr:
                _ = ax.fill_between(t, cond-se, cond+se, color=tcol,
                                    edgecolor='none', zorder=zord + 2)
            # plot mean lines
            _ = ax.plot(t, cond, color=linecol, linewidth=1.2, zorder=zord + 3)
            # TRIAL TIMECOURSE
            thk = 0.04 * ymax
            off = 0.15 * ymax
            loff = 0.01 * ymax
            stim_y = [stim_ymin, stim_ymax][kk]
            label_y = [stim_ymax, stim_ymax-off][kk]
            # lines beneath stim boxes
            if kk:  # "switch" line
                xnodes = (1, 2.5, 2.7, 4.4) if jj == 1 else (1, 2.5, 3.1, 4.4)
                ynodes = (stim_y-loff, stim_y-loff,
                          stim_y-off+loff, stim_y-off+loff)
                ax.plot(xnodes, ynodes, color=col, linewidth=1.,
                        linestyle='--', zorder=7)
            else:  # "maintain" line
                ynodes = (stim_ymax+loff, stim_ymax+loff)
                ax.plot((1, 4.4), ynodes, color=col, linewidth=1.,
                        solid_capstyle='butt', zorder=7)
            # boxes
            gap_offsets = np.array([0] * 4 + [gaps[kk]] * 2)
            stim_t = stim_times + gap_offsets
            box_x = np.r_[stim_t, stim_t[2:]]
            box_y = np.array([stim_ymax] * 6 + [stim_ymin] * 4)
            box_u = np.array([thk] * 10)
            box_d = np.array([thk] * 10)
            # colors must be tuples (not hex strings) for alpha to work
            box_c = [cc.to_rgba(x) for x in [cue] * 2 + [msk] * 8]
            if jj == 1:
                box_u[4:6] *= (1 - kk) + 0.5
                box_u[8:] *= (1 - kk) + 0.5
                box_d[4:6] *= kk
                box_d[8:] *= kk
                box_c[4:6] = [cc.to_rgba(linecol)] * 2  # or tcol
                box_c[8:] = [cc.to_rgba(linecol)] * 2
                if not kk:
                    indices = np.array([4, 5, 8, 9])
                    box_x = box_x[indices]
                    box_y = box_y[indices]
                    box_u = box_u[indices]
                    box_d = box_d[indices]
                    box_c = np.array(box_c)[indices]
            if jj == 1 or kk:
                for x, y, c, u, d in zip(box_x, box_y, box_c, box_u, box_d):
                    c = cc.to_rgba_array(c)
                    ax.fill_between((x, x+stim_dur), y+u, y-d, color=c,
                                    edgecolor='none', zorder=9)
            # timecourse labels
            xtxt = [-0.1, -0.1, 4.4][jj]
            ytxt = [[0.09, 0.075], [0.09, 0.075],
                    [stim_ymax, stim_ymin]][jj][kk]
            xytxt = [(0, 0), (0, 0), (5, 0)][jj]
            _ = ax.annotate(labels[kk], (xtxt, ytxt), xytext=xytxt,
                            textcoords='offset points', color=linecol,
                            ha='left', va='center', fontsize=9)
        # cue label
        _ = ax.annotate('cue', xy=(stim_times[1], stim_ymax + thk),
                        xytext=(0, 1.5), textcoords='offset points',
                        fontsize=9, fontstyle='italic', ha='center',
                        va='bottom', color='0.5')
        # stats
        if plot_signif:
            thresh = -1 * distributions.t.ppf(0.05 / 2, len(contr_diff) - 1)
            result = spatio_temporal_cluster_1samp_test(
                contr_diff, threshold=thresh, stat_fun=stat_fun, n_jobs=6,
                buffer_size=None, n_permutations=np.inf)
            tvals, clusters, cluster_pvals, H0 = result
            signif = np.where(np.array([p <= 0.05 for p in cluster_pvals]))[0]
            signif_clusters = [clusters[s] for s in signif]
            signif_cluster_pvals = cluster_pvals[signif]
            # we only need x[0] in clusters because this is 1-D data; x[1] in
            # clusters is just a list of all zeros (no spatial connectivity).
            # All the hacky conversions to float, int, and list are because
            # yaml doesn't understand numpy dtypes.
            pupil_signifs = dict(thresh=float(thresh),
                                 n_clusters=len(clusters),
                                 clusters=[[int(y) for y in x[0]]
                                           for x in clusters],
                                 tvals=tvals.tolist(),
                                 pvals=cluster_pvals.tolist())
            label = '_vs_'.join([l.replace(' ', '-') for l in labels])
            fname = 'voc_cluster_signifs_{}.yaml'.format(label)
            with open(op.join(out_dir, fname), 'w') as f:
                yaml.dump(pupil_signifs, stream=f)
            # plot stats
            for clu, pv in zip(signif_clusters, signif_cluster_pvals):
                '''
                # this index tells direction of tval, hence could be used to
                # decide which color to draw the significant cluster region
                # based on which curve is higher:
                idx = (np.sign(tvals[clu[0][0], 0]).astype(int) + 1) // 2
                '''
                clu = clu[0]
                cluster_ymin = ylim[0] * np.ones_like(t[clu])
                cluster_ymax = np.max(contr_mean[:, clu], axis=0)  # under top
                pval_x = t[int(np.mean(clu[[0, -1]]))]
                pval_y = -0.1 * ylim[1]
                pval_ord = np.trunc(np.log10(pv)).astype(int)

                hatch_between(ax, 9, t[clu], cluster_ymin,
                              cluster_ymax, linewidth=1.25,
                              color=signifcol, zorder=1)
                if show_pval:
                    pval_txt = '$p < 10^{{{}}}$'.format(pval_ord)
                    ax.text(pval_x, pval_y, pval_txt, ha='center',
                            va='baseline', fontdict=dict(size=10))
            # vertical lines
            if len(signif):
                for ix in (0, -1):
                    ax.plot((t[clu][ix], t[clu][ix]),
                            (cluster_ymin[ix], cluster_ymax[ix]),
                            linestyle=':', color=axiscol, linewidth=1)
        # set axis limits
        xlim[1] = 1.001 * xlim[1]
        ylim[1] = 1.001 * ylim[1]
        ax.set_ylim(*ylim)
        ax.set_xlim(*xlim)
        ax.xaxis.set_ticks(np.arange(np.ceil(xlim[1])))
        # remove yaxis / ticks / ticklabels near bottom
        ytck = [-0.1 * ymax, 1.001 * ymax]
        ytl = ax.yaxis.get_ticklocs()
        ax.spines['left'].set_bounds(*ytck)
        for sp in ['left', 'bottom']:
            ax.spines[sp].set_color(axiscol)
        ax.yaxis.set_ticks(ytl[ytl > ytck[0]])
        ax.set_ylim(*ylim)  # have to do this twice
        ax.tick_params(color=tickcol, width=0.5, labelcolor=ticklabcol)

        # annotations
        yl = u'“Effort” (a.u.)' if use_deconv else 'Pupil size (z-score)'
        yo = 1 - np.diff(ytck) / np.diff(ylim) / 2.
        ax.set_ylabel(yl, y=yo, color=axislabcol)
        ax.set_xlabel('Time (s)', color=axislabcol)

        box_off(ax, ax_linewidth=0.5)
        ax.patch.set_facecolor('none')
# fig.tight_layout(w_pad=2., rect=(0.02, 0, 1, 1))
fig.tight_layout()
fig.text(0.01, 0.98, 'a)')
fig.text(0.01, 0.66, 'b)')
fig.text(0.01, 0.34, 'c)')

if savefig:
    fig.savefig('pupil-fig-voc{}.pdf'.format(perfect_filename))
else:
    plt.ion()
    plt.show()

if only_perfect:
    df = DataFrame.from_dict(n_perfect_trials, orient='index')
    df.to_csv(op.join(out_dir, 'voc_perfect_trials.csv'))


from django.shortcuts import render, redirect, reverse
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login as auth_login, logout as auth_logout
from django.contrib import messages
from django.utils.translation import ugettext as _

from .forms import RegistrationForm

def login(request):
    login_form = AuthenticationForm()

    if request.user.is_authenticated():
        return redirect('/')
    if request.POST:
        login_form = AuthenticationForm(request, data=request.POST)
        if login_form.is_valid():
            auth_login(request, login_form.get_user())
            return redirect('/')

    context = {
        'form': login_form,
    }
    return render(request, template_name='account/login.html', context=context)

def logout(request):
    auth_logout(request)
    messages.add_message(request, messages.WARNING, _('You\'ve been logged out.'))
    return redirect(reverse('login'))

def register(request):
    register_form = RegistrationForm()

    if request.user.is_authenticated():
        return redirect('/')
    if request.POST:
        register_form = RegistrationForm(request.POST)
        if register_form.is_valid():
            user = register_form.save()
            auth_login(request, user)
            messages.add_message(request, messages.SUCCESS, _('Your account has been registered.'))
            return redirect('/')

    context = {
        'form': register_form
    }

    return render(request, template_name='account/register.html', context=context)


# Opus/UrbanSim urban simulation software.
# Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington
# See opus_core/LICENSE

from opus_core.resources import merge_resources_if_not_None, merge_resources_with_defaults
from urbansim.models.household_location_choice_model import HouseholdLocationChoiceModel
from opus_core.misc import safe_array_divide
from opus_core.datasets.dataset import Dataset, DatasetSubset
from numpy import allclose, alltrue, zeros, median, newaxis, concatenate, where
from opus_core.misc import unique
from opus_core.logger import logger
from opus_core.storage_factory import StorageFactory

class HouseholdLocationChoiceModelWithPriceAdj(HouseholdLocationChoiceModel):

    model_name = "Household Location Choice Model with Price Adjustment"
    model_short_name = "HLCM"

    def run_chunk(self, agents_index, agent_set, specification, coefficients):
        """
        This method overwrites the run_chunk method in LocationChoiceModel by introducing iterative adjustment
        to the price attribute of choice_set according to its demand
        """
        CLOSE = 0.05
        maxiter = 30
        #submarkets = define_submarket(self.choice_set, submarket_id_expression="urbansim_parcel.building.zone_id * 100 + building.building_type_id")
        submarkets = define_submarket(self.choice_set, submarket_id_expression="building.building_id")
        price_attribute_name = "average_value_per_unit"
        capacity_string = self.run_config.get("capacity_string", None)
        demand_string = self.run_config.get('demand_string', 'demand')

        ##set demand_string, so the demand for each submodel will be added as a choice_set attribute
        choices = HouseholdLocationChoiceModel.run_chunk(self, agents_index, agent_set, specification, coefficients)
        #upc = self.upc_sequence
        sdratio_submarket, sdratio_choice = self.compute_sdratio(submarkets, self.choice_set, capacity_string, demand_string)

        data_for_plot = {}
        data_for_plot['sdratio'] = sdratio_submarket[:, newaxis]
        data_for_plot[price_attribute_name] = self.choice_set.get_attribute(price_attribute_name)[:, newaxis]
        residential_building_types = {1:'SFR',2:'MFR'}
        for i in range(1, maxiter+1, 1):
            submarkets_w_demand = where(submarkets.get_attribute('demand')>0)[0]
            logger.start_block("HLCM with bidding choice iteration %s" % i)
            logger.log_status("submarket sdratio:")
            self.log_descriptives(data_array=sdratio_submarket[submarkets_w_demand])
            logger.log_status("building %s by building_type_id:" % price_attribute_name)
            self.log_descriptives(dataset=self.choice_set, attribute=price_attribute_name, by='building_type_id',
                                  show_values=residential_building_types)
            logger.log_status("excess demand by building_type_id:")
            demand_submarket = submarkets.get_attribute('demand')
            demand_supply = demand_submarket - sdratio_submarket * demand_submarket
            w_excess_demand = where(demand_supply > 0)[0]
            #submarket_building_type_id = submarkets.get_id_attribute() % 100
            submarket_building_type_id = self.choice_set.get_attribute_by_id("building_type_id", submarkets.get_id_attribute())
            self.log_descriptives(data_array=demand_supply[w_excess_demand],
                                  by=submarket_building_type_id[w_excess_demand],
                                  show_values=residential_building_types)

            #if allclose(sdratio_submarket, 1, atol=CLOSE):
            if alltrue(sdratio_submarket[submarkets_w_demand] > 1):
                logger.log_status("Convergence achieved.")
                break

            ##cap price adjustment to +/- 10%
            price_adj = 1 / sdratio_choice
            price_adj[price_adj == 0] = 1.0
            price_adj[price_adj > 1.10] = 1.10
            price_adj[price_adj < 0.9] = 0.9

            price_attribute = self.choice_set.get_attribute(price_attribute_name)

            self.choice_set.set_values_of_one_attribute(price_attribute_name, price_attribute * price_adj)
            self.choice_set.set_values_of_one_attribute(demand_string, zeros(self.choice_set.size(), dtype="float32"))
            choices = HouseholdLocationChoiceModel.run_chunk(self, agents_index, agent_set, specification, coefficients)

            sdratio_submarket, sdratio_choice = self.compute_sdratio(submarkets, self.choice_set, capacity_string, demand_string)

            data_for_plot['sdratio'] = concatenate( (data_for_plot['sdratio'], sdratio_submarket[:,newaxis]), axis=1)
            data_for_plot[price_attribute_name] = concatenate( (data_for_plot[price_attribute_name], self.choice_set.get_attribute(price_attribute_name)[:,newaxis]),
                                                       axis = 1)

            logger.end_block()

        self.plot_data(data_for_plot['sdratio'], main='sdratio_submkt')

        building_types = self.choice_set.get_attribute('building_type_id')
        data_for_plot[price_attribute_name] = concatenate( (self.choice_set.get_id_attribute()[:,newaxis], data_for_plot[price_attribute_name] ),
                                                   axis = 1)
        for building_type in [4, 12, 19]:
            self.plot_data(data_for_plot[price_attribute_name][building_types==building_type,:],
                           main='%s_bldg_type_%s' % (price_attribute_name, building_type) )

        return choices

    def compute_sdratio(self, submarkets, choice_set, capacity_string, demand_string):
        #choice_submarket_id = choice_set.compute_variables("urbansim_parcel.%s.%s" % (choice_set.get_dataset_name(), submarkets.get_id_name()[0]))
        choice_submarket_id = choice_set.get_attribute("building_id")
        choice_submarket_index = submarkets.get_id_index( choice_submarket_id )
        supply = submarkets.sum_over_ids( choice_submarket_id, self.capacity )

        demand = submarkets.compute_variables("demand=submarket.aggregate(%s.%s)" % (choice_set.get_dataset_name(), demand_string) )
        ##TODO: an adjustment ratio should be included since this variable only represents the demand from agents in this chunk
        sdratio_submarket = safe_array_divide(supply, demand)

        return (sdratio_submarket, sdratio_submarket[choice_submarket_index] )

    def log_descriptives(self, data_array=None, dataset=None, attribute=None, by=None, show_values={}):
        if data_array is None:
            data_array=dataset.get_attribute(attribute)
        if by is None:
            logger.log_status("#N: %s\tmean: %.3f\tstd: %.3f" % (data_array.size, data_array.mean(), data_array.std()) )
            logger.log_status("min: %.3f\tmedian: %.3f\tmax: %.3f" % (data_array.min(), median(data_array), data_array.max()) )
        else:
            #if type(by)==tuple:
                #by_value, show_values = by
            #else:
                #by_value = by

            if type(by)==str:
                by_str = by
                by_value = dataset.get_attribute(by_str)
            else:
                by_str = ""
                by_value = by

            if show_values is None or show_values == {}:
                show_values = unique(by_value)

            assert(by_value.size==data_array.size)

            for item in show_values.iteritems():
                if type(item) == tuple:
                    value, description = item
                    description_str = "(%s)" % description
                else:
                    value = item
                    description_str = ""
                data = data_array[by_value==value]
                logger.log_status("%s %s%s:" % (by_str, value, description_str))
                logger.log_status("#N: %s\tmean: %.3f\tstd: %.3f" % (data.size, data.mean(), data.std()) )
                logger.log_status("min: %.3f\tmedian: %.3f\tmax: %.3f" % (data.min(), median(data), data.max()) )

    def plot_data(self, data_array, main, delimiter=','):
        #def _write_to_txt_file(self, data, header, input_file, delimiter='\t'):
        logger.start_block("Writing data to file " + main)
        newfile = open(main + '.csv', 'w')
        #newfile.write(delimiter.join(header) + "\n")
        rows, cols = data_array.shape
        for n in range(rows):
            newfile.write(delimiter.join([str(x) for x in data_array[n,]]) + "\n")

        newfile.close()
        logger.end_block()

def define_submarket(choice_set, submarket_id_expression, compute_variables=[], filter=None):
    submarket_ids = choice_set.compute_variables("submarket_id=" + submarket_id_expression)
    unique_submarket_ids = unique(submarket_ids)
    storage = StorageFactory().get_storage('dict_storage')
    storage.write_table(table_name='submarkets', table_data={'submarket_id':unique_submarket_ids})
    submarkets = Dataset(in_storage=storage,
                         in_table_name='submarkets',
                         id_name='submarket_id',
                         dataset_name='submarket'
                     )
    if len(compute_variables):
        submarkets.compute_variables(compute_variables)
    if filter is not None:
        from numpy import logical_not
        submarkets.remove_elements(index= where( logical_not(submarkets.compute_variables(filter)) )[0])
        #submarkets = DatasetSubset(submarkets, index=where(submarkets.compute_variables(filter))[0])
    return submarkets


#
# @lc app=leetcode id=9 lang=python3
#
# [9] Palindrome Number
#
# https://leetcode.com/problems/palindrome-number/description/
#
# algorithms
# Easy (49.55%)
# Likes:    3196
# Dislikes: 1722
# Total Accepted:    1.2M
# Total Submissions: 2.4M
# Testcase Example:  '121'
#
# Given an integer x, return true if x is palindrome integer.
#
# An integer is a palindrome when it reads the same backward as forward. For
# example, 121 is palindrome while 123 is not.
#
#
# Example 1:
#
#
# Input: x = 121
# Output: true
#
#
# Example 2:
#
#
# Input: x = -121
# Output: false
# Explanation: From left to right, it reads -121. From right to left, it
# becomes 121-. Therefore it is not a palindrome.
#
#
# Example 3:
#
#
# Input: x = 10
# Output: false
# Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
#
#
# Example 4:
#
#
# Input: x = -101
# Output: false
#
#
#
# Constraints:
#
#
# -2^31 <= x <= 2^31 - 1
#
#
#
# Follow up: Could you solve it without converting the integer to a string?
#

# @lc code=start
class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False

        reversed_x = 0
        num = x

        while num > 0:
            reversed_x = reversed_x * 10 + num % 10
            num = num // 10

        return reversed_x == x

class Solution_HashMap:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False

        hashmap = {}

        n = self.get_digits(x)
        curr = n - 1
        for _ in range(n):
            num = x % 10
            if n - curr - 1 in hashmap:
                if hashmap[n - curr - 1] != num:
                    return False
            else:
                hashmap[curr] = num

            x = x // 10
            curr -= 1

        return True

    def get_digits(self, x):
        count = 0
        while x != 0:
            x = x // 10
            count += 1
        return count
# @lc code=end


"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""

# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='mygrations',
    version='1.0.6',
    description='A general purpose migration tool for managing MySQL updates',
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='https://github.com/cmancone/mygrations',
    author='Conor Mancone',
    author_email='cmancone@gmail.com',
    license='MIT',
    download_url='https://github.com/cmancone/mygrations/archive/v1.0.0.tar.gz',

    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Build Tools',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
    ],
    keywords='setuptools development migrations mysql',
    packages=find_packages(exclude=['contrib', 'docs', 'tests']),
    python_requires=">=3.6",
    install_requires=[
        'PyMySQL',
    ],
    # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files
    # data_files=[('/usr/local/bin', ['mygrate.py'])],
)


n=input("insertar la secuencia a ser identificada : ")
m=int(input("insertar la cantidad de secuencias candidatas"))
l=[]
l1=[]
#ACtg
def hamming(n,l1,m):
    for i in range (0,m):
        x=input("insertar el  fragmento de la especie candidata numero " + str(  i+1  ) + " : " )
        for t in x:
          l1.append(t )
    return l1
def ident(n,m,l):
 for d in range(m):
    for t1 in n:
        l.append(t1)
 return l
n1=hamming(n,l1,m)
n2=ident(n,m,l)
def comparar(n1,n2):
    for i in range(min(len(n1), len(n2))):
        if n1[i] != n2[i]:
            return n1[i]
    return len(n1) == len(n2)
print(comparar(n1,n2))


import os

import pytest
import textwrap

@pytest.fixture()
def sample_test(testdir):
    testdir.makefile(
        ".feature",
        scenario=textwrap.dedent(
            """\
            Feature: Testing
                Scenario: Test scenario
                    Given I have a scenario
                    When I start the test
                    And I know it will fails
                    Then It fails
            """
        ),
    )

    testdir.makepyfile(
        textwrap.dedent(
            """\
        import pytest
        from pytest_bdd import given, when, then, scenario

        @scenario("scenario.feature", "Test scenario")
        def test_scenario():
            pass

        @given("I have a scenario")
        def _():
            pass

        @when("I start the test")
        def _():
            pass

        @when("I know it will fails")
        def _():
            pass

        @then('It fails')
        def _():
            assert False

        """
        )
    )

    return testdir

def test_arguments_in_help(testdir):
    res = testdir.runpytest("--help")
    res.stdout.fnmatch_lines(
        [
            "*bdd-report*",
        ]
    )

def test_create_html_report_file(sample_test):
    sample_test.runpytest("--bdd-report=report.html")
    assert (sample_test.tmpdir / "report.html").exists()

def test_create_html_report_file_with_directory(sample_test):
    sample_test.runpytest("--bdd-report=./reports/report.html")
    assert (sample_test.tmpdir / "./reports/report.html").exists()

def test_create_html_report_file_with_directory_name(sample_test):
    sample_test.runpytest("--bdd-report=results/report.html")
    assert (sample_test.tmpdir / "results/report.html").exists()

def test_create_html_report_file_with_directory_and_subdirectory(sample_test):
    sample_test.runpytest("--bdd-report=./reports/year/report.html")
    assert (sample_test.tmpdir / "./reports/year/report.html").exists()

def test_content_in_report(sample_test):
    sample_test.runpytest("--bdd-report=report.html")
    content = ""
    with open((sample_test.tmpdir / "report.html"), "r") as f:
        content = f.read()
    assert content != ""

def test_information_in_report(sample_test):
    sample_test.runpytest("--bdd-report=report.html")
    content = ""
    with open((sample_test.tmpdir / "report.html"), "r") as f:
        content = f.read()
    assert "Testing" in content
    assert "Test scenario" in content
    assert "I have a scenario" in content
    assert "I start the test" in content
    assert "I know it will fails" in content
    assert " It fails" in content


import numpy as np
import matplotlib.pyplot as plt

x = np.loadtxt('test_accuracies')

plt.figure(figsize=(5.2, 3.1))
plt.errorbar(x[:, 0], x[:, 1:].mean(axis=1), yerr=np.std(x[:, 1:], axis=1, ddof=1), capsize=3, label='SVM accuracy on SNN output')
plt.axhline(y=95, color='orange', linestyle='--', label='SVM accuracy on MFSC features')
plt.xlabel('Number of training samples')
plt.ylabel('Accuracy')
plt.legend()
plt.tight_layout()

plt.savefig('accuracy.png')
plt.show()


import matplotlib
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# ------------------------- définition de fonction d'appartenance ----------------------

temperarute = ctrl.Antecedent(np.arange(14, 27, 0.1), "temperarute")
temperarute['faible'] = fuzz.trapmf(temperarute.universe, [14, 14, 17, 19])
temperarute['moyenne'] = fuzz.trimf(temperarute.universe, [17, 20, 23])
temperarute['élevée'] = fuzz.trapmf(temperarute.universe, [21, 23, 25.5, 26])

humidite = ctrl.Antecedent(np.arange(52, 101, 0.1), "humidite")
humidite['Sec'] = fuzz.trapmf(humidite.universe, [52, 52, 80, 84])
humidite['Humide'] = fuzz.trapmf(humidite.universe, [68, 84, 99, 100])

vitesse = ctrl.Consequent(np.arange(0, 101, 1), 'vitesse')

vitesse['faible'] = fuzz.trapmf(vitesse.universe, [0, 0, 30, 40])
vitesse['moyenne'] = fuzz.trapmf(vitesse.universe, [30, 45, 60, 70])
vitesse['élevée'] = fuzz.trapmf(vitesse.universe, [60, 75, 99, 100])

# afficher les fonction :
temperarute.view()
humidite.view()
vitesse.view()

# ---------------------------------------- base de régle -------------------------------------

regle_1 = ctrl.Rule(temperarute['faible'] | humidite['Sec'], vitesse['faible'])
regle_2 = ctrl.Rule(temperarute['moyenne'] & humidite['Humide'], vitesse['moyenne'])
regle_3 = ctrl.Rule(temperarute['élevée'], vitesse['élevée'])

# regle_1.view() afficher comme réseau de neurones
# peut ajouter plusieur nombre de regle selon leur condition

# ajouter les regle au simulation controle
vitesse_ctrl = ctrl.ControlSystem([regle_1, regle_2, regle_3])
sumilation = ctrl.ControlSystemSimulation(vitesse_ctrl)

# deux valeur entree
sumilation.input['temperarute'] = 18
sumilation.input['humidite'] = 80
# calculer
sumilation.compute()
print(" La valeur floue de cette base de regle : ", sumilation.output['vitesse'])

# afficher resultat dans fonction
vitesse.view(sim=sumilation)


import pandas as pd

# df = pd.read_excel("C:/Users/callM/Downloads/Parsed_FE Interviews_Cleaned.xlsx")
df = pd.read_excel(r"C:\Users\callM\Downloads\Parsed_FE Interviews_Cleaned.xlsx")

# Initialize an empty list to store project data
project_data = []

# Iterate through the rows of the DataFrame and convert data
for index, row in df.iterrows():
    project = {
        "title": row["Project.Title"],
        "technologies": row["Project.Technologies"],
        "frontend": row["Technical_Skillset.Frontend"],
        "backend": row["Technical_Skillset.Backend"],
        "databases": row["Technical_Skillset.Databases"],
        "infrastructure": row["Technical_Skillset.Infrastructre"],
    }
    project_data.append(project)

# Print the converted project_data list
for project in project_data:
    print(project)


from datetime import date

from app import app
from models import db, Plant

class TestPlant:
    '''Plant model in models.py'''

    def test_can_instantiate(self):
        '''can be instantiated with a name.'''
        p = Plant(name="Douglas Fir")
        assert(p)

    def test_can_be_created(self):
        '''can create records that can be committed to the database.'''
        with app.app_context():
            p = Plant(name="Douglas Fir")
            db.session.add(p)
            db.session.commit()
            assert(p.id)

            db.session.delete(p)
            db.session.commit()

    def test_can_be_retrieved(self):
        '''can be used to retrieve records from the database.'''
        with app.app_context():
            p = Plant.query.all()
            assert(p)

    def test_can_be_serialized(self):
        '''can create records with a to_dict() method for serialization.'''
        with app.app_context():
            p = Plant(name="Douglas Fir")
            db.session.add(p)
            db.session.commit()
            p_dict = Plant.query.filter_by(name="Douglas Fir").first().to_dict()
            assert((type(p_dict) == dict) and (p_dict["name"] == "Douglas Fir"))

            db.session.delete(p)
            db.session.commit()


class Solution:
    def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int:
        stack = [root]
        ans = 0
        while(stack):
            node = stack.pop()
            if node:
                if low <= node.val <= high:
                    ans += node.val
                if low < node.val:
                    stack.append(node.left)
                if high > node.val:
                    stack.append(node.right)
        return ans


# https://programmers.co.kr/learn/courses/30/lessons/68644

def solution(numbers):
    answer = []

    # 인덱스 하나씩 구해옴
    for i in range(len(numbers)):
        for ii in range(len(numbers)):
            result = numbers[i]+numbers[ii]
            # 같은 인덱스의 값끼리는 더하지 않고, 같은 값이 포함되지 않을 때 answer에 추가
            if i != ii and result not in answer:
                answer.append(result)

    # 정렬
    answer.sort()
    return answer

# Test Case
print("Answer :", solution([5,0,2,7])) # Answer : [2,5,7,9,12]
print("Answer :", solution([2,1,3,4,1])) # Answer : [2,3,4,5,6,7]

Training-Site/Programmers/Level1/두 개 뽑아서 더하기/source.py


from parlai.core.teachers import DialogTeacher
from .build import build

import json
import os
import glob

def _path(opt):
    build(opt)
    print('opt is', opt['datatype'])
    dt = opt['datatype'].split(':')[0]

    if dt == 'valid':
        dt = 'dev'
    elif dt != 'train' and dt != 'test':
        raise RuntimeError('Not valid datatype.')

    prefix = os.path.join(opt['datapath'], 'nlvr', 'nlvr-master', 'nlvr')
    questions_path = os.path.join(prefix, dt, dt + '.json')
    images_path = os.path.join(prefix, dt, 'images')

    return questions_path, images_path

class DefaultTeacher(DialogTeacher):
    # all possile answers for the questions
    cands = labels = ['true', 'false']

    def __init__(self, opt, shared=None):
        self.datatype = opt['datatype']
        data_path, self.images_path = _path(opt)
        opt['datafile'] = data_path
        self.id = 'nlvr'
        self.dt = opt['datatype'].split(':')[0]
        if self.dt == 'valid':
            self.dt = 'dev'

        super().__init__(opt, shared)

    def label_candidates(self):
        return self.cands

    def setup_data(self, path):
        print('loading: ' + path)

        for line in open(path, 'r'):
            ques = json.loads(line)

            image_path = os.path.join(self.images_path, ques['directory'])
            image_file_names = glob.glob(
                image_path + '/' + self.dt + '-' + ques['identifier'] + '*'
            )

            question = "True or False: " + ques['sentence']
            answer = [ques['label']] if self.dt != 'test' else None
            # print( answer)
            yield (question, answer, None, None, image_file_names[0]), True


import datetime
import inspect
import json
import boto3
from util import create_ec2_client, create_ec2_resource, print_response

def create_elastic_ip(ec2_client):
    # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.allocate_address
    # DomainのvpcはVPC、standardはEC2-Classic向け
    response = ec2_client.allocate_address(Domain='vpc')
    print_response(inspect.getframeinfo(inspect.currentframe())[2], response)
    return response['AllocationId']

def create_nat_gateway(ec2_client, allocation_id, subnet_id):
    # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.create_nat_gateway
    response = client.create_nat_gateway(
        AllocationId=allocation_id,
        SubnetId=subnet_id,
    )
    print_response(inspect.getframeinfo(inspect.currentframe())[2], response)
    return response['NatGateway']['NatGatewayId']

def describe_main_route_tables(ec2_client, vpc_id):
    # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Client.describe_route_tables
    response = ec2_client.describe_route_tables(
        Filters=[
            {
                'Name': 'association.main',
                'Values': ['true'],
            },
            {
                'Name': 'vpc-id',
                'Values': [vpc_id],
            }
        ]
    )
    main_route_table_id = response['RouteTables'][0]['RouteTableId']
    print_response(inspect.getframeinfo(inspect.currentframe())[2], main_route_table_id)
    return main_route_table_id

def wait_nat_gateway_available(ec2_client, nat_gateway_id):
    # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.Waiter.NatGatewayAvailable
    print(f'NAT Gatewayがavailableになるまで待つ(開始)：{datetime.datetime.now()}')
    waiter = ec2_client.get_waiter('nat_gateway_available')
    response = waiter.wait(
        Filters=[{
            'Name': 'state',
            'Values': ['available']
        }],
        NatGatewayIds=[nat_gateway_id]
    )
    print_response(inspect.getframeinfo(inspect.currentframe())[2], response)
    print(f'NAT Gatewayがavailableになるまで待つ(終了)：{datetime.datetime.now()}')

def create_nat_gateway_route_in_route_table(ec2_resource, route_table_id, nat_gateway_id):
    # https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.RouteTable.create_route
    route_table = ec2_resource.RouteTable(route_table_id)
    route = route_table.create_route(
        DestinationCidrBlock='0.0.0.0/0',
        NatGatewayId=nat_gateway_id,
    )
    print_response(inspect.getframeinfo(inspect.currentframe())[2], route)
    return route

if __name__ == '__main__':
    session = boto3.Session(profile_name='my-profile')
    # 使用するクライアントとリソースを作成
    client = create_ec2_client(session)
    resource = create_ec2_resource(session)

    # AWSの各IDを取得する
    with open('aws.json', mode='r') as f:
        aws = json.load(f)

    # Elastic IPを取得する
    aws['allocation_id'] = create_elastic_ip(client)

    # パブリックサブネットにNATゲートウェイを置く
    aws['nat_gateway_id'] = create_nat_gateway(client, aws['allocation_id'], aws['public_subnet_id'])

    # NATゲートウェイはすぐに使うことができないため、availableになるまで待つ
    wait_nat_gateway_available(client, aws['nat_gateway_id'])

    # NATゲートウェイのエントリを追加するため、メインのルートテーブルのIDを取得する
    aws['main_route_table_id'] = describe_main_route_tables(client, aws['vpc_id'])

    # VPC領域2でメインのルートテーブルにNATゲートウェイのエントリを追加する
    create_nat_gateway_route_in_route_table(resource, aws['main_route_table_id'], aws['nat_gateway_id'])

    # ここまでのid情報をJSONとして上書き保存
    with open('aws.json', mode='w') as f:
        json.dump(aws, f)


from collections import deque
# For debugging
import time

#-----
# Define Node class
#-----
class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

    def __repr__(self):
        return str(self.val)

#-----
# DFT - recursive
#-----
def dft(root, path=None):
    '''Depth-first traversal (recursively). Returns list w/ values in path.'''
    if not root:
        return path
    if not path:
        path = []

    print(root.val, end=' ')
    path.append(root.val)
    dft(root.left, path)
    dft(root.right, path)
    return path

#-----
# DFT - iterative
#-----
def dft_iter(root):
    '''Depth-first traversal (iteratively). Returns list w/ values in path.'''
    if root is None:
        return
    stack = [root]
    path = []
    while stack:
        node = stack.pop()
        path.append(node.val)
        print(node.val, end=' ')
        # Note we must add to the stack in *reverse* order to be processed (right then left)
        if node.right:
            stack.append(node.right)
        if node.left:
            stack.append(node.left)
    return path

#-----
# BFT - iterative
#-----
def bft(root):
    '''Breadth-first traversal, or "level-order", of tree'''
    if root is None:
        return path
    queue = deque([root])
    path = []
    while queue:
        node = queue.popleft()
        path.append(node.val)
        print(node.val, end=' ')
        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)
    return path

#-----
# BST insert
#-----
def insert_bst(root, val):
    '''Insert new node into BST, returning root node of updated tree'''
    if root is None:
        return Node(val)
    if val < root.val:
        root.left = insert_bst(root.left, val)
    else:
        root.right = insert_bst(root.right, val)
    return root

#-----
# BST lookup
#-----
def lookup_bst(root, val):
    '''Return first node found with given value'''

    if root is None:
        print(f'NO value {val} found in tree')
        return None
    if root.val == val:
        print(f'Found value {val} in tree; returning node')
        return root
    if val < root.val:
        return lookup_bst(root.left, val)
    else:
        return lookup_bst(root.right, val)

#-----
# BST delete
#-----
def delete_bst(root, val, parent=None):
    '''Delete first node found with given value; return root of updated tree.'''

    # Case: empty tree or val not found
    if root is None:
        print(f'DEBUG: value {val} not found in tree')
        return

    if root.val == val:
        # Case: leaf
        if root.left is None and root.right is None:
            # TODO: delete the parent's correct child reference
            # TODO: DEBUG this -- fails when parent is null
            if parent.val < val:
                parent.right = None
            else:
                parent.left = None

        # Case: 1 child
        elif root.left is not None:
            root.val = root.left.val
            root.left = None
        elif root.right is not None:
            root.val = root.right.val
            root.right = None

        # Case: 2 children
        else:
            #replacement_node = find_successor_bst(root.right, val)
            delete_bst(root.right, replacement_node.val)
            root.val = replacement_node.val

    elif val < root.val:
        delete_bst(root.left, val, root)
    else:
        delete_bst(root.right, val, root)

    return root

#-----
# Create test tree(s)
#-----

# EXAMPLE TREE 1
#
#       10
#     _/  \_
#    /      \
#   5        15
#  / \      /  \
# 3   7    13   17
#
node1_1 = Node(5, Node(3), Node(7))
node1_2 = Node(15, Node(13), Node(17))
tree1 = Node(10, node1_1, node1_2)

# EXAMPLE TREE X
#
#       5
#     _/ \_
#    /     \
#   5       5
#  / \       \
# 5   5       5
#

#---
# Run & assert correctness of DFT & BFT
# TODO: Add assertions and more test cases
#---
print('Calling dft()...')
assert dft(tree1) == [10, 5, 3, 7, 15, 13, 17]
print('\n')

print('Calling dft_iter()...')
assert dft_iter(tree1) == [10, 5, 3, 7, 15, 13, 17]
print('\n')

print('Calling bft()...')
assert bft(tree1) == [10, 5, 15, 3, 7, 13, 17]
print('\n')

print('Calling insert_bst(tree1, 6)...')
result = insert_bst(tree1, 6)
assert dft(result) == [10, 5, 3, 7, 6, 15, 13, 17]
print('\n')

print('Calling insert_bst(tree1, 20)...')
result = insert_bst(tree1, 20)
assert dft(result) == [10, 5, 3, 7, 6, 15, 13, 17, 20]
print('\n')

print('Calling insert_bst(None, 100)... [case: empty tree passed]')
result = insert_bst(None, 100)
assert dft(result) == [100]
print('\n')

print('Calling lookup_bst(tree1, 13)...')
result_node = lookup_bst(tree1, 13)
assert result_node.val == 13

print('Calling lookup_bst(tree1, 1000)... [case: not found]')
result_node = lookup_bst(tree1, 1000)
assert result_node == None
print('\n')

print('Calling delete_bst(tree1, 13)... [delete leaf (parent\'s left)]')
result_root = delete_bst(tree1, 13)
assert dft(result_root) == [10, 5, 3, 7, 6, 15, 17, 20]
print('\n')

print('Calling delete_bst(tree1, 20)... [delete leaf (parent\'s right)]')
result_root = delete_bst(tree1, 20)
assert dft(result_root) == [10, 5, 3, 7, 6, 15, 17]
print('\n')

print('Calling delete_bst(tree1, 17)... [delete node w/ one child]')
result_root = delete_bst(tree1, 17)
assert dft(result_root) == [10, 5, 3, 7, 6, 15]
print('\n')

print('Calling delete_bst(tree1, 5)... [delete node w/ two children]')
result_root = delete_bst(tree1, 5)
assert dft(result_root) == [10, 3, 7, 6, 15]
print('\n')

print('Calling delete_bst(Node(42), 42)... [delete only node]')
assert delete_bst(Node(42), 42) == None
print('\n')

print('Calling delete_bst(tree1, 42)... [node not found]')
assert delete_bst(tree1, 42) == None
print('\n')