from werkzeug.exceptions import HTTPException
from flask import Flask, request, Response, render_template, redirect, make_response
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import utils

ACCOUNTS = {
    "guest": "password1234",
    "admin": get_random_bytes(32).hex()
}

KEY = get_random_bytes(AES.block_size)
FLAG = "UWA{cH1aM0_1_p1nGvIni!1}"

app = Flask(__name__, static_url_path='/', static_folder='static/')

@app.route('/penguin-dashboard', methods=['GET'])
def dashboard():
    auth_cookie = request.cookies.get('auth_cookie', None)
    if auth_cookie is None:
        return redirect('/login')

    try:
        username = utils.decrypt_auth_cookie(KEY, auth_cookie)
    except:
        resp: Response = make_response(redirect('/login'))
        resp.delete_cookie('auth_cookie')
        return resp

    if not username in ACCOUNTS:
        resp: Response = make_response(redirect('/login'))
        resp.delete_cookie('auth_cookie')
        return resp

    return render_template('dashboard.html', flag=FLAG, username=username)

@app.route('/', methods=['GET', 'POST'])
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')

    username: str = request.form.get("username", None)
    if username is None:
        return render_template("login.html", error="Missing username")

    if not username in ACCOUNTS:
        return render_template("login.html", error="Invalid credentials")

    is_auth = ACCOUNTS[username] == request.form.get("password", "")

    if is_auth:
        resp: Response = make_response(redirect('/penguin-dashboard'))
        resp.set_cookie("auth_cookie", utils.encrypt_username(KEY, username.encode()), httponly=True)
        return resp

    return render_template("login.html", error="Invalid credentials")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=3000)


#Lista de Exercícios II
#1- Faça um Programa que peça os três lados de um triângulo. O programa deverá informar se os valores podem ser um
# triângulo. Indique, caso os lados formem um triângulo, se o mesmo é: equilátero, isósceles ou escaleno.

r1 = float(input('Primeiro segmento: '))
r2 = float(input('Segundo segmento: '))
r3 = float(input('Terceiro segmento: '))

if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r2 + r1:
    print('Os segmentos acima PODEM FORMAR um triângulo ', end='')
    if r1 == r2 == r3:
        print('EQUILÁTERO')
    elif r1 != r2 and r2 != r3 and r1 != r3:
        print('ESCALENO!')
    else:
        print('ISÓCELES')
else:
    print('Os segmentos acima NÂO PODEM FORMAR triângulo')

print('-='*20) #Apenas para separar os exercícios
#2- Determine se um ano é bissexto.

year = int(input('Que ano você quer analisar? '))
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
    print('O ano {} é BISSEXTO'.format(year))
else:
    print('O ano {} NÃO é BISSEXTO'.format(year))

print('-='*20)
#3- João Papo-de-Pescador, homem de bem, comprou um microcomputador para controlar o rendimento diário de seu trabalho.
# Toda vez que ele traz um peso de peixes maior que o estabelecido pelo regulamento de pesca doestado de São Paulo
# (50 quilos) deve pagar uma multa de R$ 4,00 por quilo excedente. João precisa que você faça um programa que leia a
# variável peso (peso de peixes) e verifique se há excesso. Se houver, gravar na variável excesso e na variável multa o
# valor da multa que João deverá pagar. Caso contrário mostrar tais variáveis com o conteúdo ZERO.

peso = float(input('Qual o peso da pesca? '))
excesso = 0
multa = 0
if peso > 50:
    excesso = peso - 50
    multa = excesso * 4
print(f'O execesso foi de {excesso}Kg e a multa a ser paga é de R$ {multa:.2f}')

print('-='*20)
#4- Faça um Programa que leia três números e mostre o maior deles.

n1 = float(input('Digite o primeiro número: '))
n2 = float(input('Digite o segundo número: '))
n3 = float(input('Digite o terceiro número: '))

if n1 >= n2 and n1 >= n3:
    print(f'O maior número é {n1}')
elif n2 >= n1 and n2 >= n3:
    print(f'O maior número é {n2}')
else:
    print(f'O maior número é {n3}')

print('-='*20)
#4- Faça um Programa que leia três números e mostre o maior e menor deles.

n1 = float(input('Digite o primeiro número: '))
n2 = float(input('Digite o segundo número: '))
n3 = float(input('Digite o terceiro número: '))

if n1 >= n2 and n1 >= n3:
    maior = n1
elif n2 >= n1 and n2 >= n3:
    maior = n2
else:
    maior = n3
if n1 <= n2 and n1 <= n3:
    menor = n1
elif n2 <= n1 and n2 <= n3:
    menor = n2
else:
    menor = n3
print('O maior número é {} e o menor número é {}'.format(maior, menor))

print('-='*20)
#5- Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre
# o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda,8% para o INSS e
# 5% para o sindicato, faça um programa que nos dê o salário bruto, quanto pagou ao INSS, quanto pagou ao sindicato e
# o salário líquido. Observe que Salário Bruto-Descontos = Salário Líquido. Calcule os descontos e o salário líquido

salário_hora = float(input('Quanto você ganha por hora? '))
horas_trabalho_mês = float(input('Quantas horas você trabalhou no mês? '))
salário_bruto = salário_hora * horas_trabalho_mês
ir = salário_bruto * 0.11
inss = salário_bruto * 0.08
sindicato = salário_bruto * 0.05
salário_liq = salário_bruto - ir -inss - sindicato
print('+ Salário Bruto: R${:.2f} \n- IR (11%): R${:.2f} \n- INSS (8%): R${:.2f} \n- Sindicato (5%) R${:.2f} \n='
      ' Salário Líquido: R${:.2f}'.format(salário_bruto, ir, inss, sindicato, salário_liq))

print('-='*20)
#6- Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados da área a ser
# pintada. Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados e que a tinta é vendida em
# latas de 18 litros, que custam R$ 80,00. Informe ao usuário a quantidades de latas de tinta a serem compradas e o
# preço total. Obs.: somente são vendidos um número inteiro de latas.

área = int(input('Insira a metragem a ser pintada: '))
if área % 54 == 0:
    latas = área / 54
else:
    latas = área // 54 + 1
print('Você deverá comprar {} lata(s) e o preço a ser pago é R${:.2f}'.format(latas, 80*latas))

algoritmo e logica de programacao prof masanori/Exercicios/lista de exercicios II/lista de exercicios II.py


# -*- coding: utf-8 -*-
'''
Accept a key from a hypervisor if the virt runner has
already submitted an authorization request
'''

# Import python libs
import logging

# Import salt libs
import salt.utils.virt

# Set up logging
log = logging.getLogger(__name__)

def ext_pillar(hyper_id, pillar, name, key):
    '''
    Accept the key for the VM on the hyper, if authorized.
    '''
    vk = salt.utils.virt.VirtKey(hyper_id, name, __opts__)
    ok = vk.accept(key)
    pillar['virtkey'] = {name: ok}
    return {}


import os
import glob
import time
import timeit
import dlib
from skimage import io

def train():
    options = dlib.simple_object_detector_training_options()
    options.add_left_right_image_flips = True
    options.C = 5
    options.num_threads = 4
    options.be_verbose = True
    options.detection_window_size = 1024
    options.match_eps = 0.1

    training_xml_path = "../pics/train/training-single.xml"
    # training_xml_path = "/home/external/moderation-porn-detector/oboobs.dlibxml"

    dlib.train_simple_object_detector(training_xml_path, "../boobs.svm", options)

    print("Training accuracy: {}".format(dlib.test_simple_object_detector(training_xml_path, "../boobs.svm")))

def test():
    detector = dlib.simple_object_detector("../boobs.svm")

    win_det = dlib.image_window()
    win_det.set_image(detector)
    # dlib.hit_enter_to_continue()

    print("Showing detections on the images in the faces folder...")
    win = dlib.image_window()

    tp = 0
    fn = 0
    dur = 0

    test_path = "../pics/test/*.jpg"
    # test_path = "/home/external/moderation-porn-detector/boobs-oboobs/*.jpg"

    for f in glob.glob(test_path):
        try:
            img = io.imread(f)
        except IOError as e:
            print("Image {} can't be loaded: {}".format(f, e.message))
            continue

        try:
            t_start = time.clock()
            dets = detector(img)
            t_end = time.clock()
        except RuntimeError as e:
            print("Image {} can't be detected: {}".format(f, e.message))
            continue

        dur += (t_end - t_start)

        num = len(dets)
        if num > 0:
            print("Boobs {} detected in file: {}".format(num, f))
            for k, d in enumerate(dets):
                print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
                    k, d.left(), d.top(), d.right(), d.bottom()))

            win.clear_overlay()
            win.set_image(img)
            win.add_overlay(dets)
            # dlib.hit_enter_to_continue()

            tp += 1
        else:
            fn += 1

        if tp + fn > 100:
            break

    print("tp={} fn={} precision={} dur={}".format(tp, fn, 1.0 * tp / (tp + fn), 1.0 * dur / (tp + fn)))

def camera_boobs():
    import cv2

    # cam = cv2.VideoCapture(-1)
    cam = cv2.VideoCapture("/home/nick/temp/boobs/b1.flv")

    win = dlib.image_window()
    detector = dlib.simple_object_detector("detector.svm")

    def detect():
        s, img = cam.read()
        if not s:
            return

        img2 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        dets = detector(img2)
        num = len(dets)

        if num > 0:
            print("found!")

        win.clear_overlay()
        win.set_image(img2)
        win.add_overlay(dets)

    try:
        while True:
            detect()
    except KeyboardInterrupt as e:
        print("exiting")

    cam.release()
    cv2.destroyAllWindows()

def camera_fd():
    import cv2

    cam = cv2.VideoCapture(-1)

    win = dlib.image_window()
    detector = detector = dlib.get_frontal_face_detector()

    def detect():
        s, img = cam.read()
        if not s:
            return

        img2 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        dets = detector(img2)
        num = len(dets)

        if num > 0:
            print("found!")

        win.clear_overlay()
        win.set_image(img2)
        win.add_overlay(dets)

    try:
        while True:
            detect()
    except KeyboardInterrupt as e:
        print("exiting")

    cam.release()
    cv2.destroyAllWindows()

# train()
test()
# camera_fd()
# camera_boobs()


import pycaw
from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume
import time

while (True):
    sessions = AudioUtilities.GetAllSessions()
    for session in sessions:
        volume = session.SimpleAudioVolume
        if (session.Process and session.Process.name() == "Zoom.exe" and volume.GetMasterVolume() == 1):
            volume.SetMasterVolume(0.25, None)
    time.sleep(.5)


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

import datetime
import logging
import pathlib
import subprocess
import time
from multiprocessing import Process

import carlhauser_server.Configuration.database_conf as database_conf
import carlhauser_server.Configuration.distance_engine_conf as distance_engine_conf
import carlhauser_server.Configuration.feature_extractor_conf as feature_extractor_conf
import carlhauser_server.Configuration.webservice_conf as webservice_conf
import common.ImportExport.json_import_export as json_import_export
from carlhauser_server.Helpers.arg_parser import ConfArgs
from common.environment_variable import get_homedir
from common.environment_variable import load_server_logging_conf_file
from psrecord.main import monitor

