#Flexcontrol2.1
from tkinter import*
from tkinter import ttk
from tkinter import messagebox as mb
import openpyxl as op
from datetime import date, timedelta, datetime
from fpdf import FPDF
import requests
import obtenerTokenmodulo as otm

#valores:
flexcaba=250
flexgba1=400
flexgba2=500

mercadocaba=379.99
mercadogba1=599.99
mercadogba2=819.99

tok_losada=False
tok_vallarta=False
dic_envio={}
dic_traduccion={
	'cancelled':"cancelado",
	'shipped':"en camino",
	'delivered':"entregado",
	'ready_to_ship':"En preparación",
	'pending':"pendiente"
}
dic_posicionexcel={}
dic_cambiodestino={}
fr2=False
lis_fact=[]
lam_vendedor = lambda x: "Losada" if x ==str(553279780) else"Vallarta"
wb = op.load_workbook('flexcontrol.xlsx')

dic_vgenerales={'CABA':0,'GBA 1':0,'GBA 2':0}
dic_precios={'CABA':mercadocaba,'GBA 1':mercadogba1,'GBA 2':mercadogba2}

def pretoken():
	global tok_losada
	tok_losada=otm.revisar_token_activo("losada")
	if tok_losada==False:
		otm.obtenertoken("losada")
	else:
		pass

	global tok_vallarta
	tok_vallarta=otm.revisar_token_activo("vallarta")
	if tok_vallarta==False:
		otm.obtenertoken("vallarta")
		#pretoken()
	else:
		pass
def cargarventas(tok):
	vendedor=otm.obtener_vendedor(tok)
	fecha=date.today()
	ayer=fecha+timedelta(days=-1)
	if ayer.weekday() == 6:
		ayer=ayer+timedelta(days=-2)
	fecha_a=ayer.strftime("%Y-%m-%d")
	fecha_b=fecha.strftime("%Y-%m-%d")
	url="https://api.mercadolibre.com/orders/search?seller="+str(vendedor)+"&order.date_created.from="+str(fecha_a)+"T12:00:00.000-04:00&order.date_created.to="+str(fecha_b)+"T12:00:00.000-04:00"
	headers={'Authorization': 'Bearer '+tok}
	r = requests.get(url, headers=headers)
	if r.status_code == 200:
		rjson=r.json()
		results=rjson['results']
		for item in results:
			ident_orden=item['id']
			shipping=item['shipping']
			url="https://api.mercadolibre.com/shipments/"+str(shipping['id'])
			headers={'Authorization': 'Bearer '+tok}
			r2 = requests.get(url, headers=headers)
			if r2.status_code == 200:
				rjson2=r2.json()
				logistic=rjson2['logistic_type']
				if logistic == 'self_service':
					option=rjson2['shipping_option']
					costo=option['cost']
					costo_base=option['list_cost']
					direccion=rjson2['receiver_address']
					provincia=direccion['state']['name']
					ciudad=direccion['city']['name']
					descuento=rjson2['cost_components']['loyal_discount']
					status=rjson2['status']
					if costo != costo_base:
						costo_final=option['list_cost']
						bonificado=True
					elif costo_base==0:
						costo_final=0
					else:
						porcentaje=1-descuento
						costo_final=(costo_base)/porcentaje
						bonificado=False
					dic_envio[shipping['id']]=[costo_final,bonificado,vendedor,ident_orden,provincia,ciudad,status]
					if status != 'cancelled':
						guardar_excel(shipping['id'],costo_final,bonificado,vendedor,ident_orden)
def guardar_excel(nopera,destino,bonificado,vendedor,orden):
	fecha=date.today()
	hojas = wb.sheetnames
	if str(fecha) not in hojas:
		wb.create_sheet(str(fecha))
		sheet = wb[str(fecha)]
		sheet['A1'].value = 'Número de operación'
		sheet['B1'].value = 'Tipo'
		sheet['C1'].value = 'Destino'
		sheet['D1'].value = 'Bonificado'
		sheet['E1'].value = 'Vendedor'
		sheet['F1'].value = 'Factura'
		sheet['G1'].value = 'orden'
	else:
		sheet = wb[str(fecha)]
	guardado=False
	u = (sheet.max_row + 1)
	for x in range(1, u):
		xrow = sheet.cell(column=1, row=x).value
		if str(xrow) == str(nopera):
			if sheet.cell(column=3, row=x).value == None:
				dic_envio[nopera][0]=0
			elif sheet.cell(column=3, row=x).value == "CABA":
				dic_envio[nopera][0]=309.99
			elif sheet.cell(column=3, row=x).value == "GBA 1":
				dic_envio[nopera][0]=479.99
			else:
				dic_envio[nopera][0]=649.99
			dic_posicionexcel[nopera]=x
			guardado=True
	if guardado==False:
		sheet.cell(column=1, row=u).value = nopera
		sheet.cell(column=2, row=u).value = 1
		if destino==0:
			sheet.cell(column=3, row=u).value = None
		elif destino<310:
			sheet.cell(column=3, row=u).value = "CABA"
		elif destino <480:
			sheet.cell(column=3, row=u).value = "GBA 1"
		else:
			sheet.cell(column=3, row=u).value = "GBA 2"
		sheet.cell(column=4, row=u).value = bonificado
		if vendedor == str(553279780):
			sheet.cell(column=5, row=u).value = "Losada"
		else:
			sheet.cell(column=5, row=u).value = "Vallarta"
		sheet.cell(column=7, row=u).value = orden
		dic_posicionexcel[nopera]=u
	wb.save('flexcontrol.xlsx')
def contarenvios():
	fecha=date.today()
	sheet = wb[str(fecha)]
	u = (sheet.max_row - 1)
	label_contar_tit=Label(encabezado,text="Envíos del día:")
	label_contar_tit.grid(column=3,row=2)
	label_contar=Label(encabezado,text=u)
	label_contar.grid(column=4,row=2)
