import math
import statistics
import warnings

import numpy as np
from hmmlearn.hmm import GaussianHMM
from sklearn.model_selection import KFold
from asl_utils import combine_sequences

class ModelSelector(object):
    '''
    base class for model selection (strategy design pattern)
    '''

    def __init__(self, all_word_sequences: dict, all_word_Xlengths: dict, this_word: str,
                 n_constant=3,
                 min_n_components=2, max_n_components=10,
                 random_state=14, verbose=False):
        self.words = all_word_sequences
        self.hwords = all_word_Xlengths
        self.sequences = all_word_sequences[this_word]
        self.X, self.lengths = all_word_Xlengths[this_word]
        self.this_word = this_word
        self.n_constant = n_constant
        self.min_n_components = min_n_components
        self.max_n_components = max_n_components
        self.random_state = random_state
        self.verbose = verbose

    def select(self):
        raise NotImplementedError

    def base_model(self, num_states):
        # with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=DeprecationWarning)
        # warnings.filterwarnings("ignore", category=RuntimeWarning)
        try:
            hmm_model = GaussianHMM(n_components=num_states, covariance_type="diag", n_iter=1000,
                                    random_state=self.random_state, verbose=False).fit(self.X, self.lengths)
            if self.verbose:
                print("model created for {} with {} states".format(self.this_word, num_states))
            return hmm_model
        except:
            if self.verbose:
                print("failure on {} with {} states".format(self.this_word, num_states))
            return None

class SelectorConstant(ModelSelector):
    """ select the model with value self.n_constant

    """

    def select(self):
        """ select based on n_constant value

        :return: GaussianHMM object
        """
        best_num_components = self.n_constant
        return self.base_model(best_num_components)

class SelectorBIC(ModelSelector):
    """ select the model with the lowest Baysian Information Criterion(BIC) score

    http://www2.imm.dtu.dk/courses/02433/doc/ch6_slides.pdf
    Bayesian information criteria: BIC = -2 * logL + p * logN
    """

    def select(self):
        """ select the best model for self.this_word based on
        BIC score for n between self.min_n_components and self.max_n_components

        :return: GaussianHMM object
        """
        warnings.filterwarnings("ignore", category=DeprecationWarning)

        # initialize best score and model
        best_score = float("inf")
        best_model = None

        # loop through all the components
        for num_state in range(self.min_n_components, self.max_n_components):
            try:
                model = GaussianHMM(n_components=num_state, covariance_type="diag", n_iter=1000,
                                    random_state=self.random_state, verbose=False).fit(self.X, self.lengths)
                logL = model.score(self.X, self.lengths)

                # Using the BIC equations
                parameters = num_state * num_state + 2 * num_state * len(self.X[0]) - 1
                bic = (-2) * logL + math.log(len(self.X)) * parameters

                if bic < best_score:
                    best_score = bic
                    best_model = model
            except:
                pass
        return best_model if best_model is not None else self.base_model(self.n_constant)

class SelectorDIC(ModelSelector):
    ''' select best model based on Discriminative Information Criterion

    Biem, Alain. "A model selection criterion for classification: Application to hmm topology optimization."
    Document Analysis and Recognition, 2003. Proceedings. Seventh International Conference on. IEEE, 2003.
    http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.6208&rep=rep1&type=pdf
    DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i))
    '''

    def select(self):
        warnings.filterwarnings("ignore", category=DeprecationWarning)

         # TODO implement model selection based on DIC scores
        # initialize best score and model
        best_score = float("-inf")
        best_model = None

        # loop through all the components
        for num_state in range(self.min_n_components, self.max_n_components):
            try:
                model = GaussianHMM(n_components=num_state, covariance_type="diag", n_iter=1000,
                                    random_state=self.random_state, verbose=False).fit(self.X, self.lengths)
                logL = model.score(self.X, self.lengths)

                total_logL = 0.0
                M = 0
                for word in self.hwords:
                    if word != self.this_word:
                        X, lengths = self.hwords[word]
                        total_logL += model.score(X, lengths)
                        M += 1

                dic = logL - total_logL / M

                if dic > best_score:
                    best_score = dic
                    best_model = model
            except:
                pass
        return best_model if best_model is not None else self.base_model(self.n_constant)

class SelectorCV(ModelSelector):
    ''' select best model based on average log Likelihood of cross-validation folds

    '''

    def select(self):
        warnings.filterwarnings("ignore", category=DeprecationWarning)

        # initialize best score and model
        best_score = float("-inf")
        best_model = None
        logL_list = []

        # if there is not enough samples to do kfold split
        if (len(self.sequences) < 2):
            return self.base_model(self.n_constant)

        # loop through all the components
        split_method = KFold(n_splits=min(3,len(self.sequences)))
        for num_state in range(self.min_n_components, self.max_n_components):
            # split the word sequences in to training and testing set
            # using KFold split
            try:
                for train_idx, test_idx in split_method.split(self.sequences):
                    X_train, lengths_train = combine_sequences(train_idx, self.sequences)
                    model = GaussianHMM(n_components=num_state, covariance_type="diag", n_iter=1000,
                                        random_state=self.random_state, verbose=False).fit(X_train, lengths_train)
                    X_test, lengths_test = combine_sequences(test_idx, self.sequences)
                    logL = model.score(X_test, lengths_test)
                    logL_list.append(logL)

                mean_score = np.mean(logL_list)

                if mean_score > best_score:
                    best_score = mean_score
                    best_model = model
            except:
                pass

        return best_model if best_model is not None else self.base_model(self.n_constant)


#0007_interprete_foto.py

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('appTop100', '0006_auto_20231206_1248'),
    ]

    operations = [
        migrations.AddField(
            model_name='interprete',
            name='foto',
            field=models.ImageField(blank=True, null=True, upload_to='fotos/'),
        ),
    ]


# /usr/bin/env python2
# -*- coding: utf-8 -*-

from __future__ import unicode_literals, print_function

import sys, os
from threading import Thread
import logging

logging.basicConfig(format='%(asctime)s,%(msecs)03d %(levelname)s [%(name)s] {%(threadName)s} %(message)s',
                            level=logging.INFO)
logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)

from IoticAgent import ThingRunner
from IoticAgent.Core.compat import Event

DUREX_DASH_MAC = '68:37:e9:c5:9f:ff'
SHEBA_DASH_MAC = 'fc:a6:67:a1:58:bb'

LIGHTS = ['upstairs_lamp', 'bedroom_lamp']

button_evt = Event()

class IoticDash(ThingRunner):

    def __init__(self, config=None):
        super(IoticDash, self).__init__(config=config)
        self.__on = True

    def on_startup(self):
        # Create snd_ctrl Thing
        self.__thing = self.client.create_thing("dash ctrl")
        with self.__thing.get_meta() as meta:
            meta.set_label("Tim's House RPI Dash button handler")
            meta.set_description("RPI Wifi sniffing for Dash")
            meta.set_location(52.526087, 0.391160)  # Southery White Bell Pub
        self.__thing.set_public(False)
        #
        self.__light_ctrl = self.__thing.attach(('lights', 'ctrl'))

    def main(self):
        global button_evt
        while True:
            if button_evt.is_set():
                for light in LIGHTS:
                    self.__light_ctrl.ask({'lamp': light, 'cmd': 'on' if self.__on else 'off'})
                self.__on = False if self.__on else True
                button_evt.clear()
            if self.wait_for_shutdown(2):
                return

# dashbutton.py - https://gist.github.com/mr-pj/75297864abef5c8f2d5c134be2656023#file-dashbutton-py

from pydhcplib.dhcp_network import *

netopt = {'client_listen_port':"68", 'server_listen_port':"67", 'listen_address':"0.0.0.0"}

class Server(DhcpServer):
    def __init__(self, options, dashbuttons):
        DhcpServer.__init__(self, options["listen_address"],
                                options["client_listen_port"],
                                options["server_listen_port"])
        self.dashbuttons = dashbuttons

    def HandleDhcpRequest(self, packet):
        mac = self.hwaddr_to_str(packet.GetHardwareAddress())
        self.dashbuttons.press(mac)

    def hwaddr_to_str(self, hwaddr):
        result = []
        hexsym = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
        for iterator in range(6) :
            result += [str(hexsym[hwaddr[iterator]/16]+hexsym[hwaddr[iterator]%16])]
        return ':'.join(result)

class DashButtons():
    def __init__(self):
        self.buttons = {}

    def register(self, mac, function):
        self.buttons[mac] = function

    def press(self, mac):
        if mac in self.buttons:
            self.buttons[mac]()
            return True
        return False

# dashbutton.py - end

def button_press():
    print("Got Dash button press!")
    button_evt.set()

def main():
    dashbuttons = DashButtons()
    dashbuttons.register(DUREX_DASH_MAC, button_press)
    dashbuttons.register(SHEBA_DASH_MAC, button_press)
    server = Server(netopt, dashbuttons)

    runner = IoticDash('../cfg/ioticdash.ini')
    runner.run(background=True)

    while True:
        try:
            server.GetNextDhcpPacket()
        except KeyboardInterrupt:
            break

    runner.stop()

if __name__ == '__main__':
    main()


#!/usr/bin/env python
from freenect_synch import get_depth, get_rgb
import cv
import numpy as np

def array2cv(a):
  dtype2depth = {
        'uint8':   cv.IPL_DEPTH_8U,
        'int8':    cv.IPL_DEPTH_8S,
        'uint16':  cv.IPL_DEPTH_16U,
        'int16':   cv.IPL_DEPTH_16S,
        'int32':   cv.IPL_DEPTH_32S,
        'float32': cv.IPL_DEPTH_32F,
        'float64': cv.IPL_DEPTH_64F,
    }
  try:
    nChannels = a.shape[2]
  except:
    nChannels = 1
  cv_im = cv.CreateImageHeader((a.shape[1],a.shape[0]),
          dtype2depth[str(a.dtype)],
          nChannels)
  cv.SetData(cv_im, a.tostring(),
             a.dtype.itemsize*nChannels*a.shape[1])
  return cv_im

def doloop():
    cv.NamedWindow('depth')
    cv.NamedWindow('rgb')
    global depth, rgb
    while True:
        # Get a fresh frame
        depth, rgb = get_depth(), get_rgb()

        # Build a two panel color image
        d3 = np.dstack((depth,depth,depth)).astype(np.uint8)
        da = np.hstack((d3,rgb))

        # Simple Downsample
        cv.ShowImage('both',array2cv(da[::2,::2,::-1]))
        cv.WaitKey(5)

doloop()

"""
IPython usage:
 ipython
 [1]: run -i demo_bgf
 #<ctrl -c>  (to interrupt the loop)
 [2]: %timeit -n100 QueryDepth(),QueryRGB() # profile the kinect capture

"""


import pickle

# __init__(self): este método se utiliza para inicializar la clase. En este caso, se inicializan los grupos primarios, los grupos de overflow y el índice de título.

