"""
Métodos Cuantitativos y simulación

Alumnos:
    Shara Teresa González Mena
    Esteban Quintana Cueto
    Juan Luis Suárez Ruiz
"""
import math

print("Métodos Cuantitativos y simulación\nAlumnos:\n\tShara Teresa González Mena\n\tEsteban Quintana Cueto\n\tJuan Luis Suarez Ruiz\n\n")

def formulas_generales():
    print("\n ***** Formulas Generales (Valor esperado, varianza, desviación estándar) *****\n")
    noX = int(input("Ingresa el número de x's: "))
    x = [0] * noX
    p = [0] * noX
    f = [0] * noX
    valor_esperado = 0
    varianza = 0

    for i in range(0, noX):
        x[i] = float(input("\nx = "))
        p[i] = float(input("p(%d) = " % (x[i])))
        valor_esperado += x[i]*p[i]
    f[0] = p[0]

    print("\n---- Resultados -----")
    for i in range(0, noX):
        if i > 0:
            f[i] = f[i-1] + p[i]
        print("F(%d) = %f" % (x[i],f[i]), end= " | ")
        varianza += math.pow((x[i]-valor_esperado),2)*p[i]
    desvest = math.sqrt(varianza)

    print("\n\n\tValor esperado = %f" % (valor_esperado))
    print("\tVarianza = %f" % (varianza))
    print("\tDesviación estándar = %f" % (desvest))

    return 0;

def uniforme_discreta():
    print("\n***** Distribución Uniforme Discreta *****\n")
    noX = int(input("Ingresa el número de x's: "))
    x = [0] * noX
    p = [0] * noX
    f = [0] * noX
    valor_esperado = 0
    varianza = 0

    for i in range(0, noX):
        x[i] = float(input("\nx = "))
        p[i] = float(input("p(%d) = " % (x[i])))
        valor_esperado += x[i]*p[i]
    f[0] = p[0]

    print("\n---- Resultados -----")
    for i in range(0, noX):
        if i > 0:
            f[i] = f[i-1] + p[i]
        print("F(%d) = %f" % (x[i],f[i]), end= " | ")
        varianza += math.pow((x[i]-valor_esperado),2)*p[i]

    print("\n\n\tValor esperado = %f" % (valor_esperado))
    print("\tVarianza = %f" % (varianza))
    print("\tDesviación estándar = %f" % (math.sqrt(varianza)))

    return 0;

def binomial():
    print("\n***** Distribución Binomial *****\n")
    p = float(input("Probabilidad de éxito p = "))
    q = float(input("Probabilidad de fracaso q = "))
    n = int(input("Número de pruebas n = "))
    acum = int(input("\n¿Qué deseas calcular?:\n\t1. Normal\n\t2. Acumulativa\n"))
    prob = 0

    if acum == 1:
        k = int(input("Introduce k = "))
        print("\n---- Resultados ----")
        prob = (math.factorial(n)/(math.factorial(k)*math.factorial(n-k))) * math.pow(p,k) * math.pow(q,(n-k))
        print("\n\tp(k = %i) = %f" % (k, prob))
    else:
        x1 = int(input("Introduce el límite inferior = "))
        x2 = int(input("Introduce el límite superior = "))
        print("\n---- Resultados ----")
        for i in range(x1,x2+1):
            prob += (math.factorial(n)/(math.factorial(i)*math.factorial(n-i))) * math.pow(p,i) * math.pow(q,(n-i))
        print("\n\tp(%i <= X <= %i) = %f" % (x1, x2, prob))

    print("\n\tValor esperado = %f" % (n*p))
    print("\tVarianza = %f" % (n*p*q))
    print("\tDesviación estándar = %f" % (math.sqrt(varianza)))

    return 0

def poisson():
    print("\n ***** Distribución Poisson *****")
    l = float(input("Introduce el valor de lambda = "))
    acum = int(input("¿Qué deseas calcular?\n\t1. Normal\n\t2. Acumulativa\n"))
    prob = 0

    if acum == 1:
        x = int(input("Introduce el valor de x = "))
        prob = (math.exp(l * -1) * math.pow(l ,x) ) / math.factorial(x)
        print("\n---- Resultados -----")
        print("\n\tp(X = %i) = %f" % (x, prob))
    else:
        x1 = int(input("Introduce el límite inferior = "))
        x2 = int(input("Introduce el límite superior = "))
        print("\n---- Resultados ----")
        for i in range(x1,x2+1):
            prob += (math.exp(l * -1) * math.pow(l ,i) ) / math.factorial(i)
        print("\n\tp(%i <= X <= %i) = %f" % (x1, x2, prob))

    print("\n\tValor esperado = %f" % (l))
    print("\tVarianza = %f" % (l))
    print("\tDesviación estándar = %f" % (math.sqrt(l)))

def procesos_poisson():
    print("\n***** Procesos de Poisson *****")
    alpha = float(input("Introduce el valor de alpha = "))
    t = float(input("Introduce el valor de t = "))
    acum = int(input("¿Qué deseas calcular?\n\t1. Normal\n\t2. Acumulativa\n"))
    prob = 0

    if acum == 1:
        x = int(input("Introduce el valor de x = "))
        prob = (math.exp(alpha * t * -1) * math.pow(alpha * t ,x) ) / math.factorial(x)
        print("\n---- Resultados -----")
        print("\n\tp(X = %i) = %f" % (x, prob))
    else:
        x1 = int(input("Introduce el límite inferior = "))
        x2 = int(input("Introduce el límite superior = "))
        print("\n---- Resultados ----")
        for i in range(x1,x2+1):
            prob += (math.exp(alpha * t * -1) * math.pow(alpha * t ,i) ) / math.factorial(i)
        print("\n\tp(%i <= X <= %i) = %f" % (x1, x2, prob))

    print("\n\tValor esperado = %f" % (alpha * t))
    print("\tVarianza = %f" % (alpha * t))
    print("\tDesviación estándar = %f" % (math.sqrt(alpha * t)))

    return 0

def generador_congruencial_li():
    print("\n***** Generador congruencial de numeros aleatorios *****")
    a = float(input("Introduce el valor de a = "))
    c = float(input("Introduce el valor de c = "))
    Z0 = float(input("Introduce el valor de Z0 = "))
    m = float(input("Introduce el valor de m = "))
    ite = float(input("Introduce el numero de valores aleatorios que desea generar = "))
    Zi = Z0
    R = -1
    run = 1
    print("\n\tm = %f\tc = %f\tZ0 = %f\ta = %f"%(m,c,Z0,a))

    while run <= ite :
        Zi = ((a*Zi+c) % m)
        R = Zi/m
        print("\tZ%i = %f\tR = %f\tIter = %f\n "%(run,Zi,R,run))
        run = run +1

    return 0

def exponencial():
    print("\n***** Distribución Exponencial *****")
    l = float(input("Introduce el valor de lambda = "))
    acum = int(input("¿Qué deseas calcular?\n\t1. Normal\n\t2. Acumulativa\n"))
    prob = 0

    if acum == 1:
        x = int(input("Introduce el valor de x = "))
        prob = (1 - math.exp(l * x * -1)) - (1 - math.exp(l * (x-1) * -1))
        print("\n---- Resultados -----")
        print("\n\tp(X = %i) = %f" % (x, prob))
    else:
        x1 = int(input("Introduce el límite inferior = "))
        x2 = int(input("Introduce el límite superior = "))
        print("\n---- Resultados ----")
        prob = (1 - math.exp(l * x2 * -1)) - (1 - math.exp(l * x1 * -1))
        print("\n\tp(%i <= X <= %i) = %f" % (x1, x2, prob))

    print("\n\tValor esperado = %f" % (1/l))
    print("\tVarianza = %f" % (1 / math.pow(l,2)))
    print("\tDesviación estándar = %f" % (math.sqrt(1 / math.pow(l,2))))

    return 0

options = {1 : formulas_generales,
           2 : uniforme_discreta,
           3 : binomial,
           4 : poisson,
           5 : procesos_poisson,
           6 : exponencial,
	   7 : generador_congruencial_li,
	   }

num = int(input("DISCRETAS:\n\t1. Fórmulas generales\n\t2. Distribución uniforme discreta\n\t3. Distribución binomial\n\t4. Distribución Poisson\n\t5. Procesos de Poisson\nCONTINUAS:\n\t6. Distribución exponencial\nGeneradores:\n\t7. Generador congruencial lineal\n\nElige una opción: "))

options[num]()


from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import EmployeeForm
from .models import Employee

# Create your views here.
def index(request):
    return render(request,'base.html')

def employee_list(request):
    if 'q' in request.GET:
        q=request.GET['q']
        context={'employee_list':Employee.objects.filter(Name__icontains=q)}
    else:
        # posts=Post.objects.all()
        context = {'employee_list':Employee.objects.all()}
        # return render(request,'employee_list.html',context)
    return render(request,'employee_list.html',context)

def employee_form(request,id=0):
    if request.method =="GET":
        form = EmployeeForm()
        return render(request,'employee_form.html',{'form':form})
    else:
        form = EmployeeForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('/list')

def update_form(request,id):
    if request.method =="GET":
        employee = Employee.objects.get(pk=id)
        form=EmployeeForm(instance=employee)
        return render(request,'employee_form.html',{'form':form})
    else:
        employee = Employee.objects.get(pk=id)
        form = EmployeeForm(request.POST,instance= employee)

    if form.is_valid():
            form.save()
            return redirect('/list')

def employee_delete(request,id):
    employee = Employee.objects.get(pk=id)
    employee.delete()
    return redirect('/list')


# -*- coding: utf-8 -*-
#
# Developed by Haozhe Xie <cshzxie@gmail.com>

import cv2
import matplotlib.pyplot as plt
import os

from mpl_toolkits.mplot3d import Axes3D

def get_volume_views(volume, save_dir, n_itr):
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    volume = volume.squeeze().__ge__(0.5)
    fig = plt.figure()
    ax = fig.gca(projection=Axes3D.name)
    ax.set_aspect('equal')
    ax.voxels(volume, edgecolor="k")

    save_path = os.path.join(save_dir, 'voxels-%06d.png' % n_itr)
    plt.savefig(save_path, bbox_inches='tight')
    plt.close()
    return cv2.imread(save_path)


#! /usr/bin/python
# -*- coding: utf-8 -*-

from PySide2.QtCore import Qt
from PySide2.QtWidgets import QGroupBox, QCheckBox, QGridLayout, QComboBox, \
                                 QSlider, QLabel, QPushButton