def deslplegarenvios():
	global frame2
	lis_fact.clear()
	fecha=date.today()
	sheet = wb[str(fecha)]
	frame2=Frame(frame_activo)
	frame2.pack(fill=BOTH, expand=1)
	canvas = Canvas(frame2)
	canvas.pack(side=LEFT, fill=BOTH, expand=1)
	scroll = ttk.Scrollbar(frame2, orient=VERTICAL, command=canvas.yview)
	scroll.pack(side=RIGHT, fill=Y)
	#scroll2 = ttk.Scrollbar(frame2, orient=HORIZONTAL, command=canvas.xview)
	#scroll2.pack(side=BOTTOM, fill=X)
	canvas.configure(yscrollcommand=scroll.set)
	canvas.bind('<Configure>', lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
	global frame_de_envios
	frame_de_envios = Frame(canvas)
	canvas.create_window((0,0), window=frame_de_envios, anchor="nw")
	z=0
	for item in dic_envio:
		desplegados=[]
		label_numenvio=Label(frame_de_envios,text=item)
		label_numenvio.grid(column=0,row=z)
		label_numorden=Label(frame_de_envios,text=dic_envio[item][3])
		label_numorden.grid(column=1,row=z)
		label_provincia=Label(frame_de_envios,text=dic_envio[item][4])
		label_provincia.grid(column=2,row=z)
		label_ciudad=Label(frame_de_envios,text=dic_envio[item][5])
		label_ciudad.grid(column=3,row=z)
		if dic_envio[item][0] == 0:
			entry_costo= Entry(frame_de_envios, width=4)
			entry_costo.grid(column=4,row=z)
			dic_cambiodestino[z]=entry_costo
		else:
			label_costo=Label(frame_de_envios,text='${:,.2f}'.format(dic_envio[item][0]))
			label_costo.grid(column=4,row=z)
		label_bonificado=Label(frame_de_envios,text=dic_envio[item][1])
		label_bonificado.grid(column=5,row=z)
		entry_factura= Entry(frame_de_envios, width=7)
		entry_factura.grid(column=6,row=z)
		fact=sheet.cell(column=6, row=dic_posicionexcel[item]).value
		if fact != None:
			entry_factura.insert(END,fact)
		lis_fact.append(entry_factura)
		label_vendedor=Label(frame_de_envios,text=lam_vendedor(dic_envio[item][2]))
		label_vendedor.grid(column=7,row=z)
		label_status=Label(frame_de_envios,text=dic_traduccion[dic_envio[item][-1]])
		label_status.grid(column=8,row=z)
		z+=1
def botoncargarventas():
	cargarventas(tok_vallarta)
	cargarventas(tok_losada)
	contarenvios()
	global fr2
	if fr2==True:
		global frame2
		frame2.destroy()
	deslplegarenvios()
	fr2=True
def guardar():
	fecha=date.today()
	hojas = wb.sheetnames
	if str(fecha) not in hojas:
		mb.showerror("Error","Primero es necesario cargar ventas")
	else:
		sheet = wb[str(fecha)]
	global frame_de_envios
	b=2
	for item in lis_fact:
		num_fact=item.get()
		sheet.cell(column=6, row=b).value = num_fact
		if num_fact != "":
			item.destroy()
			label_fact = Label(frame_de_envios, text=num_fact)
			label_fact.grid(column=6,row=(b-2))
		else:
			pass
		try:
			destino=dic_cambiodestino[b-2].get()
			if destino !="":
				if float(destino)==0:
					sheet.cell(column=3, row=b).value = None
				elif float(destino)<310:
					sheet.cell(column=3, row=b).value = "CABA"
				elif float(destino)<480:
					sheet.cell(column=3, row=b).value = "GBA 1"
				else:
					sheet.cell(column=3, row=b).value = "GBA 2"
				dic_cambiodestino[b-2].destroy()
				label_dest = Label(frame_de_envios, text='${:,.2f}'.format(float(destino)))
				label_dest.grid(column=4,row=(b-2))
				dic_envio[sheet.cell(column=1, row=b).value][0]=destino
				del dic_cambiodestino[b-2]
		except KeyError:
			pass
		b+=1
		wb.save('flexcontrol.xlsx')
	lis_fact.clear()
	mb.showinfo("Aviso","Guardado Satisfactoriamente")
def modificar():
	global lis_fact
	lis_fact.clear()
	fecha=date.today()
	hojas = wb.sheetnames
	if str(fecha) not in hojas:
		mb.showerror("Error","Primero es necesario cargar ventas")
	else:
		sheet = wb[str(fecha)]
	global frame_de_envios
	z=0
	for item in dic_envio:
		fact=sheet.cell(column=6, row=(z+2)).value
		entry_factura= Entry(frame_de_envios, width=7)
		entry_factura.grid(column=6,row=z)
		entry_factura.insert(END,fact)
		lis_fact.append(entry_factura)
		z+=1
def agregarenviopropio():
	global agregar_top
	agregar_top = Toplevel(raiz)
	agregar_frame=Frame(agregar_top)
	agregar_frame.pack()
	nfact_label =Label(agregar_frame, text="Número de factura:")
	nfact_label.grid(column=1, row=1)
	global nfact_entry
	nfact_entry = Entry(agregar_frame, width=8)
	nfact_entry.grid(column=2, row=1)
	destino_label =Label(agregar_frame, text="Destino:")
	destino_label.grid(column=1, row=2)
	global lugar
	lugar = ttk.Combobox(agregar_frame, values=['CABA', 'GBA 1', 'GBA 2'])
	lugar.grid(column=2, row=2)
	lugar.current(0)
	vendedor_label =Label(agregar_frame, text="Vendedor:")
	vendedor_label.grid(column=1, row=3)
	global vendedor_combo
	vendedor_combo = ttk.Combobox(agregar_frame, values=['Losada', 'Vallarta'])
	vendedor_combo.grid(column=2, row=3)
	vendedor_combo.current(0)
	boton_guardar_envpropio = Button(agregar_frame, text="Guardar", command=guardarenviopropio)
	boton_guardar_envpropio.grid(column=2,row=4)
def guardarenviopropio():
	global nfact_entry
	nfact=nfact_entry.get()
	global lugar
	luga = lugar.get()
	if luga == "CABA":
		valor=309.99
	elif luga == "GBA 1":
		valor=479.99
	else:
		valor=649.99
	global vendedor_combo
	combo = vendedor_combo.get()
	if combo == "Losada":
		vend=str(553279780)
	else:
		vend="Vallarta"
	dic_envio[nfact]=[int(valor),False,vend,nfact,luga,luga,"ready_to_ship"]
	guardar_excel(nfact,valor,False,vend,nfact)
	contarenvios()
	global frame2
	frame2.destroy()
	deslplegarenvios()
	global agregar_top
	agregar_top.destroy()
def ventanacalcular():
	today = date.today()
	global calc
	calc = Toplevel(raiz)
	aframe = Frame(calc)
	aframe.grid(column=0,row=0)
	global ingre_fecha
	ingre_fecha_label = Label(aframe, text="Último día de la semana: (AAAA-MM-DD):")
	ingre_fecha_label.grid(column=1, row=1)
	ingre_fecha = Entry(aframe, width=10)
	ingre_fecha.insert(END, today)
	ingre_fecha.grid(column=2, row=1)
	global check_vallarta_var
	check_vallarta_var = BooleanVar()
	check_vallarta=Checkbutton(aframe,text="Vallarta",var=check_vallarta_var)
	check_vallarta.grid(column=0, row=2)
	global check_losada_var
	check_losada_var = BooleanVar()
	check_losada=Checkbutton(aframe,text="Losada",var=check_losada_var)
	check_losada.grid(column=0, row=3)
	global rframe
	rframe = Frame(calc)
	rframe.grid(column=0,row=1)
	resul_label =Label(rframe, text="Resultados:")
	resul_label.grid(column=1, row=1)
	resul_caba_label =Label(rframe, text="Cantidad de envíos en CABA:")
	resul_caba_label.grid(column=1, row=2)
	resul_gba1_label =Label(rframe, text="Cantidad de envíos en GBA 1:")
	resul_gba1_label.grid(column=1, row=3)
	resul_gba2_label =Label(rframe, text="Cantidad de envíos en GBA 2:")
	resul_gba2_label.grid(column=1, row=4)
	resul_paga_label =Label(rframe, text="Cantidad a pagar:")
	resul_paga_label.grid(column=1, row=5)
	resul_paga2_label =Label(rframe, text="Cantidad de dinero recibido:")
	resul_paga2_label.grid(column=1, row=6)
	resul_paga3_label =Label(rframe, text="Saldo a pagar:")
	resul_paga3_label.grid(column=1, row=7)

	boton_calcular = Button(aframe, text="Calcular", command=precalcular)
	boton_calcular.grid(column=1, row=2)
	boton_detalles = Button(aframe, text="Detalles", command=precalcular2)
	boton_detalles.grid(column=2, row=2)
	boton_exportar = Button(aframe, text="Exportar Informe", command=exportarinforme)
	boton_exportar.grid(column=3, row=2)
def precalcular():
	global ingre_fecha
	fecharaw = ingre_fecha.get()
	year, month, day = map(int, fecharaw.split('-'))
	fecha = date(year, month, day)
	global check_losada_var
	global check_vallarta_var
	vendlosada = check_losada_var.get()
	vendvallarta = check_vallarta_var.get()
	if vendlosada == True and vendvallarta==False:
		vendedorc='Losada'
	elif vendlosada == False and vendvallarta==True:
		vendedorc='Vallarta'
	else:
		vendedorc='nada'
	calcular(fecha,vendedorc)
	dic_vgenerales['CABA']=0
	dic_vgenerales['GBA 1']=0
	dic_vgenerales['GBA 2']=0
def calculo(u, sheet, destino, vendedorc):
	lis_dest = []
	lis_bon=[]
	lis_ent=[]
	lis_prop=[]
	for x in range(1,u):
		if sheet.cell(column=5, row=x).value==vendedorc:
			xdestino=sheet.cell(column=3, row=x).value
			xbonificado = sheet.cell(column=4, row=x).value
			xtipo = sheet.cell(column=2, row=x).value
			if xdestino == destino:
				lis_dest.append('x')
				if xtipo == 2:
					lis_prop.append('x')
				else:
					if xbonificado==True:
						lis_bon.append('x')
					else:
						lis_ent.append('x')
	global drecibido
	drecibido += float((int(len(lis_bon)) * round(dic_precios[destino]/2))+(int(len(lis_ent))*dic_precios[destino]))
	dic_vgenerales[destino]+=len(lis_dest)
def detallador(u,sheet,destino,vendedorc):
	lis_dest=[]
	for x in range(1,u):
		if sheet.cell(column=5, row=x).value==vendedorc:
			xdestino=sheet.cell(column=3, row=x).value
			if xdestino == destino:
				lis_dest.append('x')
	return len(lis_dest)
def calcular(fecha, vendedor):
	ini = fecha
	fin = ini + timedelta(days=-7)
	global drecibido
	drecibido = int(0)

	try:
		while ini >= fin:
			sheet = wb[str(ini)]
			u = (sheet.max_row + 1)
			calculo(u,sheet,'CABA',vendedor)
			calculo(u,sheet,'GBA 1',vendedor)
			calculo(u,sheet,'GBA 2',vendedor)
			ini = ini + timedelta(days=-1)
	except KeyError:
		pass
	pagaraflex = float((dic_vgenerales['CABA']*flexcaba)+(dic_vgenerales['GBA 1']*flexgba1)+(dic_vgenerales['GBA 2']*flexgba2))
	totalapagar = float(pagaraflex-drecibido)
	global rframe
	bell2 = Label(rframe, text=dic_vgenerales['CABA'])
	bell2.grid(column=2, row=2)
	bell = Label(rframe, text=dic_vgenerales['GBA 1'])
	bell.grid(column=2, row=3)
	bell3 = Label(rframe, text=dic_vgenerales['GBA 2'])
	bell3.grid(column=2, row=4)
	bell4 = Label(rframe, text='${:,.2f}'.format(pagaraflex))
	bell4.grid(column=2, row=5)
	bell5 = Label(rframe, text='${:,.2f}'.format(drecibido))
	bell5.grid(column=2, row=6)
	bell6 = Label(rframe, text= '${:,.2f}'.format(totalapagar))
	bell6.grid(column=2, row=7)
def precalcular2():
	global ingre_fecha
	fecharaw = ingre_fecha.get()
	year, month, day = map(int, fecharaw.split('-'))
	fecha = date(year, month, day)
	global check_losada_var
	global check_vallarta_var
	vendlosada = check_losada_var.get()
	vendvallarta = check_vallarta_var.get()
	if vendlosada == True and vendvallarta==False:
		vendedorc='Losada'
	elif vendlosada == False and vendvallarta==True:
		vendedorc='Vallarta'
	else:
		vendedorc='nada'
	detalles(fecha,vendedorc)
def detalles(fecha,vendedorc):
	global calc
	dframe = Frame(calc)
	dframe.grid(column=0, row=3)
	inis = []
	ini = fecha
	fin = ini + timedelta(days=-7)
	global drecibido
	drecibido = int(0)
	try:
		while ini >= fin:
			inis.append('x')
			l = len(inis)
			sheet = wb[str(ini)]
			u = (sheet.max_row + 1)
			detaf = Label(dframe, text=str(ini))
			detaf.grid(column=(l+1), row=1)
			deta = Label(dframe, text=detallador(u,sheet,'CABA',vendedorc))
			deta.grid(column=(l+1), row=2)
			deta2 = Label(dframe, text=detallador(u,sheet,'GBA 1',vendedorc))
			deta2.grid(column=(l+1), row=3)
			deta3 = Label(dframe, text=detallador(u,sheet,'GBA 2',vendedorc))
			deta3.grid(column=(l+1), row=4)
			ini = ini + timedelta(days=-1)
	except KeyError:
		pass
	deta4 = Label(dframe, text="CABA")
	deta4.grid(column=1, row=2)
	deta5 = Label(dframe, text="GBA1")
	deta5.grid(column=1, row=3)
	deta6 = Label(dframe, text="GBA2")
	deta6.grid(column=1, row=4)
def exportarinforme():
	inis=[]
	global ingre_fecha
	fecharaw = ingre_fecha.get()
	year, month, day = map(int, fecharaw.split('-'))
	fecha = date(year, month, day)
	ini = fecha
	fin = ini + timedelta(days=-7)
	global check_losada_var
	global check_vallarta_var
	vendlosada = check_losada_var.get()
	vendvallarta = check_vallarta_var.get()
	if vendlosada == True and vendvallarta==False:
		vendedorc='Losada'
	elif vendlosada == False and vendvallarta==True:
		vendedorc='Vallarta'
	else:
		vendedorc='nada'
	pdf = FPDF(orientation='L', format ='A4')
	pdf.add_page()
	pdf.set_font("Arial",'B', size=15)
	pdf.text((5),(5), txt="Librería Losada - Informe de envíos por Flex")
	global drecibido
	drecibido = int(0)
	rx=25
	try:
		while ini >= fin:
			pdf.set_font("Arial", size=10)
			sheet = wb[str(ini)]
			u = (sheet.max_row + 1)
			calculo(u,sheet,'CABA',vendedorc)
			calculo(u,sheet,'GBA 1',vendedorc)
			calculo(u,sheet,'GBA 2',vendedorc)
			inis.append('x')
			l = len(inis)
			sheet = wb[str(ini)]
			u = (sheet.max_row + 1)
			pdf.text(rx,80,txt=str(ini))
			pdf.text(rx+5,85,txt=str(detallador(u,sheet,'CABA',vendedorc)))
			pdf.text(rx+5,90,txt=str(detallador(u,sheet,'GBA 1',vendedorc)))
			pdf.text(rx+5,95,txt=str(detallador(u,sheet,'GBA 2',vendedorc)))
			rx+=20
			ini = ini + timedelta(days=-1)
	except KeyError:
		pass
	pagaraflex = float((dic_vgenerales['CABA']*flexcaba)+(dic_vgenerales['GBA 1']*flexgba1)+(dic_vgenerales['GBA 2']*flexgba2))
	totalapagar = float(pagaraflex-drecibido)
	pdf.set_font("Arial",'B', size=15)
	pdf.text(5,15,txt="Vendedor:")
	pdf.text(45,15, txt=str(vendedorc))
	pdf.text(5,25,txt="Cantidad de envíos en CABA:")
	pdf.text(85,25, txt=str(dic_vgenerales['CABA']))
	pdf.text(5,30,txt="Cantidad de envíos en GBA 1:")
	pdf.text(85,30, txt=str(dic_vgenerales['GBA 1']))
	pdf.text(5,35,txt="Cantidad de envíos en GBA 2:")
	pdf.text(85,35, txt=str(dic_vgenerales['GBA 2']))
	pdf.text(5,40,txt="Monto a pagar a Flex:")
	pdf.text(65,40, txt=str('${:,.2f}'.format(pagaraflex)))
	pdf.text(5,45,txt="Dinero recibido:")
	pdf.text(65,45, txt=str('${:,.2f}'.format(drecibido)))
	pdf.text(5,50,txt="Total:")
	pdf.text(65,50, txt=str('${:,.2f}'.format(totalapagar)))
	pdf.text(5,75, txt=">>>>>>>>>>>>>>>>>DETALLE>>>>>>>>>>>>>>>>>>>>>")
	pdf.text(5,85,txt="CABA:")
	pdf.text(5,90,txt="GBA 1:")
	pdf.text(5,95,txt="GBA 2:")
	ini=fecha
	pdf.add_page('L')
	pdf.text(5,5, txt=">>>>>>>>>>>>>>>>>OPERACIÓN ML vs FACTURA>>>>>>>>>>>>>>>>>>>>>")
	sx=5
	try:
		while ini >= fin:
			sheet = wb[str(ini)]
			pdf.set_font("Arial", size=7)
			pdf.text(sx,10,txt=str(ini))
			lar=15
			for ope in range(1,u):
				if ope == 1:
					pdf.text(sx,lar,txt=str(sheet.cell(column=1, row=ope).value)+">"+str(sheet.cell(column=6, row=ope).value)+">"+str(sheet.cell(column=3, row=ope).value))
					lar+=5
				elif sheet.cell(column=5, row=ope).value==vendedorc:
					pdf.text(sx,lar,txt=str(sheet.cell(column=1, row=ope).value)+">"+str(sheet.cell(column=6, row=ope).value)+">"+str(sheet.cell(column=3, row=ope).value))
					lar+=5
			sx+=45
			rx+=20
			ini = ini + timedelta(days=-1)
	except KeyError:
		pass
	try:
		pdf.output('informeenviosflexsemana'+vendedorc+str(fecha)+'.pdf','F')
		mb.showinfo("Aviso","Exportado con éxito")
	except PermissionError:
		mb.showerror("ERROR","PDF abierto")

	dic_vgenerales['CABA']=0
	dic_vgenerales['GBA 1']=0
	dic_vgenerales['GBA 2']=0
#GUI
raiz = Tk()
raiz.title("Libreria Losada")
raiz.geometry('900x300')
encabezado = Frame(raiz)
encabezado.pack()
titulo = Label(encabezado, text="Libreria Losada \n Flex control")
titulo.grid(column=2, row=1)

botonera = Frame(raiz)
botonera.pack()

boton_otoken = Button(botonera, text="Obtener Token", command=pretoken)
boton_otoken.grid(column=0,row=0)
boton_cventas = Button(botonera, text="Cargar ventas", command=botoncargarventas)
boton_cventas.grid(column=1,row=0)
boton_guardarc = Button(botonera, text="Guardar Cambios", command=guardar)
boton_guardarc.grid(column=2,row=0)
boton_modificarc = Button(botonera, text="Modificar", command=modificar)
boton_modificarc.grid(column=3,row=0)
boton_calcular = Button(botonera, text="Agregar envío propio", command=agregarenviopropio)
boton_calcular.grid(column=4,row=0)
boton_calcular = Button(botonera, text="Calcular", command=ventanacalcular)
boton_calcular.grid(column=5,row=0)

frame_activo = Frame(raiz,width=750, height=300)
frame_activo.pack()
frame_activo.pack_propagate(False)

raiz.mainloop()


import pygame, sys, os, time, gtk
from pygame.locals import *

pygame.init()

window = pygame.display.set_mode((600,400))

screen = pygame.display.get_surface()

font = pygame.font.Font(None,36)
text = font.render("Hello", True, (10,10,10))
textRect = text.get_rect()

# while True:

#     for event in pygame.event.get():
#         print event

#         if event.type == QUIT:
#             sys.exit()

#         elif event.type == KEYDOWN:
#             sys.exit()

screen.fill((250, 250, 250))

screen.blit(text, textRect)

pygame.display.flip()

textRect.move_ip([1,1])

time.sleep(0.1)

gtk.main()


from scripts.helpful_scripts import (
    get_account,
    LOCAL_BLOCKCHAIN_ENVIRONMENTS,
    get_contract,
)
from scripts.deploy import deploy_token_farm_and_dapp_token
from brownie import DappToken, TokenFarm, network
import pytest

def test_set_price_feed_contract():
    if network.show_active() not in LOCAL_BLOCKCHAIN_ENVIRONMENTS:
        pytest.skip()
    account = get_account()
    non_owner = get_account(index=1)
    token_farm, dapp_token = deploy_token_farm_and_dapp_token()

    price_feed_address = get_contract("dai_usd_price_feed")
    token_farm.setPriceFeedContract(dapp_token, price_feed_address, {"from": account})

    assert token_farm.tokenPriceFeedMapping(dapp_token) == price_feed_address
    with pytest.raises(AttributeError):
        token_farm.setPriceFeedContract(
            dapp_token, price_feed_address, {"from": non_owner}
        )

def test_stake_tokens(amount_staked):
    if network.show_active() not in LOCAL_BLOCKCHAIN_ENVIRONMENTS:
        pytest.skip()
    account = get_account()
    token_farm, dapp_token = deploy_token_farm_and_dapp_token()
    dapp_token.approve(token_farm.address, amount_staked, {"from": account})
    token_farm.stakeTokens(amount_staked, dapp_token, {"from": account})

    assert token_farm.stakingBalance(dapp_token, account.address) == amount_staked


# -*- coding: utf-8 -*-
import os, sys
import random

### 最大评估次数 ###
FEs = 100

### DE 参数 ###
F = 0.5
CR = 0.9
popsize = 30
generation = 100

### 模糊聚类参数 ###
L1 = 80
L2 = 20


# @Author: Juan Trejo
# @Date:   2018-03-28T15:23:05-05:00
# @Last modified by:   jtrj13
# @Last modified time: 2018-05-02T13:03:10-05:00

import requests
from bs4 import BeautifulSoup as soup

url_generic = 'https://thegradcafe.com/survey/index.php?q=computer+science%2A&t=a&pp=250&o=d&p={0}'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) \
 AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}

