from tkinter import *
from tkinter import colorchooser
from tkinter import ttk
from time import sleep, time
import tkinter.messagebox as box
from numpy import sign

class EdgesWithFlag(Frame):
    img = 0
    font = "Calibria 14"
    ended = False
    extrems = [[]]
    stack = []

    width = 1090
    height = 1016
    points = [[]]
    edges = [[]]
    figure = 0

    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent
        self.init_ui()

    def choose_lines_color(self):
        self.color_lines = colorchooser.askcolor()[1]
        self.color_lines_btn.configure(bg=self.color_lines)

    def choose_fill_color(self):
        self.color_fill = colorchooser.askcolor()[1]
        self.color_fill_btn.configure(bg=self.color_fill)

    def choose_bg_color(self):
        self.color_bg = colorchooser.askcolor()[1]
        self.color_bg_btn.config(bg=self.color_bg)
        self.canvas.config(bg=self.color_bg)
        self.set_image_to_canvas()

    def add(self):
        try:
            x = float(self.x_entry.get())
            y = float(self.y_entry.get())
        except ValueError:
            box.showerror("Ошибка", "Координаты точки должны быть вещественными числами")
            return

        self.points[self.figure].append([x, y, self.color_lines])
        self.draw_line()

    def clear(self):
        self.canvas.delete("all")
        self.figure = 0
        self.points = [[]]
        self.extrems = [[]]
        self.set_image_to_canvas()

    def Bresenham_int(self, x1, y1, x2, y2):

        x = int(x1)
        y = int(y1)
        dx = int(x2 - x1)
        dy = int(y2 - y1)
        sx = int(sign(dx))
        sy = int(sign(dy))
        dx = abs(dx)
        dy = abs(dy)
        if (dx >= dy):
            fl = 0
        else:
            fl = 1
            dy, dx = dx, dy
        e = 2 * dy - dx
        for i in range(0, dx + 1):

            self.img.put(self.color_lines, (x, y))
            if (e >= 0):
                if (fl == 0):
                    y += sy
                else:
                    x += sx
                e -= 2 * dx
            if (e <= 0):
                if (fl == 0):
                    x += sx
                else:
                    y += sy
                e += 2 * dy

    def cancel(self):
        if len(self.points) == 0:
            box.showinfo("Предупреждение", "Отменять нечего")
            return
        tempCol = self.color_lines
        self.color_lines = self.color_bg
        if len(self.points[self.figure]) > 1:
            self.Bresenham_int(self.points[self.figure][-2][0],
                        self.points[self.figure][-2][1],
                        self.points[self.figure][-1][0],
                        self.points[self.figure][-1][1])
            self.points[self.figure].pop()
        else:
            self.points.pop()
            self.figure -= 1
            if (self.figure >= 0):
                self.Bresenham_int(self.points[self.figure][0][0],
                            self.points[self.figure][0][1],
                            self.points[self.figure][-1][0],
                            self.points[self.figure][-1][1])
        self.color_lines = tempCol

    def draw_line(self):
        self.ended = False
        if len(self.points[self.figure]) > 1:
            self.Bresenham_int(self.points[self.figure][-2][0],
                        self.points[self.figure][-2][1],
                        self.points[self.figure][-1][0],
                        self.points[self.figure][-1][1])

    def left_click(self, event):
        self.ended = False
        if (self.points[0] == 0):
            self.points.append(list())
        self.points[self.figure].append([event.x, event.y, self.color_lines])
        self.draw_line()

    def left_click_horizontal(self, event):
        if (len(self.points[self.figure]) == 0):
            box.showwarning("Информация", "Невозможно провести горизонтальную линию без начальной точки")
            return
        self.ended = False
        prev_y = self.points[self.figure][len(self.points[self.figure]) - 1][1]
        self.points[self.figure].append([event.x, prev_y, self.color_lines])
        self.draw_line()

    def left_click_vertical(self, event):
        if (len(self.points[self.figure]) == 0):
            box.showwarning("Информация", "Невозможно провести вертикальную линию без начальной точки")
            return
        self.ended = False
        prev_x = self.points[self.figure][len(self.points[self.figure]) - 1][0]
        self.points[self.figure].append([prev_x, event.y, self.color_lines])
        self.draw_line()

    def right_click(self, event):
        if (len(self.points[self.figure]) < 3):
            box.showerror("Ошибка", "Невозможно замкнуть вырожденную фигуру (пустую фигуру, точку или прямую)")
            return
        self.ended = True
        self.Bresenham_int(self.points[self.figure][0][0],
                   self.points[self.figure][0][1],
                   self.points[self.figure][-1][0],
                   self.points[self.figure][-1][1])
        self.figure += 1

        self.points.append(list())

    def get_rgb_tuple(self, color):
        return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16))

    def fill_area(self, pause=False):
        draw_tuple = self.get_rgb_tuple(self.color_lines)
        fill_tuple = self.get_rgb_tuple(self.color_fill)
        while self.stack:

            current_point = self.stack.pop()
            self.img.put(self.color_fill, (current_point[0], current_point[1]))

            x, y = current_point[0] + 1, current_point[1]
            while self.img.get(x, y) != draw_tuple and self.img.get(x, y) != fill_tuple and x < self.width - 1:
                self.img.put(self.color_fill, (x, y))
                x += 1
            rx = x - 1

            x = current_point[0] - 1
            while self.img.get(x, y) != draw_tuple and self.img.get(x, y) != fill_tuple and x > 0:
                self.img.put(self.color_fill, (x, y))
                x -= 1
            lx = x + 1

            if (0 < y < self.height - 1):
                for i in [1, -1]:
                    x = lx
                    y = current_point[1] + i

                    while x <= rx:
                        flag = False
                        while self.img.get(x, y) != draw_tuple and self.img.get(x, y) != fill_tuple and x <= rx:
                            flag = True
                            x += 1

                        if flag:
                            self.stack.append([x - 1, y])
                            flag = False
                        xi = x
                        while (self.img.get(x, y) != draw_tuple) and self.img.get(x, y) != fill_tuple and x <= rx:
                            x += 1

                        if x == xi:
                            x += 1
            if pause:
                sleep(0.1)
                self.canvas.update()

    def start_by_click(self, event):
        self.stack.extend([[event.x, event.y]])
        self.img.put(self.color_lines, (event.x, event.y))
        self.start()

    def start(self):
        if (not self.ended):
            box.showerror("Ошибка", "Для закрашивания необходимо замкнуть фигуру")
            return
        # self.points.pop()

        delay = self.draw_mode_chooser.get()
        if (delay == "С задержкой"):
            self.fill_area(True)
        else:
            self.fill_area()

    def set_image_to_canvas(self):
        self.img = PhotoImage(width = self.width, height = self.height, palette=self.color_bg)
        self.canvas.create_image((545, 508), image = self.img, state = "normal")
        self.img.put(self.color_bg, to=(0, 0, self.width, self.height))

    def init_ui(self):
        self.color_lines = "#000000"
        color_lines_lbl = Label(self, text="Цвет линий", font=self.font)
        color_lines_lbl.grid(row=0, column=0)
        self.color_lines_btn = Button(self, bg=self.color_lines, height=1, width=3, command=self.choose_lines_color)
        self.color_lines_btn.grid(row=0, column=1)

        self.color_bg = "#FFFFFF"
        color_bg_lbl = Label(self, text="Цвет фона", font=self.font)
        color_bg_lbl.grid(row=0, column=2)
        self.color_bg_btn = Button(self, bg=self.color_bg, height=1, width=3, command=self.choose_bg_color)
        self.color_bg_btn.grid(row=0, column=3)

        self.color_fill = "#FF0000"
        color_fill_lbl = Label(self, text="Цвет заливки", font=self.font)
        color_fill_lbl.grid(row=1, column=1)
        self.color_fill_btn = Button(self, bg=self.color_fill, height=1, width=3, command=self.choose_fill_color)
        self.color_fill_btn.grid(row=1, column=2)

        draw_mode_lbl = Label(self, text="Режим закраски:", font=self.font)
        draw_mode_lbl.grid(row=2, column=0)
        self.draw_mode_chooser = ttk.Combobox(self, values=[
            'Без задержки',
            'С задержкой'], font=self.font)
        self.draw_mode_chooser.configure(width=50)
        self.draw_mode_chooser.current(0)
        self.draw_mode_chooser.grid(row=2, column=1, columnspan=3)

        rules_lbl = Label(self, text="""Построчный алгоритм затравочного заполнения
Для добавления новой точки нажмите левую кнопку мыши
Для ввода произвольной кривой зажмите левую кнопку мыши и рисуйте на полотне
Для замыкания фигуры нажмите правую кнопку мыши
Для рисования горизонтальной линии нажмите Ctrl и левую кнопку мыши
Для рисования горизонтальной линии нажмите Shift и левую кнопку мыши
Для начала закрашивания фигуры нажмите Shift и правую кнопку мыши""", justify=CENTER, font=self.font)
        rules_lbl.grid(row=3, column=0, rowspan=7, columnspan=5)

        # add_label = Label(self, text="Добавить точку", justify=CENTER, font=self.font)
        # add_label.grid(row=6, column=1, columnspan=2)

        # x_label = Label(self, text="X:", font=self.font)
        # x_label.grid(row=7, column=0)
        # self.x_entry = Entry(self)
        # self.x_entry.grid(row=7, column=1)
        # y_label = Label(self, text="Y:", font=self.font)
        # y_label.grid(row=7, column=2)
        # self.y_entry = Entry(self)
        # self.y_entry.grid(row=7, column=3)

        # add_btn = Button(self, text="Добавить", command=self.add, justify=CENTER, font=self.font)
        # add_btn.grid(row=8, column=1, columnspan=2)

        cancel_btn = Button(self, text="Отменить добавление точки", command=self.cancel, font=self.font)
        cancel_btn.grid(row=10, column=1, columnspan=2)

        clear_btn = Button(self, text="Очистить полотно", command=self.clear, font=self.font)
        clear_btn.grid(row=11, column=1, columnspan=2)

        self.canvas = Canvas(self, bg = self.color_bg, width = 1090, height = 1016, borderwidth = 5, relief = RIDGE)
        self.set_image_to_canvas()

        self.canvas.bind('<1>', self.left_click)
        self.canvas.bind('<B1-Motion>', self.left_click)
        self.canvas.bind('<Control-Button-1>', self.left_click_horizontal)
        self.canvas.bind('<Shift-Button-1>', self.left_click_vertical)
        self.canvas.bind('<3>', self.right_click)
        self.canvas.bind('<Shift-Button-3>', self.start_by_click)
        self.canvas.grid(row=0, column=5, rowspan=20, columnspan=20)
        self.grid(row=0, column=0)