load_server_logging_conf_file()

# Small class to handle processus
class WorkerProcessus:
    def __init__(self, worker_path: pathlib.Path):
        self.worker_path: pathlib.Path = worker_path
        self.process: subprocess.Popen = None  # processus: subprocess.Popen
        self.start_time = None

        self.logger = logging.getLogger(__name__)

    def launch(self, db_conf: database_conf.Default_database_conf = None,
               dist_conf: distance_engine_conf.Default_distance_engine_conf = None,
               fe_conf: feature_extractor_conf.Default_feature_extractor_conf = None,
               ws_conf: webservice_conf.Default_webservice_conf = None,
               mode=None):
        """
        Construct an argument list and launch the process.
        :param db_conf: configuration file
        :param dist_conf: configuration file
        :param fe_conf: configuration file
        :param ws_conf: configuration file
        :param mode:  configuration element
        :return: Nothing
        """
        # Construct an argument list to be 'popen' as a new process
        arg_list = [str(self.worker_path)]

        # Save current configuration in files
        # Using self.worker_path.parent
        if db_conf is not None:
            tmp_db_conf_path = get_homedir() / "tmp_db_conf.json"
            json_import_export.save_json(db_conf, file_path=tmp_db_conf_path)
            arg_list.append(ConfArgs.DB_CONF_ARG)
            arg_list.append(str(tmp_db_conf_path.resolve()))

        if dist_conf is not None:
            tmp_dist_conf_path = get_homedir() / "tmp_dist_conf.json"
            json_import_export.save_json(dist_conf, file_path=tmp_dist_conf_path)
            arg_list.append(ConfArgs.DIST_CONF_ARG)
            arg_list.append(str(tmp_dist_conf_path.resolve()))

        if fe_conf is not None:
            tmp_fe_conf_path = get_homedir() / "tmp_fe_conf.json"
            json_import_export.save_json(fe_conf, file_path=tmp_fe_conf_path)
            arg_list.append(ConfArgs.FE_CONF_ARG)
            arg_list.append(str(tmp_fe_conf_path.resolve()))

        if ws_conf is not None:
            tmp_ws_conf_path = get_homedir() / "tmp_ws_conf.json"
            json_import_export.save_json(ws_conf, file_path=tmp_ws_conf_path)
            arg_list.append(ConfArgs.WS_CONF_ARG)
            arg_list.append(str(tmp_ws_conf_path.resolve()))

        if mode is not None:
            arg_list.append(ConfArgs.MODE_ARG)
            arg_list.append(mode)

        # Save starting time
        self.start_time = datetime.datetime.now()

        # Launch worker
        self.logger.debug(f"launching process as : {arg_list}")
        self.process = subprocess.Popen(arg_list)

    def shutdown(self, grace_time=10) -> bool:
        """
        Tru to stop within <gracetime> seconds the current processus/worker
        :param grace_time: maximum waiting time
        :return: True if stopped, False otherwise
        """
        self.logger.info(f"Trying to stop (terminate) {self.process}")
        try:
            self.process.terminate()
            time.sleep(0.2)
        finally:
            try:
                self.process.wait(timeout=grace_time)
            except subprocess.TimeoutExpired:
                self.logger.info(f"Processus {self.process} did not terminate in time. Trying to kill it.")
            finally:
                try:
                    self.process.kill()
                    self.logger.info(f"Processus exited with {self.process.returncode}")
                    return True
                except subprocess.TimeoutExpired:
                    self.logger.info(f"Processus {self.process} is still alive .. Don't know how to stop it.")
                    return False

    def is_running(self) -> bool:
        """
        Check if current processus is running
        :return: True if process running, False otherwise
        """

        if self.process.poll() is None:
            return True
        return False

    def check_status(self, id_to_display):
        """
        Check and display status on logging output
        :param id_to_display: # of the worker, if you want to print one
        :return: True if process running, False otherwise
        """

        curr_str = f"==> Worker {id_to_display} : Launched on {self}"

        is_running = self.is_running()
        if is_running:
            curr_str += " status : running ..."
        else:
            curr_str += " status : terminated or ended ..."

        self.logger.info(curr_str)
        return is_running

    def wait_until_stopped(self, timeout: int = 60) -> bool:
        """
        Wait until the worker is stopped (= terminated)
        Put timeout -1 if you don't want to function to timeout
        :param timeout: maximal waiting time for the process to stop
        :return: True if stopped, False otherwise
        """

        start = time.time()

        while self.is_running():
            time.sleep(5)
            if timeout != -1 and abs(time.time() - start) > timeout:
                self.logger.warning("Waiting for worker to stop has timeout-ed.")
                return False

        self.logger.debug(f"Worker stopped after {round(abs(time.time() - start), 3)}s.")
        return True

    def monitor_worker(self, interval: int = 1):

        # Create path where to save pictures and logs
        curr_name = str(self.worker_path.name) + "_at_" + str(self.start_time)
        logpath = pathlib.Path(get_homedir() / (curr_name + ".log"))
        graphpath = pathlib.Path(get_homedir() / (curr_name + ".pdf"))
        # monitor(self.process.pid, logfile=logpath, plot=graphpath, include_children=True)
        # pid, logfile = None, plot = None, duration = None, interval = None,
        # Launch the monitoring process
        Process(target=monitor, args=(self.process.pid, str(logpath), str(graphpath), interval, True))

    # ==================== To string ====================

    # Overwrite to print the content of the cluster instead of the cluster memory address
    def __repr__(self):
        return self.get_str()

    def __str__(self):
        return self.get_str()

    def get_str(self):
        return ''.join(map(str, [' processus=', self.process,
                                 ' worker_path=', str(self.worker_path),
                                 ' start_time=', self.start_time]))


# -*- coding: utf-8 -*-
"""
Created on Sun Nov  7 00:52:54 2021

@author: SHARATH
"""

import nltk
from nltk.corpus import stopwords
stop = stopwords.words('english')

def ie_preprocess(document):
    document = ' '.join([i for i in document.split() if i not in stop])
    sentences = nltk.sent_tokenize(document)
    sentences = [nltk.word_tokenize(sent) for sent in sentences]
    sentences = [nltk.pos_tag(sent) for sent in sentences]
    return sentences

def extract_names(document):
    names = []
    sentences = ie_preprocess(document)
    for tagged_sentence in sentences:
        for chunk in tagged_sentence:
            if chunk[1] =='NN' or chunk[1]=='JJ':
                names.append(chunk[0])
    return names

# final_name = extract_names("yes, darshan , ruchira and siddhi")


from flask import Flask
from flask_jinjahelpers import init_jinja_env

class TemplateHelperTestCase(object):
    def setup_method(self, method):
        class Application(Flask):
            def create_jinja_environment(self):
                rv = super(Application, self).create_jinja_environment()
                return init_jinja_env(rv)

        self.app = Application(__name__)
        self.app.debug = True
        self.setup_views()

        self.client = self.app.test_client()
        self.context = self.app.test_request_context()
        self.context.push()

    def teardown_method(self, method):
        self.context.pop()
        self.context = None
        self.client = None
        self.app = None


# same idea as #845: go digit by digit for <= N
from functools import cache

@cache
def c(s, d):
    """Count integers with d digits and s digit-sum"""
    if s < 0: return 0
    assert d >= 0
    if d == 0: return int(s == 0)
    return sum(c(s-i, d-1) for i in range(10))

@cache
def q(n, s):
    """Sum of values <= n with digit sum s."""
    if n < 0: return 0
    ns = sum(int(d) for d in str(n))  # n digit-sum
    w = 0  # wildcard spaces
    r = 0
    if ns == s: r += n  # consider original n

    # go digit-by-digit left (original code went right)
    # e.g. for n = 123, consider 123,
    # 122, 121, 120, 11x, 10x, 0xx
    while n:
        for i in range(n % 10):
            n -= 1
            ns -= 1
            # idea from jakob223: recurse using q instead of
            # D(s,d) = q(10**d - 1, s)
            # e.g. for 12**, add sum of 2-digits with digit-sum s,
            # plus 1200 * how many 2-digits with digit-sum s
            r += n * 10**w * c(s-ns, w) + q(10**w - 1, s-ns)

        n //= 10
        w += 1

    return r

def F(N):
    r = 0
    for d in range(1, 200):
        print(d, q(N,d)/d)
        r += q(N, d) / d
    return r

print(f"{F(1234567890123456789):.12e}".replace("+",''))


from check_sequences import *
from itertools import permutations

# Intuitive, but too long
"""
for i in range(1000,10000): # n1 = i
    if i % 100 > 9 and is_octagonal(i):
        print(i)
        for j in range(10,100):
            n2 = (i % 100) * 100 + j
            for k in range(10,100):
                n3 = (n2 % 100) * 100 + k
                for l in range(10,100):
                    n4 = (n3 % 100) * 100 + l
                    for m in range(10,100):
                        n5 = (n4 % 100) * 100 + m
                        n6 = (n5 % 100) * 100 + (i // 100)
                        check = [i,n2,n3,n4,n5,n6]
                        if len(set(check)) == 6:
                            # print(check) # tracker
                            properties = [is_triangle,is_square,is_pentagonal,is_hexagonal,is_heptagonal]
                            satisfied = []
                            for el in check[1:]:
                                for f in properties:
                                    if f(el) and f not in satisfied:
                                        satisfied.append(f)
                                        break
                            if len(satisfied) == 5:
                                print(check)
"""
def is_cyclic(lst):
    for i in range(len(lst)):
        if lst[i] // 100 != lst[i-1] % 100:
            return False
    return True