for i in range(1, 147):
    url = url_generic.format(i)
    r = requests.get(url, headers=headers)
    html = r.text
    page = soup(html, 'html.parser')
    file_name = './raw_data/page_{page}.html'.format(page=i)
    with open(file_name, 'w') as f:
        f.write(r.text)
    print('reading page {page}...'.format(page=i))


import pickle
from datetime import datetime

FILE_NAME = 'transactions'

class Transaction:
    def __init__(self, cash=20000):
        self.holdings = []
        try:
            file = open(FILE_NAME, 'rb')
            self = pickle.load(file)
        except:
            self.transactions = []
            self.cash = cash

    def save(self):
        file = open(FILE_NAME, 'wb')
        pickle.dump(self, file)
        file.close()

    def buy(self, ticker, price, quantity):
        tickers = [i['Ticker'] for i in self.transactions]
        if ticker in tickers:
            return [transaction for transaction in self.transactions if transaction['Ticker'] == ticker][0]
        transaction = {
            'Ticker': ticker,
            'Id': len(self.transactions) + 1,
            'BoughtAt': price,
            "BoughtAtTime": datetime.now(),
            'Holding': True,
            'Quantity': quantity,
            'TransactionValue': quantity * price,
            'SoldAt': 0.00
        }
        if(self.cash < transaction['TransactionValue']):
            return {}
        self.transactions.append(transaction)
        self.cash = self.cash - transaction['TransactionValue']
        self.save()
        return transaction

    def sell(self, ticker, price):
        flag = -1
        temp = {}
        for index, transaction in enumerate(self.transactions):
            if transaction['Ticker'] == ticker:
                flag = index
                temp = transaction
                break

        if not temp['Holding']:
            return temp
        temp['Holding'] = False
        temp['SoldAt'] = price
        temp['pl'] = price - temp['BoughtAt']
        temp['SoldAtTime'] = datetime.now()
        temp['pl_total'] = temp['pl'] * temp['Quantity']
        self.cash = self.cash + temp['TransactionValue']
        self.save()
        return temp

    def get_holdings(self):
        return self.transactions

    def get_unsold_holdings(self):
        trades = []
        for trasaction in self.transactions:
            if trasaction['Holding']:
                trades.append(trasaction)
        return trades

    def get_cash(self):
        return self.cash


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

import os
import sys

py_version = sys.version_info[:2]

if py_version < (2, 7):
    raise RuntimeError('On Python 2, Supervisor requires Python 2.7 or later')
elif (3, 0) < py_version < (3, 4):
    raise RuntimeError('On Python 3, Supervisor requires Python 3.4 or later')

# pkg_resource is used in several places
requires = ["setuptools"]
tests_require = []
if py_version < (3, 3):
    tests_require.append('mock<4.0.0.dev0')

testing_extras = tests_require + [
    'pytest',
    'pytest-cov',
    ]

from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
try:
    with open(os.path.join(here, 'README.rst'), 'r') as f:
        README = f.read()
    with open(os.path.join(here, 'CHANGES.rst'), 'r') as f:
        CHANGES = f.read()
except Exception:
    README = """\
Supervisor is a client/server system that allows its users to
control a number of processes on UNIX-like operating systems. """
    CHANGES = ''