if __name__ == '__main__':
    Window = Tk()
    Window.title('Закраска')
    ex = EdgesWithFlag(Window)
    Window.geometry("1800x1000")
    Window.mainloop()


import glob
import os

def h3d_parser(root_path: str):
    """
    Returns a list of absolute image paths contained in the Honda 3D dataset
    (H3D).

    Ref: https://usa.honda-ri.com/H3D

    Dataset structure (top level corrspond to 'root directory'):
    honda_h3d/
        camera_data/
            icra_benchmark_20200103_image_only/
                scenario_001/
                    *.png
                ...
            ...
        data/

    Args:
        root_path (str): Root path of dataset.

    Returns:
        List of strings corresponding to absolute image paths.
    """
    dataset_img_paths = []

    # Parse 'camera_data'
    if os.path.isdir(os.path.join(root_path, 'camera_data')):
        img_paths = glob.glob(
            f"{root_path}/camera_data/icra_benchmark_20200103_image_only/*/*.png")
        dataset_img_paths += img_paths

    return dataset_img_paths


#   Maggie Henry
#   CSCI 102 – Section G
#   Week 4 - Lab A - Missing Chess Pieces
#   References: none
#   Time: 20 minutes

king = int(input('KINGS>'))
queen = int(input('QUEENS>'))
rook = int(input('ROOKS>'))
bishop = int(input('BISHOPS>'))
knight = int(input('KNIGHTS>'))
pawn = int(input('PAWNS>'))

if king != 1:
    new_king = (1 - king)
elif king == 1:
    new_king = 0

if queen != 1:
    new_queen = (1 - queen)
elif queen == 1:
    new_queen = 0

if rook != 2:
    new_rook = (2 - rook)
elif rook == 2:
    new_rook = 0

if bishop != 2:
    new_bishop = (2 - bishop)
elif bishop == 2:
    new_bishop = 0

if knight != 2:
    new_knight = (2 - knight)
elif knight == 2:
    new_knight = 0

if pawn != 8:
    new_pawn = (8 - pawn)
elif pawn == 8:
    new_pawn = 0

print('The output below provides the number of each type you have (over or under):')
print('OUTPUT>', new_king, new_queen, new_rook, new_bishop, new_knight, new_pawn, end="")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 17:18:41 2020