class WhiteBalance_UI(QGroupBox):
    """
    A QGroupbox widget with all properties of a ui camera
    """
    def __init__(self, ui, cam):
        super(WhiteBalance_UI, self).__init__()
        self.cam = cam
        self.ui = ui
        self.setTitle('White Balance')
        WB_layout = QGridLayout()
        ui.WB = QComboBox()
        ui.WB.addItems(['auto', 'indoor', 'outdoor', 'trigger', 'manual'])
        ui.WB.currentTextChanged.connect(self.on_WB_currentTextChanged)
        WB_layout.addWidget(ui.WB, 1, 1, 1, 3)
        ui.WB_trigger_label = QLabel()
        ui.WB_trigger_label.setText('WB trigger')
        ui.WB_trigger = QPushButton()
        ui.WB_trigger.setText('WB trigger')
        ui.WB_trigger.clicked.connect(self.on_WB_trigger_clicked)
        WB_layout.addWidget(ui.WB_trigger, 1, 4, 1, 1)
        ui.RGain_label = QLabel()
        ui.RGain_label.setText('Red Gain')
        WB_layout.addWidget(ui.RGain_label, 2, 1, 1, 1)
        ui.BGain_label = QLabel()
        ui.BGain_label.setText('Blue Gain')
        WB_layout.addWidget(ui.BGain_label, 3, 1, 1, 1)
        ui.RGain = QSlider()
        ui.RGain.setOrientation(Qt.Horizontal)
        ui.RGain.setMaximum(255)
        ui.RGain.valueChanged.connect(self.on_RGain_valueChanged)
        WB_layout.addWidget(ui.RGain, 2, 2, 1, 3)
        ui.BGain = QSlider()
        ui.BGain.setOrientation(Qt.Horizontal)
        ui.BGain.setMaximum(255)
        ui.BGain.valueChanged.connect(self.on_BGain_valueChanged)
        WB_layout.addWidget(ui.BGain, 3, 2, 1, 3)
        self.setLayout(WB_layout)

    def on_WB_currentTextChanged(self, text):
        if type(text) == unicode:
            text = text.encode('utf-8')
            self.cam.WB = text
            if text == 'manual':
                self.ui.WB_trigger.setEnabled(False)
                self.ui.WB_trigger_label.setEnabled(False)
                self.ui.RGain.setEnabled(True)
                self.ui.BGain.setEnabled(True)
                self.ui.RGain_label.setEnabled(True)
                self.ui.BGain_label.setEnabled(True)
                self.WB_refresh()
            elif text == 'trigger':
                self.ui.WB_trigger.setEnabled(True)
                self.ui.WB_trigger_label.setEnabled(True)
                self.ui.RGain.setEnabled(False)
                self.ui.BGain.setEnabled(False)
                self.ui.RGain_label.setEnabled(False)
                self.ui.BGain_label.setEnabled(False)
            else:
                self.ui.WB_trigger.setEnabled(False)
                self.ui.WB_trigger_label.setEnabled(False)
                self.ui.RGain.setEnabled(False)
                self.ui.BGain.setEnabled(False)
                self.ui.RGain_label.setEnabled(False)
                self.ui.BGain_label.setEnabled(False)

    def WB_refresh(self):
        BGain = self.cam._query('BGain')
        self.ui.BGain.setValue(BGain)
        RGain = self.cam._query('RGain')
        self.ui.RGain.setValue(RGain)

    def on_WB_trigger_clicked(self):
        self.cam.WB_trigger()

    def on_RGain_valueChanged(self, value):
        self.cam.RGain = value

    def on_BGain_valueChanged(self, value):
        self.cam.BGain = value


import unittest
import sys
import logging
import time

logging.basicConfig(level=logging.DEBUG)
sys.path.append("/home/adityas/Projects/Potato")

from potato.context import Context
from potato.datastruct.dframe import DFrame

def dtype_converter(row):

    dtypes = [str, float]

    for i in range(len(row)):
        row[i] = dtypes[i](row[i])

    return row

class TestDFrame(unittest.TestCase):

    def setUp(self):
        self.context = Context("/home/adityas/Kaggle/NAB", ["art_daily_no_noise.csv"])

        #self.frame = self.context.get_frame()
        self.dframe = self.context.get_dframe(["time", "val"])
#       self.dframe.add_custom_map(dtype_converter)

    def test_generator_run(self):
        gen = self.dframe.get_generator()

        for data in gen:
            print(data.shape)

    def test_streamer(self):
        s = self.dframe.streamer
        while 1:
            line = s.get_single_line()
            if not line:
                break

        #print(len(self.frame.collect()))

if __name__ == "__main__":
    unittest.main()


import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

left = 1    #x
top=1       #y
FONT_SIZE=15
RST = None
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
draw = ImageDraw.Draw(image)
font=ImageFont.truetype("./DejaVuSansMono-Bold.ttf", FONT_SIZE)  #set font

def clsr(): #清空螢幕
    disp.begin()
    disp.clear()
    disp.display()
    draw.rectangle((0,0,width,height), outline=0, fill=0)
def partial_clsr(x,y):#部分清空 X=第幾個字 Y=第幾行
    if x>=14 :
        raise ValueError("x should <14")
    if y>=4 :
        raise ValueError("y should <4")
    x=left+(x*9)
    y=top+(FONT_SIZE*y)
    #draw.rectangle((left+(x*9),left+(x*9)+FONT_SIZE),(top+(16*y),top+(16*y)+FONT_SIZE), fill=0)
    draw.rectangle((x,y,x+9,y+FONT_SIZE), outline=0, fill=0)
    disp.image(image)
    disp.display()

def fline_print(x,y,string): #正常顏色  xy同上
    if (type(x) is not int) or (type(y) is not int):
        raise TypeError("x/y should be int")
    if x>=14 :
        raise ValueError("x should <14")
    if y>=4 :
        raise ValueError("y should <4")
    if type(string) is not str:
        raise TypeError ("should be string")
    x=left+(x*9)
    y=top+(FONT_SIZE*y)
    draw.text((x, y),string,font=font,fill=255)
    disp.image(image)
    disp.display()

def fline_reverse(x,y,string): #反白 xy同上
    if type(x) is not int:
        raise TypeError("x should be int")
    if x>=14:
        raise ValueError("x should <=14")
    if y>=4 :
        raise ValueError("y should <4")
    if type(string) is not str:
        raise TypeError ("should be string")
    x=left+(x*9)
    y=top+(FONT_SIZE*y)
    draw.rectangle ([x,y,x+9,y+FONT_SIZE], fill=255,outline=None)   #上底色
    draw.text((x, y),string,font=font,fill=0)
    disp.image(image)
    disp.display()


import statsmodels.api as sm
import numpy as np

def getNBM(x, y):
    x = sm.add_constant(np.array(x).reshape(-1, 1))
    model = sm.GLM(y, x, family=sm.families.NegativeBinomial())
    return model.fit()

def getLM(x, y):
    x = sm.add_constant(np.array(x).reshape((-1, 1)))
    model = sm.OLS(y, x)
    return model.fit()


import read_csv
import charts
data = read_csv.read_csv('./world_population.csv')

def chart_percentage(data):
    data_countries = list(map(lambda variable: variable['Country/Territory'], data))
    data_percentage = list(map(lambda variable: float(variable['World Population Percentage']), data))
    charts.generate_pie_chat(data_countries, data_percentage)

if __name__ == '__main__':
    chart_percentage(data)


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Created by xiaoming

# 本模块的功能:<>

# from .. import 花里胡哨

# strr = input('请输入:')
# eval(strr)
import tkinter

root = tkinter.Tk()
root.title('最强计算器')
root.minsize(400,500)

chang = 80
kuan = 60
# 计算器显示内容应该用字符串显示

num = tkinter.StringVar()
num.set(0)

# 创建label显示
label = tkinter.Label(root,textvariable = num,bg = 'white', font = ('黑体',30), anchor = 'e')
label.place(x = 10, y = 10,width = 380, height = 40)

#运算标志(是否按下了运算按钮 True 按了 False没按)
isys = False
# 用于存储运算列表
yslists = []
# 按钮
# 数字按钮操作
def pressno(no):
    # print(no)
    # 全局变量
    global isys
    # 判断用户是否按下了运算按钮
    if isys == True:
        # 按下了运算按钮
        num.set(no)
        # 将运算标志复位
        isys = False
        pass
    else:
        # 没按下运算按钮
        # 判断原始数字是否为0
        oldno = num.get()
        if oldno == '0':
            # 如果界面为0,如果界面不为0
            num.set(no)
        else:
            num.set(num.get()+no)
        # 获取用户按下的数字,显示到界面中
    # 获取界面中的输入内容

# 运算按钮操作
def pressys(ysflag):
    global isys
    # 设置运算被按下的标志
    isys = True

    #将每次运算的操作的信息计入一个列表['22','*','88']
    # result = eval(''.join([''''''']))

    yslists.append(num.get())
    print(yslists)
    # 计算结果
    cal_res()
    # 将下一个字符添加到列表中
    if ysflag == '=':
        yslists.clear()
    # 如果按的是符号
    elif ysflag == 'clear':
        yslists.clear()
        num.set('')
    else:
        yslists.append(ysflag)

# 计算中间结果
def cal_res():
    global yslists
    res = eval(''.join(yslists))
    print(res)
    num.set(res)
    pass
# #

# def cls_contain():
#     # 清除屏幕
#     yslists.clear()
#     num.set('')

# 定义摆放方法
def baifang_num(contain,com_func,x,y):
    btn = tkinter.Button(root,text = contain, command = lambda : com_func(contain))
    btn.place(x = chang*x, y = kuan*y, width = chang, height = kuan)