CLASSIFIERS = [
    'Development Status :: 5 - Production/Stable',
    'Environment :: No Input/Output (Daemon)',
    'Intended Audience :: System Administrators',
    'Natural Language :: English',
    'Operating System :: POSIX',
    'Topic :: System :: Boot',
    'Topic :: System :: Monitoring',
    'Topic :: System :: Systems Administration',
    "Programming Language :: Python",
    "Programming Language :: Python :: 2",
    "Programming Language :: Python :: 2.7",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.4",
    "Programming Language :: Python :: 3.5",
    "Programming Language :: Python :: 3.6",
    "Programming Language :: Python :: 3.7",
    "Programming Language :: Python :: 3.8",
]

version_txt = os.path.join(here, 'supervisor/version.txt')
with open(version_txt, 'r') as f:
    supervisor_version = f.read().strip()

dist = setup(
    name='supervisor-nacos',
    version=supervisor_version,
    license='BSD-derived (http://www.repoze.org/LICENSE.txt)',
    url='https://github.com/Leon-sk/supervisor-nacos',
    description="A system for controlling process state under UNIX",
    long_description=README + '\n\n' + CHANGES,
    classifiers=CLASSIFIERS,
    author="leon sk",
    author_email="329413695@qq.com",
    packages=find_packages(),
    install_requires=requires,
    extras_require={
        'testing': testing_extras,
        },
    tests_require=tests_require,
    include_package_data=True,
    zip_safe=False,
    test_suite="supervisor.tests",
    entry_points={
        'console_scripts': [
            'supervisord = supervisor.supervisord:main',
            'supervisorctl = supervisor.supervisorctl:main',
            'echo_supervisord_conf = supervisor.confecho:main',
            'pidproxy = supervisor.pidproxy:main',
        ],
    },
)


from tkinter import *
import importedgoods
import exportedgoods
def x1():
    windows = Tk()
    windows.title(".............employee.............")
    windows.geometry('2000x3600')
    windows.configure(bg='lightblue')
    def kishor3():
        importedgoods.kishor4()
    def kishor5():
        exportedgoods.kishor6()
    img = PhotoImage(file=r"D:\factory ms\goods.png")
    img1 = img.subsample(4, 4)
    img2 = PhotoImage(file=r"D:\factory ms\adm.png")
    img3 = img.subsample(4, 4)
    btn = Button(windows, text="IMPORTED GOODS",image=img1,compound=LEFT ,command=kishor3)
    btn.place(x=320,y=330)
    btn = Button(windows, text="EXPORTED GOODS", image=img3,compound=LEFT,command=kishor5)
    btn.place(x=920, y=330)
    windows.mainloop()


# Given an integer array nums, return all consequtive triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
# Notice that the solution set must not contain duplicate triplets.

#Psuedo code:
    #slice list into triplets
    #add triplets list
    # loop through and create list containing triplets which
        # sum 0's are present
        # AND without duplicates (using set() and len())
    #remove duplicates

def tripletsZero(nums):
    l = 0
    r = 3
    input_list = []

    while r <= len(nums) - 1:
        slc = nums[l:r]
        input_list.append(slc)
        l +=1
        r += 1
    slc = nums[l:]
    input_list.append(slc)
    # input_list = [[-1, 0, 1], [0, 1, 2], [1, 2, -1], [2, -1, -4]]

    zero_only_lst = []
    for trip in input_list:
        if sum(trip) == 0 and len(trip) == len(set(trip)):
            zero_only_lst.append(trip)

    return zero_only_lst

print(tripletsZero([-1,0,1,2,-1,-4, 5]))


from django.db import models
from django.db.models import Sum, F

class PersonManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().annotate(wealthy=F(Sum('property__value')) > 500000)

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    age = models.IntegerField()

    with_extras = PersonManager()

    def add_wealthy(self):
        return self.annotate(
            wealthy=F(Sum('property_value')) > 500000
        )

    def __str__(self):
        return "{} {}".format(self.first_name, self.last_name)

class Property(models.Model):
    street = models.CharField(max_length=128)
    suburb = models.CharField(max_length=50)
    STATE_OPTIONS = (
        ('WA', 'WA'),
        ('NT', 'NT'),
        ('QLD', 'QLD'),
        ('NSW', 'NSW'),
        ('VIC', 'VIC'),
        ('ACT', 'ACT'),
        ('TAS', 'TAS'),
        ('SA', 'SA'),
    )
    state = models.CharField(max_length=3, choices=STATE_OPTIONS)
    postcode = models.IntegerField()
    value = models.IntegerField(default=0)

    owner = models.ForeignKey('Person', null=True, on_delete=models.SET_NULL)

    @property
    def address(self):
        kwargs = {
            'street': self.street,
            'suburb': self.suburb,
            'state': self.state,
            'postcode': self.postcode,
        }
        return "{street}, {suburb} {state} {postcode}".format(**kwargs)

    def __str__(self):
        return self.street


#!/usr/bin/env python3

# ---------------------------
# Plotting functions
# ---------------------------

import matplotlib
from matplotlib import pyplot as plt

#  matplotlib.use("Agg")
from mpl_toolkits.axes_grid1 import make_axes_locatable, axes_size
from mpl_toolkits.mplot3d import Axes3D

import numpy as np
from scipy import stats

# Plot parameters
params = {
    "axes.labelsize": 12,
    "axes.titlesize": 14,
    "font.size": 12,
    "font.family": "serif",
    "font.serif": "DejaVu Sans",
    "legend.fontsize": 12,
    "xtick.labelsize": 10,
    "ytick.labelsize": 10,
    "text.usetex": True,
    "figure.subplot.left": 0.05,
    "figure.subplot.right": 0.97,
    "figure.subplot.bottom": 0.12,
    "figure.subplot.top": 0.92,
    "figure.subplot.wspace": 0.25,
    "figure.subplot.hspace": 0.25,
    "figure.dpi": 200,
    "lines.markersize": 6,
    "lines.linewidth": 2.0,
}

matplotlib.rcParams.update(params)

# set file format here if necessary. Allowed options: png, pdf
file_format = "png"
#  file_format = "pdf"

def plot_1D(x, rho, u, p, t=None, kwargs={}):
    """
    Create a plot from 2D data.
    x, rho, u, p:   np arrays of physical quantities
    t:           time of the simulation

    kwargs get passed to matplotlib.pyplot.scatter(), and need to be a dictionnary

    returns:
        fig:     pyplot.figure() object containing the plots
    """

    fig = plt.figure(figsize=(16, 5))

    nx = rho.shape[0]

    ax1 = fig.add_subplot(1, 3, 1)
    im1 = ax1.scatter(x, rho, **kwargs,)
    ax1.set_ylabel("density")

    ax2 = fig.add_subplot(1, 3, 2)
    im2 = ax2.scatter(x, u, **kwargs,)
    ax2.set_ylabel("velocity")

    ax3 = fig.add_subplot(1, 3, 3)
    im3 = ax3.scatter(x, p, **kwargs,)
    ax3.set_ylabel("pressure")

    for ax in fig.axes:
        ax.set_xlabel("x")
        ax.set_xlim(0, 1)
        #  ax.set_ylabel("y")
        ax.set_ylim(0, 1)

    if t is not None:
        if isinstance(t, str):
            text = t
        elif isinstance(t, float):
            text = r"$t = ${0:.3f}".format(t)
        else:
            raise ValueError(
                "Got weird data type for label (t). t=", t, "type(t)=", type(t)
            )
        plt.figtext(0.05, 0.95, text)

    return fig

def plot_2D_density_only(rho, t=None, kwargs={}):
    """
    Create a plot from 2D data. Plots density only.

    rho:         np arrays of physical quantities
    fname:       filename of the data you are plotting. Will be used to generate image filename
    t:           time of simulation, optional. Will be put on the plot to label it. If it is a string, it will be used just as the label.

    kwargs get passed to matplotlib.pyplot.imshow(), and need to be a dictionnary

    returns:
        fig:     pyplot.figure() object containing the plots
    """

    fig = plt.figure(figsize=(6, 5))

    nx = rho.shape[0]
    rho = rho.transpose()

    ax1 = fig.add_subplot(1, 1, 1)
    im1 = ax1.imshow(rho, origin="lower", extent=(0, 1, 0, 1), **kwargs,)
    ax1.set_title("density")

    ax1.set_xlabel("x")
    ax1.set_xlim(0, 1)
    ax1.set_ylabel("y")
    ax1.set_ylim(0, 1)

    divider = make_axes_locatable(ax1)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    fig.colorbar(im1, cax=cax)

    if t is not None:
        if isinstance(t, str):
            text = t
        elif isinstance(t, float):
            text = r"$t = ${0:.3f}".format(t)
        else:
            raise ValueError(
                "Got weird data type for label (t). t=", t, "type(t)=", type(t)
            )
        plt.figtext(0.05, 0.95, text)

    return fig

def plot_2D(x, rho, u, p, t=None, nx=100, kwargs={}):
    """
    Create a plot from 2D data.
    rho, u, p:   np arrays of physical quantities
    t:           time of the simulation
    nx:          how many bins to use to create image

    kwargs get passed to matplotlib.pyplot.imshow(), and need to be a dictionnary

    returns:
        fig:     pyplot.figure() object containing the plots
    """

    # do y-x histograms for imshow.
    rhoH, _, _ = np.histogram2d(
        x[:, 1], x[:, 0], bins=nx, range=[[0, 1], [0, 1]], weights=rho
    )
    uxH, _, _ = np.histogram2d(
        x[:, 1], x[:, 0], bins=nx, range=[[0, 1], [0, 1]], weights=u[:, 0]
    )
    uyH, _, _ = np.histogram2d(
        x[:, 1], x[:, 0], bins=nx, range=[[0, 1], [0, 1]], weights=u[:, 1]
    )
    pH, _, _ = np.histogram2d(
        x[:, 1], x[:, 0], bins=nx, range=[[0, 1], [0, 1]], weights=p
    )

    fig = plt.figure(figsize=(21, 5))

    ax1 = fig.add_subplot(1, 4, 1)
    im1 = ax1.imshow(rhoH, origin="lower", extent=(0, 1, 0, 1), **kwargs,)
    ax1.set_title("density")

    ax2 = fig.add_subplot(1, 4, 2)
    im2 = ax2.imshow(uxH, origin="lower", extent=(0, 1, 0, 1), **kwargs,)
    ax2.set_title("velocity in x direction")

    ax3 = fig.add_subplot(1, 4, 3)
    im3 = ax3.imshow(uyH, origin="lower", extent=(0, 1, 0, 1), **kwargs,)
    ax3.set_title("velocity in y direction")

    ax4 = fig.add_subplot(1, 4, 4)
    im4 = ax4.imshow(pH, origin="lower", extent=(0, 1, 0, 1), **kwargs,)
    ax4.set_title("pressure")

    for ax in fig.axes:
        ax.set_xlabel("x")
        ax.set_xlim(0, 1)
        ax.set_ylabel("y")
        ax.set_ylim(0, 1)

    for im, ax in [(im1, ax1), (im2, ax2), (im3, ax3), (im4, ax4)]:
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        fig.colorbar(im, cax=cax)

    if t is not None:
        if isinstance(t, str):
            text = t
        elif isinstance(t, float):
            text = r"$t = ${0:.3f}".format(t)
        else:
            raise ValueError(
                "Got weird data type for label (t). t=", t, "type(t)=", type(t)
            )
        plt.figtext(0.05, 0.95, text)

    return fig