@author: srujanvajram
"""

import pydicom
import os
import numpy as np
import pandas as pd
from skimage.transform import resize
from matplotlib import pyplot as plt
from math import sqrt

description = pd.read_csv("Mass-Training-Description.csv")

# =========================================================================== #
def dicom_resize(path, dimension, savedir) -> int:

    # Holds a reference to the directory that stores the DICOM files of interest
    PathDicom = path

     # Will store the DICOM files
    list_dicom = []

    # For loop walks through the direcotries and grabs the Dicom files
    for dirName, subdirList, fileList in os.walk(PathDicom):
        for fileName in fileList:
            if ".dcm" in fileName:
                list_dicom.append(os.path.join(dirName,fileName))
    # -------------------------------------- #

    # Hold a reference to the first DICOM file in the list
    RefD = pydicom.read_file(list_dicom[1])

    # Set the new dimensions
    IMG_SIZE = dimension
    TARGET_PX_AREA = dimension*dimension

    # Set new dimensions
    #newDims = (IMG_SIZE, IMG_SIZE, len(list_dicom))

    # Initialize an empty array of zeros based on new dimensions
    # ArrayDicom = np.zeros(newDims, dtype=RefD.pixel_array.dtype)

    # -------------------------------------- #
    # Read each dicom file
    i = 0
    for file in list_dicom:

        ds = pydicom.read_file(file)

        # Grab the rows and columns
        rows = ds.Rows
        cols = ds.Columns

        # Calculate a scale factor that can be multiplied to each dimension
        # of the original DICOM. Our goal is to recale the images as close to
        # the target pixel area as possible without modifying Aspect Ratio.
        scale_factor = sqrt( TARGET_PX_AREA / float(rows*cols) )

        # Calculate the new dimensions based on scale factor
        newRows = int(np.floor(rows * scale_factor))
        newCols = int(np.floor(cols * scale_factor))

        # Extract the relevant pixel data from DICOM
        image = ds.pixel_array
        resized_image = resize(image, (newRows, newCols), anti_aliasing=True)

        # Saves the numpy array to specific folder in directory
        np.savez( os.path.join(savedir, ds.PatientID), resized_image, str(ds.PatientID), int(description.breast_density[i]), str(description.pathology[i]))

        # -------------------------------------- #
        print("Operating on image " + str(i) + " of " + str(len(list_dicom)))
        print("Breast density is: ")
        print(description.breast_density[i])
        i+=1

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

    return 1

# =========================================================================== #

pathName = "/Users/srujanvajram/Documents/Internship related/UCSF/DICOM/CBIS-DDSM-Train"
dimension = 300
savedir = 'saved_numpy_files'

dicom_resize(pathName,dimension,savedir)


# This file will create a class object that utilizes another inherited class
from Inherit import FavIndianFood

# A class object for a class that utilizes inheritance
# Parent class "FavFood"; created in "Inherit2"
# Child class "FavIndianFood"; created in "Inherit"
IndianFood = FavIndianFood()

IndianFood.dish()     # A function that was not inherited
IndianFood.fried()    # A function that was inherited but redefined in the new class
IndianFood.grilled()  # A function that was inherited


import os
import time
import shutil

CHECK_INTERVAL = 3600*6
REMOVAL_THRESH = 3600

assert os.path.exists("tempfiles")
os.chdir("tempfiles")

f = open("cleaner_log.txt", "w")
f.close()

while True:
    print(f"cleaning!!!\t{time.strftime('%Y-%m-%d %H:%M:%S %z', time.localtime())}")
    f = open("cleaner_log.txt", "a")
    for item in os.listdir():
        if not os.path.isdir(item):
            continue
        if time.time()-os.path.getctime(item) >= REMOVAL_THRESH:
            shutil.rmtree(item)
            f.write(item + "\t" + time.strftime("%Y-%m-%d %H:%M:%S %z", time.localtime()) + "\n")
            f.flush()
    f.close()
    time.sleep(CHECK_INTERVAL)


#!/usr/bin/env python3
import rclpy
import math
import random
from rclpy.node import Node
from turtlesim.srv import Spawn
from functools import partial
from turtle_interfaces.msg import TurtleID

class nodeMaker(Node):
    def __init__(self):
        super().__init__("turtle_spawner")
        self.create_timer(2,self.makeClientSpawner)
        # self.makeClientSpawner()

    def makeClientSpawner(self):
        client=self.create_client(Spawn,"spawn")
        while not client.wait_for_service(1.0):
            self.get_logger().warn("waiting for spawn...")
        request = Spawn.Request()
        new_x=random.random()*11
        new_y=random.random()*11
        new_theta=random.random()*2*math.pi
        # new_x=1.0
        # new_y=4.0
        # new_theta=0.0
        request.x=new_x
        request.y=new_y
        request.theta=new_theta
        future=client.call_async(request)
        future.add_done_callback(partial(self.callback_future,x=new_x,y=new_y,theta=new_theta))

    def callback_future(self,future,x,y,theta):
        try:
            turtle=TurtleID()
            turtle.name=future.result().name
            turtle.x=x
            turtle.y=y
            turtle.theta=theta
            pub=self.create_publisher(TurtleID,"turtleID",10)
            pub.publish(turtle)
        except Exception as e:
            self.get_logger().error("Unexpected Error... {}".format(e))

def main(args=None):
    rclpy.init()
    node = nodeMaker()
    rclpy.spin(node)
    rclpy.shutdown()

if __name__=="__main__":
    main()


from rest_framework.authentication import BasicAuthentication
from rest_framework.exceptions import PermissionDenied
from django.contrib.auth import get_user_model
from django.conf import settings # for the secret key
import jwt
User = get_user_model()

# creating the authenticate function to check if user has a valid token / if user exists and therefore has permissions
class JWTAuthentication(BasicAuthentication):

    def authenticate(self, request):

        header = request.headers.get('Authorization')

        if not header: # checking if there is no header
            return None

        if header.startswith('Basic'): # checking if header starts with 'Basic'
            return None

        if not header.startswith('Bearer'): # check if header doesn't start with 'Bearer'
            raise PermissionDenied({'message': 'Invalid authorization header'})

        token = header.replace('Bearer ', '') # removing the start of the users token and storing it in a token variable to easily use

        try:
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
            user = User.objects.get(pk=payload.get('sub'))
        except jwt.exceptions.InvalidTokenError:
            raise PermissionDenied({'message': 'Invalid Token'})
        except User.DoesNotExist:
            raise PermissionDenied({'message': 'User not found'})

        return (user, token)


__author__ = "Paweł Bernecki"

from collections import deque
import copy
import random

import numpy as np
import Field

class CSP:
    def __init__(self, task=0, size=4):
        self.task = task
        self.size = size
        self.results = deque()
        self.iterations_bt = 0
        self.iterations_fc = 0

    def start(self, algorithm=1):
        variables = deque()
        if (self.task == 0):  # N queens
            array = np.zeros(shape=self.size, dtype=int)
            array[:] = [x - 10 for x in array]
            def forwardchecking(*args):
                return self.forwardchecking_queens(args[0], args[1])
            def backtracking(*args):
                return self.backtracking_queens(args[0], args[1])
            for i in range(self.size):
                variables.append(Field.Field(0, i, self.size, 0))
        else:  # Latin square
            array = np.zeros(shape=(self.size, self.size), dtype=int)
            def forwardchecking(*args):
                return self.forwardchecking_latin(args[0], args[1])
            def backtracking(*args):
                return self.backtracking_latin(args[0], args[1])
            for i in range(self.size):
                for j in range(self.size):
                    variables.append(Field.Field(i, j, self.size, 1))
        if algorithm == 0:
            forwardchecking(copy.deepcopy(array), copy.deepcopy(variables))
            iterations = self.iterations_fc
        elif algorithm == 1:
            backtracking(array, variables)
            iterations = self.iterations_bt
        else:
            print("normal bt")
            self.singlebacktrackqueens(copy.deepcopy(array), copy.deepcopy(variables))
            random.shuffle(variables)
            print("random bt")
            self.iterations_bt = 0
            self.singlebacktrackqueens(array, variables)
            iterations = -1
        return (self.results, iterations)

    def modify_domains_latin(self, variables, current_variable, value):
        for var in variables:
            if var.column == current_variable.column or var.row == current_variable.row:
                if value in var.domain:
                    var.domain.remove(value)
        return variables

    def forwardchecking_latin(self, array, variables):
        if (len(variables) == 0):
            self.results.append(copy.copy(array))
            return True
        variable = variables.popleft()
        for value in variable.domain:
            for var in variables:
                if not var.domain:
                    return False
            variables_temp = self.modify_domains_latin(copy.deepcopy(variables), variable, value)
            array[variable.row, variable.column] = value
            self.forwardchecking_latin(array, variables_temp)
            self.iterations_fc += 1
            array[variable.row, variable.column] = 0
        return False

    def backtracking_latin(self, array, variables):
        if self.check_latin(array):
            self.results.append(copy.copy(array))
            return True
        if (len(variables) == 0):
            return False
        variable = variables.popleft()
        for value in variable.domain:
            if self.check_consistancy_latin(array, variable.row, variable.column, value):
                array[variable.row, variable.column] = value
                self.backtracking_latin(array, copy.copy(variables))
                self.iterations_bt += 1
                array[variable.row, variable.column] = 0
        return False

    def check_consistancy_latin(self, array, row, col, val):
        if val in array[row] or val in array[:, col]:
            return False
        return True

    def check_latin(self, array):
        for i in range(self.size):
            if len(np.unique(array[i])) != self.size or 0 in array[i]:
                return False
            if len(np.unique(array[:, i])) != self.size or 0 in array[:, i]:
                return False
        return True

    def modify_domains_queens(self, variables, current_variable, value):
        for var in variables:
            if value in var.domain:
                var.domain.remove(value)
            if value + var.column - current_variable.column in var.domain:
                var.domain.remove(value + var.column - current_variable.column)
            if value - var.column + current_variable.column in var.domain:
                var.domain.remove(value - var.column + current_variable.column)
        return variables

    def forwardchecking_queens(self, array, variables):
        if len(variables) == 0:
            self.results.append(copy.copy(array))
            return True
        variable = variables.popleft()
        for value in variable.domain:
            for var in variables:
                if not var.domain:
                    return False
            variables_temp = self.modify_domains_queens(copy.deepcopy(variables), variable, value)
            array[variable.column] = value
            self.forwardchecking_queens(array, variables_temp)
            self.iterations_fc += 1
            array[variable.column] = -10
        return False

    def backtracking_queens(self, array, variables):
        if self.check_queens(array):
            self.results.append(copy.copy(array))
            return True
        if (len(variables) == 0):
            return False
        variable = variables.popleft()
        for value in variable.domain:
            if self.check_consistancy_queens(array, variable.column, value):
                self.backtracking_queens(array, copy.copy(variables))
                self.iterations_bt += 1
                array[variable.column] = -10
        return False

    def check_consistancy_queens(self, array, col, val):
        for i in range(len(array)):
            dr = val - array[i]
            dc = col - i
            if dr == dc or dr == -dc:
                return False

        if val in array:
            return False
        array[col] = val
        diffs = np.diff(array)
        if 1 in diffs or -1 in diffs:
            array[col] = -10
            return False
        return True

    def check_queens(self, array):
        diffs = np.diff(array)
        if 1 in diffs or -1 in diffs or 0 in diffs or -10 in array:
            return False
        return True

    def singlebacktrackqueens(self, array, variables):
        if self.check_queens(array):
            print(self.iterations_bt)
            print(array, "\n")
            return True
        if (len(variables) == 0):
            return False
        variable = variables.popleft()
        for value in variable.domain:
            if self.check_consistancy_queens(array, variable.column, value):
                if self.singlebacktrackqueens(array, copy.copy(variables)):
                    return True
                self.iterations_bt += 1
                array[variable.column] = -10
        return False

    def singleforwardcheckqueens(self, array, variables):
        if len(variables) == 0:
            print(self.iterations_fc)
            print(array, "\n")
            return True
        variable = variables.popleft()
        for value in variable.domain:
            for var in variables:
                if not var.domain:
                    return False
            variables_temp = self.modify_domains_queens(copy.deepcopy(variables), variable, value)
            array[variable.column] = value
            if self.singlebacktrackqueens(array, variables_temp):
                return True
            self.iterations_fc += 1
            array[variable.column] = -10
        return False


import os, sys

import numpy as np
import astropy.units as u
from astropy.time import Time
import matplotlib.pyplot as plt

import twobody

from models import circ_function

rnd = np.random.default_rng(seed=42)

# a_avg_FGK = 4.5 # AU
# m_tot = (0.8+1) # Msun
# P_avg_yr = np.sqrt(a_avg_FGK**3/m_tot) # Year
# P_avg = (P_avg_yr*u.year).to(u.day)
# log_P_avg = np.log10(P_avg.value)

def ecc_init(n_stars=10,e_avg=0.35,e_sigma=0.15,
             log_P_avg=5,log_P_sigma=0.5,
             P_lims=[0.1,1000],plot_filename=None):
    """
    Produce a random set of n_stars binaries,
    normally distributed in eccentricity space (set by e_avg and e_sigma)
    and uniformly distributted in eccentricity space.

    Also possible to run with
    normally distributed in period space (set by log_P_avg and
    log_P_sigma in log10(days )

    Default period distribution taken from Duchene & Kraus (2013), Sec 3.1.2
    """

    eccentricities = rnd.normal(loc=e_avg,scale=e_sigma,size=n_stars)
    eccentricities[eccentricities<0] = 0
    eccentricities[eccentricities>1] = 1

    # log_periods = rnd.normal(loc=log_P_avg,scale=log_P_sigma,size=n_stars)
    # periods = (10**log_periods) * u.day

    log_periods = rnd.uniform(low=np.log10(P_lims[0]),high=np.log10(P_lims[1]),
                              size=n_stars)
    periods = (10**log_periods)*u.day
    # periods = rnd.uniform(low=P_lims[0],high=P_lims[1],size=n_stars)*u.day

    if plot_filename is not None:
        plt.plot(periods,eccentricities,'o')
        plt.xlim(P_lims[0],P_lims[1])
        plt.xscale("log")
        plt.ylim(-0.01,1)
        plt.savefig(plot_filename,facecolor="w")

    return eccentricities, periods

def ecc_circularized(n_stars,Pcirc=7*u.day,plot_filename=None,**ecc_kwargs):
    """
    Produce a random set of n_stars binaries, where eccentricities are
    determined following the circularization function from Meibom & Mathieu 2005

    TODO: right now it just cuts the distribution at Pcirc because I don't have time
    """

    raw_eccentricities, periods = ecc_init(n_stars,**ecc_kwargs)

    x_periods = np.logspace(-1,4,100)
    y_ecc = circ_function(x_periods,Pcirc.to(u.day).value)

    eccentricities = raw_eccentricities
    eccentricities[periods<Pcirc] = 0

    if plot_filename is not None:
        plt.plot(periods,eccentricities,'o')
        plt.plot(x_periods,y_ecc,'-')
        # plt.xlim(P_lims[0],P_lims[1])
        plt.xscale("log")
        plt.ylim(-0.01,1)
        plt.savefig(plot_filename,facecolor="w")

    return eccentricities, periods

def orbit_init(n_stars=10,q_gamma=4.2,output_filename=None,circ=False,**ecc_kwargs):

    if circ:
        eccentricities, periods = ecc_circularized(n_stars,**ecc_kwargs)
    else:
        eccentricities, periods = ecc_init(n_stars,**ecc_kwargs)

    omega = rnd.uniform(low=0,high=2*np.pi,size=n_stars)*u.radian # argument of pericenter
    inc = rnd.uniform(low=0,high=np.pi,size=n_stars)*u.radian # inclination

    M0 = rnd.uniform(low=0,high=2*np.pi,size=n_stars)*u.radian # phase at reference time

    # Omega is the Longitude of ascending node; no impact on RVs
    # we'll set t0 to 2015.0 for everything as well

    q = rnd.power(q_gamma+1,size=n_stars)

    M1 = 1*u.solMass
    M2 = M1*q

    aa = (M2.value * periods.to(u.year).value**2)**(1/3) * u.au

    # K = rnd.uniform(low=1,high=100,size=n_stars)*u.km/u.s

    all_elements = []
    for i in range(n_stars):
        all_elements.append(twobody.KeplerElements(P=periods[i],e=eccentricities[i],
                                                   a=aa[i],omega=omega[i],i=inc[i],
                                                   Omega=0*u.degree,t0=Time('J2015.0'),
                                                   M0=M0[i]))

    if output_filename is not None:
        with open(output_filename,"w") as f:
            f.write("P(year),P(day),q,M2,a(au),omega(rad),i(rad),M0(rad),Omega,T0\n")
            for i in range(n_stars):
                f.write(f"{periods[i].to(u.year).value:.6f},")
                f.write(f"{periods[i].to(u.day).value:.6f},")
                f.write(f"{q[i]:.2f},")
                f.write(f"{M2[i].to(u.solMass).value:.2f},")
                f.write(f"{aa[i].to(u.au).value:.2f},")
                f.write(f"{omega[i].to(u.radian).value:.3f},")
                f.write(f"{inc[i].to(u.radian).value:.3f},")
                f.write(f"{M0[i].to(u.radian).value:.3f},")
                f.write(f"0.0,J2015.0\n")

    return all_elements

def generate_rvs(elements_list,output_filename,times=None):
    """
    Generate fake RV datasets from a list of orbital elements
    """

    if times==None:
        rand_times = rnd.uniform(low=0,high=12,size=18)*u.year
        t = Time('2007-01-10') + rand_times
    elif times=="NGC 6811":
        dates = []
        with open(os.path.expanduser("~/Dropbox/data/hecto_date_list.txt"),"r") as g:
            l = g.readline()
            while ("ngc6811" in l) is False:
                l = g.readline()
            l = g.readline()
            l = g.readline()
            while (l!="\n"):
                dates.append(l.strip())
                l = g.readline()
                if l=="":
                    break

        # print(dates)
        t = Time(dates,format="decimalyear")

    max_obs = len(t)
    time_idx = np.arange(max_obs)

    with open(output_filename,"w") as f:
        f.write("star,JD,rv(km/s)\n")

        for i,elem in enumerate(elements_list):
            orb = twobody.KeplerOrbit(elem)
            rv = orb.radial_velocity(t)

            if elem.K>(20*u.km/u.s):
                low_obs = 8
            else:
                low_obs = 3
            n_obs = rnd.integers(low=low_obs,high=max_obs)
            obs_j = rnd.choice(time_idx,size=n_obs)

            for j in obs_j:
                f.write(f"SYN{i:05d},{t[j].jd:.6f}")
                f.write(f",{rv[j].to(u.km/u.s).value:.2f}\n")

if __name__=="__main__":

    n_stars=100

    # ee,pp = ecc_init(n_stars,plot_filename="test_syn_orbits.png",P_lims=[0.1,1e4])
    # plt.close()
    # ee,pp = ecc_circularized(n_stars,plot_filename="test_syn_orbits_circ.png",P_lims=[0.1,1e4])
    # plt.close()

    elem_list = orbit_init(n_stars,output_filename="test_syn_orbits.csv",
                           circ=False,plot_filename="test_syn.png")
    generate_rvs(elem_list,output_filename="test_syn_rvs.csv",times="NGC 6811")
    plt.close()

    elem_list_circ = orbit_init(n_stars,output_filename="test_syn_circ_orbits.csv",
                                circ=True,plot_filename="test_syn_circ.png")
    generate_rvs(elem_list_circ,output_filename="test_syn_circ_rvs.csv",times="NGC 6811")
    plt.close()


"""
Linear regression is a tool for modeling the dependence between two sets of
data so that we can eventually use this model to make predictions. The name
comes from the fact that we form a linear model (straight line) of one set of
data based on a second. In the literature, the variable that we wish to model
is frequently called the response variable, and the variable that we are
using in this model is the predictor variable.

This module illustrates how to use the statsmodels package to perform a simple
linear regression to model the relationship between two sets of data.
"""
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt

from numpy.random import default_rng

rng = default_rng(12345)

x = np.linspace(0, 5, 25)
rng.shuffle(x)

trend = 2.0
shift = 5.0

y1 = trend * x + shift + rng.normal(0, 0.5, size=25)
y2 = trend * x + shift + rng.normal(0, 5, size=25)

fig, ax = plt.subplots()
ax.scatter(x, y1, c="b", label="Good correlation")
ax.scatter(x, y2, c="r", label="Bad correlation")
ax.legend()
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_title("Scatter plot of data with best fit lines")

pred_x = sm.add_constant(x)

model1 = sm.OLS(y1, pred_x).fit()
model2 = sm.OLS(y2, pred_x).fit()

print(model1.summary())
print(model2.summary())

model_x = sm.add_constant(np.linspace(0, 5))
model_y1 = model1.predict(model_x)
model_y2 = model2.predict(model_x)

ax.plot(model_x[:, 1], model_y1, 'b')
ax.plot(model_x[:, 1], model_y2, 'r')

plt.show()


# HYPER-PARAMETERS
#================================================================================
# Training
num_epochs = 5000
mini_batch_size = 1

generator_learning_rate = 0.001
generator_learning_rate_decay = generator_learning_rate / 50000
discriminator_learning_rate = 0.0005
discriminator_learning_rate_decay = discriminator_learning_rate / 50000
decay_threshold = 500

lambda_cycle = 10
lambda_identity = 5

# Loop-Control
check_epoch = 1000

# Audio Processing
sampling_rate = 16000
num_mcep = 24
frame_period = 5.0
n_frames = 128

# DEFAULT PATHS
#================================================================================
# Common
train_A_dir_default = './data/train/A1'
train_B_dir_default = './data/train/B'
model_dir_default = './model/A1_to_B'
model_name_default = 'A1_to_B.ckpt'
random_seed_default = 0
validation_A_dir_default = './data/test/A1'
output_dir_default = './data/validation_output'
tensorboard_log_dir_default = './log'
# Conversion
data_dir_default = './data/test/A1'
conversion_direction_default = 'A2B'
conv_output_dir_default = './data/converted_voices'


__author__ = "David Adelberg"
__copyright__ = "Copyright 2016, David Adelberg"
__credits__ = ["David Adelberg"]

__license__ = """May be used by members of the Yale College Student Investment
                 Group for education, research, and management of the
                 organization's portfolio. All other uses require the express
                 permission of the copyright holder. Other interested persons
                 should contact the copyright holder."""
__version__ = "0.1.0"
__maintainer__ = "David Adelberg"
__email__ = "david.adelberg@yale.edu"
__status__ = "Prototype"

import matplotlib.pyplot as plt
from pandas.tools.plotting import boxplot_frame_groupby

def make_subplot():
    """Utility method to make a subplot."""
    return(plt.figure().add_subplot(1,1,1))

def plot_returns(returns, live_date=None):
    plt.figure()
    ax = make_subplot()
    if(live_date is None):
        returns.plot(ax=ax, label="all")
    elif(isinstance(live_date, str)):
        returns[:live_date].plot(ax=ax, label="train")
        returns[live_date:].plot(ax=ax, label="test")
    else:
        for i, (d1, d2) in enumerate(zip(live_date, live_date[1:])):
            returns[d1:d2].plot(ax=ax, label="group %i" % (i+1))

def make_boxplots(df, by, title):
    make_subplot()
    grouped = df.groupby(axis=0, level=df.index.names.index(by))
    boxplot_frame_groupby(grouped, subplots=False, rot=90, return_type='axes')
    plt.title(title)


import matplotlib.pyplot as plt
import numpy as np
from hyplot.plot import PFigure

from matplotlib.ticker import ScalarFormatter
from hyplot.plot.PFormatDecorator import PSelectTickDecorator
from hyplot.visual.PRunData import PRunData

from PyQt4.QtGui import QWidget

visual.fig = plt.figure(FigureClass = PFigure.PFigure)

ax = visual.fig.add_my_subplot(111)

#_______________________________________________________________________________
# plot the simulations

sim     = 5015
labels  = [123]
colors  = ['blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'black', 'brown', 'purple']
for label, color in zip(labels, colors):
    data = PRunData(sim)
    x, profile, fit = data.getSBProfile(label)
    ax.plot(x, profile, '.', color=color, label=str(label*0.1))
    ax.plot(x, fit, color=color)

#_______________________________________________________________________________
# plot properties
ax.minorticks_on()

#ax.set_yscale('log')
#ax.set_xlim(-6, -24)
ax.set_ylim(35., 20)

fontdict = {'size':12}
# markerscale does not work : (
leg = ax.legend(loc="upper right", prop=fontdict, ncol=2, numpoints=1, shadow=True, fancybox=True, markerscale=2)

#for handle in leg.legendHandles:
#    print handle.get_xydata()

ax.set_xlabel('$r\ [\mathrm{kpc}]$')
ax.set_ylabel('$\mathrm{SB\ [mag/"}^2]$')

visual.finalize(name='DE_MB_sersic_profiles5015.png', show=False)


from scripts.helpful_scripts import get_account, get_contract
from brownie import SunucashToken, TokenFarm, network, config
from web3 import Web3
import yaml, json, os, shutil

KEPT_BALANCE = Web3.toWei(100, "ether")
initial_supply = Web3.toWei(14000000, "ether")

def deploy_token_farm_and_sunucash_token(front_end_update = False):
    account = get_account()
    sunucash_token = SunucashToken.deploy(initial_supply, {"from": account})
    token_farm = TokenFarm.deploy(
        sunucash_token.address,
        {"from": account}
        )
    tx = sunucash_token.transfer(
        token_farm.address, sunucash_token.totalSupply() - KEPT_BALANCE, {"from": account}
    )
    tx.wait(1)
    # sunacashToken, weth_token, dai_token
    weth_token = get_contract("weth_token")
    dai_token = get_contract("dai_token")
    dict_of_allowed_tokens = {
        sunucash_token: get_contract("dai_usd_price_feed"),
        dai_token: get_contract("dai_usd_price_feed"),
        weth_token: get_contract("eth_usd_price_feed"),
    }

    add_allowed_tokens(token_farm, dict_of_allowed_tokens, account)
    if front_end_update:
        update_front_end()
    return token_farm, sunucash_token

def add_allowed_tokens(token_farm, dict_of_allowed_tokens, account):
    for token in dict_of_allowed_tokens:
        add_tx = token_farm.addAllowedTokens(token.address, {"from": account})
        add_tx.wait(1)
        set_tx = token_farm.setPriceFeedContract(token.address, dict_of_allowed_tokens[token], {"from": account})
        set_tx.wait(1)
    return token_farm

def update_front_end():
    # Send the build folder
    copy_folder_to_frontend("./build", "./front-end/src/chain-info")
    # Sending the frontend our config in JSON format
    with open("brownie-config.yaml", "r") as brownie_config:
        config_dict = yaml.load(brownie_config, Loader=yaml.FullLoader)
        with open("./front_end/src/brownie-config.json", "w") as brownie_config_json:
            json.dump(config_dict, brownie_config_json)
    print("Front end updated ¡¡¡")

def copy_folder_to_frontend(src, dest):
    if os.path.exists(dest):
        shutil.rmtree(dest)
    shutil.copytree(src, dest)

def main():
    deploy_token_farm_and_sunucash_token(front_end_update= True)


# t_p function
def transmission_probability(pdf,n_cutoff=300):
    p_avg = np.mean(pdf[-n_cutoff:])
    t_p = 2.0/(1+p_avg)
    return t_p
#initial variables
x = np.arange(0, 10, 0.01)
barrier = qw.square_barrier(x)
m=1
energies = np.arange(0, 25, 0.1)
transmission = np.zeros_like(energies)
# iterate over energies
for indx,e in enumerate(energies):
    psi_x = qw.plane_wave(x, e)
    psi_tunnel = qw.tunnel_findiff_propagate(x,psi_x,barrier,e)
    pdf = qw.prob_density(psi_tunnel)
    transmission[indx]=transmission_probability(pdf)
# plot
plt.plot(energies,transmission)
plt.title('Transmission vs. Energy')
plt.xlabel(' Energy')
plt.ylabel('Transmission probability')
plt.show()


def my_min(arr):
    ans = arr[0]
    for i in arr:
        if ans > i:
            ans = i
    return ans

def my_max(arr):
    ans = arr[0]
    for i in arr:
        if ans < i:
            ans = i
    return ans

def my_sum(arr):
    ans = 0
    for i in arr:
        ans += i
    return ans

def my_product(arr):
    ans = 1
    for i in arr:
        ans *= i
    return ans

def main_func(path):
    try:
        with open(path, 'r') as file:
            data = list(map(int, file.read().split()))
        # print(data)
        return [my_min(data), my_max(data), my_sum(data), my_product(data)]
    except OverflowError:
        return "OverflowError occurred"

# main_func('data.txt')


"""cli"""
import click
import numpy
import rasterio

from rasterio.rio import options
from rasterio.io import MemoryFile
from rio_cogeo.cogeo import cog_translate
from rio_cogeo.profiles import cog_profiles

class NodataParamType(click.ParamType):
  """Nodata type."""
  name = "nodata"
  def convert(self, value, param, ctx):
    """Validate and parse band index."""
    try:
      if value.lower() == "nan":
        return numpy.nan
      elif value.lower() in ["nil", "none", "nada"]:
        return None
      else:
        return float(value)
    except (TypeError, ValueError):
      raise click.ClickException("{} is not a valid nodata value.".format(value))

@click.command()
@options.file_in_arg
@options.file_out_arg
@click.option(
  "--nodata",
  type=NodataParamType(),
  metavar="NUMBER|nan",
  help="Set nodata masking values for input dataset.",
  multiple=True,
)

def main(input, output, nodata):
  """Read tile."""
  with rasterio.open(input) as src_dst:
    profile = src_dst.profile.copy()
    profile["nodata"] = 0
    arr = src_dst.read()
    for n in nodata:
      arr[arr == n] = 0

    with MemoryFile() as memfile:
      with memfile.open(**profile) as mem:
        # Populate the input file with numpy array
        mem.write(arr)

        dst_profile = cog_profiles.get("deflate")
        cog_translate(
          mem,
          output,
          dst_profile,
          in_memory=True,
          quiet=True,
        )

if __name__ == '__main__':
  main()


TOTLE_EPOCH = 100         # 训练周期数
latent_size = 100         # 隐码的长度
BATCH_SIZE = 128          # 用于训练的训练集批量大小
lr = 0.0002               # 学习率
b1 = 0.5                  # Adam优化器的beta1超参数
b2 = 0.999                # Adam优化器的beta2超参数
channels = 1              # 图像通道数
img_size = 28             # 训练图像长宽大小
BATCH_SIZE_VALID = 1000   # 用于评估的验证集批量大小
BATCH_SIZE_TEST = 10      # 测试批量大小
gap = 1                   # 判别器等待轮数


from flask import request, Flask, jsonify
import sqlite3 as sql

app = Flask(__name__)

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

@app.route('/api/v1/signup', methods=["POST"])
def signup():
    print("SIGNUP")
    content = request.get_json()
    nome, cognome, username, password, punti = content['nome'], content['cognome'], content['username'], content['password'], content['punti']
    print(content)
    try:
        with sql.connect("./db_Transazioni.db") as conn:
            print("Connecting to database")
            curs = conn.cursor()
            curs.execute("""INSERT INTO Utente (username, password, nome, cognome, punti) VALUES(?, ?, ?, ?, ?)""", (username, password, nome, cognome, punti))
            conn.commit()
            temp = jsonify({"success": True, "result":content})
            return temp
    except Exception as e:
        print("Error in connection to database")
        return jsonify({"success":False, "error":str(e)})

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

@app.route('/api/v1/trasferisci', methods=['POST'])
def trasferisci():
    print("TRASFERIMENTO")
    content = request.get_json()
    mittente, destinatario, punteggio, causale, data = content['mittente'], content['destinatario'], content['punti'],  content['causale'], content['data']
    login_id = login()
    if login_id != None:
        print(destinatario)
        print(request.headers)
        try:
            with sql.connect("./db_Transazioni.db") as conn:
                print("Connecting to database")
                curs = conn.cursor()
                dest = curs.execute("""SELECT username FROM Utente WHERE username = ?""", (destinatario,)) #where username = ?""", destinatario)
                #dest = curs.execute("""SELECT username FROM Utente WHERE username = ? """, destinatario)
                conn.commit()
                dest = curs.fetchone()
                #se il mittente è nel db allora controllo che ci sia anche il destinatario
                print(f"DESTINATARIO {dest[0]}")
                if dest[0] != "None":
                    punti = curs.execute("SELECT punti FROM Utente WHERE username = ?", (destinatario,))
                    punti = curs.fetchone()

                    punti_mittente = curs.execute("SELECT punti FROM Utente WHERE username = ?", (mittente,))
                    punti_mittente = curs.fetchone()

                    print(f"punti mittente {punti_mittente[0]}, punteggio{punteggio}")
                    if int(punti_mittente[0]) > int(punteggio):
                        curs.execute("INSERT INTO Transazioni (mittente, destinatario, punti, causale, data) VALUES (?, ?, ?, ?, ?)",
                                        (mittente, destinatario, punteggio, causale, data))

                        print(f"Punti attuali >> {punti[0]}")
                        print(f"Punteggio {punteggio}")
                        nuovi_punti = int(punti[0]) + int(punteggio)
                        print(f"NUOVI PUNTI>> {nuovi_punti}")

                        nuovi_punti_mittente = int(punti_mittente[0]) - int(punteggio)
                        print(f"NUOVI PUNTI MITTENTE>> {nuovi_punti_mittente}")

                        curs.execute("UPDATE Utente SET punti = ? WHERE username = ?", (nuovi_punti, destinatario))
                        curs.execute("UPDATE Utente SET punti = ? WHERE username = ?", (nuovi_punti_mittente, mittente))
                        return jsonify({"success": True, "result":content})

                    else:
                        return jsonify({"error": "error punti"}), 401
                else:
                    return jsonify({"error": "error destinatario"}), 401

        except Exception as e:
            print("Error in connection to database")
            return jsonify({"success":False, "error":str(e)})
    else:
        print("Error in autentication")
        return jsonify({"error": "autenticazione fallita"}), 401

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