# hash_func(self, modelo): este método utiliza una función de hash para calcular el índice en el que se debe almacenar el juego en la tabla hash.

# insertar_juego(self, modelo, titulo, precio): este método se utiliza para insertar un nuevo juego en la base de datos. Crea un nuevo objeto Juego con los parámetros especificados, calcula su índice hash y lo agrega a la tabla hash o al grupo de overflow si la tabla hash está llena. También actualiza el índice de título.

# buscar_por_modelo(self, modelo): este método se utiliza para buscar un juego por su modelo en la base de datos. Calcula su índice hash y busca en la tabla hash y en los grupos de overflow hasta que encuentra el juego o llega al final sin encontrarlo. Devuelve el juego encontrado o None si no se encuentra.

# buscar_por_titulo(self, titulo): este método se utiliza para buscar un juego por su título en el índice de título. Devuelve el juego encontrado o None si no se encuentra.

# alquilar_juego(self, modelo): este método se utiliza para marcar un juego como alquilado en la base de datos. Busca el juego por su modelo y, si se encuentra y su estado es "EN STOCK", lo marca como "ALQUILADO" y devuelve True. De lo contrario, devuelve False.

# devolver_juego(self, modelo): este método se utiliza para marcar un juego como devuelto en la base de datos. Busca el juego por su modelo y, si se encuentra y su estado es "ALQUILADO", lo marca como "EN STOCK" y devuelve True. De lo contrario, devuelve False.

# eliminar_juego(self, modelo): este método se utiliza para eliminar un juego de la base de datos. Busca el juego por su modelo y, si se encuentra, lo elimina de la tabla hash o del grupo de overflow y lo elimina del índice de título. Devuelve True si el juego se elimina correctamente y False si no se encuentra.

# guardar_base_de_datos(self, filename): este método se utiliza para guardar los datos de la base de datos en un archivo de secuencia de bytes en el disco duro. Crea un diccionario con los datos de la tabla hash, los grupos de overflow y el índice de título y los guarda en un archivo "base_datos".

# cargar_base_de_datos(self, filename): este método se utiliza para cargar los datos de la base de datos desde un archivo de secuencia de bytes en el disco duro. Abre el archivo "base_datos", y carga los datos en un diccionario

class Juego:
    def __init__(self, modelo, titulo, precio, status):
        self.modelo = modelo
        self.titulo = titulo
        self.precio = precio
        self.status = status

class RentAGame:
    def __init__(self):
        self.capacidad = 3
        self.tabla = [[], [], []] # 3 grupos primarios
        self.overflow = [[], [], [], [], [], []] # 6 grupos de overflow
        self.indice_titulo = {}

    def hash_func(self, modelo):
        return sum([ord(c) for c in modelo]) % 3

    def insertar_juego(self, modelo, titulo, precio):

        juego = Juego(modelo, titulo.upper(), precio, "EN STOCK")
        index = self.hash_func(modelo)

        if len(self.tabla[index]) < self.capacidad:
            self.tabla[index].append(juego)
        else:
            for i in range(len(self.overflow)):
                if len(self.overflow[i]) < self.capacidad:
                    self.overflow[i].append(juego)
                    break
        self.indice_titulo[titulo.upper()] = juego.modelo

    def buscar_por_modelo(self, modelo):

        index = self.hash_func(modelo.upper())

        for juego in self.tabla[index]:
            if juego.modelo == modelo.upper():
                return juego
        for lista in self.overflow:
            for juego in lista:
                if juego.modelo == modelo.upper():
                    return juego
        return None

    def buscar_por_titulo(self, titulo):
        # clave primaria del juego obtenida con el indice
        modelo_juego = self.indice_titulo.get(titulo.upper())
        if modelo_juego:
            return self.buscar_por_modelo(modelo_juego)
        else:
            return None

    def alquilar_juego(self, modelo):

        juego = self.buscar_por_modelo(modelo)
        if juego and juego.status == "EN STOCK":
            juego.status = "ALQUILADO"
            return True
        else:
            return False

    def devolver_juego(self, modelo):

        juego = self.buscar_por_modelo(modelo)
        if juego and juego.status == "ALQUILADO":
            juego.status = "EN STOCK"
            return True
        else:
            return False

    def eliminar_juego(self, modelo):

        index = self.hash_func(modelo)
        for i, juego in enumerate(self.tabla[index]):
            if juego.modelo == modelo:
                self.tabla[index].pop(i)
                del self.indice_titulo[juego.titulo]
                return True

        for lista in self.overflow:
            for i, juego in enumerate(lista):
                if juego.modelo == modelo:
                    lista.pop(i)
                    del self.indice_titulo[juego.titulo]
                    return True
        return False

    def guardar_base_de_datos(self):

        data = {
            "tabla": self.tabla,
            "overflow": self.overflow,
            "indice_titulo": self.indice_titulo
        }
        with open("base_datos", "wb") as f:
            pickle.dump(data, f)

    def cargar_base_de_datos(self):

        with open("base_datos", "rb") as f:
            data = pickle.load(f)

        self.tabla = data["tabla"]
        self.overflow = data["overflow"]
        self.indice_titulo = data["indice_titulo"]


import sys