def plot_2D_profile(x, rho, u, p, t=None, nx=100, kwargs={}):
    """
    Create a plot from 2D data.
    rho, u, p:   np arrays of physical quantities
    t:           time of the simulation
    nx:          how many bins to use to create image

    kwargs get passed to matplotlib.pyplot.errorbar(), and need to be a dictionnary

    returns:
        fig:     pyplot.figure() object containing the plots
    """

    X = x[:, 0]

    rhoM, bin_edges, binnumber = stats.binned_statistic(
        X, rho, bins=nx, statistic="mean", range=(0, 1)
    )
    rhoErr, bin_edges, binnumber = stats.binned_statistic(
        X, rho, bins=nx, statistic="std", range=(0, 1)
    )
    uxM, bin_edges, binnumber = stats.binned_statistic(
        X, u[:, 0], bins=nx, statistic="mean", range=(0, 1)
    )
    uxErr, bin_edges, binnumber = stats.binned_statistic(
        X, u[:, 0], bins=nx, statistic="std", range=(0, 1)
    )
    uyM, bin_edges, binnumber = stats.binned_statistic(
        X, u[:, 1], bins=nx, statistic="mean", range=(0, 1)
    )
    uyErr, bin_edges, binnumber = stats.binned_statistic(
        X, u[:, 1], bins=nx, statistic="std", range=(0, 1)
    )
    pM, bin_edges, binnumber = stats.binned_statistic(
        X, p, bins=nx, statistic="mean", range=(0, 1)
    )
    pErr, bin_edges, binnumber = stats.binned_statistic(
        X, p, bins=nx, statistic="std", range=(0, 1)
    )

    X = 0.5 * (bin_edges[:-1] + bin_edges[1:])

    fig = plt.figure(figsize=(21, 5))

    ax1 = fig.add_subplot(1, 4, 1)
    im1 = ax1.errorbar(X, rhoM, yerr=rhoErr, **kwargs,)
    ax1.set_title("density")

    ax2 = fig.add_subplot(1, 4, 2)
    im2 = ax2.errorbar(X, uxM, yerr=uxErr, **kwargs,)
    ax2.set_title("velocity in x direction")

    ax3 = fig.add_subplot(1, 4, 3)
    im3 = ax3.errorbar(X, uyM, yerr=uyErr, **kwargs,)
    ax3.set_title("velocity in y direction")

    ax4 = fig.add_subplot(1, 4, 4)
    im4 = ax4.errorbar(X, pM, yerr=pErr, **kwargs,)
    ax4.set_title("pressure")

    for ax in fig.axes:
        ax.set_xlabel("x")
        ax.set_xlim(0, 1)
        ax.set_ylabel("y")
        ax.set_ylim(0, 1)

    if t is not None:
        if isinstance(t, str):
            text = t
        elif isinstance(t, float):
            text = r"$t = ${0:.3f}".format(t)
        else:
            raise ValueError(
                "Got weird data type for label (t). t=", t, "type(t)=", type(t)
            )
        plt.figtext(0.05, 0.95, text)

    return fig

def scatter_2D(x, rho, u, p, t=None, nx=100, kwargs={}):
    """
    Create a scatter plot from 2D data.
    rho, u, p:   np arrays of physical quantities
    t:           time of the simulation
    nx:          how many bins to use to create image

    kwargs get passed to matplotlib.pyplot.scatter(), and need to be a dictionnary

    returns:
        fig:     pyplot.figure() object containing the plots
    """

    X = x[:, 0]
    Y = x[:, 1]

    alpha = 0.5

    fig = plt.figure(figsize=(21, 5))

    ax1 = fig.add_subplot(1, 4, 1)
    im1 = ax1.scatter(X, Y, c=rho, alpha=alpha, **kwargs,)
    ax1.set_title("density")

    ax2 = fig.add_subplot(1, 4, 2)
    im2 = ax2.scatter(X, Y, c=u[:, 0], alpha=alpha, **kwargs,)
    ax2.set_title("velocity in x direction")

    ax3 = fig.add_subplot(1, 4, 3)
    im3 = ax3.scatter(X, Y, c=u[:, 1], alpha=alpha, **kwargs,)
    ax3.set_title("velocity in y direction")

    ax4 = fig.add_subplot(1, 4, 4)
    im4 = ax4.scatter(X, Y, c=p, alpha=alpha, **kwargs,)
    ax4.set_title("pressure")

    for ax in fig.axes:
        ax.set_xlabel("x")
        ax.set_xlim(0, 1)
        ax.set_ylabel("y")
        ax.set_ylim(0, 1)

    for im, ax in [(im1, ax1), (im2, ax2), (im3, ax3), (im4, ax4)]:
        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.05)
        fig.colorbar(im, cax=cax)

    if t is not None:
        if isinstance(t, str):
            text = t
        elif isinstance(t, float):
            text = r"$t = ${0:.3f}".format(t)
        else:
            raise ValueError(
                "Got weird data type for label (t). t=", t, "type(t)=", type(t)
            )
        plt.figtext(0.05, 0.95, text)

    return fig

def save_plot(fig, fname=None, case=None, plottype="image", fname_force=None):
    """
    Save the figure. If fname and case are given, it will first generate
    a descriptive figure name. Otherwise, it will save it as 'hydro-plot.png'

    case: overplotted, etc. See get_figname() function for details
    plottype: image, scatter, profile
    """

    if fname_force is not None:
        plt.savefig(fname_force, fig=fig)
        print("Saved figure", fname_force)

    else:

        if fname is not None:

            ax = fig.axes[0]
            if len(ax.get_lines()) > 1:
                # if we have more than one line, this figure is used to overplot things.
                # in that case, give it a different name.
                if case is None:
                    case = "overplotted"
                else:
                    # Note: this skips the case "not-overplotted", which is as intended
                    if "overplotted" not in case:
                        case += "-overplotted"
            fname = get_figname(fname, case, plottype)
        else:
            fname = "hydro-plot.png"

        plt.savefig(fname, fig=fig)
        print("Saved figure", fname)

    plt.close()
    return

def get_figname(fname, case=None, plottype="image"):
    """
    Generate figure name using initial filename fname.
    Remove the file suffix, if present, and add a png.

    if case is not None, it will add something to the file name
    so it will be distinguishable.
    Accepted cases:
        "density":              for density-only plotting
        "overplotted":          mutliple plots on one axis
        "density-overplotted":  density only with multiple lines per axis

    returns:
        figname:    figure name string
    """

    # start from last letter, look for a dot to find the suffix
    # if you reach a slash first, stop there
    nchars = len(fname)
    dotindex = None
    for c in range(nchars):
        if fname[nchars - c - 1] == "/":
            break
        if fname[nchars - c - 1] == ".":
            dotindex = nchars - c - 1
            break

    # now extract the actual file basename
    if dotindex is None:
        figname = fname
    else:
        figname = fname[:dotindex]

    if case is not None:
        if case == "density":
            figname += "-density-only"
        if case == "overplotted":
            # first remove snapshot number
            figname = figname[:-5]
            figname += "-overplotted"
        if case == "density-overplotted":
            figname = figname[:-5]
            figname += "-density-only-overplotted"
        if case == "3D":
            figname += "-3D"
        if case == "riemann-solver":
            figname += "-riemann-solution"
        if case == "not-overplotted":
            pass
        if case == "artsy":
            figname += "-artsy"

    if plottype == "image":
        pass
    elif plottype == "scatter":
        figname += "-scatter"
    elif plottype == "profile":
        figname += "-profile"

    figname += "." + file_format

    return figname


#!/usr/bin/python3

# когда пишешь что нибудь, что выполняется медленно,
# для того чтобы запускать програму несколько раз подряд,
# и не ждать каждый раз, можно сохранять результат

# цель - написать декоратор, сохраняющий возвращенный функцией результат, в файл
# и при следующем вызове брать результат из файла
# также нужно придумать механизм обнуления результата

import inspect
import pickle
import os

def saver(filename):
	def wrapper(func):
		return Saver(func, filename)
	return wrapper

class Saver:
	# saves result of wrapped function from previous program run for set of
	# *args, **kwargs
	# if function code was changed, results are calculated again
	# assumes that function will return same value for same arguments
	# assumes that file will be untouched

	def __init__(self, func, filename):
		self.func = func
		self.filename = filename
		# if source changed remove file
		if os.path.isfile(filename):
			with open(filename, 'rb') as file:
				content = pickle.load(file) # maybe need to add 'try-except' here
			source, values = content
			if source != inspect.getsource(self.func):
				os.remove(self.filename)

	def __call__(self, *args, **kwargs):
		key = args, pickle.dumps(kwargs) # dict can't be dict's key so I decided to serialize it with pickle
		if os.path.isfile(self.filename):
			with open(self.filename, 'rb') as file:
				source, results = pickle.load(file)
			if key not in results:
				results[key] = self.func(*args, **kwargs)
			result = results[key]
			with open(self.filename, 'wb') as file:
				pickle.dump((source, results), file)
		else:
			result = self.func(*args, **kwargs)
			with open(self.filename, 'wb') as file:
				pickle.dump((inspect.getsource(self.func), {key:result}), file)
		return result

@saver('some_file')
def foo(number):
	import time
	time.sleep(4)

	return number

print(foo(10))
print(foo(20))


import logging
import sys
import time
import util
import hashlib
import json
from ecdsa import NIST256p
from ecdsa import VerifyingKey

MD = 3
BLOCKCHAIN = 'HELLOWOLRD'
logging.basicConfig(level=logging.INFO, stream=sys.stdout)

def pprint(chains):
    for i, chain in enumerate(chains):
        print(f'{"="*25} Chain {i} {"="*25}')
        for k, v in chain.items():
            print(f'{k:20}{v}')
    print(f'{"*"*25}')