def login():
    print(request)
    print(f"header {request.headers}")
    print(f"REQUEST AUTHORIZATION {request.authorization}")
    if request.authorization:
        try:
            with sql.connect("./db_Transazioni.db") as conn:
                print("Connecting to database")
                print(request.authorization.username, request.authorization.password)
                curs = conn.cursor()
                utente = curs.execute("""SELECT username, id_utente FROM Utente WHERE username = ? AND password = ?""",
                                (request.authorization.username, request.authorization.password))
                utente = curs.fetchone()
                print(f"Utente[0]>> {utente[0]}")
                print(f"Id[1]>> {utente[1]}")

                #se il mittente è nel db allora controllo che ci sia anche il destinatario
                if utente[0] != "None":
                    print("Autentication")
                    return utente[1]
                else:
                    print("Error in autentication")
                    return None
        except Exception as e:
            print("Error in connection")
            return None

#----------------------------------------------------------------
@app.route("/api/v1/bilancio", methods=["GET"])
def bilancio():
    content = request.get_json()
    #print(f"ID{id}")
    id = login()
    if id != None:
        try:
            with sql.connect("./db_Transazioni.db") as conn:
                print("utente")
                curs = conn.cursor()
                punti = curs.execute("SELECT punti FROM Utente WHERE id_utente = ?", (id,))
                #punti = curs.execute("SELECT punti FROM Utente WHERE username = ?", (request.authorization.username,))

                print("dopo select")
                punti = curs.fetchone()
                print(f"Punti attuali >> {punti[0]}")

                content = (punti[0])
                return jsonify({"success": True, "result":content})

        except Exception as e:
            return jsonify({"success": False, "error": str(e)})
    else:
        print("Error in autentication")
        return jsonify({"error": "autenticazione fallita"})