def main():
    l1 = list(filter(is_triangle,range(1000,10000)))
    l2 = list(filter(is_square,range(1000,10000)))
    l3 = list(filter(is_pentagonal,range(1000,10000)))
    l4 = list(filter(is_hexagonal,range(1000,10000)))
    l5 = list(filter(is_heptagonal,range(1000,10000)))
    l6 = list(filter(is_octagonal,range(1000,10000)))

    check = [l1,l2,l3,l4,l5,l6]
    for a,b,c,d,e,f in permutations(check):
        for e1 in a:
            for e2 in list(filter(lambda x:x // 100 == e1 % 100,b)):
                for e3 in list(filter(lambda x:x // 100 == e2 % 100,c)):
                    for e4 in list(filter(lambda x:x // 100 == e3 % 100,d)):
                        for e5 in list(filter(lambda x:x // 100 == e4 % 100,e)):
                            for e6 in list(filter(lambda x:x // 100 == e5 % 100,f)):
                                if is_cyclic([e1,e2,e3,e4,e5,e6]):
                                    print(e1, e2, e3, e4, e5, e6)
                                    print("Answer:",sum([e1,e2,e3,e4,e5,e6]))
                                    return

main()


from typing import List, Tuple
import numpy as np
from exception import *
from agent import BaseAgent

class TicTacToe:
    def reset(self, opponent: BaseAgent, turn=True) -> np.ndarray:
        self._opponent = opponent
        self._board = np.zeros((3, 3), dtype=int)
        if not turn:
            agent_action = self._opponent.action(self._board)
            self._board[agent_action[0]][agent_action[1]] = -1
        return self._board.copy()

    def step(self, action: Tuple[int, int]) -> Tuple[np.ndarray, int, bool, dict]:
        '''
        Walks through the game with given action, returns the next state, reward, done, and info.
        @param Tuple[int, int] action: action to take
        @return: next state, reward, done, and info (for debugging purposes)
        @rtype: Tuple[np.ndarray, int, bool, dict]
        '''
        # Consider `reward = -1` as not only being lose but also wrong position.
        # First, place on the board for my turn
        # Assertive (the case where the action is out of range)
        if not (0 <= action[0] <= 2 and 0 <= action[1] <= 2):
            print('Action is out of action space.')
            return self._board.copy(), -1, True, {}

        if not self._possible(action):
            return self._board.copy(), -1, True, {}
        self._board[action[0]][action[1]] = 1
        if self._win():
            return self._board.copy(), 1, True, {}
        if self._all_occupied():
            return self._board.copy(), 0, True, {}

        # It's the opponent's turn
        opponent_action = self._opponent.action(-self._board)
        if not self._possible(opponent_action):
            return self._board.copy(), -1, True, {}
        self._board[opponent_action[0]][opponent_action[1]] = -1
        if self._win():
            return self._board.copy(), -1, True, {}
        if self._all_occupied():
            return self._board.copy(), 0, True, {}

        return self._board.copy(), 0, False, {}

    def _possible(self, action: Tuple[int, int]) -> bool:
        return self._board[action[0]][action[1]] == 0

    def _check(self, v: List[int]) -> int:
        _sum = sum(v)
        if _sum == 3:
            return 1
        elif _sum == -3:
            return -1
        else:
            return 0

    def _win(self) -> int: # check the winner of the game. If it's not done, return -1.
        vecs: list = [self._board.tolist()[0], self._board.T.tolist()[0], self._board.diagonal(), np.flip(self._board, 1).diagonal()]

        for vec in vecs:
            checked = self._check(vec)
            if checked != 0:
                return checked
        return 0

    def _all_occupied(self) -> bool:
        return np.square(self._board).sum() == 9

    def render(self) -> None:
        print("+---+---+---+")
        for row in range(3):
            print("|", end = '')
            for col in range(3):
                shape = ' '
                if self._board[row][col] == 1:
                    shape = 'O'
                if self._board[row][col] == -1:
                    shape = 'X'
                print(" {} |".format(shape), end = '')
            print("\n+---+---+---+")


"""Houses the Service-Now Property"""

from typing import TypeVar, Type, Dict, Any, Union

from pyservicenow.types.models._abstract_servicenow_property import AbstractServiceNowProperty

from json import dumps

S = TypeVar("S", bound="ServiceNowProperty")

class ServiceNowProperty(AbstractServiceNowProperty):
    """Service-Now Property type"""

    def __init__(self) -> None:
        super().__init__()

        self._display_value = ""
        self._value = ""
        self._link = ""

    @property
    def display_value(self) -> str:
        """Gets/Sets the display value

        Returns:
            str: The display value
        """

        return self._display_value

    @display_value.setter
    def display_value(self, value: str) -> None:
        self._display_value = value

    @property
    def value_link(self) -> str:
        """Gets/Sets the link

        Returns:
            str: The link
        """

        return self._link

    @value_link.setter
    def value_link(self, value: str) -> None:
        self._link = value

    @property
    def actual_value(self) -> str:
        """Gets/Sets the value

        Returns:
            str: The value
        """

        return self._value

    @actual_value.setter
    def actual_value(self, value: str) -> None:
        self._value = value

    @property
    def as_dict(self) -> Dict[str, Any]:

        return {
            "display_value": self.display_value,
            "value": self.actual_value,
            "link": self.value_link,
        }

    def __json__(self) -> str:

        return dumps(self.as_dict)

    @classmethod
    def __fromjson__(cls: Type[S], value: Union[str, Dict]) -> S:

        _value = cls()

        if not isinstance(value, str) and not isinstance(value, dict):
            return _value

        if value is None:
            pass
        elif isinstance(value, str):
            _value.actual_value = value
        else:
            _value.display_value = value.get("display_value", "")
            _value.actual_value = value.get("value", "")
            _value.value_link = value.get("link", "")

        return _value


def primefactor(n):
    if type(n) != int:
        raise TypeError("argument must be of type 'int'")
    if n < 2:
        return []
    factors = []
    while n % 2 == 0:
        n /= 2
        factors.append(2)
    x = 3
    limit = int(n**0.5 + 1)
    while x <= limit:
        if n % x == 0:
            n //= x
            limit = int(n**0.5 + 1)
            factors.append(x)
            continue
        x += 2
    if n != 1:
        factors.append(int(n))
    return factors

t = int(input().strip())
for i in range(t):
    n = int(input().strip())
    print(primefactor(n)[-1])


def f(t0, t1, x):
    return t0+t1*x

def sum0(t0, t1, list0, m):
    val = 0
    for i in list0:
        val += (f(t0, t1, i[0]) - i[1])
    val = val / m
    return val

def sum1(t0, t1, list0, m):
    val = 0
    for i in list0:
        val += (f(t0, t1, i[0]) - i[1])*i[0]
    val = val / m
    return val

def j(t0, t1, list0, m):
    val = 0
    for i in list0:
        val += (f(t0, t1, i[0])-i[1])**2
    val = val/(2*m)
    return val

House_prices = []
n = 0
while True:
    n += 1
    area = float(input("Enter the area:"))
    cost = float(input("Enter the cost:"))
    df = [area, cost]
    House_prices.append(df)
    ans = input("Do you want to continue?(y/n)")
    if ans == "n":
        break
tt0 = 1
tt1 = 1
alpha = 0.01
while True:
    j0 = j(tt0, tt1, House_prices, n)
    temp1 = tt0 - alpha*sum0(tt0, tt1, House_prices, n)
    temp2 = tt1 - alpha*sum1(tt0, tt1, House_prices, n)
    tt0 = temp1
    tt1 = temp2
    j1 = j(tt0, tt1, House_prices, n)
    if abs(j1-j0) < 0.000001:
        break
while True:
    area = float(input("Enter area:"))
    print(f(tt0, tt1, area))
    ans = input("Enter n to stop:")
    if ans == "n":
        break


import time
import json
from display import Display
import const

class Timer():
    def __init__(self):
        self.min = 0
        self.text = '00:00'
        self.seconds = 0
        self.display = Display()
        self.cancel = False

    def setTimer(self, min):
        self.min = min
        self.countdown_min(self.min)

    def checkCancel(self):
        data = self.checkdata()
        self.cancel = data

    def checkdata(self): #check json file for any changes
        with open(const.data_location) as f:
            data = json.load(f)
        return data['timer']
    def setCancel(self):
        with open(const.data_location, 'r', encoding='utf-8') as outjson:
            json_data = json.load(outjson)
            json_data['timer'] = False

        with open(const.data_location, 'w') as output:
            json.dump(json_data, output, indent=4)

    def countdown_min(self, t):
        seconds = t * 60
        self.seconds = seconds
        while seconds:
            self.checkCancel()
            if self.cancel == False:
                mins,sec = divmod(seconds,60)
                timer = '{:02d}:{:02d}'.format(mins, sec)
                self.text = timer
                self.display.update_screen(timer)
                time.sleep(0.94)
                seconds-=1
            else:
                break
        self.cancel = False
        self.setCancel()


import smtplib

user='sender_mail'
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(user,'sender_pwd')

message = "Test Mail"
server.sendmail(user,'recepient mail',message)
server.quit()


import re

# sc === Operation Split or Combine
# mcv === M -> method, C -> class, V -> variable

while True:
    try:
        string = input().rstrip()
        sc, mcv, operation = string.split(";")

        if sc == "S":
            if mcv == "M":
                cap = operation[:-2]

            if mcv == "C" or mcv == "V":
                cap = operation

            s = re.sub("(\w)([A-Z])", r"\1 \2", cap)
            print(s.lower())

        if sc == "C":
            cap = operation.title()
            s = re.sub(r" ", r"", cap)
            q = s[:1].lower() + s[1:]

            if mcv == "M":
                print(q + "()")

            if mcv == "C":
                print(s)

            if mcv == "V":
                print(q)

    except EOFError:
        break


# This script plots the MBAR vs true data

import matplotlib
import numpy
import sys
import os
if os.environ.get('DISPLAY','') == '': # then no display found. Use non-interactive Agg backend'
    matplotlib.use('Agg')
import matplotlib.pyplot as plt

MW = float(sys.argv[1])
true_data_file = sys.argv[2]               # The file that is used to minimize the deviations against, i.e. the target. It could be experimental data or a simulation results of a force field from literature.
mbar_data_file = sys.argv[3]               # The file that contains MBAR results at ITIC state points
true_data_label = sys.argv[4]               # Label for true data
output_figure_filename = sys.argv[5]        # Output file name
try:
    dsim_data_file = sys.argv[6]            # If provided, this argument is a file containing direct simulation results
except:
    isDSIM = False
else:
    isDSIM = True

R_const = 8.31446261815324

# Conversion factors
atm_to_mpa = 0.101325
kcalmol_to_kjmol = 4.184

bar_to_mpa = 0.1
kelvin_to_kjmol = 0.0083

# Import data
true_data = numpy.loadtxt(true_data_file, skiprows=1, usecols=(0,1,2,5,11))
true_temp_k = true_data[:,0]
true_rho_gcc = true_data[:,1]
true_p_mpa = true_data[:,2] * atm_to_mpa
true_u_kjmol = true_data[:,3] * kcalmol_to_kjmol
Nmolec = true_data[:,4]

mbar_data = numpy.loadtxt(mbar_data_file, skiprows=1, usecols=(0,1,3,5,2))
mbar_temp_k = mbar_data[:,0]
mbar_rho_gcc = mbar_data[:,1]
mbar_u_kjmol = mbar_data[:,2] * kelvin_to_kjmol
mbar_p_mpa = mbar_data[:,3] * bar_to_mpa
Neff = mbar_data[:,4]

if isDSIM:
    dsim_data = numpy.loadtxt(dsim_data_file, skiprows=1, usecols=(0,1,2,5,11))
    dsim_temp_k = dsim_data[:,0]
    dsim_rho_gcc = dsim_data[:,1]
    dsim_p_mpa = dsim_data[:,2] * atm_to_mpa
    dsim_u_kjmol = dsim_data[:,3] * kcalmol_to_kjmol

# Calcualte properties
true_u_hat = true_data[:,3] * kcalmol_to_kjmol / Nmolec / R_const / true_temp_k * 1e3
true_z = true_p_mpa * MW / ( true_rho_gcc  * R_const * true_temp_k )
true_zminus1overRho = ( true_z - 1 ) / true_rho_gcc

mbar_u_hat = mbar_data[:,2] * kelvin_to_kjmol / Nmolec / R_const / mbar_temp_k * 1e3
mbar_z = mbar_p_mpa * MW / ( mbar_rho_gcc  * R_const * mbar_temp_k )
mbar_zminus1overRho = ( mbar_z - 1 ) / mbar_rho_gcc

if isDSIM:
    dsim_u_hat = dsim_data[:,3] * kcalmol_to_kjmol / Nmolec / R_const / dsim_temp_k * 1e3
    dsim_z = dsim_p_mpa * MW / ( dsim_rho_gcc  * R_const * dsim_temp_k )
    dsim_zminus1overRho = ( dsim_z - 1 ) / dsim_rho_gcc

# Initiate plot
plt.figure(num=None, figsize=(24, 7), dpi=100, facecolor='w', edgecolor='w')
plt.subplots_adjust(left=0.04, bottom=None, right=0.99, top=None, wspace=0.3, hspace=None)
font = {'weight' : 'normal', 'size' : 14}
matplotlib.rc('font', **font)

# (Z-1)/rho vs. rho plot
plt.subplot(1, 3, 1 )
plt.xlabel("$\\rho$ [$\mathrm{g/cm^3}$]")
plt.ylabel("$(Z-1)/\\rho}$ [$\mathrm{cm^3/g}$]")
plt.scatter(true_rho_gcc, true_zminus1overRho, marker="o", facecolors='none', edgecolors='k', label=true_data_label)
plt.scatter(mbar_rho_gcc, mbar_zminus1overRho, marker="o", facecolors='none', edgecolors='r', label='MBAR')
if isDSIM:
    plt.scatter(dsim_rho_gcc, dsim_zminus1overRho, marker="o", facecolors='none', edgecolors='g', label='Direct dsimulation')
for i in range(0,len(mbar_rho_gcc)):
    plt.text(mbar_rho_gcc[i]+0.01, mbar_zminus1overRho[i], str(round(Neff[i],1)), color='red', fontsize=9, alpha=0.9, bbox=dict(color='red', alpha=0.01))
plt.legend()

# Z vs. 1000/T plot
plt.subplot(1, 3, 2 )
plt.xlabel("$1000/T$ [K$^{-1}$]")
plt.ylabel("$Z$")
plt.scatter(1000.0 / true_temp_k[:10], true_z[:10], marker="o", facecolors='none', edgecolors='k')
plt.scatter(1000.0 / true_temp_k[21:], true_z[21:], marker="o", facecolors='none', edgecolors='k')
plt.scatter(1000.0 / mbar_temp_k[:10], mbar_z[:10], marker="o", facecolors='none', edgecolors='r')
plt.scatter(1000.0 / mbar_temp_k[21:], mbar_z[21:], marker="o", facecolors='none', edgecolors='r')
if isDSIM:
    plt.scatter(1000.0 / dsim_temp_k[:10], dsim_z[:10], marker="o", facecolors='none', edgecolors='k')
    plt.scatter(1000.0 / dsim_temp_k[21:], dsim_z[21:], marker="o", facecolors='none', edgecolors='k')

# TU^ vs 1000/T plot
plt.subplot(1, 3, 3 )
#plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
plt.xlabel("$1000/T$ [K$^{-1}$]")
plt.ylabel("$T\hat{U}$ [K]")
plt.scatter(1000.0 / true_temp_k[:10], true_u_hat[:10] * true_temp_k[:10], marker="o", facecolors='none', edgecolors='k')
plt.scatter(1000.0 / true_temp_k[21:], true_u_hat[21:] * true_temp_k[21:], marker="o", facecolors='none', edgecolors='k')
plt.scatter(1000.0 / mbar_temp_k[:10], mbar_u_hat[:10] * mbar_temp_k[:10], marker="o", facecolors='none', edgecolors='r')
plt.scatter(1000.0 / mbar_temp_k[21:], mbar_u_hat[21:] * mbar_temp_k[21:], marker="o", facecolors='none', edgecolors='r')
if isDSIM:
    plt.scatter(1000.0 / dsim_temp_k[:10], dsim_u_hat[:10] * dsim_temp_k[:10], marker="o", facecolors='none', edgecolors='k')
    plt.scatter(1000.0 / dsim_temp_k[21:], dsim_u_hat[21:] * dsim_temp_k[21:], marker="o", facecolors='none', edgecolors='k')

plt.savefig(output_figure_filename)
plt.close()


"""Create art_no column in databses."""

import pathlib

import pandas as pd

from ._message import message

def create_art_no_column(root_dir):
    """Create art_no column in databases."""
    #
    message("Assign REC-No identifier to each record")

    processed_dir = pathlib.Path(root_dir) / "databases"
    files = list(processed_dir.glob("_*.zip"))
    for file in files:
        data = pd.read_csv(file, encoding="utf-8", compression="zip")
        data["art_no"] = range(1, len(data) + 1)
        data.to_csv(file, sep=",", encoding="utf-8", index=False, compression="zip")


import boto3
import json
import decimal
from decimal import Decimal
from boto3.dynamodb.conditions import Key, Attr

class DecimalEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            return float(obj)
        return json.JSONEncoder.default(self, obj)

def get_kneipen(lat, long, distance):
    dynamodb = boto3.resource("dynamodb", region_name='eu-central-1')

    table = dynamodb.Table('geo-data')
    fe = Key('lat').between(Decimal(lat) - Decimal(distance), Decimal(lat) + Decimal(distance))
    fe2 = Key('long').between(Decimal(long) - Decimal(distance), Decimal(long) + Decimal(distance))

    response = table.scan(
            FilterExpression=fe & fe2,
            )

    return response["Items"]

def handler(event, context):
    try:
        return response(get_kneipen(event["queryStringParameters"]["lat"],event["queryStringParameters"]["long"],event["queryStringParameters"]["distance"]) , 200)
    except Exception as e:
        return response('Error', 400)

def response(message, status_code):
    return {
        "statusCode": status_code,
        "headers": {
            "X-Bier": "gerne doch",
            "Access-Control-Allow-Origin": "*"
        },
        "body": json.dumps(message, cls=DecimalEncoder),
        "isBase64Encoded": False
    }


import numpy as np
import math
import csv
import matplotlib.pyplot as plt
from scipy.io import loadmat

print("Initializations")
train_set = loadmat(file_name="train.mat", mat_dtype=True)
test_set = loadmat(file_name="test.mat", mat_dtype=True)

train_data = np.transpose(train_set["train_images"])
train_labels = train_set["train_labels"].reshape(1,-1)[0]
test_data = test_set["test_images"]

random_state = np.random.get_state()
np.random.shuffle(train_data)
np.random.set_state(random_state)
np.random.shuffle(train_labels)

num_train = train_data.shape[0]
num_test = test_data.shape[0]

for i in range(0, num_train):
    train_data[i] = train_data[i] / np.linalg.norm(train_data[i])

for i in range(0, num_test):
    test_data[i] = test_data[i] / np.linalg.norm(test_data[i])
test_data = np.transpose(test_data)

pred_labels = np.zeros(num_test)
set_size = [num_train]
for si in range(0, len(set_size)):
    sz = set_size[si]
    print("Slicing, Sorting, Reshaping")
    train_slice = train_data[0:sz]
    label_slice = train_labels[0:sz]

    index = label_slice.argsort()
    t_sort = train_slice[index[::1]]
    l_sort = label_slice[index[::1]]
    t_flat = t_sort.reshape(len(t_sort), -1)
    t_flat = np.transpose(t_flat)
    for i in range(0, sz):
        t_flat[:, i] = t_flat[:, i] / np.linalg.norm(t_flat[:, i])

    priors = np.zeros(10)
    for i in l_sort:
        priors[i] = priors[i] + 1

    digit_sect = np.zeros(11)
    for i in range(0, 10):
        digit_sect[i+1] = digit_sect[i]+priors[i]

    priors = priors / len(l_sort)

    print("Covariance Matrix")
    covmat = np.zeros((10,784,784))
    mu = np.zeros((10, 784))
    for i in range(0,10):
        ai = digit_sect[i]
        ae = digit_sect[i+1]
        covmat[i,:,:] = np.cov(t_flat[:, ai:ae])
        mu[i, :] = np.mean(t_flat[:, ai:ae], axis=1)

    a = 0.001
    covmat_inv = np.zeros((10,784,784))
    seconds = np.zeros(10)
    thirds = np.zeros(10)
    for c in range(0,10):
        covmat_id = covmat[c]+a*np.identity(784)
        covmat_inv[c] = np.linalg.inv(covmat_id)
        sign, val = np.linalg.slogdet(covmat_id)
        seconds[c] = sign * val
        thirds[c] = np.log(priors[c])

    print("Predictions")
    for i in range(0, len(pred_labels)):
        if i % 1000 == 0: print("i: " + str(i))
        x = test_data[:, i]
        max_c = 0
        max_disc = -99999999
        for c in range(0, 10):
            x_mu = x - mu[c]
            qc = np.dot(x_mu, np.dot(covmat_inv[c], x_mu))
            curr = -0.5*qc - 0.5*seconds[c] + thirds[c]
            if curr > max_disc:
                max_c = c
                max_disc = curr
        pred_labels[i] = max_c

with open('test_labels.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(['Id'] + ['Category'])
    for i in range(0, len(pred_labels)):
        writer.writerow([i+1] + [int(pred_labels[i])])

hw3 - Gaussian Classifiers (LDA and QDA)/code/prob5div.py


import requests
import simpleaudio
import tempfile
import json

host = "127.0.0.1"  # "localhost"でも可能だが、処理が遅くなる
port = 50021

class SyntheticVoice:
    def __init__(self):
        self.host = host
        self.port = port

    def speaking(self, text):
        params = (
            ("text", text),
            ("speaker", 1)  # 音声の種類をInt型で指定
        )
        # 以下の検索結果でどの数値がどういった声なのか記載されている
        # https://github.com/VOICEVOX/voicevox_resource/search?q=styleId

        response1 = requests.post(
            f"http://{self.host}:{self.port}/audio_query",
            params=params
        )

        response2 = requests.post(
            f"http://{self.host}:{self.port}/synthesis",
            headers={"Content-Type": "application/json"},
            params=params,
            data=json.dumps(response1.json())
        )

        with tempfile.TemporaryDirectory() as tmp:
            with open(f"{tmp}/audi.wav", "wb") as f:
                f.write(response2.content)
                wav_obj = simpleaudio.WaveObject.from_wave_file(
                    f"{tmp}/audi.wav")
                play_obj = wav_obj.play()
                play_obj.wait_done()


import sys

from binaryninja.update import UpdateChannel, are_auto_updates_enabled, set_auto_updates_enabled, is_update_installation_pending, install_pending_update
from binaryninja import core_version
import datetime

channel = None
versions = []

def load_channel(newchannel):
  global channel
  global versions
  if (channel is not None and newchannel == channel.name):
    print("Already on the selected channel: {}".format(newchannel))
  else:
    try:
      print("Loading channel %s" % newchannel)
      channel = UpdateChannel[newchannel]
      print("Loading versions...")
      versions = channel.versions
    except Exception:
      print("%s is not a valid channel name. Defaulting to " % chandefault)
      channel = UpdateChannel[chandefault]

def select(version):
  date = datetime.datetime.fromtimestamp(version.time).strftime('%c')
  print("Version:\t%s" % version.version)
  print("Updated:\t%s" % date)
  print("Notes:\n\n-----\n%s" % version.notes)
  print(version.update())
  if is_update_installation_pending():
    print("Installing...")
    #note that the GUI will be launched after update but should still do the upgrade headless
    install_pending_update()
  # forward updating won't work without reloading
  sys.exit()

def main():
  global channel
  done = False
  # NOTE(artem): We need the dev version, for now
  load_channel("dev")
  set_auto_updates_enabled(True)
  select(channel.latest_version)

if __name__ == "__main__":
  try:
    main()
  except Exception as e:
    print("Binary Ninja update may have failed. Caught an exception trying to update: {}".format(str(e)))


import cvxpy as cvx
import numpy as np

def copy_prob(prob):
    return cvx.Problem(prob.objective, prob.constraints)

def get_scs_data(prob):
    data = prob.get_problem_data('SCS')

    # convert sparse indices and pointers to int64 so that CySCS doesn't
    # need to convert them itself (which raises a warning).
    A = data['A']
    A.indptr = A.indptr.astype(np.int64)
    A.indices = A.indices.astype(np.int64)

    return data

def form_prox(prob, x_vars):
    """ Given a CVXPY problem, form its prox.

    Given problem: min f(x),

    form the prox problem:

    min f(x) + tau*||x-x0||^2

    Parameters
    ----------
    prob: CVXPY problem
    x_vars: dict
        Dict of k:v pairs, where k is a string, and v is a CVXPY Variable that appears in `prob`

    Returns
    -------
    pxprob: CVXPY prox problem
    x0_vars: dict
        Dict of k:v pairs, where v is CVXPY Parameter object, corresponding to prox input x0
        x0_vars also contains special key '__tau', which corresponds to the regularization parameter
    """

    tau = cvx.Parameter(sign="positive")
    x0_vars = {'__tau':tau}

    obj = 0
    for k in x_vars:
        x = x_vars[k]
        x0 = cvx.Parameter(*x.size)
        x0_vars[k] = x0

        obj = obj + tau*cvx.sum_squares(x - x0)

    pxprob = cvx.Problem(prob.objective + cvx.Minimize(obj), prob.constraints)

    return pxprob, x0_vars

def rand_param_vals(x0_vars):
    """ Set the CVXPY Parameter values for the x0 prox input parameters to random numpy
    arrays of the appropriate size.

    We use this to detect where the parameters get mapped to in the SCS stuffing.

    Modifies the x0_vars in place!
    """
    for k in x0_vars:
        x = x0_vars[k]
        s = x.size

        if k == '__tau':
            x.value = np.random.rand()+1
        else:
            x.value = np.random.randn(*s)

def param_map(pxprob, x0_vars):
    """
    get the location for taus and x0 parameter input
    in terms of the stuffed SCS problem

    Parameters
    ----------
    prox_prob: CVXPY prox problem
    x0_vars: dict
        dictionary of x0 keys and __tau that point to cvxpy Parameter objects

    Returns
    -------
    dict
        mapping of variable names (including '__tau') to indices of the b, c vectors in
        stuffed SCS problem

    Notes
    -----
    xs get multiplied by -2.
    expect '__tau' to be an array of random locations to c
    expect the other elements to be slice objects of continuous chunks
    """
    # set the x0 parameters to random values, and then find those random values in the vectors
    rand_param_vals(x0_vars)

    data = get_scs_data(pxprob)

    # tau may be mapped to multiple locations in the c vector
    taus, = np.where(data['c']==x0_vars['__tau'].value)

    indmap = {'__tau':taus}

    b = data['b']
    for k in x0_vars:
        if k != '__tau':
            # because x.value sometimes returns a float, and sometimes returns a 2d np.Matrix...
            # this cleans it all up to be a 1d array in either case
            x = np.atleast_1d(np.squeeze(np.array(x0_vars[k].value)))
            ind, = np.where(b==-2*x[0])
            ind = ind[0]

            indmap[k] = slice(ind,ind+len(x))

    return data, indmap

def restuff(data, indmap, x0_vals):
    """ Modify the b,c data in `data` to reflect the x0 prox values
    in x0_vals (which should be appropriately sized numpy arrays or scalars).

    indmap is the mapping from variable names to b,c indices

    Notes
    -----
    tau maps to tau in c, but x maps to -2*x in b.
    """

    c = data['c']
    c[indmap['__tau']] = x0_vals['__tau']

    b = data['b']
    for k in x0_vals:
        if k != '__tau':
            b[indmap[k]] = -2*x0_vals[k]

def dummy_scs_output(data):
    """ `data` is a dict of SCS input data
    """
    x = np.random.randn(*data['c'].shape)
    y = np.random.randn(*data['b'].shape)

    out = {'info': {'dobj': 0,
          'iter': 0,
          'pobj': 0,
          'relGap': 0,
          'resDual': 0,
          'resInfeas': 0,
          'resPri': 0,
          'resUnbdd': 0,
          'setupTime': 0,
          'solveTime': 0,
          'status': 'Solved',
          'statusVal': 1},
         'x': x,
         'y': y,
         's': y}

    return out

def get_solmap(prob, x_vars, data=None):
    """
    Parameters
    ----------
    x_vars: dict
        k:v pairs, where v is a CVXPY Variable

    Returns
    -------
    dict
        elements are Python `slice` objects.
    """
    if data is None:
        data = get_scs_data(prob)

    out = dummy_scs_output(data)

    prob.unpack_results('SCS', out)

    solmap = {}
    for k in x_vars:
        x = np.atleast_1d(np.squeeze(np.array(x_vars[k].value)))
        ind, = np.where(x[0]==out['x'])
        ind = ind[0]
        solmap[k] = slice(ind,ind+len(x))

    return solmap

def extract_sol(scs_x, solmap):
    """ Extract a solution from the SCS output variable `x`.
    solmap is a dict mapping variable names to indices (slices) of x.
    """
    x_vals = {}
    for k in solmap:
        x_vals[k] = scs_x[solmap[k]]
        if len(x_vals[k]) == 1:
            x_vals[k] = x_vals[k][0]

    return x_vals


#Создайте словарь со списком вещей для похода в качестве ключа и их массой в качестве значения.
# Определите какие вещи влезут в рюкзак передав его максимальную грузоподъёмность.
# Достаточно вернуть один допустимый вариант. *Верните все возможные варианты комплектации рюкзака.

max_capacity = 7

list_of_items = {'tent': 3, 'first aid kit': 0.6, 'raincoat': 0.5, 'axe': 1, 'ropes': 1, \
    'foodstuff': 2, 'matches': 0.1, 'sleeping bag': 1}
my_bag = {}

for things, weight in list_of_items.items():
    if weight <= max_capacity:
        my_bag.update({things: weight})
        max_capacity = max_capacity - weight

print(my_bag)


#!/bin/python

#Assuming running from the top-level directory
import sys
sys.path.append(".")

#Import the functions
from utils import *

@delayed
def poprast_prep(pth,grid,buffs,gt0):
	#Read in current raster
	print("Running on", pth)
	array_gdal,gt,wkt,gdal_band,nodataval = open_gdal(pth)
	print("Shape of array_gdal:",np.shape(array_gdal))

	#If the array is different to our first one must re build our trees/arrays
	if gt != gt0:
		print("Different raster extent detected.")

		#Re building Index with loop
		t1=time.time()
		print("Read",pth[-25:-20],",finding indexes...")
		ind=[]
		for row in grid.itertuples():
			ind.append(get_coords_at_point(gt, row.X, row.Y))

		grid["ind"]=ind

		print("Indexed points loop", pth[-25:-20], "Time:",np.round(time.time()-t1,2),"s")

	poplist = []
	for buff in buffs:
		t1=time.time()
		#Set buffer to index units
		b=np.ceil(buff/gt[1])

		#Run the convolution with the buffer
		density_array = buffer_convolve(array_gdal,b)

		#Write out the buffered raster, if you want.
		#write_raster(density_array,gt,wkt,gdal_band,nodataval)

		#Find the value of the convolved array at each point of interest
		pop = [density_array[x] for x in grid["ind"]]

		#Add it to the buffer-list.
		poplist.append(pop)

		print("Done pop! Buffer:", buff, "Buffer (index):", b, pth[-25:-20], "Time:",np.round(time.time()-t1,2),"s")

	#Add additional info to the dataframe
	yr = str(20) + re.sub(".*(apg|APG)(\\d{2}).*", "\\2", pth)
	popdf = gpd.GeoDataFrame(poplist, index = ["popdens" + str(b) for b in buffs]).T
	popdf.insert(0, 'FID', grid.FID)
	popdf.insert(0, 'year', yr)

	#Free up mem
	gdal_data=None

	return(popdf)

##### MAIN #####
if __name__ == "__main__":

	## Read in population rasters
	poprasts = glob.glob('ABS1x1km_Aus_Pop_Grid_2006_2020/data_provided/*.tif')

	#poprasts=["ABS1x1km_Aus_Pop_Grid_2006_2020/data_provided/apg06e_f_001_20210512.tif"]#,
	#			"ABS1x1km_Aus_Pop_Grid_2006_2020/data_provided/apg09e_f_001_20210512.tif"]

	buffs = [700, 1000, 1500, 2000, 3000, 5000, 10000]

	t1=time.time()
	print("Reading points rds file...")
	grid = pyreadr.read_r('AUS_points_5km.rds')
	grid=list(grid.items())[0][1]
	#grid=grid.iloc[0:100, :]

	##Shapefile
	#grid = gpd.read_file('AUS_points_1km.shp')
	#g = np.column_stack((grid.geometry.x.to_list(),grid.geometry.y.to_list()))
	#grid = pd.DataFrame(g,columns=["X","Y"])
	#grid.insert(0, 'FID', range(1, len(grid) + 1))

	print("Done in ", np.round(time.time()-t1,2),"s",np.shape(grid))

	## Get the raster information from the first grid
	array_gdal, gt,_,_,_ = open_gdal(poprasts[0])

	#Find the indicies of the grid in the raster assuming all rasters will have same dim
	t1=time.time()
	print("Finding indexes for grid (first time)...")
	ind=[]
	for row in grid.itertuples():
		ind.append(get_coords_at_point(gt, row.X, row.Y))

	grid["ind"]=ind
	print("Indexed points loop:", np.round(time.time()-t1,2),"s")

	#Create the dask delayed object to submit to multiple workers
	t = []
	for pth in poprasts:
		t.append(poprast_prep(pth,grid,buffs,gt))

	#Run compute with dask
	print("Finished appending, running dask compute...")
	tic=time.time()
	dd=compute(t,scheduler="multiprocessing")
	#Combine all the runs
	t=pd.concat(dd[0])
	print("Done dask:",np.round(time.time()-t1,2),"s")

	#Save the result to a file
	outfile="popdensity.csv"
	t.to_csv(outfile,index=False)
	print("Finished and saved output to:", outfile)


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

from business import model as business_model
from db.mall import models as mall_models

class ProductClassificationLabel(business_model.Model):
	"""
	商品分类标签
	"""
	__slots__ = (
		'id',
		'classification_id',
		'label_id',
		'created_at',
	)

	def __init__(self, model=None):
		business_model.Model.__init__(self)

		self.context['db_model'] = model
		if model:
			self._init_slot_from_model(model)

	@staticmethod
	def create_many(create_list):
		mall_models.ClassificationHasLabel.insert_many(create_list).execute()


from typing import TYPE_CHECKING

from .client_assertion import ClientAssertionCredential
from ..._credentials.token_exchange import TokenFileMixin

if TYPE_CHECKING:
    # pylint:disable=unused-import,ungrouped-imports
    from typing import Any

class TokenExchangeCredential(ClientAssertionCredential, TokenFileMixin):
    def __init__(self, tenant_id: str, client_id: str, token_file_path: str, **kwargs: "Any") -> None:
        super().__init__(
            tenant_id=tenant_id,
            client_id=client_id,
            get_assertion=self.get_service_account_token,
            token_file_path=token_file_path,
            **kwargs
        )


from flask import json

class Data:

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

    def check_year(self, init, end):
        if init is None or end is None:
            return False
        return True

    def generate_year(self, init, end):
        init_year = int(init)
        end_year = int(end)

        list_year = []
        while (init_year <= end_year):
            list_year.append(init_year)
            init_year = init_year + 1

        return list_year

    def generate_period(self, init, end):
        init_year = int(init)
        end_year = int(end)

        list_period = []
        while (init_year < end_year):
            next_year = init_year + 1
            list_period.append([init_year, next_year])
            init_year = init_year + 1

        return list_period

    def iszero(self, a):
        return abs(a)<1e-9

    def calculate_gcf(self, a, b):
        if self.iszero(b):
            return a

        return self.calculate_gcf(b, a % b)

    def retrieve(self, params):
        init_year = params['request'].args.get('init')
        end_year = params['request'].args.get('end')
        query_type = params['type']

        if not self.check_year(init_year, end_year):
            return 'Please enter `init` and `end` as parameters.'

        list_year = self.generate_year(init_year, end_year)
        list_income_data = self.modules['income'].get_data(query_type, init_year, end_year)
        list_wealth_data = self.modules['wealth'].get_data(query_type, init_year, end_year)

        list_income = []
        list_wealth = []

        for item in list_income_data:
            list_income.append(item[1])

        for item in list_wealth_data:
            list_wealth.append(item[1])

        res_json = {
            'year': list_year,
            'income': list_income,
            'wealth': list_wealth
        }

        return json.dumps(res_json)

    def inequality(self, params):
        init_year = params['request'].args.get('init')
        end_year = params['request'].args.get('end')
        query_type = params['type']

        if not self.check_year(init_year, end_year):
            return 'Please enter `init` and `end` as parameters.'

        list_year = self.generate_year(init_year, end_year)

        list_data = []
        list_data = self.modules[query_type].get_data('all', init_year, end_year)

        factor = []
        for item in list_data:
            factor.append(self.calculate_gcf(float(item[2]), float(item[1])))

        res_json = {
            'year': list_year,
            'factor': factor
        }

        return json.dumps(res_json)

    def saving_capacity(self, params):
        request_data = params['request'].json
        init_year = request_data[u'init']
        end_year = request_data[u'end']
        group = request_data[u'group']

        if not self.check_year(init_year, end_year):
            return 'Please enter `init` and `end` as parameters.'

        list_data = self.modules['general'].get_data(init_year, end_year)
        list_data_temp = {}

        for item in list_data:
            list_data_temp[item[1]] = item

        list_period = self.generate_period(init_year, end_year)
        list_saving_capacity = []

        for period in list_period:
            x = period[0]
            y = period[1]
            total = 0

            if group == 10 or group == 50:
                total = (list_data_temp[y][3] - list_data_temp[x][3]) / list_data_temp[x][2]
            else:
                total = (list_data_temp[y][5] - list_data_temp[x][5]) / list_data_temp[x][4]

            list_saving_capacity.append(float(total))

        res_json = {
            'group': group,
            'period': list_period,
            'saving_capacity': list_saving_capacity
        }

        return json.dumps(res_json)

    def prediction(self, params):
        request_data = params['request'].json
        n_year = request_data[u'years']
        group = request_data[u'group']
        query_type = params['type']

        list_data = self.modules[query_type].get_data(group)

        values = []
        for item in list_data:
            values.append((item[0], float(item[1])))

        coef = params['regression'].calculate(values)

        i = 1
        prediction = []
        while (i <= n_year):
            year = 2014 + i
            p = params['regression'].predict(year, coef[u'm'], coef[u'b'])
            prediction.append(p)
            i = i + 1

        res_json = {
            'group': group,
            'prediction': prediction
        }

        return json.dumps(res_json)


import os
import argparse
import collections
import numpy as np
import pandas as pd
import scipy.stats as stats
from sklearn import linear_model
from sklearn.decomposition import PCA

def parse_args():

    parser = argparse.ArgumentParser(description = 'Preprocess gene expression')

    parser.add_argument('-g',
                        type = str,
                        required = True,
                        dest = 'gxfile',
                        metavar = 'FILE',
                        help = 'input gene expression file')

    parser.add_argument('-o',
                        type = str,
                        required = True,
                        dest = 'outfile',
                        metavar = 'FILE',
                        help = 'output gene expression file')

    parser.add_argument('-c',
                        type = str,
                        required = True,
                        dest = 'covfile',
                        metavar = 'FILE',
                        help = 'input covariates file')

    parser.add_argument('-m',
                        nargs = '*',
                        default = ['norm'],
                        dest = 'methods',
                        help = 'which method to apply: norm, qn, cclm, cclasso, knn or any combination')

    opts = parser.parse_args()
    return opts

def normalize_center(Y):
    # requires  G x N matrix, where G is the number of genes, and Y is the number of samples
    # returns   G x N matrix
    newY = (Y - np.mean(Y, axis = 1).reshape(-1, 1)) / np.std(Y, axis = 1).reshape(-1, 1)
    return newY

def read_expression(filename):
    # returns G x N gene expression
    #         list of N donor ids
    #         list of G gene names
    gx = list()
    genes = list()
    with open(filename, 'r') as infile:
        header = next(infile)
        for line in infile:
            linesplit = line.strip().split()
            thisgx = np.array([float(x) for x in linesplit[1:]])
            gx.append(thisgx)
            genes.append(linesplit[0])
    gx = np.array(gx)
    donors = header.strip().split()[1:]
    return gx, donors, genes

def write_expression(GX, donors, genes, filename):
    with open(filename, 'w') as fout:
        header = 'gene_ids\t' + '\t'.join(donors) + '\n'
        fout.write(header)
        for i in range(GX.shape[0]):
            line = '{:s}\t'.format(genes[i]) + '\t'.join(['{:g}'.format(x) for x in GX[i, :]]) + '\n'
            fout.write(line)

def normalize_quantiles(M):
    """
    Note: replicates behavior of R function normalize.quantiles from library("preprocessCore")

    Reference:
     [1] Bolstad et al., Bioinformatics 19(2), pp. 185-193, 2003

    Adapted from https://github.com/andrewdyates/quantile_normalize
    """

    Q = M.argsort(axis=0)
    m,n = M.shape

    # compute quantile vector
    quantiles = np.zeros(m)
    for i in range(n):
        quantiles += M[Q[:,i],i]
    quantiles = quantiles / n

    for i in range(n):
        # Get equivalence classes; unique values == 0
        dupes = np.zeros(m, dtype=np.int)
        for j in range(m-1):
            if M[Q[j,i],i]==M[Q[j+1,i],i]:
                dupes[j+1] = dupes[j]+1

        # Replace column with quantile ranks
        M[Q[:,i],i] = quantiles

        # Average together equivalence classes
        j = m-1
        while j >= 0:
            if dupes[j] == 0:
                j -= 1
            else:
                idxs = Q[j-dupes[j]:j+1,i]
                M[idxs,i] = np.median(M[idxs,i])
                j -= 1 + dupes[j]
        assert j == -1

    return M

#def inverse_quantile_normalize(M):
#    """
#    After quantile normalization of samples, standardize expression of each gene
#    """
#    R = stats.mstats.rankdata(M,axis=1)  # ties are averaged
#    Q = stats.norm.ppf(R/(M.shape[1]+1))
#    return Q

def inverse_normal_transform(M):
    """
    Transform rows to a standard normal distribution
    """
    R = stats.mstats.rankdata(M, axis=1)  # ties are averaged
    if isinstance(M, pd.DataFrame):
        Q = pd.DataFrame(stats.norm.ppf(R/(M.shape[1]+1)), index=M.index, columns=M.columns)
    else:
        Q = stats.norm.ppf(R/(M.shape[1]+1))
    return Q

def edgeR_calcNormFactors(counts_df, ref=None, logratio_trim=0.3, sum_trim=0.05, acutoff=-1e10, verbose=False):
    """
    Calculate TMM (Trimmed Mean of M values) normalization.
    Reproduces edgeR::calcNormFactors.default
    Scaling factors for the library sizes that minimize the log-fold changes between the samples for most genes.
    Effective library size: TMM scaling factor * library size
    References:
     [1] Robinson & Oshlack, 2010
     [2] R functions:
          edgeR::calcNormFactors.default
          edgeR:::.calcFactorWeighted
          edgeR:::.calcFactorQuantile
    """

    # discard genes with all-zero counts
    Y = counts_df.values.copy()
    allzero = np.sum(Y>0,axis=1)==0
    if np.any(allzero):
        Y = Y[~allzero,:]

    # select reference sample
    if ref is None:  # reference sample index
        f75 = np.percentile(Y/np.sum(Y,axis=0), 75, axis=0)
        ref = np.argmin(np.abs(f75-np.mean(f75)))
        if verbose:
            print('Reference sample index: '+str(ref))

    N = np.sum(Y, axis=0)  # total reads in each library

    # with np.errstate(divide='ignore'):
    with warnings.catch_warnings():
        warnings.simplefilter('ignore')
        logR = np.log2((Y/N).T / (Y[:,ref]/N[ref])).T  # log fold change; Mg in [1]
        absE = 0.5*(np.log2(Y/N).T + np.log2(Y[:,ref]/N[ref])).T  # average log relative expression; Ag in [1]
        v = (N-Y)/N/Y
        v = (v.T + v[:,ref]).T  # w in [1]

    ns = Y.shape[1]
    tmm = np.zeros(ns)
    for i in range(ns):
        fin = np.isfinite(logR[:,i]) & np.isfinite(absE[:,i]) & (absE[:,i] > acutoff)
        n = np.sum(fin)

        loL = np.floor(n*logratio_trim)+1
        hiL = n + 1 - loL
        loS = np.floor(n*sum_trim)+1
        hiS = n + 1 - loS
        rankR = stats.rankdata(logR[fin,i])
        rankE = stats.rankdata(absE[fin,i])
        keep = (rankR >= loL) & (rankR <= hiL) & (rankE >= loS) & (rankE <= hiS)
        # in [1], w erroneously defined as 1/v ?
        tmm[i] = 2**(np.nansum(logR[fin,i][keep]/v[fin,i][keep]) / np.nansum(1/v[fin,i][keep]))

    tmm = tmm / np.exp(np.mean(np.log(tmm)))
    return tmm

def edgeR_cpm(counts_df, tmm=None, normalized_lib_sizes=True):
    """
    Return edgeR normalized/rescaled CPM (counts per million)
    Reproduces edgeR::cpm.DGEList
    """
    lib_size = counts_df.sum(axis=0)
    if normalized_lib_sizes:
        if tmm is None:
            tmm = edgeR_calcNormFactors(counts_df)
        lib_size = lib_size * tmm
    return counts_df / lib_size * 1e6

def gtex_v6_preproc(GX):
    M = normalize_quantiles(GX)
    #R = inverse_quantile_normalize(M)
    R = inverse_normal_transform(M)
    return R

def gtex_v6_preproc_sim(GX):
    R = inverse_normal_transform(GX)
    return R

def gtex_v6p_preproc(GX):
    tmm_counts_df = edgeR_cpm(counts_df, normalized_lib_sizes=True)
    R = inverse_normal_transform(tmm_counts_df)
    return norm_df

def covcorrlm(X, W):
    # inputs: X of shape G x N (G = number of genes, N = number of samples)
    #         W of shape C x N (C = number of covariates)
    Wnorm = (W - np.mean(W, axis = 1).reshape(-1, 1)) / np.std(W, axis = 1).reshape(-1, 1)
    linreg = linear_model.LinearRegression()
    linreg.fit(Wnorm.T, X.T)
    Xcorr = X - linreg.predict(Wnorm.T).T
    return Xcorr

def covcorrlasso(X, W, alpha = 0.05):
    # inputs: X of shape G x N (G = number of genes, N = number of samples)
    #         W of shape C x N (C = number of covariates)
    Wnorm = (W - np.mean(W, axis = 1).reshape(-1, 1)) / np.std(W, axis = 1).reshape(-1, 1)
    Xcorr = np.zeros(X.shape)
    #coefs = np.zeros((X.shape[0], W.shape[0]))
    for i in range(X.shape[0]):
        lassoreg = linear_model.Lasso(alpha = alpha)
        lassoreg.fit(Wnorm.T, X[i, :])
        Xcorr[i] = X[i, :] - lassoreg.predict(Wnorm.T).T
    return Xcorr

def covcorrknn(X, kneighbor):
    # input: X of shape G x N (G = number of genes, N = number of samples)
    XT = X.T
    pca = PCA(n_components=min(X.shape[0], X.shape[1]))
    pca.fit(XT) # requires N x G
    Xpca = pca.transform(XT)

    def gene_distance(a, b):
        return np.linalg.norm(a - b)

    nsample = XT.shape[0]
    distance_matrix = np.zeros((nsample, nsample))
    for i in range(nsample):
        for j in range(i+1, nsample):
            dist = gene_distance(Xpca[i,:], Xpca[j,:])
            distance_matrix[i, j] = dist
            distance_matrix[j, i] = dist

    gx_knn = np.zeros_like(XT)
    neighbor_list = list()

    for i in range(nsample):
        neighbors = np.argsort(distance_matrix[i, :])[:kneighbor + 1][1:]
        gx_knn[i, :] = XT[i, :] - np.mean(XT[neighbors, :], axis = 0)

    return gx_knn.T

def pp_options(method, _X, cov = None):
    # a pythonic dictionary runs through all functions and creates the full dictionary
    # hence if-else is used.
    gx = _X.copy()
    #if method == 'raw':
    #    print('   > Keep raw file')
    #    res = gx
    if method == 'norm':
        print('   > Center and scale')
        res = normalize_center(gx)
    elif method == 'qnonly':
        print('   > QN only (no inverse normal transformation)')
        res = normalize_quantiles(gx)
    elif method == 'qn':
        print('   > QN (misnomer. actually only inverse normal transformation)')
        #res = gtex_v6_preproc(gx)
        res = gtex_v6_preproc_sim(gx)
    elif method == 'cclm':
        print('   > Covariate correction with linear model')
        res = covcorrlm(gx, cov)
    elif method == 'cclasso':
        print('   > Adaptive covariate correction using LASSO')
        res = covcorrlasso(gx, cov)
    elif method.startswith('knn'):
        kneighbor = int(method[3:])
        print('   > KNN correction')
        res = covcorrknn(gx, kneighbor)
    return res

if __name__ == '__main__':

    opts = parse_args()

    # Read gene expression
    print ("Reading gene expression.")
    gx, gxdonors, genes = read_expression(opts.gxfile)

    # Read covariates
    if any(['cc' in x for x in opts.methods]):
        print ("Reading covariates.")
        cov, covdonors, covnames = read_expression(opts.covfile)
        covidx = np.array([covdonors.index(x) for x in gxdonors])
        covsort = cov[:, covidx]
    else:
        cov = None

    # Perform the preprocessing
    gxpp = collections.defaultdict(lambda: None)
    gxpp['raw'] = gx

    for method in opts.methods:
        print(f'Applying {method}')
        msteps = method.split('_')
        prevstep = 'raw'
        curstep = ''

        for mstep in msteps:
            curstep = f'{mstep}' if curstep == '' else f'{curstep}_{mstep}'
            print(f'  Step: {curstep}')
            if gxpp[curstep] is None:
                gxpp[curstep] = pp_options(mstep, gxpp[prevstep], cov = cov)
            prevstep = curstep

    # Write output
    print ("Writing all outputs.")
    oprefix = os.path.splitext(opts.outfile)[0]
    osuffix = os.path.splitext(opts.outfile)[1]
    for method in opts.methods:
        ofilename = f'{oprefix}_{method}{osuffix}'
        write_expression(gxpp[method], gxdonors, genes, ofilename)


import io
import zipfile
from django import forms
from django.core.exceptions import PermissionDenied
from django.http import Http404, FileResponse, HttpResponseBadRequest, HttpResponse
from django.shortcuts import render, redirect, resolve_url, get_object_or_404
from django.urls import reverse_lazy
from django.utils.cache import patch_response_headers
from django.views import generic
from .models import Composite

class PathTop(generic.CreateView):
    model = Composite
    fields = ('name', 'is_dir', 'src', 'zip_depth')
    success_url = reverse_lazy('nuploader0:path')
    template_name = 'nuploader0/composite_list.html'

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            raise PermissionDenied
        return super().post(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['add_form'] = context['form']
        context['composite_list'] = Composite.objects.filter(parent__isnull=True).order_by('name')
        return context

class Path(generic.TemplateView):
    template_name = 'nuploader0/composite_list.html'
    model = Composite
    add_fields = fields = ('name', 'is_dir', 'src', 'zip_depth')
    update_fields = ('name', 'parent', 'zip_depth')
    url_name = 'nuploader0:path'
    path_url_kwarg = 'request_path'

    def get_request_path(self):
        return self.kwargs.get(self.path_url_kwarg, '')

    def make_clean_path_list(self):
        request_path = self.get_request_path()
        return [path for path in request_path.split('/') if path]

    def get_prev_request_path(self):
        path_list = self.make_clean_path_list()
        path_list.pop()
        return '/'.join(path_list)

    def get_prev_url(self):
        # urls.pyのURL定義では末尾にスラッシュがない。前URLは基本的にディレクトリなので、末尾に/を足す必要がある。
        prev_request_path = self.get_prev_request_path()
        if prev_request_path:
            kwargs = {self.path_url_kwarg: prev_request_path}
            url = resolve_url(self.url_name, **kwargs)
        else:
            url = resolve_url(self.url_name)

        if not url.endswith('/'):
            url += '/'
        return url

    def get_sql_kwargs(self):
        path_list = self.make_clean_path_list()
        i = 0
        kwargs = {}
        for path in path_list[::-1]:
            arg_name = 'parent__' * i + 'name'
            kwargs[arg_name] = path
            i += 1
        arg_name = 'parent__' * i + 'isnull'
        kwargs[arg_name] = True
        return kwargs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['composite'] = self.composite
        context['composite_list'] = self.composite.composite_set.all().order_by('name')

        if hasattr(self, 'add_form'):
            context['add_form'] = self.add_form
        else:
            context['add_form'] = self.get_add_form()

        if hasattr(self, 'update_form'):
            context['update_form'] = self.update_form
        else:
            context['update_form'] = self.get_update_form()

        return context

    def get_object(self):
        composite = self.composite = self.model.objects.select_related('parent').get(**self.get_sql_kwargs())
        return composite

    def get_add_form_class(self):
        if hasattr(self, 'add_form_class'):
            return self.add_form_class
        return forms.modelform_factory(self.model, fields=self.add_fields)

    def get_add_form(self):
        form_class = self.get_add_form_class()
        kwargs = {}
        # 追加ボタンを押したときだけ、追加フォームにPOSTデータを紐づける
        # これをしないと、更新フォームと処理が競合するっぽい
        if self.request.POST.get('type') == 'add':
            kwargs.update({
                'data': self.request.POST,
                'files': self.request.FILES,
            })
        form = self.add_form = form_class(**kwargs)
        return form

    def get_update_form_class(self):
        if hasattr(self, 'update_form_class'):
            return self.update_form_class
        return forms.modelform_factory(self.model, fields=self.update_fields)

    def get_update_form(self):
        form_class = self.get_update_form_class()
        kwargs = {'instance': self.composite}
        # 更新ボタンを押したときだけ、更新フォームにPOSTデータを紐づける
        # これをしないと、追加フォームと処理が競合するっぽい
        if self.request.POST.get('type') == 'update':
            kwargs.update({
                'data': self.request.POST,
                'files': self.request.FILES,
            })
        form = self.update_form = form_class(**kwargs)
        return form

    def get(self, request, *args, **kwargs):
        try:
            composite = self.get_object()
        except Composite.DoesNotExist:
            raise Http404
        else:
            if composite.is_dir:
                return self.get_dir()
            else:
                return self.get_file()

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            raise PermissionDenied

        kind = request.POST['type']
        if kind == 'delete':
            return self.post_delete(request, *args, **kwargs)
        elif kind == 'add':
            return self.post_add(request, *args, **kwargs)
        elif kind == 'update':
            return self.post_update(request, *args, **kwargs)
        else:
            return self.get(request, *args, **kwargs)

    def get_dir(self):
        context = self.get_context_data()
        return render(self.request, self.template_name, context)

    def get_file(self):
        response = FileResponse(self.composite.src)
        patch_response_headers(response, 60*60*24*7)
        return response

    def post_delete(self, request, *args, **kwargs):
        try:
            composite = self.get_object()
        except Composite.DoesNotExist:
            raise Http404
        else:
            composite.delete()

        return redirect(self.get_prev_url())

    def post_add(self, request, *args, **kwargs):
        parent = self.get_object()
        form = self.get_add_form()
        form.instance.parent = parent  # parentが先にないと、モデルのcleanでの同名ファイルの確認ができない
        if form.is_valid():
            form.save()
            return redirect(self.request.get_full_path())

        context = self.get_context_data()
        return render(self.request, self.template_name, context)

    def post_update(self, request, *args, **kwargs):
        composite = self.get_object()
        form = self.get_update_form()
        if form.is_valid():
            form.save()
            return redirect(self.get_prev_url())

        context = self.get_context_data()
        return render(self.request, self.template_name, context)

def download_zip(request, pk):
    composite = get_object_or_404(Composite, pk=pk)
    if not composite.zip_depth:
        return HttpResponseBadRequest('ZIPが許可されているファイル・ディレクトリではありません。')

    response = HttpResponse(content_type='application/zip')
    response['Content-Disposition'] = f'attachment; filename="{composite.name}.zip"'
    zip_file = zipfile.ZipFile(response, 'w')
    if not composite.is_dir:
        zip_file.writestr(composite.name, composite.src.read())
    else:
        walk_and_write(composite, zip_file, composite.zip_depth)

    return response

def walk_and_write(composite, zip_file, count, dir_name=''):
    """再帰的にCompositeを走査し、zipファイルに書き込んでいく"""
    dirs = []
    for composite in composite.composite_set.all():
        if composite.is_dir:
            dirs.append(composite)
        else:
            zip_file.writestr(dir_name + composite.name, composite.src.read())
    count -= 1

    if count:
        for composite in dirs:
            walk_and_write(composite, zip_file, count, f'{dir_name}{composite.name}/')


import tensorflow as tf

def load_graph_from_proto(proto_file):
    with tf.io.gfile.GFile(proto_file, "rb") as f:
        graph_def = tf.compat.v1.GraphDef()
        graph_def.ParseFromString(f.read())

    graph = tf.Graph()
    config = tf.compat.v1.ConfigProto()
    config.gpu_options.allow_growth = True
    session = tf.compat.v1.Session(graph=graph, config=config)
    with graph.as_default():
        tf.import_graph_def(graph_def)
    return session


# Subroutine ROT builds a Euler rotation

# The original code is as follows
# C***********************************************************************
# C*---------------------------------------------------------------------*
#       subroutine ROT(RRR, alpha, beta, gamma)
# C*---------------------------------------------------------------------*
# C***********************************************************************
# C*    subroutine to return the Euler rotation matrix where the three   *
# C*      rotation angles are alpha, a rotation about the z-axis, beta,  *
# C*      a rotation about the new y-axis, and gamma, a rotation about   *
# C*      the new z-axis.    Not thourghly checked!!!!!!!                *
# C***********************************************************************
# C****  Variables                                                    ****
#       implicit none
#        real RRR(3,3),alpha, beta, gamma
# C
#        RRR(1,1)= cos(alpha)*cos(beta)*cos(gamma)-sin(alpha)*sin(gamma)
#        RRR(1,2)= sin(alpha)*cos(beta)*cos(gamma)+cos(alpha)*sin(gamma)
#        RRR(1,3)=-sin(beta)*cos(gamma)
# C
#        RRR(2,1)=-cos(alpha)*cos(beta)*sin(gamma)-sin(alpha)*cos(gamma)
#        RRR(2,2)=-sin(alpha)*cos(beta)*sin(gamma)+cos(alpha)*cos(gamma)
#        RRR(2,3)= sin(beta)*sin(gamma)
# C
#        RRR(3,1)= cos(alpha)*sin(beta)
#        RRR(3,2)= sin(alpha)*sin(beta)
#        RRR(3,3)= cos(beta)
# C
#
# c      print *, RRR(1,1),RRR(1,2),RRR(1,3)
# c      print *, RRR(2,1),RRR(2,2),RRR(2,3)
# c      print *, RRR(3,1),RRR(3,2),RRR(3,3)
#       return
#       end

# I think we can use the numpy matrix creation for this

import numpy as np

def ROT(alpha, beta, gamma):
    RRR = np.array(
      [[ np.cos(alpha)*np.cos(beta)*np.cos(gamma)-np.sin(alpha)*np.sin(gamma),
         np.sin(alpha)*np.cos(beta)*np.cos(gamma)+np.cos(alpha)*np.sin(gamma),
        -np.sin(beta)*np.cos(gamma)],
       [-np.cos(alpha)*np.cos(beta)*np.sin(gamma)-np.sin(alpha)*np.cos(gamma),
        -np.sin(alpha)*np.cos(beta)*np.sin(gamma)+np.cos(alpha)*np.cos(gamma),
         np.sin(beta)*np.sin(gamma)],
       [ np.cos(alpha)*np.sin(beta),
         np.sin(alpha)*np.sin(beta),
         np.cos(beta)]])
    return RRR

alpha = 0 #np.pi/3
beta = np.pi/2
gamma = np.pi/10

RRR = ROT(alpha, beta, gamma)
print(RRR)


import random, math
from vec2 import Vec2

MOORE = [(-1,-1),(-1,0),(-1,1),(0,1),(0,-1),(1,0),(1,1),(1,-1)]
NEUMANN = [(1,0),(-1,0),(0,1),(0,-1)]

def get_m_networks(points):
	completed = set()
	networks = []
	for point in points:
		if point in completed: continue
		network = get_m_network(point, points)
		completed.update(network)
		networks.append(network)
	return networks

def get_m_network(point, points):
	network = set([point])
	explored = set()
	unexplored = [point]
	while True:
		if unexplored == []: break
		cur_point = unexplored[0]
		for edge in M_NEIGHBORS[cur_point]:
			if edge not in points or edge in network or edge in explored: continue
			network.add(edge)
			unexplored.append(edge)
		unexplored.remove(cur_point)
		explored.add(cur_point)
	return network

def get_n_networks(points):
	completed = set()
	networks = []
	for point in points:
		if point in completed: continue
		network = get_n_network(point, points)
		completed.update(network)
		networks.append(network)
	return networks

def get_n_network(point, points):
	network = set([point])
	explored = set()
	unexplored = [point]
	while True:
		if unexplored == []: break
		cur_point = unexplored[0]
		for edge in N_NEIGHBORS[cur_point]:
			if edge not in points or edge in network or edge in explored: continue
			network.add(edge)
			unexplored.append(edge)
		unexplored.remove(cur_point)
		explored.add(cur_point)
	return network

def random_color():
	return random.randrange(40,150),random.randrange(40,150),random.randrange(40,150)

def add_tuple(xy1, xy2):
	return xy1[0] + xy2[0], xy1[1] + xy2[1]

def subtract_tuple(xy1, xy2):
	return xy1[0] - xy2[0], xy1[1] - xy2[1]

def get_closest_point(pos, points):
	min_distance = 50000.0
	for point in points:
		vec = subtract_tuple(pos, point)
		distance = math.hypot(vec[0], vec[1])
		if distance < min_distance:
			min_distance = distance
			result = point
	return result

def get_outline(points):
	result = set()
	for point in points:
		for edge in M_NEIGHBORS[point]:
			if edge not in points:
				result.add(point)
				break
	return result

def get_trim(points):
	outline = get_outline(points)
	return points.difference(outline)

def get_trace(points):
	result = set()
	for point in points:
		dead_edges = set([xy for xy in M_NEIGHBORS[point] if xy not in points])
		result.update(dead_edges)
	return result

def get_tunnel(line):
	tunnel = set()
	for point in line:
		variance = random.randrange(-1,2), random.randrange(-1,2)
		radius = random.randrange(1,3)
		xy = add_tuple(point, variance)
		tunnel.update(build_circle(xy, radius))
	return tunnel

def get_straight_tunnel(line):
	tunnel = set()
	for point in line:
		radius = random.randrange(2,3)
		tunnel.update(build_circle(point, radius))
	return tunnel

def randomize(neighborhood, p = 0.5):
	points = set()
	for point in neighborhood:
		if random.randrange(0,100) * 0.01 < p:
			points.add(point)
	return points

def automata(neighborhood, start, dead = 3, alive = 6, iterations = 1):
	end = set(start)
	for i in range(iterations):
		points = set()
		for pos in neighborhood:
			if pos in end:
				if len([xy for xy in M_NEIGHBORS[pos] if xy in end]) > dead:
					points.add(pos)
				continue
			if len([xy for xy in M_NEIGHBORS[pos] if xy in end]) >= alive: points.add(pos)
		end = set(points)
	return end

def build_cave(neighborhood, p = 0.64):
	points = randomize(neighborhood, p)
	return automata(neighborhood, points, iterations = 5)

def build_circle(offset = (0,0), size = 5):
	result = set()
	for x in range(-size, size):
		for y in range(-size, size):
			if math.hypot(x, y) < size:
				result.add(add_tuple((x,y),offset))
	return result

def build_box(offset = (0,0), size = (100,100)):
	result = set()
	for x in range(0, size[0]):
		for y in range(0, size[1]):
			result.add(add_tuple((x,y),offset))
	return result

def build_line(xy1, xy2):
	x1, y1, x2, y2 = xy1[0], xy1[1], xy2[0], xy2[1]
	points = []
	issteep = abs(y2-y1) > abs(x2-x1)
	if issteep:
		x1, y1 = y1, x1
		x2, y2 = y2, x2
	rev = False
	if x1 > x2:
		x1, x2 = x2, x1
		y1, y2 = y2, y1
		rev = True
	deltax = x2 - x1
	deltay = abs(y2-y1)
	error = int(deltax / 2)
	y = y1
	ystep = None
	if y1 < y2:
		ystep = 1
	else:
		ystep = -1
	for x in range(x1, x2 + 1):
		if issteep:
			points.append((y, x))
		else:
			points.append((x, y))
		error -= deltay
		if error < 0:
			y += ystep
			error += deltax
    # Reverse the list if the coordinates were reversed
	if rev:
		points.reverse()
	return points

def bake_neighbors(neighborhood, relationship):
	result = {}
	for block in neighborhood:
		result[block] = set([add_tuple(block,vec) for vec in relationship if add_tuple(block,vec) in neighborhood])
	return result

NEIGHBORHOOD = build_box((-1,-1),(202,202))
M_NEIGHBORS = bake_neighbors(NEIGHBORHOOD, MOORE)
N_NEIGHBORS = bake_neighbors(NEIGHBORHOOD, NEUMANN)