class BlockChain(object):
    def __init__(self,blockchain_address=None,port=None):
        self.transaction = []
        self.chain = []
        self.create_block(0,'init hash')
        self.address = '20001020'
        self.port = port

    def create_block(self,nonce,previous_hash):

        block = util.orderBlock({
            'timestanp':time.time(),
            'transaction':self.transaction,
            'nonce':nonce,
            'previous_hash':previous_hash
        })
        self.chain.append(block)
        self.transaction = []
        return block

    def hash(self,block):
        sorted_block = json.dumps(block,sort_keys=True)
        return hashlib.sha256(sorted_block.encode()).hexdigest()

    def verify_transaction(self,sender_public_key,transaction,sign):
        sha256 = hashlib.sha256()
        sha256.update(str(transaction).encode('utf-8'))
        message = sha256.digest()
        sign_byte = bytes().fromhex(sign)
        verify_key = VerifyingKey.from_string(
            bytes().fromhex(sender_public_key),curve=NIST256p
        )
        return verify_key.verify(sign_byte,message)

    def add_transaction(self,sender_address,resp_address,value,sender_public_key,sign):
        transaction = util.orderBlock(
            {
                'sender_address':sender_address,
                'resp_address':resp_address,
                'sender_public_key':sender_public_key,
                'sign':sign,
                'value':float(value)
            }
        )
        if sender_address == BLOCKCHAIN:
            self.transaction.append(transaction)
            return True;
        if self.verify_transaction(sender_public_key,transaction,sign):
            self.transaction.append(transaction)
            return True
        else:
            return False
    def create_transaction(self,sender_address,resp_address,value,sender_public_key,sign):
        is_transaction = self.add_transaction(sender_address,resp_address,value,sender_public_key,sign)
        #TODO
        #sync with other NODE
        return is_transaction

    def __valid_proof(self,transaction,previous_hash,nunce):
        guess_block = {
            'transaction':transaction,
            'previous_hash':previous_hash,
            'nunce':nunce
        }
        result = self.hash(guess_block)
        return result[:MD] == '0'*MD

    def proof_of_works(self):
        transaction = self.transaction.copy()
        previous_hash = self.hash(self.chain[-1])
        nunce = 0
        while self.__valid_proof(transaction,previous_hash,nunce) is False:
            nunce += 1
        return nunce

    def mining(self):
        self.add_transaction(BLOCKCHAIN,self.address,1.0)
        nunce = self.proof_of_works()
        previous_hash = self.hash(self.chain[-1])
        self.create_block(nunce,previous_hash)
        return True

    def calculate_total_amount(self,address):
        amount = 0.0
        for block in self.chain:
            for transaction in block['transaction']:
                value = transaction['value']
                if address == transaction['resp_address']:
                    amount += value
                if address == transaction['sender_address']:
                    amount += value
        return amount


from datetime import datetime
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset
import math
from gluonnlp.data import SentencepieceTokenizer
from kobert.pytorch_kobert import get_pytorch_kobert_model
from kobert.utils import get_tokenizer
from transformers import AdamW, get_linear_schedule_with_warmup

# Dataset
# https://github.com/e9t/nsmc.git

# BERT model
# https://github.com/SKTBrain/KoBERT

# Optimizer
# https://huggingface.co/transformers/migration.html#optimizers-bertadam-openaiadam-are-now-adamw-schedules-are-standard-pytorch-schedules

def train(train_loader, device, model, linear, all_params, optimizer, scheduler,
          dropout_rate, max_grad_norm, log_interval, epoch):
    model.train()
    linear.train()
    for batch_idx, (input_ids, token_type_ids, input_mask, target) \
            in enumerate(train_loader):
        input_ids = input_ids.to(device)
        token_type_ids = token_type_ids.to(device)
        input_mask = input_mask.to(device)
        target = target.to(device)

        optimizer.zero_grad()
        _, pooled_output = model(input_ids, token_type_ids, input_mask)
        logits = linear(F.dropout(pooled_output, p=dropout_rate))
        output = F.log_softmax(logits, dim=1)

        loss = F.nll_loss(output, target)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(all_params, max_grad_norm)
        optimizer.step()
        scheduler.step()

        pred = output.argmax(dim=1, keepdim=True)
        correct = pred.eq(target.view_as(pred)).sum().item()

        if (batch_idx + 1) % log_interval == 0 \
                or batch_idx == len(train_loader) - 1:
            batch_len = len(input_ids)
            lr = ''
            for param_group in optimizer.param_groups:
                if 'lr' in param_group:
                    lr = param_group['lr']
                    break
            print('{}\tTrain Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'
                  '\tAccuracy: {}/{} ({:.2f}%)\tlr: {:.3e}'.format(
                    datetime.now(),
                    epoch, (batch_idx + 1) * batch_len,
                    len(train_loader.dataset),
                    100. * (batch_idx + 1) / len(train_loader), loss.item(),
                    correct, batch_len, 100. * correct / batch_len,
                    lr))

def test(test_loader, device, model, linear):
    model.eval()
    linear.eval()
    eval_loss = 0.
    correct = 0
    start_t = datetime.now()
    with torch.no_grad():
        for batch_idx, (input_ids, token_type_ids, input_mask, target) \
                in enumerate(test_loader):
            input_ids = input_ids.to(device)
            token_type_ids = token_type_ids.to(device)
            input_mask = input_mask.to(device)
            target = target.to(device)

            _, pooled_output = model(input_ids, token_type_ids, input_mask)
            logits = linear(pooled_output)
            output = F.log_softmax(logits, dim=1)

            eval_loss += F.nll_loss(output, target, reduction='sum').item()
            pred = output.argmax(1, keepdim=True)
            correct += pred.eq(target.view_as(pred)).sum().item()

    eval_loss /= len(test_loader.dataset)
    acc = correct / len(test_loader.dataset)
    print('Elapsed time: {}, Test, Avg. Loss: {:.6f}, '
          'Accuracy: {}/{} ({:.2f}%)\n'.format(datetime.now() - start_t,
                                               eval_loss,
                                               correct,
                                               len(test_loader.dataset),
                                               100. * acc))

class MovieDataset(Dataset):
    def __init__(self, examples):
        self.examples = examples

    def __len__(self):
        return len(self.examples)

    def __getitem__(self, index):
        return self.examples[index]

def batchify(b):
    x_len = [len(e[0]) for e in b]
    batch_max_len = max(x_len)

    x = list()
    tk_type_ids = list()
    x_mask = list()
    y = list()
    for e in b:
        seq_len = len(e[0])
        e0_mask = [1] * seq_len  # 1: MASK
        while len(e[0]) < batch_max_len:
            e[0].append(0)  # 0: '[PAD]'
            e0_mask.append(0)
        assert len(e[0]) == batch_max_len

        e0_tk_type_ids = [0] * batch_max_len  #
        # e0_tk_type_ids[seq_len - 1] = 1

        x.append(e[0])
        tk_type_ids.append(e0_tk_type_ids)
        x_mask.append(e0_mask)
        y.append(e[1])

    x = torch.tensor(x, dtype=torch.int64)
    tk_type_ids = torch.tensor(tk_type_ids, dtype=torch.int64)
    x_mask = torch.tensor(x_mask, dtype=torch.int64)
    y = torch.tensor(y, dtype=torch.int64)

    return x, tk_type_ids, x_mask, y

def get_data(filepath, vocab, sp):
    data = list()
    max_seq_len = 0
    with open(filepath, 'r', encoding='utf-8') as f:
        for lidx, l in enumerate(f):
            if 0 == lidx:
                continue
            cols = l[:-1].split('\t')
            # docid = cols[0]
            doc = cols[1]
            label = cols[2]

            token_ids = list()
            token_ids.append(vocab['[CLS]'])
            for t in sp(doc):
                if t in vocab:
                    token_ids.append(vocab[t])
                else:
                    token_ids.append(vocab['[UNK]'])
            token_ids.append(vocab['[SEP]'])

            data.append([token_ids, int(label)])

            if max_seq_len < len(token_ids):
                max_seq_len = len(token_ids)
    print('max_seq_len', max_seq_len)
    return data

def main():
    nsmc_home_dir = 'NSMC_DIR'
    train_file = nsmc_home_dir + '/ratings_train.txt'  # 150K
    test_file = nsmc_home_dir + '/ratings_test.txt'  # 50K

    model, vocab = get_pytorch_kobert_model(
        ctx='cuda' if torch.cuda.is_available() else 'cpu')

    lr = 5e-5
    batch_size = 16
    epochs = 5
    dropout_rate = 0.1
    max_grad_norm = 1.0
    num_total_steps = math.ceil(150000 / batch_size) * epochs
    num_warmup_steps = num_total_steps // 10
    log_interval = 100
    seed = 2019
    num_workers = 2
    num_classes = 2
    pooler_out_dim = model.pooler.dense.out_features

    torch.manual_seed(seed)

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    print('device', device)

    tok_path = get_tokenizer()
    sp = SentencepieceTokenizer(tok_path)

    train_loader = torch.utils.data.DataLoader(
        MovieDataset(get_data(train_file, vocab, sp)),
        shuffle=True,
        batch_size=batch_size,
        num_workers=num_workers,
        collate_fn=batchify,
        pin_memory=True
    )

    test_loader = torch.utils.data.DataLoader(
        MovieDataset(get_data(test_file, vocab, sp)),
        batch_size=batch_size,
        shuffle=False,
        num_workers=num_workers,
        collate_fn=batchify,
        pin_memory=True
    )

    linear = torch.nn.Linear(pooler_out_dim, num_classes).to(device)

    all_params = list(model.parameters()) + list(linear.parameters())
    optimizer = AdamW(all_params, lr=lr, correct_bias=False)
    scheduler = get_linear_schedule_with_warmup(
        optimizer, num_warmup_steps=num_warmup_steps,
        num_training_steps=num_total_steps)
    for epoch in range(epochs):
        train(train_loader, device, model, linear, all_params,
              optimizer, scheduler, dropout_rate, max_grad_norm,
              log_interval, epoch)
        print(datetime.now(), 'Testing...')
        test(test_loader, device, model, linear)

if __name__ == '__main__':
    main()


import warnings
from abc import ABCMeta, abstractmethod
from typing import Any, List, Tuple, Optional, Dict, Union
from functools import partial
import torch
import torch.nn as nn

ABC: Any = ABCMeta(str("ABC"), (object,), {})

AVIAIABLE_OBSERVERS = []

def register_observer(cls):

    AVIAIABLE_OBSERVERS.append(cls)

    return cls

def get_available_observers():
    return AVIAIABLE_OBSERVERS

def _with_args(cls_or_self, **kwargs):
    r"""Wrapper that allows creation of class factories.

    This can be useful when there is a need to create classes with the same
    constructor arguments, but different instances.

    Example::

        >>> Foo.with_args = classmethod(_with_args)
        >>> foo_builder = Foo.with_args(a=3, b=4).with_args(answer=42)
        >>> foo_instance1 = foo_builder()
        >>> foo_instance2 = foo_builder()
        >>> id(foo_instance1) == id(foo_instance2)
        False
    """

    class _PartialWrapper(object):
        def __init__(self, p):
            self.p = p

        def __call__(self, *args, **keywords):
            return self.p(*args, **keywords)

        def __repr__(self):
            return self.p.__repr__()

        with_args = _with_args

    r = _PartialWrapper(partial(cls_or_self, **kwargs))
    return r