if __name__ == "__main__":
    app.run()


import ogr
import os

# read txt and return a filename list
def readFile(filename):
    f = open(infile, 'r')
    lines = f.readlines()
    pointFilenameList = []

    for line in lines:
        pointFilenameList.append(line)

    return pointFilenameList

# input filename list and create point shape file
def createShp(pointFilenameList):
    # define list to restore x y coor and filename
    filename = []
    pointListX = []
    pointListY = []

    # register a driver
    driver = ogr.GetDriverByName('ESRI Shapefile')
    # outfile name
    outfile = 'point.shp'

    for line in pointFilenameList:
        sensor = line.split('.')[-3].split('-')[-1][0:-1]
        if sensor == 'MSS':
            y = line.split('_')[2][1:]
            x = line.split('_')[3][1:]

            pointListX.append(x)
            pointListY.append(y)
            filename.append(line)

    if os.path.exists(outfile):
        driver.DeleteDataSource(outfile)

    # create shape file
    outDS = driver.CreateDataSource(outfile)
    if outDS is None:
        print('Cannot open this file: ', outfile)

    # create layer
    outLayer = outDS.CreateLayer('point', geom_type=ogr.wkbPoint)

    # create fields
    fieldDefn1 = ogr.FieldDefn('filename', ogr.OFTString)
    fieldDefn1.SetWidth(60)
    outLayer.CreateField(fieldDefn1, 1)

    fieldDefn2 = ogr.FieldDefn('X', ogr.OFTString)
    fieldDefn2.SetWidth(4)
    outLayer.CreateField(fieldDefn2, 1)

    fieldDefn3 = ogr.FieldDefn('Y', ogr.OFTString)
    fieldDefn3.SetWidth(5)
    outLayer.CreateField(fieldDefn3, 1)

    # get feature defintion
    outFeatureDefn = outLayer.GetLayerDefn()

    # write every point to shape file
    for i in range(len(pointListX)):
        outFeature = ogr.Feature(outFeatureDefn)
        wkt = "POINT(%f %f)" % (float(pointListX[i]), float(pointListY[i]))
        point = ogr.CreateGeometryFromWkt(wkt)
        outFeature.SetGeometry(point)
        outFeature.SetField('filename', filename[i])
        outFeature.SetField('X', pointListX[i])
        outFeature.SetField('Y', pointListY[i])
        outLayer.CreateFeature(outFeature)
        outFeature.Destroy()

    outDS.Destroy()

if __name__ == '__main__':
    os.chdir('E:')
    infile = 'filelist.txt'
    namelist = readFile(infile)
    createShp(namelist)

    print('Success!')


import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.animation as anim
from matplotlib import dates

fig = plt.figure(figsize=(50,30))

path1 = r'../scraped/rare_earths.csv'
df1 = pd.read_csv(path1, nrows=2800)
yt=df1['Yttrium']
nd=df1['Neodymium']

path2=r'../scraped/sp500.csv'
df2 = pd.read_csv(path2, header=0, skiprows=range(1,10254), nrows=2800)
y=df2['S&P 500 COMPOSITE']

x=df2['Date']
new_x=[]
for elem in x:
	new=datetime.datetime.strptime(elem, '%d/%m/%Y')
	new_x.append(new)

years=dates.YearLocator()

ax1=fig.add_subplot(111)
ax1.clear()
ax1.plot(new_x,y, '-',color='#245678', label='S&P 500 Composite Index')
ax1.set_ylabel('S&P 500 Composite', color='#245678')

ax2=ax1.twinx()
ax2.plot(new_x,yt, '-',color='#fc6262', label='Yttrium')
ax2.plot(new_x,nd, '-',color="#222222", label='Neodymium')
ax2.set_ylabel('Rare Earths (USD 99% FOB China)', color='#ad3434')
xfmt=dates.DateFormatter('%Y')
ax1.xaxis.set_major_locator(years)
ax1.xaxis.set_major_formatter(xfmt)

plt.legend(loc=2)
plt.grid(True)
fig.autofmt_xdate()
plt.savefig('re-sp500.png')
plt.show()


import argparse