class Boat:
    def __init__(self, x=0, y=0, direction='E'):
        self.x = x
        self.y = y
        self.direction = direction

    def apply_instruction(self, instruction):
        clockwise_directions = ('N', 'E', 'S', 'W')
        action, value = instruction[0], int(instruction[1:])
        if action == 'N':
            self.y += value
        elif action == 'S':
            self.y -= value
        elif action == 'E':
            self.x += value
        elif action == 'W':
            self.x -= value
        elif action == 'F':
            self.apply_instruction("{}{}".format(self.direction, value))
        elif action == 'L':
            self.direction = clockwise_directions[(clockwise_directions.index(self.direction) - value // 90) % 4]
        elif action == 'R':
            self.direction = clockwise_directions[(clockwise_directions.index(self.direction) + value // 90) % 4]
        else:
            raise Exception("Action: {} is not valid.".format(action))

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Missing input file: python {} file.".format(sys.argv[0]))
        sys.exit()

    with open(sys.argv[1]) as f:
        l = f.read().splitlines()

    boat = Boat()
    for instruction in l:
        boat.apply_instruction(instruction)

print(abs(boat.x) + abs(boat.y))


# МОДУЛЬ РАБОТЫ С ДАТЧИКОМ TLV493D

# Стандартные адреса 0x5e/0x1f. При запитывание датчиков при высоком уровне на шине SDA ставится адрес 0x5e
# Если на шине SDA низкий уровень, адрес выставляется как 0x1f
# В нашем случае используется стандартный адрес 0x5e

STANDARD_TLV493D_ADDRESS = 0x5e

class TLV493D:
    def __init__(self, sensor_number):
        # Создаем внутренний буффер для общения с шиной i2c, т.к. модуль связи - отдельный модуль,
        # он сам будет разгребать буферы с датчиков
        self.write_buffer = []
        # Буфер для данных пришедших с датчика
        self.read_buffer = []

        # Состояние подключения
        self.connected = False

        # Текущий адрес
        self.address = STANDARD_TLV493D_ADDRESS
        self.sensor_number = sensor_number

        # Регистр, конфигурирующий адрес
        self.MOD1 = 0x65 - 0x20*self.sensor_number
        # Параметр используемый в i2c пакетах, как cmd но не используемый данным датчиком, необходимо выставлять равным
        # нулю. По сути это значение идет под запись в нулевой регистр датчика, который зарезервирован под нули.
        self.RESERVED = 0
        # 0x40 - 0100 0000 Выключаю бит четности, включаю Low-power period 12ms и включаю датчик температуры.
        # Можно посмотреть в документации, USER MANUAL страница 26
        self.MOD2 = 0x40

        self.configured_data = [self.RESERVED, self.MOD1, self.RESERVED, self.MOD2]
        self.connect()

    def connect(self):
        self.write_data(self.configured_data)

    def write_data(self, data):
        self.write_buffer.append(data)

    def read_data(self):
        if self.check_read_buffer():
            data_block = self.read_buffer.pop(0)

            bx_high = data_block[0]
            by_high = data_block[1]
            bz_high = data_block[2]
            # temp_high = data_block[3]
            bxy_low = data_block[4]
            bz_low = data_block[5]
            # temp_low = data_block[6]

            bx_value = (bx_high << 4) + ((bxy_low & 0xF0) >> 4)
            by_value = (by_high << 4) + (bxy_low & 0x0F)
            bz_value = (bz_high << 4) + (bz_low & 0x0F)
            # temp_value = ((temp_high & 0xF0) << 4) + temp_low

            bx = (-2048) * (bx_value >> 11) + (bx_value & 0x7FF)
            by = (-2048) * (by_value >> 11) + (by_value & 0x7FF)
            bz = (-2048) * (bz_value >> 11) + (bz_value & 0x7FF)
            return bx, by, bz
        else:
            return None

    def check_write_buffer(self):
        if len(self.write_buffer):
            return 1
        else:
            return 0

    def check_read_buffer(self):
        if len(self.read_buffer):
            return 1
        else:
            return 0


import csv

import pandas

data = pandas.read_csv("weather_data.csv")

data_dict = data.to_dict()
monday = data[data.day == "Monday"]
monday_f = (monday.temp * 9/5) + 32
print(monday_f)

data_dict = {
    "students": ["Amy", "James", "Angela"],
    "scores": [76, 56, 65]
}
datos = pandas.DataFrame(data_dict)
datos.to_csv("new_data.csv")

ardillas = pandas.read_csv("2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv")
ardillas_grises_cuenta = len(ardillas[ardillas["Primary Fur Color"] == "Gray"])
ardillas_rojas_cuenta = len(ardillas[ardillas["Primary Fur Color"] == "Cinnamon"])
ardillas_negras_cuenta = len(ardillas[ardillas["Primary Fur Color"] == "Black"])

print(ardillas_grises_cuenta)
print(ardillas_rojas_cuenta)
print(ardillas_negras_cuenta)

ardillas_dict = {
    "Fur Color": ["Gray", "Cinnamon", "Black"],
    "Count": [ardillas_grises_cuenta, ardillas_rojas_cuenta, ardillas_negras_cuenta]
}

df = pandas.DataFrame(ardillas_dict)
df.to_csv("ardillas_conteo.csv")


class Solution:
    def maximumCandies(self, candies: List[int], k: int) -> int:

        l=1
        r=max(candies)
        res=0
        while l<=r:
            m=(l+r)//2
            # print(m)

            childernServed=0
            for i in candies:
                childernServed=childernServed+i//m

            if childernServed>=k:
                l=m+1
                res=m

            else:
                r=m-1

        return res


from django.template import Library

register = Library()

ERRORS = ['error', 'reject', 'rejected']
SUCCESSES = ['accept', 'confirmed', 'fully-paid', 'shipped', 'refunded']

@register.inclusion_tag('status_label.html')
def render_status(status, status_display=None):
    if status in ERRORS:
        label_cls = 'danger'
    elif status in SUCCESSES:
        label_cls = 'success'
    else:
        label_cls = 'default'
    return {'label_cls': label_cls, 'status': status_display or status}


# Author: Yu-Chia Chen <yuchaz@uw.edu>
# LICENSE: Simplified BSD

from __future__ import print_function, division, absolute_import
import numpy as np
from .coord_search import projected_volume
from ._configure import tqdm

def ies_range_search(principal_space, intrinsic_dim, embedding_dim,
                     eigen_values, zeta_range):
    proj_volume_loss_no_regu, all_comb = projected_volume(
        principal_space, intrinsic_dim, embedding_dim)
    lambdas_comb = (np.abs(eigen_values)[all_comb]).sum(1)

    R_mean = proj_volume_loss_no_regu.mean(1)
    return R_mean[:, None] - lambdas_comb[:, None] * zeta_range[None, :], all_comb

def average_no_regu_gain(proj_vol, candidate_set_ix):
    average_gain_all = []
    n_points = proj_vol.shape[1]
    for iset in candidate_set_ix:
        sum_all = proj_vol.sum(1)
        average_gain = []
        for ii in range(n_points):
            test_val = proj_vol[:, ii]
            residual_val = (sum_all - test_val) / (n_points - 1)
            test_max_set = test_val.argmax()
            average_gain.append(residual_val[iset] - residual_val[test_max_set])
        average_gain_all.append(average_gain)

    return np.array(average_gain_all)

def zeta_search(evects, lambdas, intrinsic_dim, embedding_dim, alpha=75,
                low=1e-2, high=1e5, sep=300):
    zeta_range = np.logspace(np.log10(low), np.log10(high), sep)
    R_lambdas, all_comb = ies_range_search(
        evects, intrinsic_dim, embedding_dim, lambdas, zeta_range)
    rloss, __ = projected_volume(evects, intrinsic_dim, embedding_dim)

    all_candidate_set_ix = R_lambdas.argmax(0)
    mid_x_all = []
    candiate_set = []
    last_zeta_same_set = zeta_range[0]
    for idx_, (start_ix, end_ix, start_zeta, end_zeta) in enumerate(zip(
        all_candidate_set_ix[:-1], all_candidate_set_ix[1:],
        zeta_range[:-1], zeta_range[1:])):

        if start_ix != end_ix:
            mid_x_all.append(np.exp(0.5 * (np.log(last_zeta_same_set) + np.log(start_zeta))))
            last_zeta_same_set = end_zeta
            candiate_set.append(start_ix)
        elif idx_ == zeta_range.shape[0]-2:
            mid_x_all.append(np.exp(0.5 * (np.log(last_zeta_same_set) + np.log(end_zeta))))
            candiate_set.append(start_ix)
    candiate_set, mid_x_all = map(np.array, [candiate_set, mid_x_all])

    average_gain_all = average_no_regu_gain(rloss, candiate_set)
    ptile = np.percentile(-average_gain_all, alpha, axis=1)
    last_ix = np.where(ptile <= 1e-10)[0][-1]
    zeta_chosen = mid_x_all[last_ix]

    plotting_dicts=dict(zeta_range=zeta_range, R_lambdas=R_lambdas,
                        average_gain_all=average_gain_all,
                        all_comb=all_comb, mid_x_all=mid_x_all)

    return zeta_chosen, plotting_dicts


class Solution:
    def minFlipsMonoIncr(self, s: str) -> int:
        # 1. Flip all the 1s so far to 0s; 2. flip the current zero to 1
        meet1 = 0
        flip = 0
        for c in s:
            if c == '1':
                meet1 += 1
            else:
                flip = min(meet1, flip+1)

        return flip


class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        result = list()
        for i in range(1,n+1):
            if i % 3 is not 0 and i % 5 is not 0:
                result.append(str(i))

            elif i % 3 is 0 and i % 5 is not 0:
                result.append('Fizz')

            elif i % 3 is not 0 and i % 5 is 0:
                result.append('Buzz')

            else:
                result.append('FizzBuzz')

        return result


# See: https://cloud.google.com/run/docs/quickstarts/build-and-deploy/deploy-python-service

import os

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    name = os.environ.get("NAME", "World")
    return "Hello {}!".format(name)

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))


import csv
import datetime
from model import User, Trade, Order, db

def find_orders(file_path):
    orders_list=[]
    with open(file_path) as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        account_trade_history = False

        for row in csv_reader:

            if len(row) > 0 and account_trade_history == False:
                #Finds where Account Trade History section begins
                if "Account Trade History" in row[0]:
                    account_trade_history = True
                    trade_counter = 0

                    continue
            #reverts boolean after end of trade history is reached
            elif len(row) == 0 and account_trade_history == True:
                account_trade_history = False

            #Ignore rows that aren't in Account Trade History section
            if account_trade_history:
                #Skips first row of trade history, which is column headers
                if trade_counter > 0:
                    orders_list.append(row)
                trade_counter += 1

    return orders_list

def parse_order_row(order_row):
    exec_time = datetime.datetime.strptime(order_row[1], "%m/%d/%y %H:%M:%S")
    spread = order_row[2]
    side = order_row[3]
    qty = int(order_row[4])
    pos_effect = order_row[5]
    symbol = order_row[6]

    #expiration date is only for options and future contracts
    #future contracts only have the month and year because it always expires on the third friday of the month
    if order_row[7] == '':
        expiration = None
    elif len(order_row[7].split()) == 2:
        expiration = datetime.datetime.strptime(order_row[7], "%b %y")
    elif len(order_row[7].split()) == 3:
        expiration = datetime.datetime.strptime(order_row[7], "%d %b %y")

    #strike price is for only options
    if order_row[8] == '':
        strike_price = None
    else:
        strike_price = float(order_row[8])

    type = order_row[9]
    price = float(order_row[10])
    order_type = order_row[12]

    return exec_time, spread, side, qty, pos_effect, symbol, expiration, strike_price, type, price, order_type

def create_order(user_id, exec_time, spread, side, qty, pos_effect, symbol, expiration, strike_price, type, price, order_type):

    #query database to find open trade for the user that matches the order symbol, spread, & side
    open_trade = Trade.query.filter_by(user_id=user_id, symbol=symbol, spread=spread, open=True).first()

    if open_trade is None:

        #make a new trade if no open trade is found
        open_trade = Trade(user_id=user_id, open_date=exec_time, symbol=symbol, entry_price=price, side=side, spread=spread, position=qty)
        db.session.add(open_trade)
        db.session.commit()

        order = add_order_to_db(trade=open_trade, exec_time=exec_time, spread=spread, side=side, qty=qty, pos_effect=pos_effect, symbol=symbol, expiration=expiration, strike_price=strike_price, type=type, price=price, order_type=order_type)

    else:

        #check if new order qty is large enough to close the current open position and one is positive while the other is negative
        #split order into two separate orders, one that closes the open trade, one that opens a new trade
        if abs(qty) > abs(open_trade.position) and ((open_trade.position ^ qty) < 0):

            #split qty's apart
            qty_one = open_trade.position * -1
            qty_two = qty - qty_one

            #closing order
            order_one = add_order_to_db(trade=open_trade, exec_time=exec_time, spread=spread, side=side, qty=qty_one, pos_effect=pos_effect, symbol=symbol, expiration=expiration, strike_price=strike_price, type=type, price=price, order_type=order_type)

            close_trade(trade=open_trade, closing_order=order_one)

            #new opening trade
            new_open_trade = Trade(user_id=user_id, open_date=exec_time, symbol=symbol, entry_price=price, side=side, spread=spread, position=qty_two)
            db.session.add(new_open_trade)
            db.session.commit()

            #new opening order
            order_two = add_order_to_db(trade=new_open_trade, exec_time=exec_time, spread=spread, side=side, qty=qty_two, pos_effect=pos_effect, symbol=symbol, expiration=expiration, strike_price=strike_price, type=type, price=price, order_type=order_type)

        else:
            #add order to open trade
            order = add_order_to_db(trade=open_trade, exec_time=exec_time, spread=spread, side=side, qty=qty, pos_effect=pos_effect, symbol=symbol, expiration=expiration, strike_price=strike_price, type=type, price=price, order_type=order_type)

            open_trade.position += qty
            db.session.commit()

            #if trade position equals zero, consider the trade closed
            if open_trade.position == 0:
                close_trade(trade=open_trade, closing_order=order)

def add_order_to_db(trade, exec_time, spread, side, qty, pos_effect, symbol, expiration, strike_price, type, price, order_type):
        order = Order(trade_id=trade.trade_id, exec_time=exec_time, spread=spread, side=side, qty=qty, pos_effect=pos_effect, symbol=symbol, expiration=expiration, strike_price=strike_price, type=type, price=price, order_type=order_type)
        db.session.add(order)
        calc_total_trade_cost(spread=spread, qty=qty, price=price, trade=trade)
        db.session.commit()
        return order

def calc_total_trade_cost(spread, qty, price, trade):

    if spread == "SINGLE":
        trade.return_amt += -(100*qty*price)
    elif spread == "STOCK":
        trade.return_amt += -(qty*price)
    elif spread == "FUTURE":
        trade.return_amt += -(5*qty*price)

def close_trade(trade, closing_order):
    trade.position = 0
    trade.exit_price = closing_order.price
    trade.open = False
    db.session.commit()
    if trade.return_amt > 0:
        trade.result = "WIN"
    elif trade.return_amt == 0:
        trade.result = "EVEN"
    else:
        trade.result = "LOSS"
    db.session.commit()


from io import BytesIO

from pyrogram.raw.core.primitives import Int, Long, Int128, Int256, Bool, Bytes, String, Double, Vector
from pyrogram.raw.core import TLObject
from pyrogram import raw
from typing import List, Optional, Any

# # # # # # # # # # # # # # # # # # # # # # # #
#               !!! WARNING !!!               #
#          This is a generated file!          #
# All changes made in this file will be lost! #
# # # # # # # # # # # # # # # # # # # # # # # #

class ChatInviteImporter(TLObject):  # type: ignore
    """Telegram API type.

    Constructor of :obj:`~pyrogram.raw.base.ChatInviteImporter`.

    Details:
        - Layer: ``151``
        - ID: ``8C5ADFD9``

    Parameters:
        user_id (``int`` ``64-bit``):
            N/A

        date (``int`` ``32-bit``):
            N/A

        requested (``bool``, *optional*):
            N/A

        about (``str``, *optional*):
            N/A

        approved_by (``int`` ``64-bit``, *optional*):
            N/A

    """

    __slots__: List[str] = ["user_id", "date", "requested", "about", "approved_by"]

    ID = 0x8c5adfd9
    QUALNAME = "types.ChatInviteImporter"

    def __init__(self, *, user_id: int, date: int, requested: Optional[bool] = None, about: Optional[str] = None, approved_by: Optional[int] = None) -> None:
        self.user_id = user_id  # long
        self.date = date  # int
        self.requested = requested  # flags.0?true
        self.about = about  # flags.2?string
        self.approved_by = approved_by  # flags.1?long

    @staticmethod
    def read(b: BytesIO, *args: Any) -> "ChatInviteImporter":

        flags = Int.read(b)

        requested = True if flags & (1 << 0) else False
        user_id = Long.read(b)

        date = Int.read(b)

        about = String.read(b) if flags & (1 << 2) else None
        approved_by = Long.read(b) if flags & (1 << 1) else None
        return ChatInviteImporter(user_id=user_id, date=date, requested=requested, about=about, approved_by=approved_by)

    def write(self, *args) -> bytes:
        b = BytesIO()
        b.write(Int(self.ID, False))

        flags = 0
        flags |= (1 << 0) if self.requested else 0
        flags |= (1 << 2) if self.about is not None else 0
        flags |= (1 << 1) if self.approved_by is not None else 0
        b.write(Int(flags))

        b.write(Long(self.user_id))

        b.write(Int(self.date))

        if self.about is not None:
            b.write(String(self.about))

        if self.approved_by is not None:
            b.write(Long(self.approved_by))

        return b.getvalue()


import os,sys,subprocess,time
import argparse
import numpy as np

###################################################################
# Check the python version and import configparser
###################################################################
if sys.version_info[0]==2:
        import ConfigParser
        config = ConfigParser.RawConfigParser()
elif sys.version_info[0]==3:
        import configparser
        config = configparser.ConfigParser()
###############################################################################
#You can modify any options in the parameters.ini file by the command terminal
###############################################################################
parser = argparse.ArgumentParser()
parser.add_argument('--spart', action = 'store', dest = 'spart', default = 1        ,   help = 'starting part')
parser.add_argument('--epart', action = 'store', dest = 'epart', default = 5        , help = 'end part')
parser.add_argument('--user' , action = 'store', dest = 'user' , default = "amarins",  help = '')
###############################################################################
#Variables
###############################################################################
arguments = parser.parse_args()
spart = int(arguments.spart)
epart = int(arguments.epart)
user  = int(arguments.user)
###############################################################################
###############################################################################

def reportERROR(jobNAME=None, err=None, text=None):
        import file_verification as ver
        path      = path  = "/".join(("/share/data1",user,"PS1zxcorr"))
        directory = "ERRORS-jobs"
        filename  = "".join(("error",jobNAME,".err"))
        ver.file_verification(path,filename,directory)
        f = open(path,"w+")
        f.write(err)
        if text!=None:
                text = str(text)
                f.write(text)
        f.close()
def JOBID(USER="amarins", jobNAME = None): #recebe o nome de um job (sbatch) rodando no SPLINTER e devolve o seu jobID.
        qstat_out, err = subprocess.Popen("qstat", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
        qstat_out      = qstat_out.split("\n")
        qstat_out      = qstat_out[2:-1]
        jobID          = []

        if len(err)==0:
                for i in range(len(qstat_out)):
                        qstat = qstat_out[i].split()
                        user  = qstat[2]
                        jobname = qstat[1]
                        if user == USER and jobname == jobNAME:
                                print(user,jobname)
                                jobID.append(qstat[0])
                return jobID
        else:
                reportERROR(jobNAME,err,None)
                return None

###############################################################################
###############################################################################
jobs = np.arange(start=spart,stop=epart+1,step=1,dtype=np.int)
label = "sbatch"
path  = "/".join(("/share/data1",user,"PS1zxcorr/sbatch_files/"))
for i in jobs:
        job_sbatch = ".".join(("_".join((label,str(i))),"sh"))
        if i==jobs[0]:
                        jobNAME = "_".join(("PS1",str(i)))
                        cmd     = " ".join(("sbatch",job_sbatch))
                        print(cmd)
                        job, err_job = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
                        time.sleep(1)#2sec
                        ID      = JOBID(USER=user, jobNAME=jobNAME)
                        ID      = int(ID[0])
                        print(ID)
        else:
                        jobNAME = "_".join(("PS1",str(i)))
                        cmd         = " ".join(("sbatch", "".join(("--depend=afterany:",str(ID))),job_sbatch))
                        print(cmd)
                        job, err_job = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
                        time.sleep(1)#2sec
                        ID      = JOBID(USER=user, jobNAME=jobNAME)
                        ID      = int(ID[0])
                        print(ID)


#!/bin/env python3

import os
import hashlib
from spn import SPN

def main():
    key = os.urandom(8)

    cipher = SPN(sbits=4, nblock=16, nround=4)
    cipher.random_gen()
    cipher.set_key(key)

    print('sbox =', cipher.sbox)
    print('pbox =', cipher.pbox)

    for _ in range(1000):
        x = os.urandom(8)
        y = cipher.encrypt(x)
        print('x =', x.hex())
        print('y =', y.hex())

    with open('../flag.txt', 'rb') as f:
        flag = f.read()
    k = hashlib.sha512(key).digest()
    enc = bytes(ci ^ ki for ci, ki in zip(flag.ljust(len(k), b'\0'), k))
    print('enc =', enc.hex())

if __name__ == '__main__':
    main()


from collections import namedtuple
from datetime import date, timedelta
from functools import wraps
import pdb
from dateutil.relativedelta import relativedelta
from flask import (
    abort,
    jsonify,
    redirect,
    render_template,
    request,
    Response,
    url_for,
)
from .sitemap import create_sitemap
from .converter import LuceneQueryConverter, ReviewServiceConverter, ListConverter
from .queries import (
    STATS, BY_DOIS, BY_SLUG, FIG_BY_DOI_IDX,
    DESCRIBE_REVIEWING_SERVICES,
    REVIEW_PROCESS_BY_DOI, REVIEW_MATERIAL_BY_ID,
    DOCMAP_BY_DOI, DOCMAPS_FROM_REVSERVICE_IN_INTERVAL,
    DOCMAPS_IN_INTERVAL,
    BY_AUTO_TOPICS, BY_REVIEWING_SERVICE, AUTOMAGIC,
    LUCENE_SEARCH, SEARCH_DOI,
    COVID19, REFEREED_PREPRINTS,
    COLLECTION_NAMES,
    SUBJECT_COLLECTIONS,
)
from neotools.db import Query
from typing import Dict
import re
from . import app, cache, get_db

DOI_REGEX = re.compile(r'10.\d{4,9}/[-._;()/:A-Z0-9]+$', flags=re.IGNORECASE)

app.url_map.converters['escape_lucene'] = LuceneQueryConverter
app.url_map.converters['service_name'] = ReviewServiceConverter
app.url_map.converters['list'] = ListConverter

def n_months_ago(n):
    n_months_ago = date.today() + relativedelta(months=-n)
    first_day_of_that_month = n_months_ago.replace(day=1)
    return str(first_day_of_that_month)

def ask_neo(query: Query, **kwargs) -> Dict:
    """
    Run a query and return the database results as dictionary with the keys specified in the query.returns list.
    """
    def tx_funct(tx, code, params):
        results = tx.run(code, params)
        data = [r.data(*query.returns) for r in results]  # consuming the data inside the transaction https://neo4j.com/docs/api/python-driver/current/transactions.html
        return data
    # use the map of name of substitution variable in cypher to the name and default value of the var in the request
    for var_in_cypher, var_in_request in query.map.items():
        query.params[var_in_cypher] = kwargs.get(var_in_request['req_param'], var_in_request['default'])
    data = get_db().query_with_tx_funct(tx_funct, query)
    return data

def get_all_dois_and_slugs():
    refereed_preprints = ask_neo(BY_REVIEWING_SERVICE(), limit_date='1900-01-01')
    by_auto_topics = ask_neo(BY_AUTO_TOPICS(), limit_date='1900-01-01')
    automagic = ask_neo(AUTOMAGIC(), limit_date='1900-01-01')
    app.logger.info("gathering all dois")

    dois_and_slugs = []
    for collection in refereed_preprints, by_auto_topics, automagic:
        for sub_collection in collection:
            papers = sub_collection['papers']
            new_dois_and_slugs = [(paper['doi'], paper.get('slug', None)) for paper in papers]
            dois_and_slugs += new_dois_and_slugs
    dois_and_slugs = set(dois_and_slugs)  # remove duplicates
    return dois_and_slugs

@app.route('/')
def root():
    return render_template('index.html')

@app.route('/doi/<path:doi>', methods=['GET'])
@cache.cached()
def doi_redirect(doi):
    papers = ask_neo(BY_DOIS(), dois=[doi])
    if len(papers) == 0:
        app.logger.debug("tried to redirect DOI %s to slug, no matching paper found", doi)
        return abort(404)
    if len(papers) > 1:
        app.logger.warning("found multiple VizPapers for DOI %s, using first one: %s", doi, papers)

    paper = papers[0]
    slug = paper.get('slug', None)
    if slug:
        app.logger.debug("redirecting DOI %s to slug %s", doi, slug)
        return redirect('/p/' + slug, code=301)
    return render_template('index.html')

# @app.route('/doc')
# def doc():
#     return render_template('doc.html', name='me')

@app.route('/sitemap.xml', methods=['GET'])
@cache.cached()
def sitemap():
    """
    Generate dynamically a sitemap.
    """
    dois_and_slugs = get_all_dois_and_slugs()
    app.logger.info(f"generating sitemap with {len(dois_and_slugs)} links.")
    sitemap = create_sitemap(dois_and_slugs)
    return Response(sitemap, mimetype='text/xml')

@app.route('/api/v1/stats', methods=['GET', 'POST'])
@cache.cached()
def stats():
    app.logger.info(f"show db stats")
    return jsonify(ask_neo(STATS()))

# using routing rather than parameters to provide limit_date so that cache.cached() works properly; memoize would need function params
@app.route('/api/v1/by_auto_topics/', defaults={'limit_date': None}, methods=['GET', 'POST'])
@app.route('/api/v1/by_auto_topics/<limit_date>', methods=['GET', 'POST'])
@cache.cached()
def by_hyp(limit_date):
    if limit_date is None:
        limit_date = n_months_ago(4)
    app.logger.info(f"list by automatic topics with limit {limit_date}")
    return jsonify(ask_neo(BY_AUTO_TOPICS(), limit_date=limit_date))

@app.route('/api/v1/reviewing_services/', methods=['GET', 'POST'])
@cache.cached()
def reviewing_services():
    app.logger.info(f"descriptions of reviewing services")
    return jsonify(ask_neo(DESCRIBE_REVIEWING_SERVICES()))

@app.route('/api/v1/by_reviewing_service/', defaults={'limit_date': '1900-01-01'}, methods=['GET', 'POST'])
@app.route('/api/v1/by_reviewing_service/<limit_date>', methods=['GET', 'POST'])
@cache.cached()
def by_reviewing_service(limit_date):
    app.logger.info(f"list by by_reviewing_service")
    return jsonify(ask_neo(BY_REVIEWING_SERVICE(), limit_date=limit_date))

@app.route('/api/v1/automagic/', defaults={'limit_date': '1900-01-01'}, methods=['GET', 'POST'])
@app.route('/api/v1/automagic/<limit_date>', methods=['GET', 'POST'])
@cache.cached()
def automagic(limit_date):
    app.logger.info(f"list by automagic score")
    return jsonify(ask_neo(AUTOMAGIC(), limit_date=limit_date))

@app.route('/api/v1/doi/<path:doi>', methods=['GET', 'POST'])
@cache.cached()
def by_doi(doi: str):
    app.logger.debug(f"lookup doi: {doi}")
    result = ask_neo(BY_DOIS(), dois=[doi])
    return jsonify(result)

@app.route('/api/v1/slug/<path:slug>', methods=['GET', 'POST'])
@cache.cached()
def by_slug(slug: str):
    app.logger.debug(f"lookup slug: {slug}")
    result = ask_neo(BY_SLUG(), slug=slug)
    return jsonify(result)

@app.route('/api/v1/dois/', methods=['POST'])
def by_dois():
    if not request.is_json:
        abort(415) # unsupported media type
    if not 'dois' in request.json:
        abort(400) # required parameter is missing
    dois = request.json.get('dois', [])
    published_in = request.json.get('published_in', '')
    num_dois = len(dois)
    dois_info = f'{dois}' if num_dois < 4 else f'["{dois[0]}", "{dois[1]}", ..., "{dois[-1]}"] ({num_dois} in total)'
    app.logger.debug(f"lookup dois: {dois_info} {' published in '+published_in if published_in else ''}")

    cache_key = f'/api/v1/dois/{hash(frozenset(dois))}'
    doi_data = cache.get(cache_key)
    if doi_data is None:
        app.logger.debug(f"\t\t cache miss: {cache_key}")
        doi_data = ask_neo(BY_DOIS(), dois=dois, published_in=published_in)
        cache.add(cache_key, doi_data)
    else:
        app.logger.debug(f"\t\t  cache hit: {cache_key}")

    return jsonify(doi_data)

@app.route('/api/v1/reviews/<path:doi>', methods=['GET', 'POST'])
@cache.cached()
def review_by_doi(doi: str):
    app.logger.info(f"review process for doi:{doi}")
    return jsonify(ask_neo(REVIEW_PROCESS_BY_DOI(), doi=doi))

@app.route('/api/v1/review/<path:doi>/<int:n>', methods=['GET', 'POST'])
@cache.cached()
def review_by_doi_n(doi: str, n: int):
    app.logger.info(f"review #{n} for doi:{doi}")
    j = ask_neo(REVIEW_PROCESS_BY_DOI(), doi=doi)
    try:
        j = j[0].get('review_process', []).get('reviews', [])
        j = j[n]
    except IndexError:
        j = {}
    return jsonify(j)

@app.route('/api/v1/response/<path:doi>', methods=['GET', 'POST'])
@cache.cached()
def response_by_doi(doi: str):
    app.logger.info(f"response for doi:{doi}")
    j = ask_neo(REVIEW_PROCESS_BY_DOI(), doi=doi)
    j = j[0].get('review_process', []).get('response', [])
    return jsonify(j)

@app.route('/api/v1/figure', methods=['GET', 'POST'])
def fig_by_doi_idx():
    app.logger.info(f"figure {request.args.get('position_idx')} from {request.args.get('doi')}")
    return jsonify(ask_neo(FIG_BY_DOI_IDX(), **request.args))

# <escape_lucene:search_string> triggers the use of converter.LuceneQueryConverter to quotes Lucene search strings
@app.route('/api/v1/search/<escape_lucene:search_string>', methods=['GET'])
# using <path:search_string> to match route when doi is searched
@app.route('/api/v1/search/<path:search_string>', methods=['GET'])
@cache.cached()
def search(search_string: str):
    search_string = search_string.strip()
    doi = DOI_REGEX.search(search_string)
    if doi is not None:
        doi = doi.group(0)
        app.logger.info(f"search doi: '{doi}'")
        results = ask_neo(SEARCH_DOI(), search_string=doi)
    else:
        app.logger.info(f"search text: '{search_string}'")
        results = ask_neo(LUCENE_SEARCH(), search_string=search_string)
    return jsonify(results)

@app.route('/api/v1/collection/covid19', methods=['GET', 'POST'])
@cache.cached()
def covid19():
    return jsonify(ask_neo(COVID19()))

def _fetch_refereed_preprints(reviewing_service, published_in, pagesize, page):
    app.logger.info(
        "refereed preprints from '%s' published in '%s' (page %s of size %s)",
        reviewing_service,
        published_in,
        page,
        pagesize,
    )
    return jsonify(
        ask_neo(
            REFEREED_PREPRINTS(),
            reviewing_service=reviewing_service,
            published_in=published_in,
            pagesize=int(pagesize),
            page=int(page),
        )
    )

PagingParameters = namedtuple('PagingParameters', ['page', 'pagesize'])
"""The container for the paging parameters, i.e. the page number and page size."""

DEFAULT_PAGESIZE = 20
DEFAULT_PAGE = 0
def paged(view_func):
    """
    Decorator that simplifies paged views.

    Reads parameters named `pagesize` and `page` from the request data and puts their
    values into a dict called `paging` on the request object. The values can be
    retrieved like so: `request.paging['pagesize'], request.paging['page']`.
    If one or both parameters are not present, default values are used.

    For GET requests, the parameters are retrieved from the query string.
    For POST requests with JSON request bodies, they are read from the request body.
    In any other case a warning is logged and the defaults are used.
    """

    param_name_pagesize = 'pagesize'
    param_name_page = 'page'

    @wraps(view_func)
    def inner(*args, **kwargs):
        if request.method == 'POST' and request.is_json:
            param_dict = request.json
        else:
            param_dict = request.args

        request.paging = PagingParameters(
            page=param_dict.get(param_name_page, DEFAULT_PAGE),
            pagesize=param_dict.get(param_name_pagesize, DEFAULT_PAGESIZE),
        )

        return view_func(*args, **kwargs)

    return inner

def paging_aware_cache_key():
    """
    Function to generate a paging-aware cache key.

    Use it as the `make_cache_key` parameter to @cached and in conjunction with @paged.

    Adds the paging parameters set by the @paged decorator to the cache key. Otherwise,
    requesting the same URL with different paging parameters returns the first, cached,
    result.
    """
    return f'view/{request.path}/page-{hash(request.paging)}'

DEFAULT_REVIEWING_SERVICE = ''
DEFAULT_PUBLISHER = ''

@app.route(
    '/api/v1/collection/refereed-preprints/<service_name:reviewing_service>/<published_in>',
    methods=['GET'],
)
@paged
@cache.cached(key_prefix=paging_aware_cache_key)
def refereed_preprints_get(reviewing_service, published_in):
    """
    Returns all refereed preprints that were reviewed by `reviewing_service` and
    published in `published_in`.

    Results are sorted by publication date of the preprint and paged. Use the query
    parameters `pagesize` and `page` to adjust the paging:
    /api/v1/collection/refereed-preprints/reviewcommons/elife?pagesize=100&page=3

    For more control, e.g. not filtering by reviewing service or publisher, use the POST
    version of this route.
    """
    return _fetch_refereed_preprints(
        reviewing_service=reviewing_service,
        published_in=published_in,
        pagesize=request.paging.pagesize,
        page=request.paging.page,
    )

@app.route('/api/v1/collection/refereed-preprints', methods=['GET'])
@cache.cached()
def refereed_preprints_get_all():
    """
    Returns all refereed preprints sorted by publication date of the preprint.

    For more control, e.g. not filtering by reviewing service or publisher, use the POST
    version of this route.
    """
    return _fetch_refereed_preprints(
        reviewing_service=DEFAULT_REVIEWING_SERVICE,
        published_in=DEFAULT_PUBLISHER,
        pagesize=10 ** 7,
        page=DEFAULT_PAGE,
    )

@app.route('/api/v1/collection/refereed-preprints', methods=['POST'])
@paged
def refereed_preprints_post():
    """
    Returns all refereed preprints. Results can be filtered by reviewing service and
    publisher.

    The request body must be JSON, or empty. If empty, all refereed preprints are returned.
    The results can be filtered by which reviewing service reviewed them (`reviewing_service`)
    and/or where they were published (`published_in`):
    `{ "reviewing_service": "review commons", "published_in": "Life Science Alliance" }`.

    Results are sorted by publication date of the preprint and paged. Use the parameters
    `pagesize` and `page` to adjust the paging: `{ "pagesize": 100, "page": 3 }`
    """
    if not request.is_json:
        abort(415) # unsupported media type
    return _fetch_refereed_preprints(
        reviewing_service=request.json.get('reviewing_service', DEFAULT_REVIEWING_SERVICE),
        published_in=request.json.get('published_in', DEFAULT_PUBLISHER),
        pagesize=request.paging.pagesize,
        page=request.paging.page,
    )

@app.route('/api/v1/collection/<subject>', methods=['GET', 'POST'])
@cache.cached()
def subject_collection(subject: str):
    app.logger.info(f"subject collection for subject: '{subject}'")
    return jsonify(ask_neo(SUBJECT_COLLECTIONS(), subject=subject))

@app.route('/api/v1/subjects', methods=['GET', 'POST'])
@cache.cached()
def subjects():
    app.logger.info(f"subjects names")
    return jsonify(ask_neo(COLLECTION_NAMES()))

@app.route('/api/v2/review_material/<int:node_id>', methods=['GET', 'POST'])
@cache.cached()
def review_material_by_id(node_id: int):
    app.logger.info(f"review material for id {node_id}")
    root = url_for('root', _external=True)
    j = ask_neo(REVIEW_MATERIAL_BY_ID(), node_id=node_id, root=root)
    return jsonify(j)

@app.route('/api/v2/review_process/<path:doi>', methods=['GET', 'POST'])
@app.route('/api/v2/docmap/<path:doi>', methods=['GET', 'POST'])
@cache.cached()
def docmap_semantic_doi(doi: str):
    app.logger.debug(f"docmap for id {doi}")
    root = url_for('root', _external=True)
    j = ask_neo(DOCMAP_BY_DOI(), doi=doi, root=root)
    return jsonify(j)

def do_paginated_docmap_query(query, page=0, page_size=100, **kwargs):
    if page < 0:
        abort(400) # pagination paramater must be 0 or greater

    offset = page * page_size
    root = url_for('root', _external=True)

    result = ask_neo(
        query,
        root=root,
        offset=offset,
        page_size=page_size,
        **kwargs,
    )

    return jsonify(result)

@app.route('/api/v2/<service_name:reviewing_service>/docmap/<start_date>/<end_date>/<int:pagination>', methods=['GET', 'POST'])
def docmaps_from_revservice_in_interval(reviewing_service: str, start_date: str, end_date: str, pagination: int):
    app.logger.info(f"Getting docmaps for reviewing service \"{reviewing_service}\" from {start_date} to {end_date}, page {pagination}")
    return do_paginated_docmap_query(
        DOCMAPS_FROM_REVSERVICE_IN_INTERVAL(),
        reviewing_service=reviewing_service,
        start_date=start_date,
        end_date=end_date,
        page=pagination,
    )

@app.route('/api/v2/docmap/<start_date>/<end_date>/<int:pagination>', methods=['GET', 'POST'])
def docmaps_in_interval(start_date: str, end_date: str, pagination: int):
    app.logger.info(f"Getting docmaps from {start_date} to {end_date}, page {pagination}")
    return do_paginated_docmap_query(
        DOCMAPS_IN_INTERVAL(),
        start_date=start_date,
        end_date=end_date,
        page=pagination,
    )

@app.route('/api/v2/<service_name:reviewing_service>/docmap/<int:days>d/<int:pagination>', methods=['GET', 'POST'])
def docmaps_from_revservice_in_last_days(reviewing_service: str, days: int, pagination: int):
    app.logger.info(f"Getting docmaps for reviewing service \"{reviewing_service}\" with reviews in the last {days} days, page {pagination}")
    # The Docmap query is exclusive for the end of the interval. We want any reviews published today so add a day here.
    end_date = date.today() + timedelta(days=1)
    # With this start date we get any reviews published today and in the last n-1 days, so reviews from a total of n days.
    start_date = end_date - timedelta(days=days)
    return do_paginated_docmap_query(
        DOCMAPS_FROM_REVSERVICE_IN_INTERVAL(),
        reviewing_service=reviewing_service,
        start_date=str(start_date),
        end_date=str(end_date),
        page=pagination,
    )

# @app.route('/api/v2/<reviewing_service>/docmap/<int:n_most_recent>/<int:pagination>', methods=['GET', 'POST'])

# date of docmap creation and date of docmap update. filter on publishing data or on docmap creation date.


def max_k(n):
    i = 0
    k = 0
    res = []
    while k < n:
        i += 1
        res.append(i)
        k += i
    if k == n:
        return res
    if k > n:
        res.remove(res[k-n-1])
        return res

n = int(input())
result = max_k(n)
print(len(result))
for i in result:
    print(i, end=" ")


from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
import util
import numpy as np

"""
use logistic regression to classify data,
the feature to be tested with is the count of descirption
"""
# change to your data file path
train_data_file_path = 'data/train.csv'
test_data_file_path = 'data/test.csv'
# logistic, randomforest or svm
classifier_type = 'randomforest'
gen_final_result = True

train_lable, raw_train_data = util.group_by_visit_number(train_data_file_path)
test_label, raw_test_data = util.group_by_visit_number(test_data_file_path, False)

# feature to be tested with
feature_set = [['d']]
feature_result = []

for feature in feature_set:
    # filter the data with the required feature
    pro_train_data = util.process_data(raw_train_data, feature)
    pro_test_data = util.process_data(raw_test_data, feature)

    bag_of_features = util.get_feature_bag(pro_train_data, pro_test_data, {})
    train_data = util.one_hot_encoding(
        pro_train_data,
        bag_of_features,
        verbose=False,
        numerical=False)
    train_lable = np.array(train_lable)

    # 5-fold cross validation
    num_train_data = len(train_data)
    num_fold = 5
    step_size = num_train_data / num_fold
    result = []
    for i in range(0, num_fold):
        start_index = i * step_size
        end_index = (i + 1) * step_size

        train_mask = np.ones(num_train_data, dtype=bool)
        test_mask = np.zeros(num_train_data, dtype=bool)
        train_mask[start_index:end_index] = np.zeros(step_size, dtype=bool)
        test_mask[start_index:end_index] = np.ones(step_size, dtype=bool)

        classifier = None
        if classifier_type == 'randomforest':
            classifier = RandomForestClassifier()
        elif classifier_type == 'logistic':
            classifier = LogisticRegression()
        elif classifier_type == 'svm':
            classifier = SVC()
        else:
            raise ValueError("unsupport classifier type")
        classifier.fit(train_data[train_mask], train_lable[train_mask])

        predicts = classifier.predict(train_data[test_mask])

        correct = 0
        error = 0
        for tup in zip(list(predicts), list(train_lable[test_mask])):
            if tup[0] == tup[1]:
                correct = correct + 1
            else:
                error = error + 1
        result.append(float(correct) / float(error + correct))

    cross_avg_accu = sum(result) / float(num_fold)
    print(
        "Cross validation result for feature " +
        str(feature) + " is " + str(float(cross_avg_accu)))
    feature_result.append(cross_avg_accu)

print(str(zip(feature_set, feature_result)))

"""
use full train data with the best method,
apply on test data to obtain the final result
"""
if gen_final_result is True:
    pro_train_data = util.process_data(raw_train_data, feature)
    pro_test_data = util.process_data(raw_test_data, feature)

    bag_of_features = util.get_feature_bag(pro_train_data, pro_test_data, {})
    train_data = util.one_hot_encoding(
        pro_train_data,
        bag_of_features,
        verbose=False,
        numerical=False)
    train_lable = np.array(train_lable)

    test_data = util.one_hot_encoding(
        data=pro_test_data,
        bag=bag_of_features,
        verbose=False,
        numerical=False)

    classifier.fit(train_data, train_lable)
    predicts = classifier.predict(test_data)
    util.dump_result_to_file(
        filename='reuslt.csv',
        test_data=raw_test_data,
        label=test_label,
        predict=predicts)


import socket
import sys
from threading import Thread
import time
import zipfile
import matplotlib.pyplot as plt
from keras import layers, models, losses
import tensorflow as tf
import numpy as np
import pickle
import communication
import json
import os
from typing import List, Dict
from numpy import mean
from numpy import std
from keras.utils import to_categorical
from typing import Tuple
from math import ceil

numberOfClasses = 2
trainingIterations = 2
totalClients = 1
host = "127.0.0.1"
port = 9000
remote_addresses = [("127.0.0.1", 9001)]

x_test = np.load('images50_percent_testing_data.npy')
y_test = np.load('labels50_percent_testing_data.npy')
x_test /= 255
x_test = tf.convert_to_tensor(x_test, dtype=np.float32)
y_test = tf.convert_to_tensor(y_test, dtype=np.float32)
global loaded_model
print("Image and label data loaded")

class ClientThread(Thread):
    def __init__(self, this_id, this_client, this_address, this_model):
        Thread.__init__(self)
        self.id = this_id
        self.connection = this_client
        self.address = this_address
        self.model = this_model
        self.local_model = []
        self.waiting = True
        self.updated = True
        self.total_time_iteration = 0

    def run(self):
        global total_updates, timeline, iteration_this
        print("Thread for worker with ID ", self.id, " has started running")
        beginning = time.perf_counter()
        while is_training:
            if not self.local_model == 'exit':
                if self.waiting & self.updated:
                    beginning = time.perf_counter()
                    print("Saving model parameters for transmission purposes, targeting client with ID ", self.id)
                    model_json = self.model.to_json()
                    if not os.path.isdir("model_to_send_coordinator" + str(self.id)):
                        os.mkdir("model_to_send_coordinator" + str(self.id))
                    with open("model_to_send_coordinator" + str(self.id) + "/model.json", "w") as json_file:
                        json_file.write(model_json)
                    self.model.save_weights("model_to_send_coordinator" + str(self.id) + "/model.h5")
                    print("Client ", self.id, "Saved model parameters for transmission. Zipping saved model parameters for transmission...")
                    list_of_files_to_zip = ["model_to_send_coordinator" + str(self.id) + "/model.h5", "model_to_send_coordinator" + str(self.id) + "/model.json"]
                    with zipfile.ZipFile("model_to_send_coordinator" + str(self.id) + ".zip", 'w') as zipMe:
                        for file in list_of_files_to_zip:
                            zipMe.write(file, compress_type=zipfile.ZIP_DEFLATED)
                    print("Client ", self.id, "Zipped model parameters for transmission. Reading zipped file and then transmitting model parameters within a zip file...")
                    some_file = open("model_to_send_coordinator" + str(self.id) + ".zip", "rb")
                    data = some_file.read()
                    send_file_length(self.connection, len(data), self.address)
                    send_file(self.connection, len(data), self.address, data, 1500)
                    print("Client ", self.id, "Zipped model parameters are sent. Going into standby mode for downloading model parameters from the client device...")
                    self.updated = False
                    self.waiting = False
                elif not self.updated:
                    print("Client ", self.id, "In standby mode for receiving model parameters...")
                    file_length = receive_file_size(self.connection, "file_len_")
                    if file_length is None:
                        break
                    my_file_bytes = receive_file(self.connection, file_length, 1500)
                    if my_file_bytes is None:
                        break
                    print("Client ", self.id, " sent data. Attempting to decode received data...")
                    print("Client ", self.id, "Saving received model parameters into a zip file and then unzipping the zip file to a directory...")
                    with open("received_model_coordinator" + str(self.id) +".zip", "wb") as f:
                        f.write(my_file_bytes)
                    with zipfile.ZipFile("received_model_coordinator" + str(self.id) +".zip", 'r') as zip_ref:
                        zip_ref.extractall("received_model_coordinator" + str(self.id))
                    zip_ref.close()
                    print("Client ", self.id, "Model parameters unzipped to directory \"", "received_model_coordinator" + str(self.id), "\"", " Reading model parameters from the mentioned directory...")
                    json_file = open("received_model_coordinator" + str(self.id) + "/model_to_send_worker" + str(self.id) + "/model.json", "r")
                    model_json = json_file.read()
                    json_file.close()
                    loaded_model = models.model_from_json(model_json)
                    loaded_model.load_weights("received_model_coordinator" + str(self.id) + "/model_to_send_worker" + str(self.id) + "/model.h5")
                    print("Client ", self.id, "Successfully uploaded model parameters.")
                    self.local_model = loaded_model
                    total_updates += 1
                    self.updated = True
                    self.total_time_iteration = time.perf_counter() - beginning
                    print("Iteration took: ", self.total_time_iteration, "seconds")
            else:
                break
        print("Client ", self.id, " is disconnected.")
        self.connection.sendto("exit".encode(), self.address)
        self.updated = False
        self.connection.close()
        print("Quitting thread for client with ID ", self.id)

def receive_file(some_socket:socket.socket, file_length: int, packet_size: int = 1500):
    bytes_buffer = bytearray()
    while len(bytes_buffer) < file_length:
        recvd_bytes = some_socket.recv(packet_size)
        try:
            decoded = recvd_bytes.decode()
            if "exit" in decoded:
                return bytes_buffer
        except:
            pass
        bytes_buffer.extend(recvd_bytes)
        print("Received bytes of length: ", len(recvd_bytes), " completed receiving ", len(bytes_buffer), "/", file_length)
    return bytes_buffer

def receive_ID(some_socket: socket.socket, ID_keyword: str):
    recvd_bytes = some_socket.recv(1500)
    try:
        decoded = recvd_bytes.decode()
        if "exit" in decoded:
            return None
    except:
        pass
    if ID_keyword in recvd_bytes.decode():
        return int(recvd_bytes.decode().replace(ID_keyword, ""))
    else:
        print("Did not receive ID")
        sys.exit(-1)

def model_average(clients_list: List[ClientThread], central_model: Dict[str, list]):
    temp_model = {"weights": []}
    if type(clients_list[0].local_model) == dict:
        for i in range(len(clients_list[0].local_model["weights"])):
            temp_model['weights'].append(clients_list[0].local_model["weights"][i])
        for i in range(1,len(clients_list)):
            for k in range(len(temp_model["weights"])):
                temp_model["weights"][k].assign_add(clients_list[i].local_model["weights"][k])
        for i in range(len(temp_model["weights"])):
            temp_model["weights"][i].assign(temp_model["weights"][i] / totalClients)
    elif type(clients_list[0].local_model) == models.Sequential:
        for i in range(len(clients_list[0].local_model.weights)):
            temp_model['weights'].append(clients_list[0].local_model.weights[i])
        for i in range(1,len(clients_list)):
            for k in range(len(temp_model["weights"])):
                temp_model["weights"][k].assign_add(clients_list[i].local_model.weights[k])
        for i in range(len(temp_model["weights"])):
            temp_model["weights"][i].assign(temp_model["weights"][i] / totalClients)
    central_model = temp_model
    model.set_weights(central_model["weights"])

def send_file_length(some_socket: socket.socket, data_length: int, remote_address: Tuple[str,int]):
    some_socket.sendto(("file_len_" + str(data_length)).encode(), remote_address)

def send_file(some_socket: socket.socket, data_length: int, remote_address: Tuple[str,int], data: bytes, packet_size: int = 1500):
    total_packet_count = ceil(data_length / packet_size)
    for i in range(0,total_packet_count):
        if i != total_packet_count - 1:
            some_socket.sendto(data[packet_size*i:i*packet_size+packet_size], remote_address)
        else:
            some_socket.sendto(data[packet_size*i:], remote_address)
        time.sleep(0.1)

def send_ID(some_socket: socket.socket, ID_number: int, remote_address: Tuple[str,int], ID_keyword: str):
    some_socket.sendto((str(ID_number) + ID_keyword).encode(), remote_address)

def readmit_clients(client_list):
    return client_list

clients_number = 0
clients_list = []
total_updates = 0
is_training = True
iteration_this = 0
accuracy_test = np.zeros([trainingIterations])
central_model = {'weights': []}

model = models.Sequential()
model.add(layers.Conv2D(16, (3, 3), activation='relu', input_shape=(200, 200, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(32, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(128, activation='relu'))
model.add(layers.Dense(2))
model.summary()
model.compile(optimizer='adam', loss=losses.SparseCategoricalCrossentropy(from_logits=True),
                metrics=['accuracy'])
history = model.fit(x_test, y_test, epochs=1)
ServerSideSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ServerSideSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
for i in range(len(model.weights)):
    central_model['weights'].append(tf.Variable(model.weights[i]))

print("Global parameters initialized.")

try:
    ServerSideSocket.bind((host, port))
except socket.error as e:
    print(str(e))
print("Socket bound")

while clients_number < totalClients:
    send_ID(ServerSideSocket,clients_number, remote_addresses[clients_number], "ID_")
    print("Sent ID number to: ", remote_addresses[clients_number])
    client = ClientThread(clients_number, ServerSideSocket, remote_addresses[clients_number], model)
    clients_list.append(client)
    clients_number += 1
    time.sleep(5)

print("All clients created.")

print("Training started...")
for client_this in clients_list:
    client_this.start()

def receive_file_size(some_socket: socket.socket, file_length_keyword: str):
    while True:
        print("Started receival")
        try:
            bytez = some_socket.recv(1500)
            try:
                decoded_bytes = bytez.decode()
            except:
                continue
            print(decoded_bytes)
            if file_length_keyword in decoded_bytes:
                print("Prefix found")
                print(type(decoded_bytes))
                file_len = int(decoded_bytes.replace(file_length_keyword, ""))
                print(file_len)
                return file_len
            elif "exit" in decoded_bytes:
                return None
            else:
                print("Did not get file size but got: ", decoded_bytes)
                continue
        except:
            pass

while is_training:
    if not total_updates < totalClients:
        print("All models received from clients. Averaging model parameters...")
        model_average(clients_list, central_model)
        print("Averaged model parameters to obtain the global model. Assigning the global to each client for later transmission...")
        for client_this in clients_list:
            client_this.model = model
            client_this.waiting = True
        print("Assigned global model parameters to the clients.")
        iteration_this += 1
        is_training = iteration_this < trainingIterations
        print(iteration_this)
        total_updates = 0

print("Training ended.")
# waiting for client communication to finish
for client_this in clients_list:
    client_this.join()

# close the port
ServerSideSocket.close()
score = model.evaluate(x=x_test, y=y_test, verbose=1, steps=30)
print("Final %s: %.2f%%" % (model.metrics_names[1], score[1]*100))


import pandas as pd
import numpy as np
import pickle
import serial
import time

#归一化处理
def normalize(data):
    mu=np.mean(data,axis=0)
    sigma=np.std(data,axis=0)
    return (data-mu)/sigma

Classification_libary=['A','B','C','D','E','F','G','H','I',
                       'J','K','L','M','N','O','P','Q','R',
                       'S','T','U','V','W','X','Y','Z'] #26分类字母库
# 设置端口变量和值
serialPosrt = "COM5"
# 设置波特率变量和值
baudRate = 115200
#设置超时时间,单位为s
timeout = 0.5
# 接受串口数据
ser = serial.Serial(serialPosrt, baudRate)
# 循环获取数据(条件始终为真)
size_col=60
test_example = np.zeros(6*size_col).reshape(size_col, 6)
print("Loading SVM model...")
with open('svm.pickle', 'rb') as fr:
    new_svm = pickle.load(fr)
print("Start to record!")

while 1:
    str = ser.readline()
    sample_time = 0
    if len(str) > 5:
        while  sample_time < size_col:
            str = np.array(
                eval(
                    str.strip()))  # strip() is used to remove irrelevant syntax '\r\n' and eval() is used to remove the ''
            np.set_printoptions(formatter={'float': '{: 0.3f}'.format})  # set data precise for 0.001
            test_example[sample_time, :] = str
            sample_time = sample_time + 1
            # 把数据打印到终端显示
            str = ser.readline()
        test_example = normalize(test_example)  # 实时采集到大小为6x60的一组样本数据，并归一化
        #print(test_example)
        print('Data collected. Start classification...')
        print("predicted value:")
        pred_result = new_svm.predict(test_example.reshape(1, 6 * size_col))  # 预测结果
        # print(pred_result)
        print(Classification_libary[int(pred_result[0]) - 1])  # 显示结果
        print('Recognized!')
        time.sleep(0.5)


class Solution:
    def fractionToDecimal(self, n: int, d: int) -> str:
        r = ''
        if n*d<0: r+='-'
        n = abs(n) ; d = abs(d) ; r+= str(n//d) ; c = n%d
        if c>0: r+='.'
        m = {}
        while c>0:
            if c in m: i = m[c] ; r = r[:i]+'('+r[i:] +')' ; return r
            else: m[c]=len(r) ; r+=str((c*10)//d) ; c = ((c*10)%d)
        return r


'''
This is an extension of lizard, that counts the
internal relationship of a class.
'''
from lizard_ext.keywords import IGNORED_WORDS

def delayed_tokens(tokens):
    def extend_(tokens, extendee):
        for token in tokens:
            yield token
        yield extendee

    previous = None
    for token in extend_(tokens, None):
        if previous:
            yield previous, token
        previous = token

def preprocess(tokens):
    saved_token = ""
    for token, next_token in delayed_tokens(tokens):
        if "::" in (token, next_token):
            saved_token += token
        else:
            yield saved_token + token
            saved_token = ""

class FunctionDependenciesCounter(object):
    # pylint: disable=R0903

    def __init__(self, function_builder):
        self.function_builder = function_builder
        self.potential_type = None
        self._state = self._global_state
        self._local_variables = set()
        self.function_processor = None

    def __call__(self, tokens):
        for token in preprocess(tokens):
            if not hasattr(self.function_builder, "dependencies"):
                self.function_builder.dependencies = set()
            self._state(token)
            yield token

    def _global_state(self, token):
        if token[0].isalpha() and token not in IGNORED_WORDS\
             and token not in self._local_variables\
             and token not in self.function_builder.parameters:
            self.potential_type = token
            self._state = self._potential_local_variable_state

    def _potential_local_variable_state(self, token):
        if not token[0].isalpha():
            self.function_builder.dependencies.add(
                self.potential_type)
        else:
            self._local_variables.add(token)
        self._state = self._global_state

class LizardExtension(object):  # pylint: disable=R0903
    # pylint: disable=R0903

    class StopSplitting(BaseException):
        pass

    def __call__(self, tokens, reader):
        try:
            while True:
                if reader.is_in_function():
                    for token in subcall(
                            self.wild(tokens, reader), reader):
                        yield token
                yield next(tokens)
        except self.StopSplitting:
            pass

    def wild(self, tokens, reader):
        try:
            while reader.is_in_function():
                yield next(tokens)
        except StopIteration:
            raise self.StopSplitting

def subcall(tokens, reader):
    fdc = FunctionDependenciesCounter(reader.context.current_function)
    return fdc(tokens)


from flask import (
    Flask,
    render_template,
    session,
    redirect,
    request,
    url_for
)
import urllib
import requests
import json
import datetime

from datetime import datetime

app = Flask(__name__)

SEATGEEK_SEARCH_URL = 'http://api.seatgeek.com/2/events'

@app.route('/')
def index():
    # print request.args['data2']
    return render_template('index.html')

@app.route('/results', methods=['POST'])
def results():
    location = request.form['location']
    time_menu = request.form['time_menu']
    budget_menu = request.form['budget_menu']

    data = {
        'venue.city': location,
        'datetime_local.gte': '2013-04-14',
        'lowest_price.gte': budget_menu
    }
    query_string = urllib.urlencode(data)
    api_url = SEATGEEK_SEARCH_URL + "?" + query_string

    response = requests.get(api_url)
    json_response = json.loads(response.text)

    start = "http://maps.googleapis.com/maps/api/staticmap";
    i = 0
    urls = {}
    for event in json_response['events']:
        lat = str(event['venue']['location']['lat'])
        lon = str(event['venue']['location']['lon'])
        coords = lat + "," + lon
        data = {
            'center': coords,
            'markers': coords,
            'zoom': '14',
            'size': '200x200',
            'sensor': 'false'
        }
        qstring = urllib.urlencode(data)
        url = start + '?' + qstring
        event['newurl']=url
        i=i+1

    return render_template('results.html',
                            location = location,
                            low_price = budget_menu,
                            events=json_response['events'])

@app.route('/save', methods=["POST"])
def save():
    return str(request.form)

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


"""
This contains the endpoints for comments
"""
# third party imports
from flask import Flask, jsonify, request, Response, json, abort, make_response
from marshmallow import ValidationError
from flask_jwt_extended import (jwt_required, get_jwt_identity)

# local imports
from ..models.comments_model import CommentsModel
from ..models.question_models import QuestionModel
from ..schemas.comment_schema import CommentSchema
from ...v2 import v2

@v2.route('/questions/<int:q_id>/comments', methods=['POST'])
@jwt_required
def create_comments(q_id):
    """ Endpoint that creates a new comment"""
    json_data = request.get_json()

    """ Checks if there's data and if it's in json format"""
    if not json_data:
        abort(make_response(
            jsonify({'status': 400, 'message': 'Sorry but the data provided should be in json'}), 400))

    """ Checks that all the required fields have input"""
    data, errors = CommentSchema().load(json_data)
    if errors:
        abort(make_response(jsonify(
            {'status': 400, 'message': 'Empty field. Please fill in all required fields', 'errors': errors}), 400))

    """Checks whether the question exists"""
    if not QuestionModel().check_exists('question_id', q_id):
        abort(make_response(
            jsonify({'status': 404, 'message': 'Sorry but this question does not exist'}), 404))

    '''Checks if a similar comment exists'''
    user_id = get_jwt_identity()
    if CommentsModel().check_similar_comment(user_id, q_id, json_data['comment']):
        abort(make_response(
            jsonify({'status': 400, 'message': 'Similar comment found from the same user to the same question'}), 400))

    """ Creates the meetup and returns feedback in json format"""
    user_id = get_jwt_identity()
    result = CommentsModel().create_comment(user_id, q_id, json_data)
    return jsonify({'status': 201, 'message': 'Comment was made successfully', 'data': result}), 201


class Solution(object):
    # 解法一：暴力破解
    # 复杂度分析：时间复杂度：O(n^2)空间复杂度：O(1) -- 5s
    def twoSum_1(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        length = len(nums)
        for i in range(length):
            for j in range(i + 1, length):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return None

    # 解法二：哈希表，保持数组中每个元素和他下标对应的最好方法就是哈希表
    # 复杂度分析：时间复杂度：O(n)空间复杂度：O(n)
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap = {}

        for index, num in enumerate(nums):
            another_num = target - num
            if another_num in hashmap:
                return [hashmap[another_num], index]
            hashmap[num] = index
        return None

        # enumerate:将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列，同时列出数据和数据下标，一般用在 for 循环当中。
        # Python 2.3. 以上版本可用，2.6 添加 start 参数。
        # enumerate(sequence, [start=0])
        # sequence -- 一个序列、迭代器或其他支持迭代对象。
        # start -- 下标起始位置。

if __name__ == '__main__':
    nums = [0, 5, 4, 0]
    target = 0
    print(Solution().twoSum(nums, target))

链表中等难度/#1两数之和.py


#importing all required module to the file
from Mitra import *

def solveLE(matrix,varList,rtList):
    'solveLE is a global function to solve system of linear equations using gauss elimination method.'
    '''This function first making matrix an upper triangular matrix and then solve for each variable. It uses gauss elimination
    method to do that. It will give error for below conditions:
    1. matrix is empty
    2. no. of row(s) or no. of column(s) of matrix is not same
    3. matrix is neither object of Matrix nor of SquareMatrix
    4. varList is not a list type or it is list type containing values other than string type
    5. varList size is not equal to the no. of row(s) of matrix or to the no. of column(s) of matrix
    6. rtList is not a list type or it is list type containing values other than int or float type
    7. rtList size is not equal to the size of varList'''
    if not (isinstance(matrix, Matrix)):
        raise NoMatrixFoundError("matrix is not type a of 'Matrix' or 'SquareMatrix'")
    if matrix.isEmpty():
        raise EmptyMatrixError("system of linear equations must contains one equation.")
    if not(matrix.isSquareMatrix()):
        raise NoSquareMatrixError("matrix must be square matrix to solve system of linear equations.")
    if isinstance(varList, list):
        for every in range(0, len(varList)):
            if not(isinstance(varList[every], str)):
                raise ValueError("variable(s) list must contain only str type value(s).")
    else:
        raise ValueError("varList must be of list type.")
    dimList = matrix.getDimension()
    if dimList[0] != len(varList):
        raise MatrixDimensionError("dimension of matrix must be equal to the size of variable list.")
    if isinstance(rtList, list):
        for every in range(0, len(rtList)):
            if not(isinstance(rtList[every], (int, float))):
                raise ValueError("right hand side value(s) of equaton(s) must be int or float type only.")
    else:
        raise ValueError("rtList must be of list type.")
    if len(rtList) != len(varList):
        raise MatrixDimensionError("dimension of matrix must be equal to the size of rtList.")
    for dig in  range(0, dimList[0]):
        for row in range(dig+1, dimList[0]):
            if matrix[dig][dig] == 0:
                (matrix[row],matrix[dig]) = (matrix[dig],matrix[row])
                (rtList[row],rtList[dig]) = (rtList[dig],rtList[row])
                continue
            kConst = matrix[row][dig] / matrix[dig][dig]
            for col in range(0, dimList[1]):
                matrix[row][col] = matrix[row][col] - (matrix[dig][col] * kConst)
            rtList[row] = rtList[row] - (rtList[dig] * kConst)
    ansList = []
    for row in range(0, dimList[0]):
        if row == 0:
            ansList.append(rtList[dimList[0]-1] / matrix[dimList[0]-1][dimList[0]-1])
        else:
            for col in range(0, row+1):
                if col == row:
                    ansList.append(rtList[dimList[0]-1-row] / matrix[dimList[0]-1-row][dimList[0]-1-col])
                else:
                    rtList[dimList[0]-1-row] = rtList[dimList[0]-1-row] - (matrix[dimList[0]-1-row][dimList[0]-1-col] * ansList[col])
    ansDict = {}
    for item in range(0, dimList[0]):
        ansDict[varList[item]] = ansList[dimList[0]-1-item]
    return ansDict


# 1747번
import sys
input=sys.stdin.readline

n=1004000
l=[True for _ in range(n+1)]
l[1]=False
for i in range(2,int(n**0.5)+1):
    if l[i]:
        j=i+i
        while j<=n:
            l[j]=False
            j+=i
n=int(input())
while True:
    if l[n] and str(n)==str(n)[::-1]:
        print(n)
        break
    n+=1


'''
Your function should find all of the words
that appear in both strings. The result must be represented
as a string of words separated by commas in alphabetic order.

Example:

checkio("hello,world", "hello,earth") == "hello"
checkio("one,two,three", "four,five,six") == ""
checkio("one,two,three", "four,five,one,two,six,three") == "one,three,two"

'''

def checkio(first, second):
    commonList = ""
    commonList = [word for word in first.split(",")
                  if word in second.split(",")]
    if len(commonList) > 1:
        return ','.join(sorted(commonList))
    else:
        return ''.join(commonList)

# These "asserts" using only for self-checking \
# and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio("hello,world", "hello,earth") == "hello", "Hello"
    assert checkio("one,two,three", "four,five,six") == "", "Too different"
    assert checkio("one,two,three",
                   "four,five,one,two,six,three") == "one,three,two", "1 2 3"


#Fasta file A,C,G,T 개수, Class 사용
import sys

class FASTA:
    def __init__(self,file_name:str):
        self.file_name=file_name
        self.count={}
        self.length=0
    def count_base(self):
        with open(self.file_name,"r") as handle:
            for line in handle:
                if line.startswith(">"):
                    continue
            line=line.strip()
            for s in line:
                if s in self.count:
                    self.count[s] += 1
                else:
                    self.count[s] = 1
    """
    #대화형 파이썬으로 결과 보기
    import tool
    t = tool.FASTA("059.fasta")
    t
    #<tool.FASTA object at 0x104b038d0>
    dir(t)
    #['__class__','__delattr__', ...]
    t.count_base()
    tcount
    #{'A':497,'T':514, 'C':444,'G':585}
    """
    def __len__(self):
        for k,v in self.count.items():
            self.length += v
        return self.length

#네 줄이 하나의 리드를 구성할 때 1st 헤더 2 nd 서열 3 rd 구분자 + 4 th quality

class FASTQ:
    def __init__(self, file_name):
        self.file_name = file_name
        self.read_num=0
        self.base ={}
    def count_read_num(self):
        cnt=0
        with open(self.file_name, 'r') as handle:
            for line in handle:
                if cnt % 4 == 0:
                    header = line.strip()
                    self.read_num += 1
                elif cnt % 4 == 1:
                    seq = line.strip()
                    for s in seq:
                        if s in self.base:
                            self.base[s] += 1
                        else:
                            self.base[s] =1
                elif cnt % 4 == 3:
                    qual = line.strip()
                cnt +=1

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(f"#usage:python {sys.argv[0]}[fasta]")
        sys.exit

    file_name = sys.argv[1]
    """
    t = FASTA(file_name)
    t.count_base()
    t=FASTA(file_name)
    t.count_read_num()
    print(t.read.num)
    print(t.count)
    print(t.length)
    print(len(t))
    """
    t = FASTQ(file_name)
    t.count_read_num()
    print(t.read_num)
    print(t.base)
#VCF(Variant Calling Format)_변이 정보 표기 메타데이터"##" 헤더와 변이 위치 "#"


from typing import List

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        # Strategy 1 - use sorted string as a key, its value is the
        # original string
        hashmap = {}
        for string in strs:
            sorted_string_tuple = tuple(sorted(string))
            if sorted_string_tuple in hashmap.keys():
                hashmap[sorted_string_tuple].append(string)
            else:
                hashmap[sorted_string_tuple] = [string]
        return hashmap.values()
        """
        # Strategy 2 - use tuple of character counts as a key, its value is
        # the original string
        hashmap = {}
        for string in strs:
            key = [0] * 26 # count how many times the character shows up
            for character in string:
                # The difference is the position of index in the list
                # eg. ord('d') - ord('a') is 3
                key[ord(character)-ord('a')] += 1
            if tuple(key) in hashmap.keys():
                hashmap[tuple(key)].append(string)
            else:
                hashmap[tuple(key)] = [string]
        return hashmap.values()
        """

#strs = ["a"]
#strs = [""]
strs = ["eat","tea","tan","ate","nat","bat"]
result = Solution().groupAnagrams(strs)
print("Group anagrams are", result)