for i in range(1,10):
    baifang_num(str(i),pressno,x = (i+2)%3, y = 4-(i//3.1))

# 数字0
baifang_num('0',pressno,1,5)

# 数字.
baifang_num('.',pressno,2,5)

# 等号
baifang_num('=',pressys,3,5)

# 加号
baifang_num('+',pressys,3,4)

# 加号
baifang_num('-',pressys,3,3)

# 加号
baifang_num('*',pressys,3,2)

# 加号
baifang_num('/',pressys,3,1)

# 清空
baifang_num('clear',pressys,0,5)

#
# btn2 = tkinter.Button(root,text = '0', command = lambda : pressno('0'))
# btn2.place(x = 70, y = 5*50, width = 70, height = 50)

#
# # 数字.
# btn2 = tkinter.Button(root,text = '.', command = lambda : pressno('.'))
# btn2.place(x = 70*2, y = 5*50, width = 70, height = 50)

#
# #等号
# btneq = tkinter.Button(root,text = '=', command = lambda : pressys('='))
# btneq.place(x = 0, y = 250, width = 70, height = 50)

#
#
# # 数字2
# btn2 = tkinter.Button(root,text = '2', command = lambda : pressno('2'))
# btn2.place(x = 10, y = 50, width = 50, height = 50)
#
#
# # 数字8
# btn8 = tkinter.Button(root,text = '8', command = lambda : pressno('8'))
# btn8.place(x = 240, y = 50, width = 50, height = 50)
#
# #运算
# btnx = tkinter.Button(root,text = 'x', command = lambda : pressys('*'))
# btnx.place(x = 10, y = 250, width = 50, height = 50)
#
# #等号
# btneq = tkinter.Button(root,text = '=', command = lambda : pressys('='))
# btneq.place(x = 240, y = 250, width = 50, height = 50)

# 加入主消息循环
root.mainloop()

'''
当你的才华还撑不起你的野心时,那你就应该静下心来学习
当你的能力还驾驭不了你的目标时,那就应该沉下心来历练
'''

计算器图形化过程化1.py


import os
import time

import numpy as np
import tensorflow as tf

import constants

class ModelEvaluator:
    def __init__(self, model_path, pred_op_name="softmax:0",
                 input_word_op_name_1="input_word_1:0", input_char_op_name_1="input_char_1:0",
                 input_word_op_name_2="input_word_2:0", input_char_op_name_2="input_char_2:0"):
        """
        :param input_op_name: Input tensor name from the TF Graph
        :param pred_op_name: Prediction operation name from the TF Graph
        :param model_path: ModelEvaluator path including the model name + step. E.g.
        'my-save-dir/my-model-10000'
        """

        # Create a new session and restore the graph + variables
        self.sess = tf.Session()
        new_saver = tf.train.import_meta_graph(model_path + ".meta")
        new_saver.restore(self.sess, model_path)
        graph = tf.get_default_graph()

        # Restore ops for input and prediction
        self.pred_op = graph.get_tensor_by_name(pred_op_name)
        self.input_op_char_1 = graph.get_tensor_by_name(input_char_op_name_1)
        self.input_op_word_1 = graph.get_tensor_by_name(input_word_op_name_1)

        self.input_op_char_2 = graph.get_tensor_by_name(input_char_op_name_2)
        self.input_op_word_2 = graph.get_tensor_by_name(input_word_op_name_2)

        print("ModelEvaluator restored from " + model_path)

    def predict(self, input_word, input_char, batch_size=32):
        """
        Outputs the model prediction class for all examples.
        :param batch_size: Mini-batch size
        :param input: Numpy array of the all input example
        :return: Prediction result indexes (class), varies on the model type
        """

        size = input_word.shape[0]
        num_batches = size // batch_size

        predictions = []
        for b in range(num_batches):
            input_word_b = input_word[b * batch_size:(b + 1) * batch_size][:, 0]
            input_char_b = input_char[b * batch_size:(b + 1) * batch_size][:, 0]
            input_word_b_2 = input_word[b * batch_size:(b + 1) * batch_size][:, 1]
            input_char_b_2 = input_char[b * batch_size:(b + 1) * batch_size][:, 1]
            prediction = self.sess.run([self.pred_op],
                                       feed_dict={
                                           self.input_op_char_1: input_char_b,
                                           self.input_op_word_1: input_word_b,
                                           self.input_op_char_2: input_char_b_2,
                                           self.input_op_word_2: input_word_b_2})[0]

            predictions.extend(np.argmax(prediction, axis=1))

            if b % 20 == 0:
                print("Processed batch {}/{}".format(b, num_batches))

        # Last few examples didn't fit into any of the batches
        if batch_size * num_batches < size:
            input_word_b = input_word[batch_size * num_batches:][:, 0]
            input_char_b = input_char[batch_size * num_batches:][:, 0]
            input_word_b_2 = input_word[batch_size * num_batches:][:, 1]
            input_char_b_2 = input_char[batch_size * num_batches:][:, 1]
            prediction = self.sess.run([self.pred_op],
                                       feed_dict={
                                           self.input_op_char_1: input_char_b,
                                           self.input_op_word_1: input_word_b,
                                           self.input_op_char_2: input_char_b_2,
                                           self.input_op_word_2: input_word_b_2})[0]
            predictions.extend(np.argmax(prediction, axis=1))

        assert len(
            predictions) == size, "Number of predicted and input examples does not match"

        return np.array(predictions)

if __name__ == "__main__":
    # Example of usage
    path = os.path.join(constants.TF_WEIGHTS,
                        "CNN_BILSTM_FC_model_v_loss_0.289724265536.ckpt-1872")
    model = ModelEvaluator(path)

    start = time.time()

    # Simulate prediction
    num_examples = 100
    data = np.ones((num_examples, 100, 25))
    data_char = np.ones((num_examples, 80))


#Detecting figures

class Figure:

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

    def sorting(self):
        return self.outcome.sort()

    #@staticmethod
    def checking(self, outcome):

        figures = []
        is_full = []
        outcome.sort()

        if (1 in outcome) and (2 in outcome) and (3 in outcome) and (4 in outcome) and (5 in outcome):
            figures.append('straight')

        elif (2 in outcome) and (3 in outcome) and (4 in outcome) and (5 in outcome) and (6 in outcome):
            figures.append('bigger_straight')

        elif not figures:
            for die in outcome:
                counts = outcome.count(die)
                if counts == 2 and 'pair' + str(die) not in figures:
                    figures.append('pair' + str(die))
                    is_full.append('pair')

                elif counts == 3  and 'three' + str(die) not in figures:
                    figures.append('three' + str(die))
                    is_full.append('three')

                elif counts == 4  and ('four' + str(die)) not in figures:
                    figures.append('four' + str(die))

                elif counts == 5  and ('flush' + str(die)) not in figures:
                    figures.append('flush' + str(die))

        if 'pair' in is_full and 'three' in is_full:
            figures.clear()
            figures.append('full house')

        if figures == []:
            figures.append('empty hand')

        print(figures)
        return figures


#!/usr/bin/env python
from __future__ import with_statement
import os
from contextlib import closing
from zipfile import ZipFile, ZIP_DEFLATED
import re
import subprocess

def ziprelease(silent=False):
    basedir = "./Legendary Rune Maker/bin/Release/net462"

    assert os.path.isdir(basedir)
    with closing(ZipFile("Release.zip", "w", ZIP_DEFLATED)) as z:
        for root, dirs, files in os.walk(basedir):
            # NOTE: ignore empty directories
            for fn in files:
                absfn = os.path.join(root, fn)
                zfn = absfn[len(basedir) + len(os.sep):]  # relative path

                if (zfn.startswith("cache") or zfn.endswith(".json") or
                        zfn.endswith(".xml")):
                    continue

                if (not silent):
                    print(zfn)

                z.write(absfn, zfn)

version = [x for x in
            [re.findall(r"(?<=AssemblyVersion\(\").*(?=\")", line) for line in open("./Legendary Rune Maker/Properties/AssemblyInfo.cs")]
            if len(x) == 1][0][0]

def setSetupVersion(version):
    with open('./setup/script.iss', 'r') as f:
        content = f.read()
        content = re.sub(r'(?<=MyAppVersion \").*(?=\")', version, content, flags = re.M)

    with open('./setup/script.iss', 'w') as f:
        f.write(content)

print("Building version " + version + "...")

# code = os.system("msbuild /p:Configuration=Release")

# if (code != 0):
#     print("Build failed!")
#     input("Press Enter to continue...")
#     exit()

print("Packing...")
ziprelease(True)

print("Setting version on InnoSetup script...")
setSetupVersion(version)

print("Compiling setup...")
subprocess.run("C:/Program Files (x86)/Inno Setup 5/ISCC.exe setup/script.iss")

print()
input("Done")


import random

numbers = "0123456789"

while 1:
    try:
        num_count = int(input("Hoeveel 'burgerservicenummers' wil je genereren? : "))
        for a in range(0,num_count): # aantal opgevraagde bsn-nummers
            bsn_num = ""
            for a in range(0, 9): # lengte van de bsn-nummer
                num_char = random.choice(numbers) # willekeurige cijfers van 0 t/m 9 om te genereren
                bsn_num      = bsn_num + num_char
            print("Je gegenereerde burgerservicenummer is : ", bsn_num)
    except ValueError as e: # fout handeling
        print("Fout: Controlleer je laatste wijziging!", e)

    except NameError as e: # fout handeling
        print("Fout: Controlleer of je de juiste functie naam hebt gebruikt!", e)

    except SyntaxError as e: # fout handeling
        print("Fout: Controlleer op typfouten of onjuiste wijzigingen!", e)


from otree.api import (
    models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,
    Currency as c, currency_range
)
import random

class Constants(BaseConstants):
    name_in_url = 'survey2'
    players_per_group = None
    num_rounds = 1

class Subsession(BaseSubsession):
    pass

class Group(BaseGroup):
    pass

class Player(BasePlayer):

    birthdate = models.StringField(
        label='¿Cuál es su edad? Por favor, use el formato años-meses (por ejemplo, 20-4).',
        widget=widgets.TextInput())

    gender = models.StringField(
        choices=['Masculino', 'Femenino', 'Otro'],
        label='¿Con que género se identifica?',
        widget=widgets.RadioSelect())

    ethnicity = models.StringField(
        choices=['Afro-Ecuatoriana', 'Mestiza', 'Asiatica', 'Indígena', 'Blanca', 'Prefiero no decir'],
        label='¿Con que etnia se identifica?',
        widget=widgets.RadioSelect())

    other_langs = models.StringField(
        label='¿Qué idiomas habla bien?',
        widget=widgets.TextInput())

    langs_used_weekly = models.StringField(
        label='¿Qué idiomas (incluyendo sus idiomas maternos y el Castellano) usa al menos una vez a la semana?',
        widget=widgets.TextInput())

    nationality = models.StringField(
        label='¿Cuál es su nacionalidad?',
        widget=widgets.TextInput())

    birthplace = models.StringField(
        label='¿Donde nació usted? (Ciudad, Provincia/Estado, País)',
        widget=widgets.TextInput())

    residence = models.StringField(
        label='¿En qué país reside?',
        widget=widgets.TextInput())

    bool_student = models.StringField(
        choices=['Sí','No'],
        label='¿Es usted estudiante?',
        widget=widgets.RadioSelect())

    profession = models.StringField(
        label='Si usted no es estudiante, ¿cuál es su profesión? Si es estudiante, escriba \'NA\' en la caja',
        widget=widgets.TextInput())

    education_level = models.StringField(
        choices=['Ninguno','Educación Inicial (Jardín)','Educación General Básica (Primaria)','Bachillerato (Secundaria)',
        'Algo de estudios universitarios (actualmente o pasado)','Instituto Técnico','Licenciatura o equivalente',
        'Maestría o equivalente','Doctorado'],
        label='¿Cuál es su nivel educativo?',
        widget=widgets.RadioSelect())

    phil_course_count = models.StringField(
        choices=['Nunca he tomado un curso de Economía',
                 'He tomado 1 o 2 cursos de Economía',
                 'He tomado más de 2 cursos de Economía, pero la Economía no es la disciplina en la que fui formado.',
                 'Estudio Economía y estoy por obtener una licenciatura en Economía.',
                 'Estudio Economía y tengo una licenciatura en Economía.',
                 'Estoy estudiando un posgrado en Economía.',
                 'Tengo un doctorado en Economía'],
        label='¿Cuántos cursos de Economía recibió durante sus estudios?',
        widget=widgets.RadioSelect())

    parents_income_level = models.StringField(
        choices=['400 o menos','401 a 800','801 a 1200','1201 a 1600',
        '1601 a 2000','2001 o más'],
        label='Hasta donde sabe, ¿cuál es el nivel de ingreso mensual conjunto de sus padres (en dólares)?',
        widget=widgets.RadioSelect())

    parents_edu_level = models.StringField(
        choices=['Ninguno','Educación Inicial (Jardín)','Educación General Básica (Primaria)','Bachillerato (Secundaria)',
        'Algunos estudios universitarios','Instituto Técnico','Licenciatura o equivalente',
        'Maestría o equivalente','Doctorado'],
        label='Hasta donde sabe, ¿cuál es el nivel educativo más alto que alcanzó alguno de sus padres (el que tenga más estudios)?',
        widget=widgets.RadioSelect())

    religion = models.StringField(
        choices=['Ninguna','Católica','Evangelista','Protestante (distinto de evangelista)',
                 'Mormona','Cristiana ortodoxa','Cristiana (otra)','Judía','Musulmana',
                 'Hinduísta','Budista','Sintoísta','Confucionista','Daoista','Jainista',
                 'Sikh','Atea o agnóstica','Otra'],
        label='¿Cuál es su afiliación religiosa actual? ',
        widget=widgets.RadioSelect())

    politics = models.StringField(
        choices=['Muy de izquierda','Izquierda','Centro-izquierda','Centro','Centro-derecha','Derecha','Muy de derecha'],
        label='En términos generales, ¿cuál es su inclinación política?',
        widget=widgets.RadioSelect())

    civil_status = models.StringField(
        choices=['Soltero','Casado','Divorciado','Viudo','Prefiero no decir'],
        label='¿Cuál es su estado civil?',
        widget=widgets.RadioSelect())


from aiogram import types
from aiogram.dispatcher import FSMContext
from sqlalchemy.orm import Session

from bot import dp, bot, MESSAGES
from keyboards import admin_question_kb, cancel_btn
from models import UserModel, QuestionModel, engine
from states import AnswerState

from handlers.logic import update_link_to_appoinment
from .filter import AdminFilter

async def view_question(callback_query: types.CallbackQuery, question_id: int):
    with Session(engine) as session:
        is_answered = session.query(QuestionModel).filter(
            QuestionModel.id == question_id
        ).first().is_answered

        questions = session.query(QuestionModel).filter(
            QuestionModel.is_answered == is_answered
        ).all()

        count = len(questions)

        index = list(map(lambda x: x.id, questions)).index(question_id)

        text = MESSAGES["admin_question_detail"].format(questions[index].questioner_name, questions[index].question, questions[index].date)

        if questions[index].is_answered:
            text += MESSAGES["admin_question_answer"].format(questions[index].answer)

        kb = types.InlineKeyboardMarkup(row_width=3, resize_keyboard=True)

        btns = []

        if index > 0:
            another_question_id = questions[index - 1].id

            btns.append(
                types.InlineKeyboardButton("<<<", callback_data=f"admin_view_question_{another_question_id}")
            )

        btns.append(
            types.InlineKeyboardButton(f"{index + 1}/{count}", callback_data=f"empty")
        )

        if index < count - 1:
            another_question_id = questions[index + 1].id

            btns.append(
                types.InlineKeyboardButton(">>>", callback_data=f"admin_view_question_{another_question_id}")
            )

        if not questions[index].is_answered:
            kb.add(
                types.InlineKeyboardButton("🗣 Ответить", callback_data=f"admin_answer_question_{question_id}")
            )

        kb.add(*btns)
        kb.add(
            types.InlineKeyboardButton("◀ Назад", callback_data=f"admin_questions")
        )

        await callback_query.message.edit_text(text, reply_markup=kb)

@dp.callback_query_handler(AdminFilter(), lambda cb: cb.data == "admin_questions")
async def view_questions_callback(callback_query: types.CallbackQuery):
    await bot.answer_callback_query(callback_query.id)

    await callback_query.message.edit_text(MESSAGES["admin_questions"], reply_markup=admin_question_kb)

@dp.callback_query_handler(AdminFilter(), lambda cb: cb.data == "admin_view_questions")
async def view_questions_callback(callback_query: types.CallbackQuery):
    await bot.answer_callback_query(callback_query.id)

    with Session(engine) as session:
        question = session.query(QuestionModel).filter(
            QuestionModel.is_answered == False
        ).first()

    if question:
        await view_question(callback_query, question.id)
        return

    kb = types.InlineKeyboardMarkup(resize_keyboard=True)
    kb.add(
        types.InlineKeyboardButton("◀ Назад", callback_data="admin_questions")
    )

    await callback_query.message.edit_text(MESSAGES["admin_no_new_questions"], reply_markup=kb)

@dp.callback_query_handler(AdminFilter(), lambda cb: "admin_view_question_" in cb.data)
async def view_question_callback(callback_query: types.CallbackQuery):
    await bot.answer_callback_query(callback_query.id)

    question_id = int(callback_query.data.replace("admin_view_question_", ""))

    await view_question(callback_query, question_id)

@dp.callback_query_handler(AdminFilter(), lambda cb: "admin_answer_question_" in cb.data)
async def start_answer_question_callback(callback_query: types.CallbackQuery, state: FSMContext):
    await bot.answer_callback_query(callback_query.id)

    question_id = int(callback_query.data.replace("admin_answer_question_", ""))

    async with state.proxy() as data:
        data["question_id"] = question_id

    await AnswerState.answer.set()
    await bot.send_message(callback_query.from_user.id, "Введите текст ответа:")

@dp.message_handler(AdminFilter(), state=AnswerState.answer)
async def end_answer_question_handler(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        answer = message.text
        question_id = data["question_id"]

    await state.finish()

    with Session(engine) as session:
        admin_id = session.query(UserModel).filter(
            UserModel.telegram_id == message.from_user.id
        ).first().id

        session.query(QuestionModel).filter(
            QuestionModel.id == question_id
        ).update({
            QuestionModel.defendant_id: admin_id,
            QuestionModel.answer: answer,
            QuestionModel.is_answered: True,
        })

        user_telegram_id = session.query(UserModel).join(
            QuestionModel, UserModel.id == QuestionModel.questioner_id
        ).filter(
            QuestionModel.id == question_id
        ).first().telegram_id

        session.commit()

    await bot.send_message(user_telegram_id, MESSAGES["you_have_answer"])

    kb = types.InlineKeyboardMarkup(resize_keyboard=True)
    kb.add(
       types. InlineKeyboardButton("◀ Назад", callback_data="admin_questions")
    )

    await bot.send_message(message.from_user.id, MESSAGES["admin_answer_sended"], reply_markup=kb)

@dp.callback_query_handler(AdminFilter(), lambda cb: cb.data == "admin_answered_questions")
async def view_questions_callback(callback_query: types.CallbackQuery):
    await bot.answer_callback_query(callback_query.id)

    with Session(engine) as session:
        question = session.query(QuestionModel).filter(
            QuestionModel.is_answered == True
        ).order_by(
            ~QuestionModel.id
        ).first()

    if question:
        await view_question(callback_query, question.id)
    else:
        kb = types.InlineKeyboardMarkup(resize_keyboard=True)
        kb.add(
            types.InlineKeyboardButton("◀ Назад", callback_data="admin_questions")
        )

        await callback_query.message.edit_text(MESSAGES["admin_no_question_history"], reply_markup=kb)


"Bu program girilen listenin içerisinde kaç tane 1 rakamı bulunduğunu ekrana yazar."
Liste=[12,1,1,10,20,13,53,19]
toplam=0

for i in range(len(Liste)):
    if Liste[i]==int(1):
        toplam+=1

if toplam==0:
    print("Listenin içinde 1 rakamı bulunmuyor.")
else:
    print("Listenin içinde",toplam,"tane 1 rakamı bulunuyor.")


from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer
from .forms import RegisterForm, LoginForm
from rest_framework.schemas import AutoSchema
import coreapi

from tudutul.models import User

class RegistrationViewSchema(AutoSchema):

    def get_manual_fields(self, path, method):
        extra_fields = []

        if method.lower() == 'post':
            extra_fields = [
                coreapi.Field('email'),
                coreapi.Field('login'),
                coreapi.Field('pass'),
                coreapi.Field('repeated_pass')
            ]

        return super().get_manual_fields(path, method) + extra_fields

class LoginViewSchema(AutoSchema):

    def get_manual_fields(self, path, method):
        extra_fields = []

        if method.lower() == 'post':
            extra_fields = [
                coreapi.Field('login'),
                coreapi.Field('password'),
            ]

        return super().get_manual_fields(path, method) + extra_fields

class LogoutViewSchema(AutoSchema):

    def get_manual_fields(self, path, method):
        extra_fields = []

        if method.lower() == 'get':
            extra_fields = [
                coreapi.Field('login'),
            ]

        return super().get_manual_fields(path, method) + extra_fields

class RegistrationView(APIView):

    renderer_classes = [JSONRenderer]
    schema = RegistrationViewSchema()

    def post(self, request):
        """
        Parameters

            - 'email' string
            - 'login' string
            - 'pass' string
            - 'repeated_pass' string

        Response

            - 'registered' bool
            - 'ans' string
        """

        form = RegisterForm(request.data)
        answer = ""
        registered = False

        if form.is_valid():
            form.save()
            registered = True
            answer = "User successfully registered"
        else:
            answer = form.reason()

        return Response(data = {"registered": registered, "ans": answer})

class LoginView(APIView):

    renderer_classes = [JSONRenderer]
    schema = LoginViewSchema()

    def get(self, request):
        """
        Response

            - 'logged' bool
            - 'userLogin' string
            - 'userEmail' string
        """
        user = None

        user_session_key = 'userLogin'

        if 'Authorization' in request.headers:
            user = User.objects.filter(pk=request.headers['Authorization'])
        elif user_session_key in request.session:
            user = User.objects.filter(pk=request.session['userLogin'])
        else:
            return Response(data={"logged": False})

        request.session['userEmail'] = user[0].email
        email = user[0].email
        return Response(data = {"logged": True, "userLogin": request.session.get(user_session_key), "userEmail:": email})

    def post(self, request):
        """
        Parameters

            - 'login' string
            - 'password' string
        Response

            - 'logged' bool
            - 'ans' string
        """
        user_session_key = 'userLogin'
        logged = False

        form = LoginForm(request.data)
        if form.is_valid():
            # set session
            request.session['userLogin'] = form.login
            user = User.objects.filter(pk=request.session['userLogin'])
            request.session['userEmail'] = user[0].email
            logged = True
            answer = "User successfully logged in"
        else:
            answer = form.reason()

        return Response(data = {"logged": logged, "ans": answer})

class AccountView(APIView):

    renderer_classes = [JSONRenderer]

    def get(self, request):
        """
        Response

            - 'logged' bool
            - 'ans' string
        """

        if 'userLogin' in request.session:
            return Response(data = {"userLogin": request.session.get('userLogin')})
        if 'Authorization' in request.headers:
            return Response(data={"userLogin": request.headers['Authorization']})

class LogoutView(APIView):

    renderer_classes = [JSONRenderer]
    schema = LogoutViewSchema()

    def get(self, request):
        """
        Parameters

            - 'login' string
        Response

            - 'userLogin' string
        """
        if request.headers.get('Authorization') == request.GET.get('login'):
            answer = 'Logged out'
        elif request.session.get('userLogin') == request.GET.get('login'):
            request.session.pop(key = 'userLogin')
            answer = 'Logged out'
        else:
            answer = 'User ' + request.GET.get('login') + ' is not logged in'

        return Response({'userLogin': answer})


import numpy as np
from scipy.integrate import odeint
import matplotlib
import matplotlib.pyplot as pl

# define the ODE as a first order system
def ODE3(x,t):
    return [
        x[1],
        x[2],
        np.exp(-t/2) - (3*t)
        ]

# initial values
x0=[ 10.6, -3.6, 31.2]
#y0 = [1, -1, 0]
# points at which the solution value is requested
t = np.linspace(0,10,501)
# numerical integration
y=odeint(ODE3, x0, t)
# y[-1,:] contains the value at x=10

# plot the solution with subplots for each component
plt.plot(t,y)


import numpy as np
import keras
from keras.models import load_model
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img

# Load and prepare the image

def load_image(filename):
    img = load_img(filename, grayscale=True, target_size=(28, 28))
    img = img_to_array(img)

    # Reshape into a single sample with 1 channel
    img = img.reshape(1, 28, 28, 1)

    # Prepare pixel data
    img = img.astype('float32')
    img = img / 255.0

    return img

def test_trained_model():
    model = load_model('artifacts/model_fashion_classifier.h5py')
    img = load_image('samples/ankle_boot.png')

    result = model.predict_classes(img)
    print(result[0])

test_trained_model()


def longestValidParentheses(s):

    n=len(s)

    maxlength=0

    left=0

    right=0

    for i in range(n):

        if s[i]=='(':

            left+=1

        else:

            right+=1

        if left==right and maxlength<(left+right):

            maxlength=left+right

        elif right>left:
            left=right=0

    left=0

    right=0

    for i in range(n-1,-1,-1):

        if s[i]=='(':

            left+=1

        else:

            right+=1

        if left==right and maxlength<(left+right):

            maxlength=(left+right)

        elif right<left:
            left=right=0

    print(maxlength)

s="(()))())("

longestValidParentheses(s)

'''def longest(s):

    n=len(s)

    max_length=0

    ss=[]

    ss.append(-1)

    for i in range(n):

        if s[i]=="(" :

            ss.append(i)

        elif s[i]==")" :

            ss.pop()

            if not ss:

                ss.append(i)

            else:

                a=len(ss)

                if max_length<(i-ss[a-1]):

                    max_length=i-ss[a-1]

    print(max_length)

s=")()())"

longest(s)'''


# 杨辉三角
# 给定一个非负整数 numRows，生成杨辉三角的前 numRows 行。

# 在杨辉三角中，每个数是它左上方和右上方的数的和。

# 示例:

# 输入: 5
# 输出:
# [
#     [1],
#     [1, 1],
#     [1, 2, 1],
#     [1, 3, 3, 1],
#     [1, 4, 6, 4, 1]
# ]
from typing import List

# class Solution:

#     def generate(self, numRows: int) -> List[List[int]]:
#         res = []
#         if numRows < 1:
#             return res
#         elif numRows == 1:
#             res.append([1])
#             return res
#         elif numRows == 2:
#             res.append([1])
#             res.append([1, 1])
#             return res
#         res.append([1])
#         res.append([1, 1])
#         for i in range(3, numRows + 1):
#             temp = []
#             for j in range(i):
#                 if j == 0:
#                     temp.append(1)
#                 elif j == i - 1:
#                     temp.append(1)
#                 else:
#                     temp.append(res[i-2][j-1] + res[i-2][j])
#             res.append(temp)
#         return res

# BEST SOULUTION
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        result=[1 for c in range(numRows)]
        for i in range(numRows):
            result[i]=[1]*(i+1)
        for i in range(2,numRows):
            for j in range(1,i):
                result[i][j]=result[i-1][j-1]+result[i-1][j]
        return result

if __name__ == "__main__":
    soul = Solution()
    print(soul.generate(5))


import tensorflow as tf
import trimesh
import os

MODELNET40_DOWNLOAD_URL = "http://modelnet.cs.princeton.edu/ModelNet40.zip"

OUTPUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "output_data")

def download_maybe(output_dir: str):
    data_dir = os.path.join(output_dir, "ModelNet40")
    if not os.path.exists(os.path.join(output_dir, "ModelNet40")):
        tf.keras.utils.get_file(
            "modelnet40.zip",
            MODELNET40_DOWNLOAD_URL,
            extract=True,
            cache_subdir=output_dir
        )
    return data_dir

def read_OFF_file(path):
    raw = tf.io.read_file(path)  # Read the data.

    raw = tf.strings.substr(raw, 3, tf.strings.length(raw))  # Substring and remove the "OFF"
    raw = tf.strings.strip(raw)  # Strip the extra spaces

    raw = tf.strings.regex_replace(raw, r"#.*\n$", "\n")  # Remove comments
    raw = tf.strings.split(raw, '\n')  # Split by lines.

    meta_data = tf.strings.to_number(input=tf.strings.split(raw[0], " "), out_type=tf.int32)
    num_verts, num_faces, num_edges = tf.split(meta_data, 3)
    num_verts = tf.reshape(num_verts, ())
    num_faces = tf.reshape(num_faces, ())
    # num_edges = tf.reshape(num_edges, ())  # Irrelevant in 'OFF' format

    start_idx_of_verts = 1  # First line is "OFF" (we removed it), second line is: "num_verts num_faces num_edges"
    end_idx_of_verts = start_idx_of_verts + num_verts
    start_idx_of_faces = end_idx_of_verts
    end_idx_of_faces = start_idx_of_faces + num_faces
    # start_idx_of_edges = end_idx_of_faces  # Irrelevant in 'OFF' format
    # end_idx_of_edges = start_idx_of_edges + num_edges  # Irrelevant in 'OFF' format

    vertices_raw = tf.strings.strip(raw[start_idx_of_verts:end_idx_of_verts])  # Remove extra spaces ' '
    faces_raw = tf.strings.strip(raw[start_idx_of_faces:end_idx_of_faces])
    # edges_raw = tf.strings.strip(raw[start_idx_of_edges:end_idx_of_edges])  # Irrelevant in 'OFF' format

    points = tf.strings.to_number(tf.strings.split(vertices_raw, " "), out_type=tf.float32).to_tensor()
    points = points - tf.reduce_mean(points, axis=0, keepdims=True)

    faces = tf.strings.to_number(tf.strings.split(faces_raw, " "), out_type=tf.int32).to_tensor()
    _, faces = tf.split(faces, axis=1, num_or_size_splits=(1, 3))  # Discard the first column which describes how many points.

    # edges = tf.strings.to_number(tf.strings.split(edges_raw, " "), out_type=tf.int32).to_tensor()  # Irrelevant in 'OFF' format

    return (points, faces), path

def main():
    global OUTPUT_DIR
    os.makedirs(OUTPUT_DIR, exist_ok=True)
    data_dir = download_maybe(output_dir=OUTPUT_DIR)

    dataset = tf.data.Dataset.list_files(os.path.join(data_dir, "**", "**", "**.off"), shuffle=True)
    dataset = dataset.map(read_OFF_file, num_parallel_calls=tf.data.experimental.AUTOTUNE)
    # dataset = dataset.batch(1)
    dataset = dataset.prefetch(1)
    for x in dataset:
        (points, faces), path = x
        path = path.numpy().decode()
        tm = trimesh.Trimesh(vertices=points, faces=faces)
        tm.show(caption=path)

if __name__ == '__main__':
    main()


list = []#名片容器
while True:
	def num():
		a = {}

		name = input('请输入名字')
		age = int(input('请输入年龄'))
		a['name'] = name
		a['age'] = age
		list.append(a)
		print('添加成功')
#		break
#		q()

	def q():
		w = open('1.txt','w')
		w.write(str(list))
		w.close()
		s()

	def s():
		f1 = open('2.txt','r')
		content = f1.read()
		if len(content) != 0:
			print(type(content))
			list = eval(content)
			for i in list:
				for k,v in i.items():
					print(k,v)
		print(list)
		f1.close()
		num()


# Напишите функцию, которая считает сумму цифр любого целого положительного числа
# вход: 459
# выход: 18

N = int(input("Введите число="))
sum = 0
while N > 0:
    d = N % 10
    N = N // 10
    sum += d
print("Сумма всех чисел в числе=", sum)


import downloader
from bs4 import BeautifulSoup

def get_sub_areas(city):
    url_prefix = "https://www.rew.ca/sitemap/real-estate/"
    city_url = url_prefix + city
    html = downloader.get_html(city_url)

    soup = BeautifulSoup(html, "html.parser")
    sub_areas = soup.select(".gridblock-link")
    if sub_areas:
        for sub_area in sub_areas:
            yield sub_area.get('href').split('/')[3]
    else:
        yield city

def get_list(province):
    url_prefix = "https://www.rew.ca/sitemap/real-estate/"
    province_url = url_prefix + province
    html = downloader.get_html(province_url)

    soup = BeautifulSoup(html, "html.parser")
    areas = soup.select(".gridblock-link")
    for area in areas:
        for i in get_sub_areas(area.get('href').split('/')[3]):
            print(i)
            with open(province + '_sub_area_list.txt', 'a') as fd:
                fd.write('%s\n' % i)


# ************************************************************
#      Condicionar Nuvens de Pontos para 2048 pontos
#         Por: Jefferson S. Almeida - 08/03/2020
#        E-mail: jeffersonsilva@lapisco.ifce.edu.br
# ************************************************************

from plyfile import PlyData, PlyElement
import random
import numpy as np
import os
from os import path

directory = '/home/jefferson/PycharmProjects/PointCloudRandom/data2048'
data_dtype='uint8'
pointnumber = 2048

if path.exists(directory):
	print('...')
else:
	os.mkdir(directory)

def export_ply(pc, filename):
	vertex = np.zeros(pc.shape[0], dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4')])
	sh = pc.shape[0]
	for i in range(sh):
		# print(pc[i][0], pc[i][1], pc[i][2])
		vertex[i] = (pc[i][0], pc[i][1], pc[i][2])
	ply_out = PlyData([PlyElement.describe(vertex, 'vertex', comments=['vertices'])], text=True, comments=['created by: Jefferson (jeffersonsilva@lapisco.ifce.edu.br)'])
	ply_out.write(filename)

filenames = [line.rstrip() for line in open("filelist", 'r')]

data = np.zeros((len(filenames), pointnumber, 3))

for i in range(0, len(filenames)):
	plydata = PlyData.read(filenames[i] + ".ply")
	# print(i, plydata.elements[0].count)
	size = plydata.elements[0].count

	dataTemp = np.zeros((len(filenames), size, 3))

	if (size >= pointnumber):
		rand = random.sample(range(size), k=pointnumber)
		rand.sort()

		for j in range(0, len(rand)):
			row = rand[j]
			# print(j, row)
			data[i, j-1] = [plydata['vertex']['x'][row], plydata['vertex']['y'][row], plydata['vertex']['z'][row]]

	elif (size < pointnumber):
		difference = pointnumber - size
		dataDiff = np.zeros((len(filenames), difference, 3))
		dataDiff[:] = [plydata['vertex']['x'][0], plydata['vertex']['y'][0], plydata['vertex']['z'][0]]

		for j in range(0, size):
			dataTemp[0, j-1] = [plydata['vertex']['x'][j], plydata['vertex']['y'][j], plydata['vertex']['z'][j]]
		data = np.concatenate((dataTemp, dataDiff), axis=1)

	name = directory + '/' + filenames[i] + 'size2048' + '.ply'
	export_ply(data[0], name)
	print(i)


import copy
from functools import lru_cache
from typing import Dict, List, Optional, Union

from tapa.common.base import Base
from tapa.common.constant import Constant
from tapa.common.external_port import ExternalPort
from tapa.common.interconnect_instance import InterconnectInstance
from tapa.common.task_definition import TaskDefinition

class TaskInstance(Base):
  """TAPA task instance.

  Attributes:
    idx: The index of this task as nested in its parent.
  """

  def __init__(self, idx: int, *args, **kwargs):
    """Construct a TAPA task instance.

    Args:
      idx: The index of this task as nested in its parent.
    """
    super(TaskInstance, self).__init__(*args, **kwargs)
    self.idx = idx

  @lru_cache(None)
  def get_external_port(self, name: str) -> Optional[ExternalPort]:
    """Returns the external port of this task instance."""
    if name in self.get_external_ports():
      return self.get_external_ports()[name]
    else:
      return None

  @lru_cache(None)
  def get_external_ports(self) -> Dict[str, ExternalPort]:
    """Returns the external ports of this task instance."""
    return {
        p['name']: ExternalPort(p['name'], p, self)
        for p in self.definition.obj['ports']
    } if self.definition.get_level() == TaskDefinition.Level.TOP else {}
    # Non-top tasks have no external ports

  @lru_cache(None)
  def get_interconnect_inst(self, name: str) -> Optional[InterconnectInstance]:
    """Returns the local interconnect of this task instance."""

    if self.definition.get_level() == TaskDefinition.Level.LEAF:
      return None
    inter_def = self.definition.get_interconnect_def(name)
    return InterconnectInstance(name, None, self,
                                inter_def) if inter_def else None

  @lru_cache(None)
  def get_interconnect_insts(self) -> List[InterconnectInstance]:
    """Returns the local interconnects of this task instance."""

    return [
        self.get_interconnect_inst(inter_def.name)
        for inter_def in self.definition.get_interconnect_defs()
    ] if self.definition.get_level() != TaskDefinition.Level.LEAF else []

  @lru_cache(None)
  def get_in_scope_interconnect_or_port(
      self, name: str) -> Optional[Union[InterconnectInstance, ExternalPort]]:
    """Returns the interconnect or port that has `name` in this task's scope.

    The interconnect that has `name` might be in this local scope either
    through ports or instantiated locally.  This function is to lookup the
    original interconnect or external port recursively.

    Args:
      name: Name of the interconnect or port in the local scope.

    Returns:
      The corresponding interconnect or external port.
    """

    inter_inst = self.get_interconnect_inst(name)

    if inter_inst is not None:
      return inter_inst

    # If not instantiated locally
    if self.definition.get_level() != TaskDefinition.Level.TOP:
      # 1. lookup its parents if this is not the top level task
      insts_all = self.parent.definition.obj['tasks']
      insts_self = insts_all[self.definition.name]
      inst = insts_self[self.idx]
      arg = inst['args'][name]
      parent_name = arg['arg']

      # FIXME: constants should be speficied explicitly in tapacc
      if parent_name.startswith("64'd"):
        # this is an int constant
        return Constant(parent_name, arg)
      else:
        # this is passed from its parent
        return self.parent.get_in_scope_interconnect_or_port(parent_name)
    else:
      # 2. or if this task is the top level task, get the external port
      return self.get_external_port(name)

  @lru_cache(None)
  def recursive_get_interconnect_insts(self) -> List[InterconnectInstance]:
    """Returns all local interconnects of this task and its subtasks."""

    if self.definition.get_level() == TaskDefinition.Level.LEAF:
      return []
    insts = self.get_interconnect_insts()
    for task_inst in self.get_subtasks_insts():
      insts.extend(task_inst.recursive_get_interconnect_insts())
    return insts

  @lru_cache(None)
  def get_subtasks_insts(self) -> List['TaskInstance']:
    """Returns the subinstances of this task instance."""

    if self.definition.get_level() == TaskDefinition.Level.LEAF:
      return []
    insts = []
    for task_def in self.definition.get_subtask_defs():
      task_instances = self.definition.get_subtask_instantiations(task_def.name)
      for idx, inst in enumerate(task_instances):
        insts.append(
            TaskInstance(idx, f'{task_def.name}_{idx}', inst, self, task_def))
    return insts

  @lru_cache(None)
  def get_leaf_tasks_insts(self) -> List['TaskInstance']:
    """Returns the instances of the leaf tasks of under this instance."""

    if self.definition.get_level() == TaskDefinition.Level.LEAF:
      return [self]
    insts = []
    for task_inst in self.get_subtasks_insts():
      insts.extend(task_inst.get_leaf_tasks_insts())
    return insts

  def to_dict(self, interconnect_global_name: bool = False) -> Dict:
    """Transform the task instance object to its JSON description.

    Args:
      interconnect_global_name:
        Use the global names as the name of the interconnects.

    Returns:
      The dict as in the graph JSON description.
    """
    obj = super(TaskInstance, self).to_dict()

    if interconnect_global_name:
      # Transform args to their global names
      for name, arg in obj['args'].items():
        inter_inst = self.get_in_scope_interconnect_or_port(name)
        if inter_inst:
          arg['arg'] = inter_inst.global_name

    return obj


'''
https://app.codility.com/programmers/lessons/5-prefix_sums/passing_cars/

Task description
A non-empty array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road.

Array A contains only 0s and/or 1s:

0 represents a car traveling east,
1 represents a car traveling west.
The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.

For example, consider array A such that:

  A[0] = 0
  A[1] = 1
  A[2] = 0
  A[3] = 1
  A[4] = 1
We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).

Write a function:

def solution(A)

that, given a non-empty array A of N integers, returns the number of pairs of passing cars.

The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000.

For example, given:

  A[0] = 0
  A[1] = 1
  A[2] = 0
  A[3] = 1
  A[4] = 1
the function should return 5, as explained above.

Assume that:

N is an integer within the range [1..100,000];
each element of array A is an integer that can have one of the following values: 0, 1.
Complexity:

expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1) (not counting the storage required for input arguments).
'''

# https://app.codility.com/demo/results/trainingT85V7D-WT5/
def solution(A):

    count = 0
    n_east = 0

    for a in A:

        # going east a = 0 -> we add it to the pool of pairs
        if a == 0:
            n_east += 1
        else:
            # goes west: crosses with previous cars
            count += n_east

        # check max count
        if count > 1000000000:
            return -1

    return count

A = [0,1,0,1,1]
solution(A)

A = [0,1]
solution(A)

A = [1,0]
solution(A)

A = [0,1,0,1,0,0,0,0,0,1]
solution(A)
solution_n2(A)

A = [0]
solution(A)

A = [1]
solution(A)


import random
from faker import Faker
from database import create_connection, close_connection

fake = Faker()

tanzania_regions = [
    'Arusha', 'Dar es Salaam', 'Dodoma', 'Geita', 'Iringa', 'Kagera',
    'Katavi', 'Kigoma', 'Kilimanjaro', 'Lindi', 'Manyara', 'Mara',
    'Mbeya', 'Morogoro', 'Mtwara', 'Mwanza', 'Njombe', 'Pemba Kusini',
    'Pemba Kaskazini', 'Pwani', 'Rukwa', 'Ruvuma', 'Shinyanga', 'Simiyu',
    'Singida', 'Songwe', 'Tabora', 'Tanga', 'Unguja Kusini', 'Unguja Kaskazini',
    'Zanzibar Central/South', 'Zanzibar North', 'Zanzibar Urban/West'
]

# Create database connection
conn = create_connection()
cursor = conn.cursor()

# Create customers table if it doesn't exist
cursor.execute('''
    CREATE TABLE IF NOT EXISTS customers (
        customer_id UUID PRIMARY KEY,
        name VARCHAR(100),
        age INTEGER,
        gender VARCHAR(10),
        marital_status VARCHAR(20),
        education_level VARCHAR(50),
        work_residence VARCHAR(100),
        employment_status VARCHAR(50),
        income INTEGER
    )
''')

# Generate fake data for customers table
customers_data = [
    (
        fake.uuid4(),
        fake.name(),
        random.randint(18, 65),
        random.choice(['Male', 'Female']),
        random.choice(['Married', 'Single', 'Divorced', 'Widowed']),
        random.choice(['High School', 'Bachelor', 'Master', 'PhD']),
        random.choice(tanzania_regions),
        random.choice(['Employed', 'Unemployed', 'Self-employed']),
        random.randint(350000, 3500000)
    )
    for _ in range(500)
]

# Insert customers data into customers table
cursor.executemany('''
    INSERT INTO customers (customer_id, name, age, gender, marital_status, education_level, work_residence, employment_status, income)
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
''', customers_data)

# Define the table schemas (including relationships)
table_schemas = {
    'accounts': '''
        CREATE TABLE IF NOT EXISTS accounts (
            account_id UUID PRIMARY KEY,
            customer_id UUID,
            account_type VARCHAR(20),
            account_number VARCHAR(50),
            opening_date DATE,
            balance NUMERIC(10, 2),
            FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
        )
    ''',
    'transactions': '''
        CREATE TABLE IF NOT EXISTS transactions (
            transaction_id UUID PRIMARY KEY,
            account_id UUID,
            transaction_date DATE,
            transaction_type VARCHAR(20),
            amount NUMERIC(10, 2),
            FOREIGN KEY (account_id) REFERENCES accounts (account_id)
        )
    ''',
    'credit_history': '''
        CREATE TABLE IF NOT EXISTS credit_history (
            customer_id UUID PRIMARY KEY,
            credit_limit NUMERIC(10, 2),
            credit_score INTEGER,
            FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
        )
    '''
}

# Create additional tables
for table_name, table_schema in table_schemas.items():
    cursor.execute(table_schema)

# Generate and insert data for accounts
accounts_data = [
    (
        fake.uuid4(),
        random.choice(customers_data)[0],
        random.choice(['Savings', 'Checking']),
        fake.credit_card_number(),
        fake.date_between(start_date='-10y', end_date='today'),
        random.randint(10000, 25000000)
    )
    for _ in range(700)
]

cursor.executemany('''
    INSERT INTO accounts (account_id, customer_id, account_type, account_number, opening_date, balance)
    VALUES (%s, %s, %s, %s, %s, %s)
''', accounts_data)

# Generate and insert data for transactions
transactions_data = [
    (
        fake.uuid4(),
        random.choice(accounts_data)[0],
        fake.date_between(start_date='-2y', end_date='today'),
        random.choice(['Deposit', 'Withdrawal', 'Transfer']),
        random.randint(10000, 15000000)
    )
    for _ in range(500000)
]

cursor.executemany('''
    INSERT INTO transactions (transaction_id, account_id, transaction_date, transaction_type, amount)
    VALUES (%s, %s, %s, %s, %s)
    ON CONFLICT DO NOTHING
''', transactions_data)

# Generate and insert data for credit history
credit_history_data = [
    (
        random.choice(customers_data)[0],
        random.randint(1000, 50000),
        random.randint(300, 850)
    )
    for _ in range(300000)
]

cursor.executemany('''
    INSERT INTO credit_history (customer_id, credit_limit, credit_score)
    VALUES (%s, %s, %s)
    ON CONFLICT DO NOTHING
''', credit_history_data)

# Commit the changes
conn.commit()

# Close the connection
close_connection(conn)


# -*- coding: utf-8 -*-
# Automatic Python module class tree generation, using Mermaid for rendering
# source: https://gist.github.com/Zulko/e0910cac1b27bcc3a1e6585eaee60121

import inspect

def class_name(cls):
    """Return a string representing the class"""
    # NOTE: can be changed to str(class) for more complete class info
    return cls.__name__

def classes_tree(module, base_module=None):
    if base_module is None:
        base_module == module.__name__
    module_classes = set()
    inheritances = []
    def inspect_class(cls):
        if class_name(cls) not in module_classes:
            if cls.__module__.startswith(base_module):
                module_classes.add(class_name(cls))
                for base in cls.__bases__:
                    inheritances.append((class_name(base), class_name(cls)))
                    inspect_class(base)
    for cls in [e for e in module.__dict__.values() if inspect.isclass(e)]:
        inspect_class(cls)
    return module_classes, inheritances

def classes_tree_to_mermaid(module_classes, inheritances):
    return "graph TD;\n" + "\n".join(
        list(module_classes) + [
            "%s --> %s" % (a, b)
            for a, b in inheritances
        ]
    )
if __name__ == "__main__":
  #import pizza.region as region
  #module_classes, inheritances = classes_tree(region, base_module='pizza')
  #print (classes_tree_to_mermaid(module_classes, inheritances))

    import pizza.raster as raster
    module_classes, inheritances = classes_tree(raster, base_module='pizza')
    print (classes_tree_to_mermaid(module_classes, inheritances))


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

# distribution.py
# definitions of spatial distribution characters

import math
import statistics

import numpy as np
import pandas as pd
from tqdm import tqdm  # progress bar

from .utils import _azimuth

__all__ = [
    "Orientation",
    "SharedWallsRatio",
    "StreetAlignment",
    "CellAlignment",
    "Alignment",
    "NeighborDistance",
    "MeanInterbuildingDistance",
    "NeighboringStreetOrientationDeviation",
    "BuildingAdjacency",
    "Neighbors",
]

class Orientation:
    """
    Calculate the orientation of object

    Captures the deviation of orientation from cardinal directions.
    Defined as an orientation of the longext axis of bounding rectangle in range 0 - 45.
    Orientation of LineStrings is represented by the orientation of line
    connecting first and last point of the segment.

    Adapted from :cite:`schirmer2015`.

    Parameters
    ----------
    gdf : GeoDataFrame
        GeoDataFrame containing objects to analyse

    Attributes
    ----------
    series : Series
        Series containing resulting values
    gdf : GeoDataFrame
        original GeoDataFrame

    Examples
    --------
    >>> buildings_df['orientation'] = momepy.Orientation(buildings_df).series
    100%|██████████| 144/144 [00:00<00:00, 630.54it/s]
    >>> buildings_df['orientation'][0]
    41.05146788287027
    """

    def __init__(self, gdf):
        self.gdf = gdf
        # define empty list for results
        results_list = []

        def _dist(a, b):
            return math.hypot(b[0] - a[0], b[1] - a[1])

        for geom in tqdm(gdf.geometry, total=gdf.shape[0]):
            if geom.type in ["Polygon", "MultiPolygon", "LinearRing"]:
                # TODO: vectorize once minimum_rotated_rectangle is in geopandas from pygeos
                bbox = list(geom.minimum_rotated_rectangle.exterior.coords)
                axis1 = _dist(bbox[0], bbox[3])
                axis2 = _dist(bbox[0], bbox[1])

                if axis1 <= axis2:
                    az = _azimuth(bbox[0], bbox[1])
                else:
                    az = _azimuth(bbox[0], bbox[3])
            elif geom.type in ["LineString", "MultiLineString"]:
                coords = geom.coords
                az = _azimuth(coords[0], coords[-1])
            else:
                results_list.append(np.nan)

            if 90 > az >= 45:
                diff = az - 45
                az = az - 2 * diff
            elif 135 > az >= 90:
                diff = az - 90
                az = az - 2 * diff
                diff = az - 45
                az = az - 2 * diff
            elif 181 > az >= 135:
                diff = az - 135
                az = az - 2 * diff
                diff = az - 90
                az = az - 2 * diff
                diff = az - 45
                az = az - 2 * diff
            results_list.append(az)

        self.series = pd.Series(results_list, index=gdf.index)

class SharedWallsRatio:
    """
    Calculate shared walls ratio of adjacent elements (typically buildings)

    .. math::
        \\textit{length of shared walls} \\over perimeter

    Note that data needs to be topologically correct. Overlapping polygons will lead to
    incorrect results.

    Adapted from :cite:`hamaina2012a`.

    Parameters
    ----------
    gdf : GeoDataFrame
        GeoDataFrame containing gdf to analyse
    unique_id : str, list, np.array, pd.Series
        the name of the dataframe column, ``np.array``, or ``pd.Series`` with unique id
    perimeters : str, list, np.array, pd.Series (default None)
        the name of the dataframe column, ``np.array``, or ``pd.Series`` where is stored perimeter value

    Attributes
    ----------
    series : Series
        Series containing resulting values
    gdf : GeoDataFrame
        original GeoDataFrame
    id : Series
        Series containing used unique ID
    perimeters : GeoDataFrame
        Series containing used perimeters values
    sindex : rtree spatial index
        spatial index of gdf

    Examples
    --------
    >>> buildings_df['swr'] = momepy.SharedWallsRatio(buildings_df, 'uID').series
    100%|██████████| 144/144 [00:00<00:00, 648.72it/s]
    >>> buildings_df['swr'][10]
    0.3424804411228673
    """

    def __init__(self, gdf, unique_id, perimeters=None):
        self.gdf = gdf

        gdf = gdf.copy()
        self.sindex = gdf.sindex  # define rtree index
        # define empty list for results
        results_list = []

        if perimeters is None:
            gdf["mm_p"] = gdf.geometry.length
            perimeters = "mm_p"
        else:
            if not isinstance(perimeters, str):
                gdf["mm_p"] = perimeters
                perimeters = "mm_p"

        self.perimeters = gdf[perimeters]

        if not isinstance(unique_id, str):
            gdf["mm_uid"] = unique_id
            unique_id = "mm_uid"
        self.id = gdf[unique_id]

        gdf["_bounds"] = gdf.geometry.bounds.apply(list, axis=1)
        for i, row in tqdm(
            enumerate(
                gdf[[perimeters, "_bounds", gdf._geometry_column_name]].itertuples()
            ),
            total=gdf.shape[0],
        ):
            neighbors = list(self.sindex.intersection(row[2]))
            neighbors.remove(i)

            # if no neighbour exists
            length = 0
            if not neighbors:
                results_list.append(0)
            else:
                length = gdf.iloc[neighbors].intersection(row[3]).length.sum()
                results_list.append(length / row[1])

        self.series = pd.Series(results_list, index=gdf.index)

class StreetAlignment:
    """
    Calculate the difference between street orientation and orientation of object in degrees

    Orientation of street segment is represented by the orientation of line
    connecting first and last point of the segment. Network ID linking each object
    to specific street segment is needed. Can be generated by :func:`momepy.get_network_id`.
    Either ``network_id`` or both ``left_network_id`` and ``right_network_id`` are required.

    .. math::
        \\left|{\\textit{building orientation} - \\textit{street orientation}}\\right|

    Parameters
    ----------
    left : GeoDataFrame
        GeoDataFrame containing objects to analyse
    right : GeoDataFrame
        GeoDataFrame containing street network
    orientations : str, list, np.array, pd.Series
        the name of the dataframe column, ``np.array``, or ``pd.Series`` where is stored object orientation value
        (can be calculated using :class:`momepy.Orientation`)
    network_id : str (default None)
        the name of the column storing network ID in both left and right
    left_network_id : str, list, np.array, pd.Series (default None)
        the name of the left dataframe column, ``np.array``, or ``pd.Series`` where is stored object network ID
    right_network_id : str, list, np.array, pd.Series (default None)
        the name of the right dataframe column, ``np.array``, or ``pd.Series`` of streets with unique network id (has to be defined beforehand)
        (can be defined using :func:`momepy.unique_id`)

    Attributes
    ----------
    series : Series
        Series containing resulting values
    left : GeoDataFrame
        original left GeoDataFrame
    right : GeoDataFrame
        original right GeoDataFrame
    network_id : str
        the name of the column storing network ID in both left and right
    left_network_id : Series
        Series containing used left ID
    right_network_id : Series
        Series containing used right ID

    Examples
    --------
    >>> buildings_df['street_alignment'] = momepy.StreetAlignment(buildings_df, streets_df, 'orientation', 'nID', 'nID').series
    100%|██████████| 144/144 [00:00<00:00, 529.94it/s]
    >>> buildings_df['street_alignment'][0]
    0.29073888476702336
    """

    def __init__(
        self,
        left,
        right,
        orientations,
        network_id=None,
        left_network_id=None,
        right_network_id=None,
    ):
        self.left = left
        self.right = right
        self.network_id = network_id

        left = left.copy()
        right = right.copy()

        if network_id:
            left_network_id = network_id
            right_network_id = network_id
        else:
            if left_network_id is None and right_network_id is not None:
                raise ValueError("left_network_id not set.")
            if left_network_id is not None and right_network_id is None:
                raise ValueError("right_network_id not set.")
            if left_network_id is None and right_network_id is None:
                raise ValueError(
                    "Network ID not set. Use either network_id or left_network_id and right_network_id."
                )

        if not isinstance(orientations, str):
            left["mm_o"] = orientations
            orientations = "mm_o"
        self.orientations = left[orientations]

        if not isinstance(left_network_id, str):
            left["mm_nid"] = left_network_id
            left_network_id = "mm_nid"
        self.left_network_id = left[left_network_id]
        if not isinstance(right_network_id, str):
            right["mm_nis"] = right_network_id
            right_network_id = "mm_nis"
        self.right_network_id = right[right_network_id]

        right["_orientation"] = Orientation(right).series

        merged = left[[left_network_id, orientations]].merge(
            right[[right_network_id, "_orientation"]],
            left_on=left_network_id,
            right_on=right_network_id,
            how="left",
        )

        self.series = np.abs(merged[orientations] - merged["_orientation"])

class CellAlignment:
    """
    Calculate the difference between cell orientation and orientation of object

    .. math::
        \\left|{\\textit{building orientation} - \\textit{cell orientation}}\\right|

    Parameters
    ----------
    left : GeoDataFrame
        GeoDataFrame containing objects to analyse
    right : GeoDataFrame
        GeoDataFrame containing tessellation cells (or relevant spatial units)
    left_orientations : str, list, np.array, pd.Series
        the name of the left dataframe column, ``np.array``, or ``pd.Series`` where is stored object orientation value
        (can be calculated using :class:`momepy.Orientation`)
    right_orientations : str, list, np.array, pd.Series
        the name of the right dataframe column, ``np.array``, or ``pd.Series`` where is stored object orientation value
        (can be calculated using :class:`momepy.Orientation`)
    left_unique_id : str
        the name of the ``left`` dataframe column with unique id shared between ``left`` and ``right`` gdf
    right_unique_id : str
        the name of the ``right`` dataframe column with unique id shared between ``left`` and ``right`` gdf

    Attributes
    ----------
    series : Series
        Series containing resulting values
    left : GeoDataFrame
        original left GeoDataFrame
    right : GeoDataFrame
        original right GeoDataFrame
    left_orientations : Series
        Series containing used left orientations
    right_orientations : Series
        Series containing used right orientations
    left_unique_id : Series
        Series containing used left ID
    right_unique_id : Series
        Series containing used right ID

    Examples
    --------
    >>> buildings_df['cell_alignment'] = momepy.CellAlignment(buildings_df, tessellation_df, 'bl_orient', 'tes_orient', 'uID', 'uID').series
    100%|██████████| 144/144 [00:00<00:00, 799.09it/s]
    >>> buildings_df['cell_alignment'][0]
    0.8795123936951939

    """

    def __init__(
        self,
        left,
        right,
        left_orientations,
        right_orientations,
        left_unique_id,
        right_unique_id,
    ):
        self.left = left
        self.right = right

        left = left.copy()
        right = right.copy()
        if not isinstance(left_orientations, str):
            left["mm_o"] = left_orientations
            left_orientations = "mm_o"
        self.left_orientations = left[left_orientations]
        if not isinstance(right_orientations, str):
            right["mm_o"] = right_orientations
            right_orientations = "mm_o"
        self.right_orientations = right[right_orientations]
        self.left_unique_id = left[left_unique_id]
        self.right_unique_id = right[right_unique_id]

        comp = left[[left_unique_id, left_orientations]].merge(
            right[[right_unique_id, right_orientations]],
            left_on=left_unique_id,
            right_on=right_unique_id,
            how="left",
        )
        if left_orientations == right_orientations:
            left_orientations = left_orientations + "_x"
            right_orientations = right_orientations + "_y"
        self.series = np.absolute(comp[left_orientations] - comp[right_orientations])
        self.series.index = left.index

class Alignment:

    """
    Calculate the mean deviation of solar orientation of objects on adjacent cells from an object

    .. math::
        \\frac{1}{n}\\sum_{i=1}^n dev_i=\\frac{dev_1+dev_2+\\cdots+dev_n}{n}

    Parameters
    ----------
    gdf : GeoDataFrame
        GeoDataFrame containing objects to analyse
    spatial_weights : libpysal.weights, optional
        spatial weights matrix
    orientations : str, list, np.array, pd.Series
        the name of the left dataframe column, ``np.array``, or ``pd.Series`` where is stored object orientation value
        (can be calculated using :class:`momepy.Orientation`)
    unique_id : str
        name of the column with unique id used as ``spatial_weights`` index.

    Attributes
    ----------
    series : Series
        Series containing resulting values
    gdf : GeoDataFrame
        original GeoDataFrame
    orientations : Series
        Series containing used orientation values
    sw : libpysal.weights
        spatial weights matrix
    id : Series
        Series containing used unique ID

    Examples
    --------
    >>> buildings_df['alignment'] = momepy.Alignment(buildings_df, sw, 'uID', bl_orient).series
    100%|██████████| 144/144 [00:01<00:00, 140.84it/s]
    >>> buildings_df['alignment'][0]
    18.299481296455237
    """

    def __init__(self, gdf, spatial_weights, unique_id, orientations):
        self.gdf = gdf
        self.sw = spatial_weights
        self.id = gdf[unique_id]

        # define empty list for results
        results_list = []
        gdf = gdf.copy()
        if not isinstance(orientations, str):
            gdf["mm_o"] = orientations
            orientations = "mm_o"
        self.orientations = gdf[orientations]

        data = gdf.set_index(unique_id)[orientations]

        # iterating over rows one by one
        for index, orient in tqdm(data.iteritems(), total=data.shape[0]):
            if index in spatial_weights.neighbors.keys():
                neighbours = spatial_weights.neighbors[index].copy()
                if neighbours:
                    orientation = data.loc[neighbours]
                    deviations = abs(orientation - orient)

                    results_list.append(statistics.mean(deviations))
                else:
                    results_list.append(np.nan)
            else:
                results_list.append(np.nan)

        self.series = pd.Series(results_list, index=gdf.index)

class NeighborDistance:
    """
    Calculate the mean distance to adjacent buildings (based on ``spatial_weights``)

    If no neighbours are found, return ``np.nan``.

    .. math::
        \\frac{1}{n}\\sum_{i=1}^n dist_i=\\frac{dist_1+dist_2+\\cdots+dist_n}{n}

    Adapted from :cite:`schirmer2015`.

    Parameters
    ----------
    gdf : GeoDataFrame
        GeoDataFrame containing objects to analyse
    spatial_weights : libpysal.weights
        spatial weights matrix based on unique_id
    unique_id : str
        name of the column with unique id used as ``spatial_weights`` index.

    Attributes
    ----------
    series : Series
        Series containing resulting values
    gdf : GeoDataFrame
        original GeoDataFrame
    sw : libpysal.weights
        spatial weights matrix
    id : Series
        Series containing used unique ID

    Examples
    --------
    >>> buildings_df['neighbour_distance'] = momepy.NeighborDistance(buildings_df, sw, 'uID').series
    100%|██████████| 144/144 [00:00<00:00, 345.78it/s]
    >>> buildings_df['neighbour_distance'][0]
    29.18589019096464
    """

    def __init__(self, gdf, spatial_weights, unique_id):
        self.gdf = gdf
        self.sw = spatial_weights
        self.id = gdf[unique_id]
        # define empty list for results
        results_list = []

        data = gdf.set_index(unique_id).geometry

        # iterating over rows one by one
        for index, geom in tqdm(data.iteritems(), total=data.shape[0]):
            if index in spatial_weights.neighbors.keys():
                neighbours = spatial_weights.neighbors[index]
                building_neighbours = data.loc[neighbours]
                if len(building_neighbours) > 0:
                    results_list.append(
                        building_neighbours.geometry.distance(geom).mean()
                    )
                else:
                    results_list.append(np.nan)
            else:
                results_list.append(np.nan)

        self.series = pd.Series(results_list, index=gdf.index)

class MeanInterbuildingDistance:
    """
    Calculate the mean interbuilding distance

    Interbuilding distances are calculated between buildings on adjacent cells based on
    ``spatial_weights``, while the extent is defined in ``spatial_weights_higher``.

    .. math::

    Parameters
    ----------
    gdf : GeoDataFrame
        GeoDataFrame containing objects to analyse
    unique_id : str
        name of the column with unique id used as ``spatial_weights`` index
    spatial_weights : libpysal.weights
        spatial weights matrix
    spatial_weights_higher : libpysal.weights, optional
        spatial weights matrix - If None, Queen contiguity of a higher ``order`` will be calculated
        based on ``spatial_weights``
    order : int
        Order of Queen contiguity

    Attributes
    ----------
    series : Series
        Series containing resulting values
    gdf : GeoDataFrame
        original GeoDataFrame
    sw : libpysal.weights
        spatial weights matrix
    id : Series
        Series containing used unique ID
    sw_higher : libpysal.weights
        Spatial weights matrix of higher order
    order : int
        Order of Queen contiguity (only if spatial_weights_higher was not set)

    Notes
    -----
    Fix UserWarning.

    Examples
    --------
    >>> buildings_df['mean_interbuilding_distance'] = momepy.MeanInterbuildingDistance(buildings_df, sw, 'uID').series
    Generating weights matrix (Queen) of 3 topological steps...
    Generating adjacency matrix based on weights matrix...
    Computing interbuilding distances...
    100%|██████████| 746/746 [00:03<00:00, 200.14it/s]
    Computing mean interbuilding distances...
    100%|██████████| 144/144 [00:00<00:00, 317.42it/s]
    >>> buildings_df['mean_interbuilding_distance'][0]
    29.305457092042744
    """

    def __init__(
        self, gdf, spatial_weights, unique_id, spatial_weights_higher=None, order=3
    ):
        self.gdf = gdf
        self.sw = spatial_weights
        self.id = gdf[unique_id]

        if spatial_weights_higher is None:
            print(
                "Generating weights matrix (Queen) of {} topological steps...".format(
                    order
                )
            )
            self.order = order
            from momepy import sw_high

            # matrix to define area of analysis (more steps)
            spatial_weights_higher = sw_high(k=order, weights=spatial_weights)
        self.sw_higher = spatial_weights_higher

        data = gdf.set_index(unique_id).geometry

        # define empty list for results
        results_list = []

        print("Generating adjacency matrix based on weights matrix...")
        # define adjacency list from lipysal
        adj_list = spatial_weights.to_adjlist()
        adj_list["distance"] = -1

        print("Computing interbuilding distances...")
        # measure each interbuilding distance of neighbours and save them to adjacency list
        for row in tqdm(adj_list.itertuples(), total=adj_list.shape[0]):
            inverted = adj_list[(adj_list.focal == row.neighbor)][
                (adj_list.neighbor == row.focal)
            ].iloc[0]["distance"]
            if inverted == -1:
                building_object = data.loc[row.focal]

                building_neighbour = data.loc[row.neighbor]
                adj_list.loc[row.Index, "distance"] = building_neighbour.distance(
                    building_object
                )
            else:
                adj_list.at[row.Index, "distance"] = inverted

        print("Computing mean interbuilding distances...")
        # iterate over objects to get the final values
        for uid in tqdm(data.index, total=data.shape[0]):
            # define neighbours based on weights matrix defining analysis area
            if uid in spatial_weights_higher.neighbors.keys():
                neighbours = spatial_weights_higher.neighbors[uid].copy()
                neighbours.append(uid)
                if neighbours:
                    selection = adj_list[adj_list.focal.isin(neighbours)][
                        adj_list.neighbor.isin(neighbours)
                    ]
                    results_list.append(np.nanmean(selection.distance))
            else:
                results_list.append(np.nan)

        self.series = pd.Series(results_list, index=gdf.index)

class NeighboringStreetOrientationDeviation:
    """
    Calculate the mean deviation of solar orientation of adjacent streets

    Orientation of street segment is represented by the orientation of line
    connecting first and last point of the segment.

    .. math::
        \\frac{1}{n}\\sum_{i=1}^n dev_i=\\frac{dev_1+dev_2+\\cdots+dev_n}{n}

    Parameters
    ----------
    gdf : GeoDataFrame
        GeoDataFrame containing street network to analyse

    Attributes
    ----------
    series : Series
        Series containing resulting values
    gdf : GeoDataFrame
        original GeoDataFrame
    orientation : Series
        Series containing used street orientation values
    sindex : rtree spatial index
        spatial index of gdf

    Examples
    --------
    >>> streets_df['orient_dev'] = momepy.NeighboringStreetOrientationDeviation(streets_df).series
    Preparing street orientations...
    Generating spatial index...
    100%|██████████| 33/33 [00:00<00:00, 249.02it/s]
    >>> streets_df['orient_dev'][6]
    7.043096518688273
    """

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

        results_list = []
        gdf = gdf.copy()

        # iterating over rows one by one
        print(" Preparing street orientations...")
        for geom in tqdm(gdf.geometry, total=gdf.shape[0]):

            start = geom.coords[0]
            end = geom.coords[-1]
            az = _azimuth(start, end)
            if 90 > az >= 45:
                diff = az - 45
                az = az - 2 * diff
            elif 135 > az >= 90:
                diff = az - 90
                az = az - 2 * diff
                diff = az - 45
                az = az - 2 * diff
            elif 181 > az >= 135:
                diff = az - 135
                az = az - 2 * diff
                diff = az - 90
                az = az - 2 * diff
                diff = az - 45
                az = az - 2 * diff
            results_list.append(az)
        self.orientation = pd.Series(results_list, index=gdf.index)

        gdf["tmporient"] = self.orientation

        print(" Generating spatial index...")
        self.sindex = gdf.sindex
        results_list = []

        for row in tqdm(gdf.itertuples(), total=gdf.shape[0]):
            possible_neighbors_idx = list(self.sindex.intersection(row.geometry.bounds))
            possible_neighbours = gdf.iloc[possible_neighbors_idx]
            neighbors = possible_neighbours[
                possible_neighbours.intersects(row.geometry)
            ]
            neighbors.drop([row.Index])

            deviations = np.abs(neighbors.tmporient - row.tmporient)

            if not deviations.empty:
                results_list.append(np.mean(deviations))
            else:
                results_list.append(0)

        self.series = pd.Series(results_list, index=gdf.index)

class BuildingAdjacency:
    """
    Calculate the level of building adjacency

    Building adjacency reflects how much buildings tend to join together into larger structures.
    It is calculated as a ratio of joined built-up structures and buildings within
    the extent defined in ``spatial_weights_higher``.

    Adapted from :cite:`vanderhaegen2017`.

    Parameters
    ----------
    gdf : GeoDataFrame
        GeoDataFrame containing objects to analyse
    spatial_weights_higher : libpysal.weights
        spatial weights matrix
    unique_id : str
        name of the column with unique id used as ``spatial_weights`` index
    spatial_weights : libpysal.weights, optional
        spatial weights matrix - If None, Queen contiguity matrix will be calculated
        based on gdf. It is to denote adjacent buildings (note: based on unique ID).

    Attributes
    ----------
    series : Series
        Series containing resulting values
    gdf : GeoDataFrame
        original GeoDataFrame
    sw_higher : libpysal.weights
        spatial weights matrix
    id : Series
        Series containing used unique ID
    sw : libpysal.weights
        spatial weights matrix

    Examples
    --------
    >>> buildings_df['adjacency'] = momepy.BuildingAdjacency(buildings_df, swh, unique_id='uID').series
    Calculating spatial weights...
    Spatial weights ready...
    100%|██████████| 144/144 [00:00<00:00, 9301.73it/s]
    Calculating adjacency...
    100%|██████████| 144/144 [00:00<00:00, 335.55it/s]
    >>> buildings_df['adjacency'][10]
    0.23809523809523808
    """

    def __init__(self, gdf, spatial_weights_higher, unique_id, spatial_weights=None):
        self.gdf = gdf
        self.sw_higher = spatial_weights_higher
        self.id = gdf[unique_id]
        results_list = []

        # if weights matrix is not passed, generate it from gdf
        if spatial_weights is None:
            print("Calculating spatial weights...")
            from libpysal.weights import Queen

            spatial_weights = Queen.from_dataframe(
                gdf, silence_warnings=True, ids=unique_id
            )
            print("Spatial weights ready...")

        self.sw = spatial_weights
        patches = dict(zip(gdf[unique_id], spatial_weights.component_labels))

        print("Calculating adjacency...")
        for uid in tqdm(self.id, total=gdf.shape[0]):
            if uid in spatial_weights_higher.neighbors.keys():
                neighbours = spatial_weights_higher.neighbors[uid].copy()
                if neighbours:
                    neighbours.append(uid)

                    patches_sub = [patches[x] for x in neighbours]
                    patches_nr = len(set(patches_sub))

                    results_list.append(patches_nr / len(neighbours))
                else:
                    results_list.append(np.nan)
            else:
                results_list.append(np.nan)

        self.series = pd.Series(results_list, index=gdf.index)

class Neighbors:
    """
    Calculate the number of neighbours captured by ``spatial_weights``

    If ``weighted=True``, number of neighbours will be divided by the perimeter of object
    to return relative value.

    Adapted from :cite:`hermosilla2012`.

    Parameters
    ----------
    gdf : GeoDataFrame
        GeoDataFrame containing objects to analyse
    spatial_weights : libpysal.weights
        spatial weights matrix
    unique_id : str
        name of the column with unique id used as ``spatial_weights`` index
    weighted : bool (default False)
        if ``True``, number of neighbours will be divided by the perimeter of object, to return relative value

    Attributes
    ----------
    series : Series
        Series containing resulting values
    gdf : GeoDataFrame
        original GeoDataFrame
    values : Series
        Series containing used values
    sw : libpysal.weights
        spatial weights matrix
    id : Series
        Series containing used unique ID
    weighted : bool
        used weighted value

    Examples
    --------
    >>> sw = libpysal.weights.contiguity.Queen.from_dataframe(tessellation_df, ids='uID')
    >>> tessellation_df['neighbours'] = momepy.Neighbors(tessellation_df, sw, 'uID').series
    100%|██████████| 144/144 [00:00<00:00, 6909.50it/s]
    >>> tessellation_df['neighbours'][0]
    4
    """

    def __init__(self, gdf, spatial_weights, unique_id, weighted=False):
        self.gdf = gdf
        self.sw = spatial_weights
        self.id = gdf[unique_id]
        self.weighted = weighted

        neighbours = []
        for index, geom in tqdm(
            gdf.set_index(unique_id).geometry.iteritems(), total=gdf.shape[0]
        ):
            if index in spatial_weights.neighbors.keys():
                if weighted is True:
                    neighbours.append(
                        spatial_weights.cardinalities[index] / geom.length
                    )
                else:
                    neighbours.append(spatial_weights.cardinalities[index])
            else:
                neighbours.append(np.nan)

        self.series = pd.Series(neighbours, index=gdf.index)