def get_simbol_and_count(text):
    result = {}
    for letter in text.lower():
        result[letter] = result.get(letter, 0) + 1
    return sorted(result.items(), key=lambda item: item[1])[-1]

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Программа для определения символа и числа вхождений'
    )
    parser.add_argument("text", help="Строка из латинских символов")
    args = parser.parse_args()
    print(get_simbol_and_count(args.text))


# 1. Unidades de tempo. Crie um programa Python que leia do usuário um valor de intervalo de
# tempo expresso em número de dias, horas, minutos e segundos. O programa deve computar e
# exibir a quantidade total de segundos deste intervalo de tempo informado.

# Início

print("Insira um número de dias, horas, minutos e segundos para ver o valor total do intervalo em segundos.")

# Solocita os dados

dias = int(input("Insira o número de dias: "))
horas = int(input("Insira o número de horas: "))
minutos = int(input("Insira o número de minutos: "))
segundos = int(input("Insira o número de segundos: "))

# Cálculo

diasphoras = dias * 24
horaspminutos = (horas + diasphoras) * 60
segundostotais = ((minutos + horaspminutos) * 60) + segundos

# Imprime a resposta

print(f"   O perído de {dias} dia(s), {horas} hora(s), {minutos} minuto(s) e {segundos} segundo(s)")
print(f"equivale a {segundostotais} segundos.")


# -*- coding: utf-8 -*-
"""
Created on Wed Jun  1 19:35:24 2022

@author: User
"""

quantity = 3
totalMoney = 1000
price = 450

string = "I have {1} dollars so I can buy {1} football for {2:.2f} dollars"
print(string.format(quantity, totalMoney, price))


import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import matplotlib.cm as cm
import Tkinter as tk  # python 2.7
import ttk            # python 2.7
import sys

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self,master)
        self.createWidgets()

    def createWidgets(self):
        fig=plt.figure(figsize=(8,8))
        ax=fig.add_axes([0.1,0.1,0.8,0.8])
        ax.set_ylim(-400,400)
        ax.set_xlim(-400,400)
        ax.axhline(ls='--',color='black')
        ax.axvline(ls='--',color='black')
        canvas=FigureCanvasTkAgg(fig,master=root)
        canvas.get_tk_widget().grid(row=0,column=1)
        canvas.show()

        colors = cm.rainbow(np.linspace(0,1,56))
        self.cplotbutton=tk.Button(master=root, text="continuous\nplot", command=lambda: self.continuous_plot(canvas,ax,colors))
        self.cplotbutton.grid(row=0,column=0)
        self.plotbutton=tk.Button(master=root, text="plot", command=lambda: self.plot(canvas,ax,colors))
        self.plotbutton.grid(row=1,column=0)
        self.plotbutton.place(x=10,y=300)
        self.plotbutton=tk.Button(master=root, text="no\nclear\nplot", command=lambda: self.noclear_plot(canvas,ax,colors))
        self.plotbutton.grid(row=1,column=0)
        self.plotbutton.place(x=10,y=500)

    def continuous_plot(self,canvas,ax,colors):
        while True:
            self.plot(canvas,ax,colors)
        return

    def noclear_plot(self,canvas,ax,colors):
        c = 20
        while c > 0:
            try:
                filename = "test/csv1x3.csv"
                raw = np.genfromtxt(filename, delimiter=',')
            except:
                print("error")
            else:
                if len(raw)>= 56:
                    for r,color in zip(raw,colors):
                        ax.plot(r[0],r[1],linestyle="None",marker='o',color=color)
                    canvas.draw()
                    c -= 1
                else:
                    print("len not enough")
        return

    def plot(self,canvas,ax,colors):
        try:
            filename = "test/csv1x3.csv"
            raw = np.genfromtxt(filename, delimiter=',')
        except:
            print("error")
            return
        else:
            if len(raw)>= 56:
                ax.clear()
                ax.set_ylim(-400,400)
                ax.set_xlim(-400,400)
                ax.axhline(ls='--',color='black')
                ax.axvline(ls='--',color='black')
                for r,color in zip(raw,colors):
                    ax.plot(r[0],r[1],linestyle="None",marker='o',color=color)
                canvas.draw()
            else:
                print("len not enough")
            return

root=tk.Tk()
app=Application(master=root)
app.mainloop()


# -*- coding: utf-8 -*-
import math
import re
import scrapy
from jd.items import JdItem
from urllib.parse import quote

class JdsSpider(scrapy.Spider):
    name = 'jds'
    allowed_domains = ['jd.com']

    def start_requests(self):
        for thing in self.settings.get('THING'):
            a = 'https://search.jd.com/Search?keyword='
            b = quote(thing)
            c = '&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=shou&page=1&s=1&click=0'
            url = a + b + c
            yield scrapy.Request(url=url, callback=self.parse, dont_filter=True)

    def parse(self, response):
        max = self.settings.get('MAX_PAGE')
        projects = response.xpath('//*[@id="J_goodsList"]/ul/li')
        print(projects)
        for project in projects:
            item = JdItem()
            item['title'] = project.xpath('./div/div[4]/a/em/text()').getall()
            if item['title'] == []:
                item['title'] = project.xpath('./div/div[3]/a/em/text()').getall()
            item['price'] = project.xpath('./div/div[3]/strong/i/text()').get()
            if item['price'] == None:
                item['price'] = project.xpath('./div/div[2]/strong/i/text()').get()
            item['picture'] = project.xpath('./div/div[1]/a/img/@data-lazy-img').get()
            print(item)
        url = response.url
        a = int(re.search(r'page=(\d+)', url).group(1)) + 2
        b = re.sub((r'page=(\d+)'), 'page=' + str(a), url)
        c = int(re.search(r's=(\d+)', url).group(1)) + 60
        d = re.sub((r's=(\d+)'), 's=' + str(c), b)
        a = a/2
        if math.ceil(a) < max+1:
            yield scrapy.Request(
                url=d,
                callback=self.parse
            )


import utils as ut;
import os
import caffe
import caffe.draw
from scipy import misc
import numpy as np
from caffe.proto import caffe_pb2
from google.protobuf import text_format

solver_fn='mnist_vae_solver_adam.prototxt'
net_fn='mnist_vae.prototxt'

try:
  net_proto = caffe_pb2.NetParameter()
  text_format.Merge(open(net_fn).read(), net_proto)
  caffe.draw.draw_net_to_file (net_proto, 'vae_train_net.png', 'TB',
                               phase=caffe.TRAIN)
  caffe.draw.draw_net_to_file (net_proto, 'vae_test_net.png', 'TB',
                               phase=caffe.TEST)
except:
  print("Unable to draw network.  Perhaps your caffe.draw doesn't support phases?");

if not os.path.exists("snapshots"):
  os.makedirs("snapshots")

caffe.set_mode_gpu();
solver = caffe.get_solver(solver_fn);

solver.solve()

net=caffe.Net('mnist_vae.prototxt',
              'snapshots/mnist_vae_iter_60000.caffemodel', caffe.TEST)
net.forward()
imlist=[];
for i in range(0,100):
  imlist.append(net.blobs['decode1neuron'].data[i,:].reshape((28,28)));
misc.imsave('vae_out.png',ut.imtile(imlist))


# PEP8 - whitespaces and variable names.
class pizza:
    def __init__(cls, obj, mybread_type, cheese_type, meat_type, pizza_toppings, size):
        obj.bread_type = mybread_type
        obj.cheese_type = cheese_type
        obj.meatType = meat_type
        obj.toppings = pizza_toppings
        obj.size = size

    @classmethod
    def create_chicago_pizza(cls, size):
        bread = 'deep-dish bread'
        cheese = 'mozzarella cheese'
        meat_type = 'Italian sausage'
        toppings = ['green bell pepper', 'mushroom', 'chunky tomato sauce', 'onion']
        return cls(bread, cheese, meat_type, toppings, size)

    @classmethod
    def create_california_pizza(cls, meat_type, size):
        bread = 'thin crust'
        cheese = 'feta cheese'
        toppings = ['garlic', 'spinach', 'broccoli', 'olives', 'red onion', 'red bell pepper']
        return cls(bread, cheese, meat_type, toppings, size)

    def printInfo(obj):
        print('bread type is: ', obj.bread_type)
        print('cheese type is: ', obj.cheese_type)
        print('meat type is: ', obj.meat_type)
        print('Toppings are: ', end='')
        print(', '.join(map(str, obj.toppings)))

myPizza = pizza.create_california_pizza('chicken', 'large')
myPizza.printInfo()


import pytest
from selenium import webdriver
# from selenium.webdriver.chrome.options import Options as chOptions
# from selenium.webdriver.firefox.options import Options as ffOptions
# import os

@pytest.fixture(scope="class")
def init_driver(request):
    driver = webdriver.Chrome()
    driver.implicitly_wait(10)
    driver.maximize_window()
    request.cls.driver = driver
    yield
    # driver.quit()

@pytest.fixture(scope="class")
def init_driver_with_metamask(request):
    EXTENSION_PATH = "D:\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Extensions\\nkbihfbeogaeaoehlefnkodbefgpgknn\\10.14.1_0.crx"

    opt = webdriver.ChromeOptions()
    opt.add_extension(EXTENSION_PATH)
    driver = webdriver.Chrome(chrome_options=opt)
    driver.implicitly_wait(10)
    driver.maximize_window()
    request.cls.driver = driver
    yield
    # driver.quit()


# Levy Dragon Fractal Curve
# FB - 200912093

from turtle import *

def draw_fractal(length, angle, level, initial_state, target, replacement, target2, replacement2):

    state = initial_state

    for counter in range(level):
        state2 = ''
        for character in state:
            if character == target:
                state2 += replacement
            elif character == target2:
                state2 += replacement2
            else:
                state2 += character
        state = state2

    # draw
    for character in state:
        if character == 'F':
            forward(length)
        elif character == '+':
            right(angle)
        elif character == '-':
            left(angle)

if __name__ == '__main__':

    draw_fractal(5, 90, 10, 'FX', 'X', 'X+YF+', 'Y', '-FX-Y')


""" 152. Maximum Product Subarray
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
"""
class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        if len(nums) == 0: return 0
        if len(nums) == 1: return nums[0]
        leftIndex, totalProd = 0,1
        prodArray = [0]
        for i in range(len(nums)):
            if nums[i] == 0:
                prodArray.append(Solution.nonNegProd(self, nums[leftIndex:i]))
                leftIndex = i+1
        prodArray.append(Solution.nonNegProd(self, nums[leftIndex:len(nums)]))
        return max(prodArray)

    def nonNegProd(self, nums: List[int]) -> int:
        if len(nums) == 0: return 0
        if len(nums) == 1: return nums[0]
        numNeg, totalProd = 0, 1
        for i in range(len(nums)):
            totalProd*=nums[i]
            if nums[i] < 0: numNeg+=1
        if numNeg % 2 ==0: return totalProd
        leftProd, rightProd = totalProd, totalProd
        for i in range(len(nums)-1,-1,-1):
            leftProd/=nums[i]
            if nums[i] < 0: break
        for i in range(len(nums)):
            rightProd/=nums[i]
            if nums[i] < 0: break
        return  int(leftProd) if leftProd > rightProd else int(rightProd)