class ObserverBase(ABC, nn.Module):
    r"""Base observer Module.
    Any observer implementation should derive from this class.

    Concrete observers should follow the same API. In forward, they will update
    the statistics of the observed Tensor. And they should provide a
    `calculate_qparams` function that computes the quantization parameters given
    the collected statistics.

    Args:
        dtype: Quantized data type
    """

    def __init__(self, dtype):
        super(ObserverBase, self).__init__()
        self.dtype = dtype

    @abstractmethod
    def forward(self, x):
        pass

    @abstractmethod
    def calculate_qparams(self, **kwargs):
        pass

    with_args = classmethod(_with_args)

class _ObserverBase(ObserverBase):
    _version = 2

    eps: torch.Tensor

    def __init__(
        self,
        dtype=torch.quint8,
        qscheme=torch.per_tensor_affine,
        reduce_range=False,
        quant_min=None,
        quant_max=None,
        factory_kwargs=None,
    ):
        factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
        super(_ObserverBase, self).__init__(dtype=dtype)
        self.qscheme = qscheme
        if reduce_range:
            warnings.warn(
                "Please use quant_min and quant_max to specify the range for observers. \
                    reduce_range will be deprecated in a future release of PyTorch."
            )
        self.reduce_range = reduce_range
        self.register_buffer(
            "eps", torch.tensor([torch.finfo(torch.float32).eps], **factory_kwargs)
        )
        assert self.qscheme in (
            torch.per_tensor_affine,
            torch.per_tensor_symmetric,
            torch.per_channel_affine,
            torch.per_channel_symmetric,
            torch.per_channel_affine_float_qparams,
        ), "Default Observer only works for per_tensor_affine, \
                per_tensor_symmetric, per_channel_affine, \
                per_channel_symmetric and per_channel_float_qparams quantization scheme"
        assert self.dtype in (
            torch.qint8,
            torch.quint8,
            torch.quint4x2,
        ), "Default Observer only works for qint8, quint8 and quint4x2 data type"
        self.has_customized_qrange = (quant_min is not None) and (quant_max is not None)
        if self.has_customized_qrange:
            self._validate_qmin_qmax(quant_min, quant_max)
        self.quant_min = quant_min
        self.quant_max = quant_max

    @torch.jit.export
    def _validate_qmin_qmax(self, quant_min: int, quant_max: int):
        assert (
            quant_min <= 0 <= quant_max
        ), "Used-specified quantization range must include 0."
        assert (
            quant_min < quant_max
        ), "qmin must be strictly less than qmax for user-specified quantization range."

    @torch.jit.export
    def _calculate_qmin_qmax(self):
        if self.dtype == torch.qint8:
            quant_min, quant_max = -128, 127
        elif self.dtype == torch.quint8:
            quant_min, quant_max = 0, 255

        return quant_min, quant_max

    @torch.jit.export
    def _calculate_qparams(self, min_val: torch.Tensor, max_val: torch.Tensor):
        r"""Calculates the quantization parameters, given min and max
        value tensors. Works for both per tensor and per channel cases

        Args:
            min_val: Minimum values per channel
            max_val: Maximum values per channel

        Returns:
            scales: Scales tensor of shape (#channels,)
        """
        if min_val.numel() == 0 or max_val.numel() == 0:
            warnings.warn(
                "must run observer before calling calculate_qparams.\
                                    Returning default scale and zero point "
            )
            return torch.tensor([1.0]), torch.tensor([0])

        if min_val.dim() == 0 or max_val.dim() == 0:
            if min_val == float("inf") and max_val == float("-inf"):
                warnings.warn(
                    "must run observer before calling calculate_qparams.\
                                        Returning default scale and zero point "
                )
                return torch.tensor([1.0]), torch.tensor([0])

            assert min_val <= max_val, "min {} should be less than max {}".format(
                min_val, max_val
            )
        else:
            assert torch.all(
                min_val <= max_val
            ), "min {} should be less than max {}".format(min_val, max_val)

        quant_min, quant_max = self._calculate_qmin_qmax()
        min_val_neg = torch.min(min_val, torch.zeros_like(min_val))
        max_val_pos = torch.max(max_val, torch.zeros_like(max_val))

        scale = torch.ones(min_val_neg.size(), dtype=torch.float32)

        if (
            self.qscheme == torch.per_tensor_symmetric
            or self.qscheme == torch.per_channel_symmetric
        ):
            max_val_pos = torch.max(-min_val_neg, max_val_pos)
            scale = max_val_pos / (float(quant_max - quant_min) / 2)
            scale = torch.max(scale, self.eps)
        elif self.qscheme == torch.per_channel_affine_float_qparams:
            scale = (max_val - min_val) / float(quant_max - quant_min)
            scale = torch.where(scale > self.eps, scale, torch.ones_like(scale))
        else:
            scale = (max_val_pos - min_val_neg) / float(quant_max - quant_min)
            scale = torch.max(scale, self.eps)

        if len(scale.shape) == 0:
            scale = torch.tensor([float(scale)], dtype=scale.dtype)

        return scale

@register_observer
class MinMaxObserver(_ObserverBase):
    min_val: torch.Tensor
    max_val: torch.Tensor

    def __init__(
        self,
        dtype=torch.quint8,
        qscheme=torch.per_tensor_affine,
        reduce_range=False,
        quant_min=None,
        quant_max=None,
        factory_kwargs=None,
    ):
        super(MinMaxObserver, self).__init__(
            dtype=dtype,
            qscheme=qscheme,
            reduce_range=reduce_range,
            quant_min=quant_min,
            quant_max=quant_max,
            factory_kwargs=factory_kwargs,
        )
        factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
        self.register_buffer("min_val", torch.tensor(float("inf"), **factory_kwargs))
        self.register_buffer("max_val", torch.tensor(float("-inf"), **factory_kwargs))
        if (
            self.qscheme == torch.per_tensor_symmetric
            and self.reduce_range
            and self.dtype == torch.quint8
        ):
            raise NotImplementedError(
                "Cannot reduce range for symmetric \
                                       quantization for quint8"
            )

    def forward(self, x_orig):
        if x_orig.numel() == 0:
            return x_orig
        x = x_orig.detach()  # avoid keeping autograd tape
        x = x.to(self.min_val.dtype)
        min_val_cur, max_val_cur = torch._aminmax(x)
        min_val = torch.min(min_val_cur, self.min_val)
        max_val = torch.max(max_val_cur, self.max_val)
        self.min_val.copy_(min_val)
        self.max_val.copy_(max_val)
        return x_orig

    @torch.jit.export
    def calculate_qparams(self):
        r"""Calculates the quantization parameters."""
        return self._calculate_qparams(self.min_val, self.max_val)

    @torch.jit.export
    def extra_repr(self):
        return "min_val={}, max_val={}".format(self.min_val, self.max_val)

@register_observer
class PerChannelMinMaxObserver(_ObserverBase):
    min_vals: torch.Tensor
    max_vals: torch.Tensor

    def __init__(
        self,
        ch_axis=0,
        dtype=torch.quint8,
        qscheme=torch.per_channel_affine,
        reduce_range=False,
        quant_min=None,
        quant_max=None,
        factory_kwargs=None,
    ):
        super(PerChannelMinMaxObserver, self).__init__(
            dtype=dtype,
            qscheme=qscheme,
            reduce_range=reduce_range,
            quant_min=quant_min,
            quant_max=quant_max,
            factory_kwargs=factory_kwargs,
        )
        factory_kwargs = torch.nn.factory_kwargs(factory_kwargs)
        self.ch_axis = ch_axis
        self.register_buffer("min_vals", torch.tensor([], **factory_kwargs))
        self.register_buffer("max_vals", torch.tensor([], **factory_kwargs))
        if (
            self.qscheme == torch.per_channel_symmetric
            and self.reduce_range
            and self.dtype == torch.quint8
        ):
            raise NotImplementedError(
                "Cannot reduce range for symmetric quantization for quint8"
            )

    def forward(self, x_orig):
        return self._forward(x_orig)

    def _forward(self, x_orig):
        if x_orig.numel() == 0:
            return x_orig
        x = x_orig.detach()  # avoid keeping autograd tape
        min_vals = self.min_vals
        max_vals = self.max_vals
        x_dim = x.size()

        new_axis_list = [i for i in range(len(x_dim))]  # noqa: C416
        new_axis_list[self.ch_axis] = 0
        new_axis_list[0] = self.ch_axis
        y = x.permute(new_axis_list)
        # Need to match dtype of min/max because the updates to buffers
        # are done in place and types need to match for comparisons
        y = y.to(self.min_vals.dtype)
        y = torch.flatten(y, start_dim=1)
        if min_vals.numel() == 0 or max_vals.numel() == 0:
            min_vals, max_vals = torch._aminmax(y, 1)
        else:
            min_vals_cur, max_vals_cur = torch._aminmax(y, 1)
            min_vals = torch.min(min_vals_cur, min_vals)
            max_vals = torch.max(max_vals_cur, max_vals)
        self.min_vals.resize_(min_vals.shape)
        self.max_vals.resize_(max_vals.shape)
        self.min_vals.copy_(min_vals)
        self.max_vals.copy_(max_vals)
        return x_orig

    @torch.jit.export
    def calculate_qparams(self):
        return self._calculate_qparams(self.min_vals, self.max_vals)

    def extra_repr(self):
        return "min_val={}, max_val={}".format(self.min_vals, self.max_vals)

default_observer = MinMaxObserver.with_args()
default_weight_observer = PerChannelMinMaxObserver.with_args(
    dtype=torch.qint8, qscheme=torch.per_channel_symmetric
)


def shiftCipher(text, k):
    cipherText = ""
    a = ord('a')
    z = ord('z')
    for i in range(len(text)):
        n = ord(text[i])
        n = (n + k % 26) #add an amount between 0 and 25
        if n > z:
            n -= 26
        c = chr(n)
        cipherText += c
    return cipherText


import datetime
import os
import random

BENCH_DIR = './benchmark_dir'
GIT_INIT = 'git init > /dev/null'
GIT_ADD = 'git add --all'
GIT_COMMIT = 'git commit -m "git bench" > /dev/null'
html_template = []

def clean():
    os.system('rm -rf ./.git')
    os.system('rm -rf {}'.format(BENCH_DIR))
    os.system('mkdir {}'.format(BENCH_DIR))