#! -*- coding:utf-8 -*-
from keras.layers import *
from keras.models import Model
import keras.backend as K
from keras.callbacks import Callback
from keras.optimizers import Adam
from keras.regularizers import l2
# from keras_bert import load_trained_model_from_checkpoint
from bert4keras.models import build_transformer_model
from utils import seq_gather, extract_items, metric
from tqdm import tqdm
import numpy as np

def E2EModel(bert_config_path, bert_checkpoint_path, LR, num_rels):
    bert_model = build_transformer_model(bert_config_path, bert_checkpoint_path,seq_len=None)
    for l in bert_model.layers:
        l.trainable = True

    tokens_in = Input(shape=(None,))
    segments_in = Input(shape=(None,))
    gold_sub_heads_in = Input(shape=(None,))
    gold_sub_tails_in = Input(shape=(None,))
    sub_head_in = Input(shape=(1,))
    sub_tail_in = Input(shape=(1,))
    gold_obj_heads_in = Input(shape=(None, num_rels))
    gold_obj_tails_in = Input(shape=(None, num_rels))

    tokens, segments, gold_sub_heads, gold_sub_tails, sub_head, sub_tail, \
    gold_obj_heads, gold_obj_tails = tokens_in, segments_in, gold_sub_heads_in, \
                                     gold_sub_tails_in, sub_head_in, sub_tail_in, \
                                     gold_obj_heads_in, gold_obj_tails_in
    mask = Lambda(lambda x: K.cast(K.greater(K.expand_dims(x, 2), 0),
                                   'float32'))(tokens)

    tokens_feature = bert_model([tokens, segments])
    pred_sub_heads = Dense(1, activation='sigmoid')(tokens_feature)
    pred_sub_tails = Dense(1, activation='sigmoid')(tokens_feature)

    subject_model = Model([tokens_in, segments_in], [pred_sub_heads, pred_sub_tails])

    sub_head_feature = Lambda(seq_gather)([tokens_feature, sub_head])
    sub_tail_feature = Lambda(seq_gather)([tokens_feature, sub_tail])
    sub_feature = Average()([sub_head_feature, sub_tail_feature])

    tokens_feature = Add()([tokens_feature, sub_feature])
    pred_obj_heads = Dense(num_rels, activation='sigmoid')(tokens_feature)
    pred_obj_tails = Dense(num_rels, activation='sigmoid')(tokens_feature)

    object_model = Model([tokens_in, segments_in, sub_head_in, sub_tail_in],
                         [pred_obj_heads, pred_obj_tails])

    hbt_model = Model([tokens_in, segments_in, gold_sub_heads_in, gold_sub_tails_in,
                       sub_head_in, sub_tail_in, gold_obj_heads_in, gold_obj_tails_in],
                      [pred_sub_heads, pred_sub_tails, pred_obj_heads, pred_obj_tails])

    gold_sub_heads = K.expand_dims(gold_sub_heads, 2)
    gold_sub_tails = K.expand_dims(gold_sub_tails, 2)

    sub_heads_loss = K.binary_crossentropy(gold_sub_heads, pred_sub_heads)
    sub_heads_loss = K.sum(sub_heads_loss * mask) / K.sum(mask)
    sub_tails_loss = K.binary_crossentropy(gold_sub_tails, pred_sub_tails)
    sub_tails_loss = K.sum(sub_tails_loss * mask) / K.sum(mask)

    obj_heads_loss = K.sum(K.binary_crossentropy(gold_obj_heads, pred_obj_heads),
                           2, keepdims=True)
    obj_heads_loss = K.sum(obj_heads_loss * mask) / K.sum(mask)
    obj_tails_loss = K.sum(K.binary_crossentropy(gold_obj_tails, pred_obj_tails),
                           2, keepdims=True)
    obj_tails_loss = K.sum(obj_tails_loss * mask) / K.sum(mask)

    loss = (sub_heads_loss + sub_tails_loss) + (obj_heads_loss + obj_tails_loss)

    hbt_model.add_loss(loss)
    hbt_model.compile(optimizer=Adam(LR))
    hbt_model.summary()

    return subject_model, object_model, hbt_model


from flask import Flask, render_template, request, redirect, json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt, mpld3
import datetime
import matplotlib.patches as mpatches
import seaborn as sns; sns.set()
import pickle as cPickle
from dateutil import parser

df = pd.read_csv('prod_filiere_hourly_mod2.csv')
df['date'] = pd.to_datetime(df['date'])
glob = cPickle.load(open( "results2.pkl", "rb" ) )

app = Flask(__name__)

@app.route('/firstpage', methods=['GET'])
def firstpage():
    return render_template('Firstpage/index.html')

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index2.html')

@app.route('/power', methods=['GET', 'POST'])
def input():
    if request.method == 'GET':
        global Begin, End, W, Sol, Sto, H, H2, Storage1
        wind0, solar0, storage0, Storage1, Begin = None, None, 180, 0, '2017-01-01'
        W, Sol, Sto = 5, 5, 180
        Data = get_power(df, wind0, solar0, storage0)
        p = plot_power(Data, Begin)
        p2 = plot_power2(glob, Storage1)
        (H, H2) = (mpld3.fig_to_html(p), mpld3.fig_to_html(p2))
    if request.method == 'POST' and ('storage1' in request.form):
        Storage1 = int(int(request.form['storage1']) / 180) -1
        p2 = plot_power2(glob, Storage1)
        H2 = mpld3.fig_to_html(p2)
    if request.method == 'POST' and not('storage1' in request.form):
        W = int(request.form['wind'])
        Sol = int(request.form['solar'])
        Sto = int(request.form['storage'])
        Begin = request.form['begin']
        Data = get_power(df, W, Sol, Sto)
        p = plot_power(Data, Begin)
        H = mpld3.fig_to_html(p)
    return render_template('index3.html', begin=Begin, h=H, h2=H2, wind=W, solar=Sol, storage=Sto, storage1=180*(Storage1+1))

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

## Methods ##

def select_data(D, begin, duration, columns, columns2):
    end = parser.parse(begin) + datetime.timedelta(7,0)
    D1 = D[(D['date'] <= end) & (D['date'] >= begin)][columns]
    D1['time'] = 0
    for i in range(int(len(D1) / duration)):
        D1.iloc[i*duration:(i+1)*duration, -1] = i
    D2 = D1.groupby(['time']).mean()
    D2.insert(0, 'start', 0)
    for i in range(2, len(D2.columns)-3):
        D2.iloc[:,i] = D2.iloc[:,i-1] + D2.iloc[:,i]
    D2.iloc[:,0] = pd.DataFrame([D2.iloc[:,0], D2.iloc[:,1]]).min()

    D3 = D[(D['date'] <= end) & (D['date'] >= begin)][columns2]
    D3['time'] = 0
    for i in range(int(len(D3) / duration)):
        D3.iloc[i*duration:(i+1)*duration, -1] = i
    D4 = D3.groupby(['time']).mean()
    D4.insert(0, 'nuclear', 0)
    for i in range(2, len(D4.columns)-1):
        D4.iloc[:,i] = D4.iloc[:,i-1] + D4.iloc[:,i]

    D5 = D[(D['date'] <= end) & (D['date'] >= begin)][columns2 + columns]
    D5['time'] = 0
    for i in range(int(len(D5) / duration)):
        D5.iloc[i*duration:(i+1)*duration, -1] = i
    D6 = D5.groupby(['time']).mean()
    D6.insert(0, 'nuclear', 0)
    return (D2, D4, D6)

def get_power(df, wind, solar, storage):
    params = make_params(storage)
    df_mod = run_model(df, wind, solar, params)
    return df_mod

def plot_power(dat, begin):
    cols = [['wind', 'solar', 'hydrolake', 'thermal', 'pumpedhydro', 'total-nuclear-hydroriver'],
            ['NC', 'Wind', 'Solar', 'HL', 'TH', 'PH', 'total-nuclear-hydroriver', 'waste', 'short']]
    labels = ['Nuclear', 'Wind', 'Solar', 'Hydro', 'Fossil', 'Storage', 'total-nuclear-hydroriver', 'Waste', 'Shortage']
    # cols2 = ['HLcur', 'PHcur']
    colors = [['red',      'lime',  'yellow', 'royalblue', 'silver',  'magenta'],
              ['red', 'green', 'orange', 'blue',      'grey', 'purple'],
               ['chocolate', 'olive']]

    resolution = [1, 24*7*2]
    (E, H, G) = select_data(dat, begin, 1, cols[1], cols[0])
    sums = np.sum(G, axis=0)
    sums['pumpedhydro'] = np.sum(np.abs(G['pumpedhydro']), axis = 0)
    sums['PH'] = np.sum(np.abs(G['PH']), axis = 0)

    sumsall = np.sum(dat, axis = 0) / 1000
    sumsall['pumpedhydro'] = np.sum(np.abs(dat['pumpedhydro']), axis = 0) / 1000
    sumsall['PH'] = np.sum(np.abs(dat['PH']), axis = 0) / 1000
    sumsall['0'] = 0
    labs = ('Nuclear', 'Wind', 'Solar', 'Hydro', 'Fossil', 'Storage', 'Waste', 'Shortage')
    indices = [[0,7,1,8,2,9,3,10,4,11,5,12,14,15],
               ['0', 'NC', 'wind', 'Wind', 'solar', 'Solar', 'hydrolake', 'HL', 'thermal', 'TH', 'pumpedhydro', 'PH', 'waste', 'short']]

    data = [H, E, sums, sumsall]
    titles = ['Historic power profile', 'Power profile from model', "Energy produced this week", "Energy produced over 3 years"]
    labels2 = ['Energy (GWh)', 'Energy (TWh)']

    fig = plt.figure(figsize = (12, 6))
    for i in range(2):
        ax = fig.add_subplot(2, 2, i+1)
        al = 1.0
        patches = []
        for j in range(len(cols[i])-1-2*i):
            if j == len(cols[i])-2-2*i:
                al = 0.5
            ax.fill_between(range(len(data[i])), data[i].iloc[:, j], data[i].iloc[:, j+1], facecolor=colors[1][j+1-i], interpolate=True, alpha=al)
            patches.append(mpatches.Patch(color=colors[1][j+1-i], label=labels[j+1-i]))
        ax.set_title(titles[i] , fontsize = 20, color = 'white')
        ax.set_xlabel('Time (hours)', fontsize = 15, color = 'white')
        ax.set_ylabel('Power (GW)', fontsize = 15, color = 'white')
        plt.xticks(fontsize = 12)
        plt.yticks(fontsize = 12)
        ax.plot(range(len(data[i])), data[i].iloc[:, -1-2*i], color='black')
        plt.legend(handles=patches, fontsize = 8, bbox_to_anchor=(0, 1), loc=2)

    bar_width = 0.3
    for i in range(2):
        ax = fig.add_subplot(2, 2, i+3)
        patches = []
        for j in range(6):
            plt.bar(j, data[i+2][indices[i][2*j]], bar_width, color=colors[0][j])
            plt.bar(j+bar_width, data[i+2][indices[i][2*j+1]], bar_width, color=colors[1][j], label=labels[j])
            patches.append(mpatches.Patch(color=colors[1][j], label=labels[j]))
        for j in range(2):
            plt.bar(j+6+bar_width, data[i+2][indices[i][j+12]], bar_width, color=colors[2][j])
            patches.append(mpatches.Patch(color=colors[2][j], label=labels[7+j]))
        ax.set_title(titles[i+2], fontsize = 20, color = 'white')
        ax.set_ylabel(labels2[i], fontsize = 15, color = 'white')
        ax.text(0.76, 0.9,'left=historic data - right=model', horizontalalignment='center', verticalalignment='center', transform=ax.transAxes)
        plt.xticks(np.arange(len(labs)) + 0.15, labs, color = 'white')
        # plt.legend(handles=patches, fontsize = 8, bbox_to_anchor=(0.8, 1), loc=2)
    plt.tight_layout()
    return fig

def plot_power2(glob, sto):
    fig2 = plt.figure(figsize = (10, 6))
    titles = ['Electricity from wind and solar (%)', 'Electricity wasted (%)',
             'Electricity from nuclear (%)', 'Electricity from fossil fuels (%)']
    index = [6, 4, 3, 2]
    vmins = [0, 0, 50, 0]
    vmaxs = [30, 7, 80, 20]
    for i in range(4):
        fig2.add_subplot(2, 2, i+1)
        ax = sns.heatmap(glob[index[i],::-1,:,sto], annot=True, vmin=vmins[i], vmax=vmaxs[i], cmap = 'viridis')
        ax.set_title(titles[i] , fontsize = 20)
        ax.set_xlabel('Solar power (GW)', fontsize = 18)
        ax.set_ylabel('Wind power (GW)', fontsize = 18)
        plt.xticks(np.arange(10) + 0.5, 5 * np.arange(1, 11), fontsize = 12)
        plt.yticks(np.arange(10) + 0.5, 5 * np.arange(1, 11), fontsize = 12)
    plt.tight_layout()
    return fig2

def make_params(PH_cap = 180):
    # All data in GW or GWh
    # Pumped hydro
    PHcap = PH_cap
    absPH = 3.0 + PH_cap / 180
    PHpow = [-absPH, absPH]
    PHeff = 0.85
    # HydroLake
    HLref = 1.5 # refill
    HLcap = 3600
    HLpow = [0.0, 8.5]
    # Thermal
    THpow = [0.0, 10.0]
    # Nuclear ramp rate (per hour)
    NCramp = 1.0 / 24
    NClim = [1800, 2700]
    NCmax = 63
    return [PHcap, PHpow, PHeff, HLref, HLcap, HLpow, THpow, NCramp, NClim, NCmax]

def run_model(df2, wind, solar, params):
    [PHcap, PHpow, PHeff, HLref, HLcap, HLpow, THpow, NCramp, NClim, NCmax] = params
    M = df2.drop(['time', 'date'], axis = 1).as_matrix()
    PHcur, HLcur, LIcur, NC = PHcap/2, HLcap/2, 0, 5
    W, S = wind, solar
    for i in range(len(M)):
        # Remove nuclear, wind and solar from total
        ratioW, ratioS = 1, 1
        if W != None:
            ratioW = W / M[i,8]
        if S != None:
            ratioS = S / M[i,9]
        power = M[i,7] - NC - ratioW * M[i,4] - ratioS * M[i,3]

        # Use hydrolake, pumped hydro and thermal
        waste = 0
        HLcur += HLref
        waste += max(HLcur - HLcap, 0)
        HLcur = min(HLcur, HLcap)

        HL = 0
        r1 = HLcur/HLcap*HLpow[1]
        r2 = PHcur/PHcap*PHpow[1]
        if power > 0:
            HLid = r1 / (r1+r2) * power
            PHid = r2 / (r1+r2) * power
            HL = max(HLpow[0], min(HLpow[1], HLid))
            HL = max(HLcur - HLcap, min(HL, HLcur))
            PH = max(PHpow[0], min(PHpow[1], PHid))
        else:
            PH = max(PHpow[0], power)

        PH = max(PHcur - PHcap, min(PH, PHcur))
        power -= (HL+PH)
        waste += max(-power, 0)

        TH = max(THpow[0], min(THpow[1], power))
        power -= TH
        if (TH < THpow[1]) & (PH > PHpow[0]):
            THHL = min(THpow[1] - TH, HL * max(0, 1 - 4*HLcur/HLcap))
            TH += THHL
            HL -= THHL
            THPH = min(THpow[1] - TH, (PH - PHpow[0]) * max(0, 1 - 4*PHcur/PHcap))
            TH += THPH
            PH -= THPH
        HLcur -= HL
        if PH > 0:
            PHcur -= PH
        else:
            PHcur -= PH / PHeff
        short = max(0, power)
        M[i,10] = NC
        M[i,11] = ratioW * M[i,4]
        M[i,12] = ratioS * M[i,3]
        M[i,13] = HL
        M[i,14] = HLcur
        M[i,15] = PH
        M[i,16] = PHcur
        M[i,17] = TH
        M[i,18] = waste
        M[i,19] = short
        M[i,20] = M[i,14] - M[max(0, i-24*7), 14]

        # Change long-term nuclear power depending on current lake evolution
        NC += NCramp * max(-1, 0.25 + min(1, 4*(TH / THpow[1]) - HLcur/HLcap - PHcur/PHcap))
        NC = min(NC, NCmax - M[i,5])

    df3 = pd.DataFrame(M, range(len(M)), df2.columns[2:])
    #df3 = df3.rename(index=str, columns={"date": "HLevo"})
    df3.index = df2.index
    df3['date'] = df2['date']
    print(np.mean(df3['HLcur']) / HLcap)
    print(np.mean(df3['PHcur']) / PHcap)
    return df3


"""      # [1,3,2,6,5]
二叉搜索树的后序遍历序列（递归分治 / 单调栈，清晰图解）

后序遍历定义： [ 左子树 | 右子树 | 根节点 ] ，即遍历顺序为 “左、右、根” 。
二叉搜索树定义： 左子树中所有节点的值 << 根节点的值；右子树中所有节点的值 >> 根节点的值；其左、右子树也分别为二叉搜索树。

"""
class Solution:
    def verifyPostorder(self, postorder) -> bool:
        def recur(i, j):
            if i >= j:
                return True
            p = i
            while postorder[p] < postorder[j]:
                p += 1
            m = p
            while postorder[p] > postorder[j]:
                p += 1
            return p == j and recur(i, m-1) and recur(m, j)
        return recur(0, len(postorder) -1 )

剑指offer/33_ 二叉搜索树的后序遍历序列.py

33_ 二叉搜索树的后序遍历序列.py


def main():
    N=int(input())
    S=input()
    flag=False
    for s in S:
        if s =="x":
            print("No")
            return 0
        elif s=="o":
            flag=True
    if flag:
        print("Yes")
        return 0
    print("No")

if __name__=="__main__":
    main()


import typing as t
from typer import Typer, echo

app = Typer()

@app.command()
def hello(name: str) -> None:
    echo(f"Hello {name}")

@app.command()
def goodbye(name: str, formal: bool = False) -> None:
    if formal:
        echo(f"Goodbye Ms. {name}. Have a good day.")
    else:
        echo(f"Bye {name}!")

@app.command()
def run_dcf(filename: str, formal: bool = False) -> None:
    if formal:
        echo(f"Goodbye Ms. {filename}. Have a good day.")
    else:
        echo(f"Bye {filename}!")

if __name__ == "__main__":
    app()


from torchvision import datasets, transforms
from base import BaseDataLoader
from data_loader.dataset import SeqFeature
from data_loader.seq_encoder import all_seqs_x
from pathlib import Path
import torch

class SeqDataLoader(BaseDataLoader):
    """
    sequence data loader using BaseDataLoader
    """

    def __init__(self, seq_data, min_seq_len, batch_size,
                 shuffle=True,
                 validation_split=0.0,
                 num_workers=1,
                 training=True):
        neg_seq_file, pos_seq_file = seq_data["0"], seq_data["1"]

        neg_seq = all_seqs_x(neg_seq_file, min_seq_len)
        pos_seq = all_seqs_x(pos_seq_file, min_seq_len)

        data = torch.FloatTensor(neg_seq + pos_seq)

        data_target = torch.LongTensor([0] * len(neg_seq) + [1] * len(pos_seq))

        dataset = SeqFeature(data, data_target)
        self.dataset = dataset

        super().__init__(self.dataset, batch_size, shuffle, validation_split, num_workers)


def extractKerambit(item):
	"""
	# Kerambit's Incisions

	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or 'preview' in item['title'].lower():
		return None
	if 'Yobidasa' in item['tags'] and (vol or chp):
		if not postfix and ':' in item['title']:
			postfix = item['title'].split(':')[-1]
		return buildReleaseMessageWithType(item, 'Yobidasareta Satsuriku-sha', vol, chp, frag=frag, postfix=postfix)
	return False


import torch.nn as nn
from utils.conv_block import ConvBlock

class ProtoNet(nn.Module):
    """
    Model as described in the reference paper,
    source: https://github.com/jakesnell/prototypical-networks/blob/f0c48808e496989d01db59f86d4449d7aee9ab0c/protonets/models/few_shot.py#L62-L84
    """

    def __init__(self, input_dim, hid_dim=64, z_dim=64):
        super(ProtoNet, self).__init__()
        self.block1 = ConvBlock(input_dim, hid_dim, 3, max_pool=2, padding=1)
        self.block2 = ConvBlock(hid_dim, hid_dim, 3, max_pool=2, padding=1)
        self.block3 = ConvBlock(hid_dim, hid_dim, 3, max_pool=2, padding=1)
        self.block4 = ConvBlock(hid_dim, z_dim, 3, max_pool=2, padding=1)

    def forward(self, x):
        out = self.block1(x)
        out = self.block2(out)
        out = self.block3(out)
        out = self.block4(out)
        out = out.view(out.size(0), -1)

        return out