def generate_and_commit():
    filename = 'file' + str(random.randint(1, 5000))
    gen_dir = os.path.join(BENCH_DIR, filename)
    if not os.path.exists(gen_dir):
        os.system('mkdir {0} && cd {0} && {init}'.format(gen_dir, init=GIT_INIT))
    template_file = "html_templates/type{}.html".format(random.randint(0, 9))
    os.system('cat {} > {}/{}'.format(template_file, gen_dir, filename))
    os.system('cd {dir} && {add} && {commit}'.format(
        dir=gen_dir,
        add=GIT_ADD,
        commit=GIT_COMMIT
    ))

def main():
    clean()
    print('cleaned')
    start_time = datetime.datetime.now()
    print('start benchmark')
    for _ in range(20):
        batch_start = datetime.datetime.now()
        for _ in range(1000):
            generate_and_commit()
        batch_end = datetime.datetime.now()
        duration = batch_end - batch_start
        print(duration, 1000 / duration.total_seconds())
    end_time = datetime.datetime.now()
    print(end_time - start_time)

if __name__ == '__main__':
    main()


import monkey_object as mobject

def test_string_hash_key():
    hello1 = mobject.String(value="Hello World")
    hello2 = mobject.String(value="Hello World")
    diff1 = mobject.String(value="different string")
    diff2 = mobject.String(value="different string")

    assert hello1.hash_key == hello2.hash_key, "strings with same content have different hash keys"
    assert hello1.hash_key != diff1.hash_key, "strings with different content have same hash keys"
    assert diff1.hash_key == diff2.hash_key, "strings with same content have different hash keys"

def test_int_hash_key():
    a1 = mobject.Integer(value=1)
    a2 = mobject.Integer(value=1)
    diff = mobject.Integer(value=30)

    assert a1.hash_key == a2.hash_key, "int with same content have different hash keys"
    assert a1.hash_key != diff.hash_key, "int with different content have same hash keys"

def test_bool_hash_key():
    t1 = mobject.Boolean(value=True)
    t2 = mobject.Boolean(value=True)
    f1 = mobject.Boolean(value=False)

    assert t1.hash_key == t2.hash_key, "bool with same content have different hash keys"
    assert t1.hash_key != f1.hash_key, "bool with different content have same hash keys"


from django.utils.dateparse import parse_date
from datetime import datetime
from django.http import HttpResponse

import os
from django.conf import settings
from django.http import JsonResponse
import datetime
import docx
from django.shortcuts import render, redirect
from docx.shared import Inches
from docx2pdf import convert
from djangoProject import settings
import google_translate
import pdfkit

def index(request):
    return render(request, 'index.html')

def letter(request):
    if request.method == 'POST':
        print(request.POST)
    return render(request, 'letter.html')

def lawsuit(request):
    return render(request, 'lawsuits.html')

def why(request):
    return render(request, 'why.html')

LIBRE_OFFICE = r"/usr/bin/soffice"

def convert_to_pdf(input_docx, out_folder):
    p = Popen([LIBRE_OFFICE, '--headless', '--convert-to', 'pdf', '--outdir',
               out_folder, input_docx])
    print([LIBRE_OFFICE, '--convert-to', 'pdf', input_docx])
    p.communicate()

current_upload = 0

def file_upload(request):
    global current_upload
    if request.method == 'POST':
        numMessages = int(request.POST.get('numMessages'))
        file = request.FILES.get('file')
        if file:  # check if file exists
            file_name = f'temp{current_upload}.png'
            file_path = os.path.join(settings.MEDIA_ROOT, file_name)
            with open(file_path, 'wb+') as destination:
                for chunk in file.chunks():
                    destination.write(chunk)
            current_upload += 1
            if current_upload == numMessages:
                current_upload = 0
                return JsonResponse({'status': 'success', 'message': 'All files uploaded successfully'})
            else:
                return JsonResponse({'status': 'success', 'message': 'File uploaded successfully'})
        else:
            return JsonResponse({'status': 'error', 'message': 'File not found'})

def letter(request):
    if request.method == 'POST':
        today = datetime.date.today()
        date_string = today.strftime("%d/%m/%Y")
        username = request.POST['full_name']
        useremail = request.POST['email']
        userphone = request.POST['phone_number']
        company_name = request.POST['company_name']
        company_address = request.POST['company_address']
        company_id = request.POST['company_id']

        if request.POST['spam_type'] == 'email':
            type_address = useremail
            received = "מייל"
            dev = "כתובת מייל"
        else:
            type_address = userphone
            received = "מסרון"
            dev = "טלפון"

        if request.POST['unsubscribed_button'] == 'false':
            could_you_unsubscribe = "אם לא די בכך, הרי שהמסרון ממילא לא עומד בדרישות החוק הצורניות בכך שאין בו אפשרות הסרה כדין"
        else:
            could_you_unsubscribe = " "

        # Get the number of message

        num_messages = int(request.POST['num_messages'])
        dates_and_times = []
        date_of_message = [''] * num_messages
        time_of_message = [''] * num_messages
        for i in range(num_messages):
            date_of_message[i] = parse_date(request.POST['message_{}_date'.format(i)]).strftime("%d/%m/%Y")
            time_of_message[i] = (request.POST['message_{}_time'.format(i)])
            dates_and_times.append((date_of_message[i], time_of_message[i]))
        date_of_message = ""
        time_of_message = ""
        messages = ""
        for date, time in dates_and_times[:1:1]:
            messages += f"ביום {date}  בשעה {time}\n"
        for date, time in dates_and_times[1::1]:
            messages += f"ביום {date}  בשעה {time}\n"

        print(dates_and_times)  # Output:

        keywords = {
            "da1te": date_string,
            "UserName": username,
            "UserEmail": useremail,
            "UserPhone": userphone,
            "dev": dev,
            "1515": type_address,
            "received": received,
            "date_of_message": messages,
            "could_you_unsubscrive": could_you_unsubscribe,
            "company_name": company_name,
            "Company_address": company_address,
            "company_id": company_id,

        }

        # Filename of the template
        template_filename = 'static/docx/template.docx'

        # Open the temp file
        document = docx.Document(template_filename)
        document.core_properties.encoding = 'UTF-8'

        # Replace keywords in the contents
        for paragraph in document.paragraphs:
            for run in paragraph.runs:
                for key, value in keywords.items():
                    run.text = run.text.replace(key, value)

        # Iterate through all the paragraphs in the docx
        hebrew_alphabet = ["א׳", "ב", "ג", "ד", "ה", "ו", "ז", "ח", "ט", "י", "כ", "ל", "מ", "נ", "ס", "ע", "פ", "צ",
                           "ק", "ר", "ש", "ת"]

        try:
            photo_path = [''] * num_messages
            # insert the photos and text for attachments
            for i in range(num_messages):
                input = ("נספח " + hebrew_alphabet[i] +
                         "\n")
                new_para = document.add_paragraph(input)
                photo_path[i] = settings.MEDIA_ROOT + ('/temp' + f'{i}' + '.png')
                new_para.add_run().add_picture(photo_path[i], width=Inches(2.5))
        except FileNotFoundError:
            return render(request, 'letter.html', {'error': 'Please attach a file before submitting the form'})

        # changes the font

        for paragraph in document.paragraphs:
            for run in paragraph.runs:
                # Set the font to Arial
                run.font.name = "Arial"
        document.save('static/docx/modified_document.docx')
        # convert to PDF
        filetype = str(request.POST['output_file'])

        if (filetype == 'PDF'):
            # sample_doc = 'static/docx/modified_document.docx'
            # out_folder = 'static/docx'
            # convert_to_pdf(sample_doc, out_folder)
            doc = ("static/docx/modified_document.docx")
            savedoc = ("static/docx/modified_document.pdf")
            convert(doc,savedoc)

        folder = 'media'

        for filename in os.listdir(folder):
            if filename.startswith("temp") and filename.endswith(".png"):
                file_path = os.path.join(folder, filename)
                try:
                    os.unlink(file_path)
                except Exception as e:
                    print("Failed to delete file: ", e)

        download_success = True

        # document.save('static/docx/modified_document.docx')

        return render(request, 'form.html', {'download_success': download_success, 'type': filetype})

        print("Finished replacing keywords in temp file.")
    else:
        # Set the download_success flag to False
        download_success = False

        # Save the modified Word document
    return render(request, 'letter.html')

def home(request):
    return render(request, 'Home.html')

def form(request):
    # Set the download_success flag to True
    download_success = True

    # Render the form template
    return render(request, 'form.html', {'download_success': download_success})

def importError(request):

    return render(request, 'importError.html')

def download_file(request):
    if request.method == 'POST':
        if request.POST['type'] == 'PDF':
            file_path = 'static/docx/modified_document.pdf'
            filename = "Letter.pdf"
            content_type = 'application/pdf'
        if request.POST['type'] == 'lawsuit':
            file_path = 'static/docx/destination.docx'
            filename = "lawsuit.docx"
            content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

        else:
            file_path = 'static/docx/modified_document.docx'
            filename = "Letter.docx"

            content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'

        # Process form submission
        # Open the file in binary mode
        with open(file_path, 'rb') as f:
            # Read the file content
            file_content = f.read()

        print(file_path)
        # Create the HttpResponse object with the file content

        response = HttpResponse(file_content,
                                content_type=content_type)
        # Set the Content-Disposition header to attachment
        response['Content-Disposition'] = f'attachment; {filename}'

        # Set the download_success flag to True
        download_success = True

        # Return the HttpResponse object
        return response
    else:
        # Set the download_success flag to False
        download_success = False

    # Render the form template
    return render(request, 'form.html', {'download_success': download_success})


from socket import *
import datetime
import time
import random

server = "127.0.0.1"
port = 9000
clientSocket = socket(family = AF_INET, type=SOCK_DGRAM)
print("Kerkesat qe mund te beni : IP , PORT, PRINTO, KENO, KONVERTO, HOST, TIME, FAKTORIEL, ZANORET")
while True:
    kerkesa=input("Shkruaj kerkesen : ")

    clientSocket.sendto(kerkesa.encode("ASCII"),(server,port))
    if kerkesa=="KONVERTO":
         Opcioni=input("Opcioni: ")
         clientSocket.sendto(Opcioni.encode("ASCII"),(server,port))
         Opcioni, adresenEServerit = clientSocket.recvfrom(1024)
         print(Opcioni.decode("ASCII"))
    elif kerkesa=="PRINTO":
        mesazh = input("Fjalia juaj: ")
        clientSocket.sendto(mesazh. encode("ASCII"), (server, port))
        mesazhiKthyer, adresenEServerit = clientSocket.recvfrom(1024)
        print(mesazhiKthyer.decode("ASCII"))

    pergjigja , serverAddress=clientSocket.recvfrom(1024)
    print("Pergjigja: " + pergjigja.decode("ASCII"))