import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server
from gpiozero import Motor, MCP3008
from time import sleep

PATH = '/home/pi/marsrover/'

rightMotor = Motor(16,19)
leftMotor = Motor(20,21)

adc = MCP3008(channel=1)

Vref = 3.3
potentialDividerMultiplier = 4.03 # Vin--10k--+--3.3k--GND
                                  #           |
                                  #           A1

class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition()

    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            # New frame, copy the existing buffer's content and notify all
            # clients it's available
            self.buffer.truncate()
            with self.condition:
                self.frame = self.buffer.getvalue()
                self.condition.notify_all()
            self.buffer.seek(0)
        return self.buffer.write(buf)

class StreamingHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(301)
            self.send_header('Location', '/index.html')
            self.end_headers()
        elif self.path == '/index.html':
            f = open(PATH+'index.html', 'rb')
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        elif self.path == '/style.css':
            f = open(PATH+'style.css', 'rb')
            self.send_response(200)
            self.send_header('Content-Type', 'text/css')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        elif self.path == '/stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
            self.end_headers()
            try:
                while True:
                    with output.condition:
                        output.condition.wait()
                        frame = output.frame
                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame))
                    self.end_headers()
                    self.wfile.write(frame)
                    self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))
        elif self.path == '/MarsBackground.png':
            f = open(PATH+'MarsBackground.png', 'rb')
            self.send_response(200)
            self.send_header('Content-Type', 'image/png')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        elif self.path == '/jquery.min.js':
            f = open(PATH+'jquery.min.js', 'rb')
            self.send_response(200)
            self.send_header('Content-Type', 'application/javascript')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        elif self.path == '/marsui.js':
            f = open(PATH+'marsui.js', 'rb')
            self.send_response(200)
            self.send_header('Content-Type', 'application/javascript')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        elif self.path == '/static.gif':
            f = open(PATH+'static.gif', 'rb')
            self.send_response(200)
            self.send_header('Content-Type', 'image/gif')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        elif self.path == '/voltage' or self.path == '/voltage/':
            self.voltage = adc.value * Vref * potentialDividerMultiplier
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.end_headers()
            self.voltagestr = "[{ \"value\": " + "{:0.3f}".format(self.voltage) + " }]"
            self.wfile.write(self.voltagestr.encode('utf-8'))
        elif self.path.split("/")[1] == 'forward':
            try:
                delay = (int(self.path.split("/")[2]))
            except:
                self.send_response(200)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                self.wfile.write("error".encode('utf-8'))
                return
            leftMotor.forward(speed=0.5)
            rightMotor.forward(speed=0.5)
            sleep(delay)
            leftMotor.stop()
            rightMotor.stop()
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.end_headers()
            self.wfile.write("ok".encode('utf-8'))
        elif self.path.split("/")[1] == 'backward':
            try:
                delay = (int(self.path.split("/")[2]))
            except:
                self.send_response(200)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                self.wfile.write("error".encode('utf-8'))
                return
            leftMotor.backward(speed=0.5)
            rightMotor.backward(speed=0.5)
            sleep(delay)
            leftMotor.stop()
            rightMotor.stop()
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.end_headers()
            self.wfile.write("ok".encode('utf-8'))
        elif self.path.split("/")[1] == 'right':
            try:
                delay = (int(self.path.split("/")[2]))
            except:
                self.send_response(200)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                self.wfile.write("error".encode('utf-8'))
                return
            leftMotor.forward(speed=0.5)
            rightMotor.backward(speed=0.5)
            sleep(delay)
            leftMotor.stop()
            rightMotor.stop()
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.end_headers()
            self.wfile.write("ok".encode('utf-8'))
        elif self.path.split("/")[1] == 'left':
            try:
                delay = (int(self.path.split("/")[2]))
            except:
                self.send_response(200)
                self.send_header('Content-Type', 'text/html')
                self.end_headers()
                self.wfile.write("error".encode('utf-8'))
                return
            leftMotor.backward(speed=0.5)
            rightMotor.forward(speed=0.5)
            sleep(delay)
            leftMotor.stop()
            rightMotor.stop()
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.end_headers()
            self.wfile.write("ok".encode('utf-8'))
        else:
            self.send_error(404)
            self.end_headers()

class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
    allow_reuse_address = True
    daemon_threads = True

with picamera.PiCamera(resolution='640x480', framerate=10) as camera:
    output = StreamingOutput()
    camera.vflip = True
    camera.hflip = True
    camera.start_recording(output, format='mjpeg')
    try:
        address = ('', 80)
        server = StreamingServer(address, StreamingHandler)
        server.serve_forever()
    finally:
        camera.stop_recording()


#!/usr/bin/env python
# encoding: utf-8

import time

from progressbar import ProgressBar

def main():
    # 初始化
    pb = ProgressBar(' ', '*')

    # 更新进度到20%
    pb.progress(percent=0.2)

    # 显示当前进度，并伴随消息
    pb.progress(percent=0.2, msg='blablabla...')

    # 一个从1 到 1000进度的显示过程，并伴有详细信息(为模拟进度过程用了0.01的sleep，
    # 实际使用中可以去掉time.sleep)
    for i in range(1000):
        pb.progress(percent=float(i) / 1000, msg='app id -> %d' % i)

    time.sleep(2)

if __name__ == '__main__':
    main()


#encoding=utf8

import json
import pandas as pd

def json2csv(data_file):
    with open(data_file) as f:
        train = f.read().encode("utf8")
    dic = {}
    train = json.loads(train)
    keys = train.keys()
    id_list = train[keys[0]].keys()
    dic["id"] = id_list

    data = pd.DataFrame(dic)
    for key in keys:
        word_list = []
        for i in id_list:
            word = train[key][i]
            try:
                word = word.replace("\r", "")
            except:
                pass
            word_list.append(word)
        data[key] = word_list

    return data

def get_data():
    train_data=json2csv("train.json")
    test_data=json2csv("test.json")
    return train_data,test_data

if __name__=="__main__":
    train_data, test_data=get_data()
    train_data.to_csv("train.csv",index=None,encoding="utf8")
    test_data.to_csv("test.csv",index=None,encoding="utf8")


"""
练习3
在控制台中输入一个月份
返回该月份的天数
1 3 5 7 8 10 12(31天）
4 6 9 11(30天）
2 （当28天
使用元组
"""
month = int(input("请输入月份："))
day_of_month = (31, 28, 31,30, 31, 30, 31, 31, 30, 31, 30, 31)
if month > 12 or month < 1:
    print("输入错误")
else:
    print(day_of_month[month-1])

month =int(input("请输入月份："))
if month<1 or month>12:
    print("输入错误")
else:
    day_of_month = (31,28,31,30,31,30,31,31,30,31,30,31)
    print(day_of_month[month-1])

int_month = int(input("输入一个月份"))
if int_month<1 or int_month>12:
    print("输入有误")
else:
    #将每月的天数，存入元组
    day_of_month = (31,28,31,30,31,30,31,30,31,30,31)
    print(day_of_month[int_month-1])

# #利用元组
# int_month = int(input("输入一个月份"))
# if int_month<1 or int_month>12:
#     print("输入有误")
# elif int_month == 2:
#     print("该月份有28天")
# #elif int_month == 4 or int_month == 6 or int_month == 9 or int_month == 11:
# elif int_month in (4,6,9,11):
#     print("该月份有30天")
# else:
#     print("该月份有31天")


import random
import os
if os.name == 'nt':
    os.system("")
ketthuc = False
diem = 0
socau = 0
while ketthuc == False:
#    dai = int(input("dai: "))
#    rong = int(input("rong: "))
#    cao = int(input("cao: "))
#    day = int(input("day: "))
#    day2 = int(input("day2: "))
#    bk = int(input("bk: "))
#    canh =int(input("canh: "))
#    hcn = dai * rong
#    htron  =  bk * bk * 3.14
#    hv  = canh * canh
#    htg  =  day * cao
#    hthang =  (day + day2) * cao / 2
    print("---------------Toán học vui-----------------")
#    print("Câu số: "+str(socau)+" Điểm: "+ str(diem)+"\nMời bạn chọn phép tính: ")
    print("1: hcn")
    print("2: htron")
    print("3: hv")
    print("4: htg")
    print("5: hthang")
    chon = input("Bạn chọn số: ")
    if chon == "1": #hcn
        dai = int(input("Nhập dài = "))
        rong = int(input("Nhập rộng = "))
        ketqua = dai * rong
        print("Diện tích hcn= ", ketqua)
    elif chon == "2": #htron
        bk = int(input("Nhập bk ="))
        ketqua = bk*bk * 3.14
        ketqua2 = (bk+bk) *3.14
        print("Diện tích htron = ", ketqua)
        print("chu vi htron = ", ketqua2)
    elif chon == "3": #hv
        canh = int(input("Nhập canh ="))
        ketqua = (canh*canh)
        ketqua2 = canh * 4
        print("Diện tích hv = ", ketqua)
        print("chu vi hv = ", ketqua2)
    elif chon == "4": #htg
        day = int(input("Nhập day ="))
        cao = int(input("Nhập cao ="))
        canhA = int(input("Nhập canhA = "))
        canhB = int(input("Nhập canhB = "))
        canhC = int(input("Nhập canhC = "))
        ketqua = day * cao / 2
        ketqua2 = canhA + canhB + canhC
        print("Diện tích htg= ", ketqua)
        print("chu vi htg= ", ketqua2)
    elif chon == "5": #hthang
        day = int(input("Nhập day ="))
        day2 = int(input("Nhập day2 ="))
        cao = int(input("Nhập cao ="))
        ketqua = (day + day2) * cao / 2
        print("Diện tích hthang= ", ketqua)
    else:
        print("Cảm ơn bạn! Nghỉ thôi nào!")
        ketthuc = True


import os
from pytz import timezone
from datetime import datetime

import requests.exceptions

from helpers import log
from .sudo_query_helpers import query, update
from .kalliope_adapter import construct_kalliope_poststuk_in
from .kalliope_adapter import open_kalliope_api_session
from .kalliope_adapter import post_kalliope_poststuk_in
from .queries import construct_unsent_berichten_query
from .queries import construct_select_bijlagen_query
from .queries import construct_increment_bericht_attempts_query
from .queries import construct_bericht_sent_query
from .queries import construct_select_original_bericht_query
from .queries import construct_create_kalliope_sync_error_query
from .update_with_supressed_fail import update_with_suppressed_fail

TIMEZONE = timezone('Europe/Brussels')
ABB_URI = "http://data.lblod.info/id/bestuurseenheden/141d9d6b-54af-4d17-b313-8d1c30bc3f5b"
PUBLIC_GRAPH = "http://mu.semte.ch/graphs/public"
MAX_SENDING_ATTEMPTS = int(os.environ.get('MAX_SENDING_ATTEMPTS'))
INZENDING_BASE_URL = os.environ.get('INZENDING_BASE_URL')
PS_IN_PATH = os.environ.get('KALLIOPE_PS_IN_ENDPOINT')

def process_berichten_out():
    """
    Fetch Berichten that have to be sent to Kalliope from the triple store,
    convert them to the correct format for the Kalliope API, post them and finally mark them as sent.

    :returns: None
    """
    q = construct_unsent_berichten_query(ABB_URI, MAX_SENDING_ATTEMPTS)
    berichten = query(q)['results']['bindings']
    log("Found {} berichten that need to be sent to the Kalliope API".format(len(berichten)))
    if len(berichten) == 0:
        return
    with open_kalliope_api_session() as session:
        for bericht_res in berichten:
            try:
                (bericht, conversatie, bijlagen) = prepare_message_and_conversation(bericht_res)
                poststuk_in = construct_kalliope_poststuk_in(conversatie, bericht)
                bestuurseenheid_uuid =\
                    bericht['van'].split('/')[-1]  # NOTE: Add graph as argument to query because Virtuoso
                graph =\
                    "http://mu.semte.ch/graphs/organizations/{}/LoketLB-berichtenGebruiker".format(bestuurseenheid_uuid)
                log("Posting bericht <{}>. Payload: {}".format(bericht['uri'], poststuk_in))

                post_result = send_message(session, poststuk_in, bericht, bijlagen, graph)
                if post_result:
                    set_message_as_sent(bericht, bijlagen, graph)

            except Exception as e:
                message = """
                            General error while trying to send bericht {}.
                            Error: {}
                          """.format(bericht['uri'] if 'bericht' in locals() else "[No message defined]", e)
                error_query =\
                    construct_create_kalliope_sync_error_query(PUBLIC_GRAPH,
                                                               bericht['uri'] if 'bericht' in locals() else None,
                                                               message,
                                                               e)
                update_with_suppressed_fail(error_query)
                log(message)
    pass

def prepare_message_and_conversation(bericht_res):
    bericht = {
        'uri': bericht_res['bericht']['value'],
        'van': bericht_res['van']['value'],
        'verzonden': bericht_res['verzonden']['value'],
        'inhoud': bericht_res['inhoud']['value'],
    }

    origineel_bericht_uri = get_initial_message_uri(bericht)

    REPLY_SUBJECT_PREFIX = "Reactie op "
    betreft = REPLY_SUBJECT_PREFIX + bericht_res['betreft']['value']
    conversatie = {
        'inhoud': bericht_res['inhoud']['value'],
        'betreft': betreft,
        'origineelBerichtUri': origineel_bericht_uri
    }
    if 'dossieruri' in bericht_res:
        conversatie['dossierUri'] = bericht_res['dossieruri']['value']
    q_bijlagen = construct_select_bijlagen_query(bericht['uri'])
    bijlagen = query(q_bijlagen)['results']['bindings']
    bericht['bijlagen'] = []
    for bijlage_res in bijlagen:
        bijlage = {
            'name': bijlage_res['bijlagenaam']['value'],
            'filepath': bijlage_res['file']['value'].replace("share://", "", 1),
            'type': bijlage_res['type']['value'],
        }
        bericht['bijlagen'].append(bijlage)

    return bericht, conversatie, bijlagen

def get_initial_message_uri(bericht):
    q_origineel = construct_select_original_bericht_query(bericht['uri'])
    return query(q_origineel)['results']['bindings'][0]['origineelbericht']['value']

def send_message(session, poststuk_in, bericht, bijlagen, graph):
    try:
        return post_kalliope_poststuk_in(PS_IN_PATH, session, poststuk_in)
    except Exception as e:
        message = "Something went wrong while posting following poststuk in, skipping: {}\n{}".format(poststuk_in,
                                                                                e)
        update(construct_create_kalliope_sync_error_query(PUBLIC_GRAPH, bericht['uri'], message, e))
        update(construct_increment_bericht_attempts_query(graph, bericht['uri']))
        log(message)
        raise e

def set_message_as_sent(bericht, bijlagen, graph):
    # We consider the moment when the api-call succeeded the 'ontvangen'-time
    ontvangen = datetime.now(tz=TIMEZONE).\
                                 replace(microsecond=0).isoformat()
    q_sent = construct_bericht_sent_query(graph, bericht['uri'], ontvangen)
    update(q_sent)
    log("successfully sent bericht {} with {} bijlagen to Kalliope".format(bericht['uri'],
                                                                           len(bijlagen)))


from flask_login import login_required, current_user
from flask import render_template,request,redirect,url_for,abort
from ..models import  User,Pitch,Comment
from .forms import CommentForm,UpdateProfile,AddPitch
from .. import db,photos
from . import main
import markdown2

@main.route('/')
def index():
    return render_template('index.html',title='tasha')

@main.route('/pitched/comment/<int:id>', methods = ['GET','POST'])
@login_required
def new_comment(id):
    form = CommentForm()
    pitch = Pitch.get_pitch(id)
    if form.validate_on_submit():
        comment = form.comment.data
        new_comment = Comment(pitch_id=id, comment_content=comment, user_id=current_user.id)
        new_comment.save_comment()
    comment = Comment.get_comments(id)

    return render_template('new_comment.html', comment_form=form, pitch=pitch, comment=comment)

@main.route('/pitched', methods=['GET', 'POST'])
def post():
    form = AddPitch()
    if form.validate_on_submit():
        new_pitch = Pitch(pitch_content=form.pitch.data,pitch_category=form.category.data)
        db.session.add(new_pitch)
        db.session.commit()
    pitch=Pitch.query.all()
    return render_template('pitched.html',form=form, pitch=pitch)

@main.route('/pick', methods=['GET', 'POST'])
def pickup():
    pickup = Pitch.query.filter_by(pitch_category="pick-up-lines").all()
    print(pickup)
    return render_template('pickup.html', pitch=pickup)
@main.route('/Interview', methods=['GET', 'POST'])
def interview():
    interview = Pitch.query.filter_by(pitch_category="interview").all()
    print(interview)
    return render_template('interview.html', pitch=interview)
@main.route('/Product', methods=['GET', 'POST'])
def product():
    product = Pitch.query.filter_by(pitch_category="product").all()
    print(product)
    return render_template('product.html', pitch=product)

@main.route('/user/<uname>/update',methods = ['GET','POST'])
@login_required
def update_profile(uname):
    user = User.query.filter_by(username = uname).first()
    if user is None:
        abort(404)

    form = UpdateProfile()

    if form.validate_on_submit():

        user.bio = form.bio.data

        db.session.add(user)
        db.session.commit()

        return redirect(url_for('.profile',uname=user.username))

    return render_template('profile/update.html',form =form)

@main.route('/user/<uname>/update/pic',methods= ['POST','GET'])
@login_required
def update_pic(uname):
    user = User.query.filter_by(username = uname).first()
    if 'photo' in request.files:
        filename = photos.save(request.files['photo'])
        path = f'photos/{filename}'
        user.profile_pic_path = path
        user_photo = PhotoProfile(pic_path = path,user = user)
        db.session.commit()
    return redirect(url_for('main.update_profile',uname=uname))

@main.route('/user/comment',methods=['GET','POST'])
def comment():
    form = form


import os
import pickle
import numpy as np
import sys
from tqdm.autonotebook import tqdm
import queue
import threading
import math
import time

def read_files(q, file_list, output=False):
    if output:
        generator = tqdm(file_list)
    else:
        generator = file_list

    for fn in generator:
        if '.npy' in fn:
            entry = np.load(os.path.join(input_folder, fn))
            q.put(dict(fn=fn, entry=entry))
    q.put('finish')

start_t = time.time()

input_folder = sys.argv[1]
output_file = sys.argv[2]
num_parts = int(sys.argv[3])
num_threads = 20

directory_list = os.listdir(input_folder)
part_size = math.ceil(len(directory_list) / num_parts)

for part_num in range(num_parts):
    q = queue.Queue()
    data = dict()
    threads = []
    finish_threads = 0
    part_data = directory_list[part_num * part_size: (part_num + 1) * part_size]

    for t in range(num_threads):
        num_entries = math.ceil(len(part_data) / num_threads)
        thread_data = part_data[t * num_entries: (t + 1) * num_entries]
        thread = threading.Thread(target=read_files, args=(q, thread_data, t == 0))
        thread.start()
        threads.append(thread)

    while finish_threads != num_threads:
        if not q.empty():
            entry = q.get()
            if entry == 'finish':
                print('finish thread signal')
                finish_threads += 1
            else:
                data[entry['fn']] = entry['entry']
                # print('.')

    for thread in threads:
        thread.join()

    with open("{}.{}".format(output_file, part_num), 'wb') as out_file:
        pickle.dump(data, out_file, protocol=-1)

print(time.time() - start_t)


# Lab 3: Version 2 ---- Handles numbers 100-999
'''
The biggest change on this version is adding a 'hundreds' dictionary
and adding to function to seperate and return appropriate function
'''
# Number is input
num = int(input('Enter number: '))

# Dictionaries with int as key, and values as english representation
ones = {
    1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five',
    6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 0: ''
}

tens = {
    1: 'Ten', 2: 'Twenty', 3: 'Thirty', 4: 'Forty', 5: 'Fifty',
    6: 'Sixty', 7: 'Seventy', 8: 'Eighty', 9: 'Ninety', 0: ''
}

hundreds = {
    1: 'One Hundred', 2: 'Two Hundred', 3: 'Three Hundred', 4: 'Four Hundred', 5: 'Five Hundred',
    6: 'Six Hundred', 7: 'Seven Hundred', 8: 'Eight Hundred', 9: 'Nine Hundred', 0: ''
}

# Function breaking number into seperate digits and returning appropriate phrase
def phrase(num):
    huns_digit = num//100
    tens_digit = (num%100)//10
    ones_digit = num%10
    phrase = f'{hundreds[huns_digit]} {tens[tens_digit]} {ones[ones_digit]}'

    if ones_digit == 0 and tens_digit == 0 and huns_digit == 0:
        return 'Zero'
    if tens_digit == 1 and ones_digit == 1:
        return f'{hundreds[huns_digit]} Eleven'
    elif tens_digit == 1 and ones_digit == 2:
        return f'{hundreds[huns_digit]} Twelve'
    elif tens_digit == 1 and ones_digit == 3:
        return f'{hundreds[huns_digit]} Thirteen'
    elif tens_digit == 1 and 3 < ones_digit <= 9:
        return f'{hundreds[huns_digit]} {ones[ones_digit]}teen'
    else:
        return phrase

phrase(num)
# Input number returned as a phrase
print(f"You've entered {phrase(num)}")


from sys import stdin
from collections import defaultdict

if __name__ == "__main__":
    N = int(stdin.readline())
    alphabet_dict = defaultdict(int)
    result_dict = defaultdict(int)

    str_list = []
    for _ in range(N):
        str_list.append(str(stdin.readline().strip())[::-1])

    count_list = []
    for idx in range(8):
        count_list.append(defaultdict(int))

        for s in str_list:
            if len(s) > idx:
                count_list[idx][s[idx]] += 1

    for idx in range(7,-1,-1):
        if len(count_list[idx]):
            for key in count_list[idx].keys():
                alphabet_dict[key] += count_list[idx][key]*(10**idx if idx!= 0 else 1)

    number = 9
    for key in dict(sorted(alphabet_dict.items(), key=lambda item:item[1], reverse=True)).keys():
        result_dict[key] = number
        number -= 1

    for i, string in enumerate(str_list):
        string = list(string)
        for idx,s in enumerate(string[::-1]):
            string[idx] = str(result_dict[s])
        str_list[i] = int(''.join(string))
    print(sum(str_list))


import math
import numpy as np

def runKMeans(k,patches,maxIter):
    """
    Runs K-means to learn k centroids, for maxIter iterations.

    Args:
      k - number of centroids.
      patches - 2D numpy array of size patchSize x numPatches
      maxIter - number of iterations to run K-means for

    Returns:
      centroids - 2D numpy array of size patchSize x k
    """
    # This line starts you out with randomly initialized centroids in a matrix
    # with patchSize rows and k columns. Each column is a centroid.
    centroids = np.random.randn(patches.shape[0],k)

    numPatches = patches.shape[1]

    for i in range(maxIter):
        # BEGIN_YOUR_CODE (around 19 lines of code expected)
        points = list()

        mapping = dict()
        for j in range(numPatches): #iterating over the patches
          point = patches[:,j]
          minindex = 0
          minvalue = float('inf')
          for l in range(k): #iterating over the centroids
            centroid = centroids[:,l]

            if l not in mapping:
              mapping[l] = set()
            distance = np.linalg.norm(centroid - point)
            if distance < minvalue:
              minindex = l
              minvalue = distance
          mapping[minindex].add(j)

        for centroid in mapping.keys():
          centroids[:,centroid] = np.mean(patches[np.ix_(range(patches.shape[0]),list(mapping[centroid]))], axis=1)
        # END_YOUR_CODE
    return centroids


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

import time

import logging
import datetime

#import ventanaIngreso
import PDF_catalogo

from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
from tkinter import scrolledtext
from tkinter import filedialog
from tkinter import Menu
import tkinter as tk
from tkinter import ttk

import os
import os.path

import sqlite3
from sqlite3 import Error

import shutil

diccionario_textos = {}
diccionario_objetos = {}
diccionario_pinturas = {}
dicCat = {}
dicCatUbic = {}
dicProductores = {}
diccionario_objetos["ID_LOTE_A_EDITAR"] = "NULL"

direccionBaseDeDatos = 'database/iltanohacienda.db'

dire = "C:/Users/Santiago/Desktop/mipdf2.pdf"

dicLotes = {}
dicLotesUbic = {}

rematename = "remate1"

padX = 5
padY = 5

def treeview_sort_column(tv, col, reverse):
	l = [(tv.set(k, col), k) for k in tv.get_children('')]
	l.sort(reverse=reverse)

	# rearrange items in sorted positions
	for index, (val, k) in enumerate(l):
		tv.move(k, '', index)

	# reverse sort next time
	tv.heading(col, command=lambda: \
	treeview_sort_column(tv, col, not reverse))

	#tablaADicLotesUbic()

def sql_connection():
	try:
		con = sqlite3.connect(direccionBaseDeDatos)
		return con
	except Error:
		messagebox.showerror("ERROR", "Error conectando a la base de datos")
def actualizar_db(con, tabla, condiciones):
	cursorObj = con.cursor()
	cursorObj.execute("SELECT * FROM " + str(tabla) + condiciones)
	rows = cursorObj.fetchall()

	return rows
def actualizar_db2(con, tabla, condiciones):
	cursorObj = con.cursor()
	cursorObj.execute("SELECT cantidad FROM " + str(tabla) + condiciones)
	rows = cursorObj.fetchall()

	return rows

def actualizarProductores():
	con = sql_connection()
	condiciones = ""
	rows = actualizar_db(con, "productores", condiciones)
	for row in rows:
		dicProductores[str(row[3])] = str(row[1])

#Tabla lotes
def lotesFiltrar():
	pal_claveCorral = str(diccionario_objetos["entry_corralVendedor"].get())
	pal_clavePintura = str(diccionario_objetos["entry_pinturaVendedor"].get())
	pal_claveVendedor = str(diccionario_objetos["entry_vendedorVendedor"].get())

	con = sql_connection()
	condiciones =  ' WHERE corral LIKE "%' + pal_claveCorral + '%" AND pintura LIKE "%' + pal_clavePintura + '%" AND productor LIKE "%' + pal_claveVendedor + '%" AND estado = "activo" AND remate = "' + rematename + '"'
	rows = actualizar_db(con, "lotes", condiciones)

	dicAux = {}

	if(len(rows)==0):
		messagebox.showerror("ERROR", "No se encontro en la base de datos")
		return 0

	i = 0
	for row in rows:
		dicAux[str(i)] = {
		"id" : str(row[0]),
		"corral" : str(row[4]),
		"productor" : dicProductores[str(row[2])],
		"cantidad" : str(row[3]),
		"categoria" : str(row[6]),
		"pintura" : str(row[7]),
		"peso" : str(row[12]),
		"promedio" : str(row[13]),
		"cuit" : str(str(row[2])),
		}
		i+=1

	if(len(rows)==1):
		cargarDatosVendedor(rows[0][2])
		cargarDatosLotes(rows[0][0])

		diccionario_objetos["entry_corralVendedor"].delete(0, tk.END)
		diccionario_objetos["entry_pinturaVendedor"].delete(0, tk.END)
		diccionario_objetos["entry_vendedorVendedor"].delete(0, tk.END)

		diccionario_objetos["entry_comprador"].focus()
		return 0

	cargarTablaLotes(dicAux)
	borrarDatosLoteComprador()

def actualizarTablaLotes():
	con = sql_connection()
	condiciones = " WHERE remate = '" + rematename + "' AND estado = 'activo'"
	rows = actualizar_db(con, "lotes", condiciones)

	i=0
	for row in rows:
		dicLotes[str(i)] = {
		"id" : str(row[0]),
		"corral" : str(row[4]),
		"productor" : dicProductores[str(row[2])],
		"cantidad" : str(row[3]),
		"categoria" : str(row[6]),
		"pintura" : str(row[7]),
		"peso" : str(row[12]),
		"promedio" : str(row[13]),
		"cuit" : str(str(row[2])),
		}
		i+=1
	cargarTablaLotes(dicLotes)
def cargarTablaLotes(dicLotesCargar):
	tabla = diccionario_objetos["tabla_lotesCargados"]

	cant_lotes = len(dicLotesCargar)

	try:
		for i in tabla.get_children():
			tabla.delete(i)

		for i in range(0, cant_lotes):
			tabla.insert("", str(i), tags=(str(dicLotesCargar[str(i)]["id"]), str(dicLotesCargar[str(i)]["cuit"])), text = str(i), iid= str(i), values = (str(dicLotesCargar[str(i)]["corral"]),
				str(dicLotesCargar[str(i)]["productor"]),
				str(dicLotesCargar[str(i)]["cantidad"]),
				str(dicLotesCargar[str(i)]["categoria"]),
				str(dicLotesCargar[str(i)]["pintura"]),
				str(dicLotesCargar[str(i)]["peso"]),
				str(dicLotesCargar[str(i)]["promedio"]),))
	except:
		messagebox.showerror("ERROR", "Error al cargar")

	#print(rows)

def seleccionarTablaLote():
	tabla = diccionario_objetos["tabla_lotesCargados"]

	seleccion = tabla.item(tabla.selection())

	lote = seleccion["tags"][0]
	productor = seleccion["tags"][1]

	borrarDatosMontosCalculos()
	cargarDatosVendedor(productor)
	cargarDatosLotes(lote)
def cargarDatosVendedor(productor):
	con = sql_connection()
	condiciones = " WHERE ndoc = '" + str(productor) + "'"
	rows = actualizar_db(con, "productores", condiciones)

	row = rows[0]

	texto_alias = str(row[1])
	texto_razon = str(row[2])
	texto_cuit = str(row[3])
	texto_ruca = str(row[19])
	texto_observaciones = str(row[13])

	diccionario_objetos["texto_aliasVendedor"].set(texto_alias)
	diccionario_objetos["texto_razonVendedor"].set(texto_razon)
	diccionario_objetos["texto_cuitVendedor"].set(texto_cuit)
	diccionario_objetos["texto_rucaVendedor"].set(texto_ruca)

	diccionario_objetos["txt_observacionesVendedor"].configure(state="normal")
	diccionario_objetos["txt_observacionesVendedor"].delete("1.0", tk.END)
	diccionario_objetos["txt_observacionesVendedor"].insert("1.0", texto_observaciones)
	diccionario_objetos["txt_observacionesVendedor"].configure(state="disabled")
def cargarDatosLotes(lote):
	con = sql_connection()
	condiciones = " WHERE estado = 'activo' AND remate = '" + rematename + "' AND lote = '" + str(lote) + "'"
	rows = actualizar_db(con, "compraventa", condiciones)

	if(len(rows)==1):
		MsgBox = messagebox.askquestion('ATENCION', 'Este lote ya ha sido cargado ¿Desea cargarlo?', icon = 'warning')
		if(MsgBox == 'yes'):
			id_compraventa = rows[0][0]
			id_comprador = rows[0][2]
			precio = rows[0][3]

			con = sql_connection()
			condiciones = " WHERE id = '" + str(lote) + "'"
			rows = actualizar_db(con, "lotes", condiciones)
			row = rows[0]
			diccionario_objetos["ID_LOTE_A_EDITAR"] = str(id_compraventa)
			diccionario_objetos["ID_LOTE"] = lote
			diccionario_objetos["datosLote_texto_catHacienda"].set(str(row[6]))
			diccionario_objetos["datosLote_texto_catVenta"].set(str(row[5]))
			diccionario_objetos["datosLote_texto_corral"].set(str(row[4]))
			diccionario_objetos["datosLote_texto_cantidad"].set(str(row[3]))
			diccionario_objetos["datosLote_texto_neto"].set(str(row[12]))
			diccionario_objetos["datosLote_texto_promedio"].set(str(row[13]))

			diccionario_objetos["datosLote_txt_observaciones"].configure(state="normal")
			diccionario_objetos["datosLote_txt_observaciones"].delete("1.0", tk.END)
			diccionario_objetos["datosLote_txt_observaciones"].insert("1.0", (str(row[14])) + " - " + (str(row[15])))
			diccionario_objetos["datosLote_txt_observaciones"].configure(state="disabled")

			cargarDatosComprador(id_comprador)
			diccionario_objetos["entry_kilo"].delete(0, tk.END)
			diccionario_objetos["entry_kilo"].insert(0, precio)
			calcularKilo(precio)

	else:
		con = sql_connection()
		condiciones = " WHERE id = '" + str(lote) + "'"
		rows = actualizar_db(con, "lotes", condiciones)

		row = rows[0]

		diccionario_objetos["ID_LOTE_A_EDITAR"] = "NULL"
		diccionario_objetos["ID_LOTE"] = lote
		diccionario_objetos["datosLote_texto_catHacienda"].set(str(row[6]))
		diccionario_objetos["datosLote_texto_catVenta"].set(str(row[5]))
		diccionario_objetos["datosLote_texto_corral"].set(str(row[4]))
		diccionario_objetos["datosLote_texto_cantidad"].set(str(row[3]))
		diccionario_objetos["datosLote_texto_neto"].set(str(row[12]))
		diccionario_objetos["datosLote_texto_promedio"].set(str(row[13]))

		diccionario_objetos["datosLote_txt_observaciones"].configure(state="normal")
		diccionario_objetos["datosLote_txt_observaciones"].delete("1.0", tk.END)
		diccionario_objetos["datosLote_txt_observaciones"].insert("1.0", (str(row[14])) + " - " + (str(row[15])))
		diccionario_objetos["datosLote_txt_observaciones"].configure(state="disabled")

#Tabla Compradores
def compradorFiltrar():
	pal_clave = str(diccionario_objetos["entry_comprador"].get())

	con = sql_connection()
	condiciones =  ' WHERE (nombre LIKE "%' + pal_clave + '%" OR razon LIKE "%' + pal_clave + '%" OR ndoc LIKE "%' + pal_clave + '%" OR grupo LIKE "%' + pal_clave + '%" OR con_iva LIKE "%' + pal_clave + '%" OR localidad LIKE "%' + pal_clave + '%" OR provincia LIKE "%' + pal_clave + '%" OR ruca LIKE "%' + pal_clave + '%" OR establecimiento LIKE "%' + pal_clave + '%") AND estado = "activo"'
	rows = actualizar_db(con, "productores", condiciones)
	if(len(rows)==1):
		cargarDatosComprador(rows[0][3])
		cargarTablaCompradores([])
	else:
		cargarTablaCompradores(rows)
def cargarTablaCompradores(rows):
	tabla = diccionario_objetos["tabla_compradores"]

	for j in tabla.get_children():
		tabla.delete(j)

	try:
		for row in rows:
			texto_alias = str(row[1])
			texto_cuit = str(row[3])

			tabla.insert("", tk.END, tags=(str(row[0]), str(row[3])), values = (texto_alias,
				texto_cuit,))
	except:
		messagebox.showerror("ERROR", "Error al cargar")

def seleccionarTablaComprador():
	tabla = diccionario_objetos["tabla_compradores"]

	seleccion = tabla.item(tabla.selection())

	productor = seleccion["tags"][1]

	cargarDatosComprador(productor)
def cargarDatosComprador(productor):
	con = sql_connection()
	condiciones = " WHERE ndoc = '" + str(productor) + "'"
	rows = actualizar_db(con, "productores", condiciones)

	row = rows[0]

	texto_alias = str(row[1])
	texto_razon = str(row[2])
	texto_cuit = str(row[3])
	texto_ruca = str(row[19])
	texto_observaciones = str(row[13])

	diccionario_objetos["texto_aliasComprador"].set(texto_alias)
	diccionario_objetos["texto_razonComprador"].set(texto_razon)
	diccionario_objetos["texto_cuitComprador"].set(texto_cuit)
	diccionario_objetos["texto_rucaComprador"].set(texto_ruca)

	diccionario_objetos["txt_observacionesComprador"].configure(state="normal")
	diccionario_objetos["txt_observacionesComprador"].delete("1.0", tk.END)
	diccionario_objetos["txt_observacionesComprador"].insert("1.0", texto_observaciones)
	diccionario_objetos["txt_observacionesComprador"].configure(state="disabled")

#CONSTRUCTORES
def labelLoteBuscar(lbl_lote):
	lbl_buscar = tk.LabelFrame(lbl_lote, text="Buscar LOTE", backgroun="#E0F8F1")
	lbl_buscar.place(x = 30, y = 0, width = 260, height = 198)

	tk.Label(lbl_buscar, text="Corral:", font=("Helvetica Neue",20, "bold"), anchor="e", backgroun="#E0F8F1").place(x = 0, y = 0, width = 120)
	tk.Label(lbl_buscar, text="Pintura:", font=("Helvetica Neue",20, "bold"), anchor="e", backgroun="#E0F8F1").place(x = 0, y = 50, width = 120)
	tk.Label(lbl_buscar, text="Vendedor:", font=("Helvetica Neue",10, "bold"), anchor="e", backgroun="#E0F8F1").place(x = 0, y = 100, width = 120)

	entry_corral = Entry(lbl_buscar, font=("verdana",20))
	entry_pintura = Entry(lbl_buscar, font=("verdana",20))
	entry_vendedor = Entry(lbl_buscar, font=("verdana",10))

	entry_corral.place(x = 130, y = 0, width = 100)
	entry_pintura.place(x = 130, y = 50, width = 100)
	entry_vendedor.place(x = 130, y = 100, width = 100)

	btn_buscar = tk.Button(lbl_buscar, text="Buscar", font=("verdana",12, "bold"), backgroun="#CBF9E1", command = lotesFiltrar)
	btn_buscar.place(x = 60, y = 135, width=140, height=40)

	diccionario_objetos["entry_corralVendedor"] = entry_corral
	diccionario_objetos["entry_pinturaVendedor"] = entry_pintura
	diccionario_objetos["entry_vendedorVendedor"] = entry_vendedor

	def entryCorral():
		entry_pintura.focus()
		lotesFiltrar()
	def entryPintura():
		entry_vendedor.focus()
		lotesFiltrar()
	def entryVendedor():
		diccionario_objetos["entry_comprador"].focus()
		lotesFiltrar()

	entry_corral.bind("<Return>", (lambda event: entryCorral()))
	entry_pintura.bind("<Return>", (lambda event: entryPintura()))
	entry_vendedor.bind("<Return>", (lambda event: entryVendedor()))
def labelLoteTabla(lbl_lote):
	lbl_tabla = Label(lbl_lote)
	lbl_tabla.place(x = 300, y = 2, width = 600, height = 196)

	sbr_lotesCargados = Scrollbar(lbl_tabla)
	sbr_lotesCargados.pack(side=RIGHT, fill="y")

	tabla_lotesCargados = ttk.Treeview(lbl_tabla, columns=("corral", "productor", "cantidad", "categoria" , "pintura", "kg", "promedio"), selectmode=tk.BROWSE, height=7, show='headings')
	tabla_lotesCargados.pack(side=LEFT, fill="both", expand=True)
	sbr_lotesCargados.config(command=tabla_lotesCargados.yview)
	tabla_lotesCargados.config(yscrollcommand=sbr_lotesCargados.set)

	tabla_lotesCargados.heading("corral", text="Corral", command=lambda: treeview_sort_column(tabla_lotesCargados, "corral", False))
	tabla_lotesCargados.heading("productor", text="Productor", command=lambda: treeview_sort_column(tabla_lotesCargados, "productor", False))
	tabla_lotesCargados.heading("cantidad", text="Cant", command=lambda: treeview_sort_column(tabla_lotesCargados, "cantidad", False))
	tabla_lotesCargados.heading("categoria", text="Categoria", command=lambda: treeview_sort_column(tabla_lotesCargados, "categoria", False))
	tabla_lotesCargados.heading("pintura", text="Pint", command=lambda: treeview_sort_column(tabla_lotesCargados, "pintura", False))
	tabla_lotesCargados.heading("kg", text="Peso", command=lambda: treeview_sort_column(tabla_lotesCargados, "kg", False))
	tabla_lotesCargados.heading("promedio", text="Prom", command=lambda: treeview_sort_column(tabla_lotesCargados, "promedio", False))

	tabla_lotesCargados.column("corral", width=30)
	tabla_lotesCargados.column("productor", width=160)
	tabla_lotesCargados.column("cantidad", width=30)
	tabla_lotesCargados.column("categoria", width=100)
	tabla_lotesCargados.column("pintura", width=30)
	tabla_lotesCargados.column("kg", width=30)
	tabla_lotesCargados.column("promedio", width=30)

	diccionario_objetos["tabla_lotesCargados"] = tabla_lotesCargados

	tabla_lotesCargados.bind('<Double-1>', (lambda event: seleccionarTablaLote()))
	tabla_lotesCargados.bind('<Return>', (lambda event: seleccionarTablaLote()))
def labelLoteInfor(lbl_lote):
	lbl_info = tk.LabelFrame(lbl_lote, text="VENDEDOR", backgroun="#E0F8F1")
	lbl_info.place(x = 910, y = 0, width = 368, height = 198)

	texto_alias = StringVar()
	texto_alias.set("") # Caso 1
	texto_razon = StringVar()
	texto_razon.set("")
	texto_cuit = StringVar()
	texto_cuit.set("     -")
	texto_ruca = StringVar()
	texto_ruca.set("     -")

	lbl_alias = tk.Label(lbl_info, font=("Helvetica Neue",14,"bold"), anchor="w", backgroun="#E0F8F1")
	lbl_alias.place(x=0, y=0, width=350)
	lbl_alias.config(textvariable=texto_alias)

	lbl_razon = tk.Label(lbl_info, font=("Helvetica Neue",10), anchor="w", backgroun="#E0F8F1")
	lbl_razon.place(x=0, y=30, width=350)
	lbl_razon.config(textvariable=texto_razon)

	lbl_cuit = tk.Label(lbl_info, font=("verdana",12), anchor="w", backgroun="#E0F8F1")
	lbl_cuit.place(x=40, y=63, width=140)
	lbl_cuit.config(textvariable=texto_cuit)

	lbl_ruca = tk.Label(lbl_info, font=("verdana",12), anchor="w", backgroun="#E0F8F1")
	lbl_ruca.place(x=245, y=63, width=100)
	lbl_ruca.config(textvariable=texto_ruca)

	Label(lbl_info, font=("verdana",10), text="CUIT:", backgroun="#E0F8F1").place(x=0, y=65)
	Label(lbl_info, font=("verdana",10), text="RUCA:", backgroun="#E0F8F1").place(x=200, y=65)

	txt_observaciones = scrolledtext.ScrolledText(lbl_info, backgroun="#edfffa")
	txt_observaciones.place(x = 0, y = 95, width = 362, height = 80)
	txt_observaciones.config(state="disabled")

	diccionario_objetos["texto_aliasVendedor"] = texto_alias
	diccionario_objetos["texto_razonVendedor"] = texto_razon
	diccionario_objetos["texto_cuitVendedor"] = texto_cuit
	diccionario_objetos["texto_rucaVendedor"] = texto_ruca
	diccionario_objetos["txt_observacionesVendedor"] = txt_observaciones

def labelCompradorBuscador(lbl_comprador):
	#--Buscador
	lbl_comprador_aux = Label(lbl_comprador, backgroun="#E0F8F1")
	lbl_comprador_aux.place(x = 30, y = 0, width = 365, height = 198)

	lbl_ventana_productor_buscador_entry = tk.LabelFrame(lbl_comprador_aux, text="Filtrar", backgroun="#E0F8F1")
	lbl_ventana_productor_buscador_tabla = tk.LabelFrame(lbl_comprador_aux, text="Productores", backgroun="#E0F8F1")

	lbl_ventana_productor_buscador_entry.grid(column = 0, row = 0)
	lbl_ventana_productor_buscador_tabla.grid(column = 0, row = 1)

	#--
	entry_filtrar_productor = Entry(lbl_ventana_productor_buscador_entry, width="43")
	entry_filtrar_productor.pack(side = LEFT, padx = padX, pady = 5)

	btn_produc_filtrar = Button(lbl_ventana_productor_buscador_entry, width="9", text="Filtrar", command= lambda: compradorFiltrar())
	btn_produc_filtrar.pack(side = LEFT, padx = 10, pady = 0)

	sbr_productor = Scrollbar(lbl_ventana_productor_buscador_tabla)
	sbr_productor.pack(side=RIGHT, fill="y")

	tabla_productor = ttk.Treeview(lbl_ventana_productor_buscador_tabla, columns=("cliente", "doc"), selectmode=tk.BROWSE, height=5, show='headings')
	tabla_productor.pack(side=LEFT, fill="both", expand=True)
	sbr_productor.config(command=tabla_productor.yview)
	tabla_productor.config(yscrollcommand=sbr_productor.set)

	tabla_productor.heading("cliente", text="Productor")
	tabla_productor.heading("doc", text="CUIT/DNI")

	tabla_productor.column("cliente", width=240)
	tabla_productor.column("doc", width=100)

	diccionario_objetos["entry_comprador"] = entry_filtrar_productor
	diccionario_objetos["tabla_compradores"] = tabla_productor

	entry_filtrar_productor.bind("<Return>", (lambda event: compradorFiltrar()))
	tabla_productor.bind('<Double-1>', (lambda event: seleccionarTablaComprador()))
	tabla_productor.bind('<Return>', (lambda event: seleccionarTablaComprador()))
def labelLoteDatos(lbl_comprador):
	lbl_info = tk.LabelFrame(lbl_comprador, text="LOTE SELECCIONADO", backgroun="#E0F8F1")
	lbl_info.place(x = 400, y = 0, width = 505, height = 198)

	texto_catHacienda = StringVar()
	texto_catHacienda.set("") # Caso 1
	texto_catVenta = StringVar()
	texto_catVenta.set("")

	lbl_catVenta = tk.Label(lbl_info, font=("Helvetica Neue",12, "bold"), anchor="w", backgroun="#E0F8F1")
	lbl_catVenta.place(x=0, y=0, width=500)
	lbl_catVenta.config(textvariable=texto_catVenta)

	lbl_catHacienda = tk.Label(lbl_info, font=("Helvetica Neue",10,"bold"), anchor="w", backgroun="#E0F8F1")
	lbl_catHacienda.place(x=0, y=20, width=500)
	lbl_catHacienda.config(textvariable=texto_catHacienda)

	tk.Label(lbl_info, text="Corral", font=("Helvetica Neue",8), anchor="c", backgroun="#9bd1c1").place(x=0, y=42, width=125, height=13)
	tk.Label(lbl_info, text="Cantidad", font=("Helvetica Neue",8), anchor="c", backgroun="#9bd1c1").place(x=125, y=42, width=125, height=13)
	tk.Label(lbl_info, text="Peso Neto", font=("Helvetica Neue",8), anchor="c", backgroun="#9bd1c1").place(x=250, y=42, width=125, height=13)
	tk.Label(lbl_info, text="Peso Prom", font=("Helvetica Neue",8), anchor="c", backgroun="#9bd1c1").place(x=375, y=42, width=125, height=13)

	texto_corral = StringVar()
	texto_corral.set("")
	texto_cantidad = StringVar()
	texto_cantidad.set("")
	texto_neto = StringVar()
	texto_neto.set("")
	texto_promedio = StringVar()
	texto_promedio.set("")

	lbl_corral = tk.Label(lbl_info, font=("Helvetica Neue",25,"bold"), anchor="c", backgroun="#E0F8F1")
	lbl_corral.place(x=0, y=55, width=125)
	lbl_corral.config(textvariable=texto_corral)

	lbl_cantidad = tk.Label(lbl_info, font=("Helvetica Neue",25,"bold"), anchor="c", backgroun="#E0F8F1")
	lbl_cantidad.place(x=125, y=55, width=125)
	lbl_cantidad.config(textvariable=texto_cantidad)

	lbl_neto = tk.Label(lbl_info, font=("Helvetica Neue",25,"bold"), anchor="c", backgroun="#E0F8F1")
	lbl_neto.place(x=250, y=55, width=125)
	lbl_neto.config(textvariable=texto_neto)

	lbl_promedio = tk.Label(lbl_info, font=("Helvetica Neue",25,"bold"), anchor="c", backgroun="#E0F8F1")
	lbl_promedio.place(x=375, y=55, width=125)
	lbl_promedio.config(textvariable=texto_promedio)

	txt_observaciones = scrolledtext.ScrolledText(lbl_info, backgroun="#edfffa")
	txt_observaciones.place(x = 0, y = 110, width = 500, height = 68)
	txt_observaciones.insert("1.0", "ASDASDASD")
	txt_observaciones.config(state="disabled")

	diccionario_objetos["datosLote_texto_catHacienda"] = texto_catHacienda
	diccionario_objetos["datosLote_texto_catVenta"] = texto_catVenta
	diccionario_objetos["datosLote_texto_corral"] = texto_corral
	diccionario_objetos["datosLote_texto_cantidad"] = texto_cantidad
	diccionario_objetos["datosLote_texto_neto"] = texto_neto
	diccionario_objetos["datosLote_texto_promedio"] = texto_promedio
	diccionario_objetos["datosLote_txt_observaciones"] = txt_observaciones
def labelCompradorInfor(lbl_comprador):
	lbl_info = tk.LabelFrame(lbl_comprador, text="COMPRADOR", backgroun="#E0F8F1")
	lbl_info.place(x = 910, y = 0, width = 368, height = 198)

	texto_alias = StringVar()
	texto_alias.set("Seleccione un comprador de la lista") # Caso 1
	texto_razon = StringVar()
	texto_razon.set("")
	texto_cuit = StringVar()
	texto_cuit.set("     -")
	texto_ruca = StringVar()
	texto_ruca.set("     -")

	lbl_alias = tk.Label(lbl_info, font=("Helvetica Neue",14,"bold"), anchor="w", backgroun="#E0F8F1")
	lbl_alias.place(x=0, y=0, width=350)
	lbl_alias.config(textvariable=texto_alias)

	lbl_razon = tk.Label(lbl_info, font=("Helvetica Neue",10), anchor="w", backgroun="#E0F8F1")
	lbl_razon.place(x=0, y=30, width=350)
	lbl_razon.config(textvariable=texto_razon)

	lbl_cuit = tk.Label(lbl_info, font=("verdana",12), anchor="w", backgroun="#E0F8F1")
	lbl_cuit.place(x=40, y=63, width=140)
	lbl_cuit.config(textvariable=texto_cuit)

	lbl_ruca = tk.Label(lbl_info, font=("verdana",12), anchor="w", backgroun="#E0F8F1")
	lbl_ruca.place(x=245, y=63, width=100)
	lbl_ruca.config(textvariable=texto_ruca)

	Label(lbl_info, font=("verdana",10), text="CUIT:", backgroun="#E0F8F1").place(x=0, y=65)
	Label(lbl_info, font=("verdana",10), text="RUCA:", backgroun="#E0F8F1").place(x=200, y=65)

	txt_observaciones = scrolledtext.ScrolledText(lbl_info, backgroun="#edfffa")
	txt_observaciones.place(x = 0, y = 95, width = 362, height = 80)
	txt_observaciones.config(state="disabled")

	diccionario_objetos["texto_aliasComprador"] = texto_alias
	diccionario_objetos["texto_razonComprador"] = texto_razon
	diccionario_objetos["texto_cuitComprador"] = texto_cuit
	diccionario_objetos["texto_rucaComprador"] = texto_ruca

	diccionario_objetos["txt_observacionesComprador"] = txt_observaciones

def labelCompradorMontos(lbl_montos):
	lbl_montos = tk.LabelFrame(lbl_montos, text="Montos", backgroun="#E0F8F1")
	lbl_montos.place(x = 40, y = 10, width = 200, height = 220)

	tk.Label(lbl_montos, text="$/kg", font=("Helvetica Neue",20, "bold"), anchor="c", backgroun="#E0F8F1").place(x = 0, y = 0, width = 190)
	tk.Label(lbl_montos, text="$/Lote", font=("Helvetica Neue",20, "bold"), anchor="c", backgroun="#E0F8F1").place(x = 0, y = 100, width = 190)

	entry_kilo = Entry(lbl_montos, font=("verdana",20))
	entry_lote = Entry(lbl_montos, font=("verdana",20))

	entry_kilo.place(x = 20, y = 35, width = 150)
	entry_lote.place(x = 20, y = 135, width = 150)

	entry_lote.bind("<Return>", (lambda event: calcularLote(entry_lote.get())))
	entry_kilo.bind("<Return>", (lambda event: calcularKilo(entry_kilo.get())))

	diccionario_objetos["entry_kilo"] = entry_kilo
	diccionario_objetos["entry_lote"] = entry_lote
def labelCalculosLote(lbl_montos):
	lbl_calculos = tk.LabelFrame(lbl_montos, text="Calculos Aproximados", backgroun="#E0F8F1")
	lbl_calculos.place(x = 260, y = 10, width = 830, height = 220)

	mod_alt = -20
	tk.Label(lbl_calculos, text="Martillo", font=("Helvetica Neue",14, "bold"), anchor="c", backgroun="#E0F8F1").place(x = 0, y = 20+mod_alt, width = 280)

	tk.Label(lbl_calculos, text="Precio por KG $", font=("Helvetica Neue",12), anchor="e", backgroun="#E0F8F1").place(x = 0, y = 60+mod_alt, width = 160)
	tk.Label(lbl_calculos, text="Precio por Cabeza $", font=("Helvetica Neue",12), anchor="e", backgroun="#E0F8F1").place(x = 0, y = 90+mod_alt, width = 160)
	tk.Label(lbl_calculos, text="Precio de Lote $", font=("Helvetica Neue",12), anchor="e", backgroun="#E0F8F1").place(x = 0, y = 120+mod_alt, width = 160)

	tk.Label(lbl_calculos, text="Comision", font=("Helvetica Neue",14, "bold"), anchor="c", backgroun="#E0F8F1").place(x = 280, y = 20+mod_alt, width = 280)
	tk.Label(lbl_calculos, text="Impuestos", font=("Helvetica Neue",14, "bold"), anchor="c", backgroun="#E0F8F1").place(x = 280, y = 100+mod_alt, width = 280)

	tk.Label(lbl_calculos, text="Porcen. %", font=("Helvetica Neue",12), anchor="e", backgroun="#E0F8F1").place(x = 280, y = 60+mod_alt, width = 100)
	tk.Label(lbl_calculos, text="$", font=("Helvetica Neue",12), anchor="e", backgroun="#E0F8F1").place(x = 430, y = 60+mod_alt, width = 20)

	tk.Label(lbl_calculos, text="IVA Hac. %", font=("Helvetica Neue",12), anchor="e", backgroun="#E0F8F1").place(x = 280, y = 140+mod_alt, width = 100)
	tk.Label(lbl_calculos, text="IVA Com. %", font=("Helvetica Neue",12), anchor="e", backgroun="#E0F8F1").place(x = 280, y = 170+mod_alt, width = 100)
	tk.Label(lbl_calculos, text="$", font=("Helvetica Neue",12), anchor="e", backgroun="#E0F8F1").place(x = 430, y = 140+mod_alt, width = 20)
	tk.Label(lbl_calculos, text="$", font=("Helvetica Neue",12), anchor="e", backgroun="#E0F8F1").place(x = 430, y = 170+mod_alt, width = 20)

	tk.Label(lbl_calculos, text="Otros", font=("Helvetica Neue",14, "bold"), anchor="c", backgroun="#E0F8F1").place(x = 570, y = 20+mod_alt, width = 250)
	tk.Label(lbl_calculos, text="Total aprox. a liquidar $:", font=("Helvetica Neue",14, "bold"), anchor="c", backgroun="#E0F8F1").place(x = 570, y = 140+mod_alt, width = 250)

	tk.Label(lbl_calculos, text="Otros $", font=("Helvetica Neue",12), anchor="e", backgroun="#E0F8F1").place(x = 570, y = 60+mod_alt, width = 100)
	tk.Label(lbl_calculos, text="Otros $", font=("Helvetica Neue",12), anchor="e", backgroun="#E0F8F1").place(x = 570, y = 90+mod_alt, width = 100)

	texto_kg = StringVar()
	texto_kg.set("")
	texto_cabeza = StringVar()
	texto_cabeza.set("")
	texto_lote = StringVar()
	texto_lote.set("")
	texto_comision = StringVar()
	texto_comision.set("")
	texto_ivaHacienda = StringVar()
	texto_ivaHacienda.set("")
	texto_ivaComision = StringVar()
	texto_ivaComision.set("")
	texto_total = StringVar()
	texto_total.set("")

	arregloY=-2

	lbl_kg = tk.Label(lbl_calculos, font=("Helvetica Neue",14,"bold"), anchor="w", backgroun="#E0F8F1")
	lbl_kg.place(x=160, y=60+mod_alt+arregloY, width=120)
	lbl_kg.config(textvariable=texto_kg)

	lbl_cabeza = tk.Label(lbl_calculos, font=("Helvetica Neue",14,"bold"), anchor="w", backgroun="#E0F8F1")
	lbl_cabeza.place(x=160, y=90+mod_alt+arregloY, width=120)
	lbl_cabeza.config(textvariable=texto_cabeza)

	lbl_lote = tk.Label(lbl_calculos, font=("Helvetica Neue",14,"bold"), anchor="w", backgroun="#E0F8F1")
	lbl_lote.place(x=160, y=120+mod_alt+arregloY, width=120)
	lbl_lote.config(textvariable=texto_lote)

	lbl_comision = tk.Label(lbl_calculos, font=("Helvetica Neue",14,"bold"), anchor="w", backgroun="#E0F8F1")
	lbl_comision.place(x=450, y=60+mod_alt+arregloY, width=120)
	lbl_comision.config(textvariable=texto_comision)

	lbl_ivaHacienda = tk.Label(lbl_calculos, font=("Helvetica Neue",14,"bold"), anchor="w", backgroun="#E0F8F1")
	lbl_ivaHacienda.place(x=450, y=170+mod_alt+arregloY, width=120)
	lbl_ivaHacienda.config(textvariable=texto_ivaHacienda)

	lbl_ivaComision = tk.Label(lbl_calculos, font=("Helvetica Neue",14,"bold"), anchor="w", backgroun="#E0F8F1")
	lbl_ivaComision.place(x=450, y=140+mod_alt+arregloY, width=120)
	lbl_ivaComision.config(textvariable=texto_ivaComision)

	lbl_total = tk.Label(lbl_calculos, font=("Helvetica Neue",22,"bold"), anchor="c", backgroun="#E0F8F1")
	lbl_total.place(x=570, y=170+mod_alt+arregloY, width=250)
	lbl_total.config(textvariable=texto_total)

	entry_comisionPorcentaje = Entry(lbl_calculos, font=("verdana",12))
	entry_comisionPorcentaje.place(x = 380, y = 60+mod_alt, width = 50)

	entry_ivaHaciendaPorcentaje = Entry(lbl_calculos, font=("verdana",12))
	entry_ivaHaciendaPorcentaje.place(x = 380, y = 140+mod_alt, width = 50)

	entry_ivaComisionPorcentaje = Entry(lbl_calculos, font=("verdana",12))
	entry_ivaComisionPorcentaje.place(x = 380, y = 170+mod_alt, width = 50)

	entry_ivaHaciendaPorcentaje.insert(0, 10.5)
	entry_ivaComisionPorcentaje.insert(0, 10.5)
	entry_comisionPorcentaje.insert(0, 4.5)

	entry_otros1 = Entry(lbl_calculos, font=("verdana",12))
	entry_otros1.place(x = 680, y = 60+mod_alt, width = 130)
	entry_otros2 = Entry(lbl_calculos, font=("verdana",12))
	entry_otros2.place(x = 680, y = 90+mod_alt, width = 130)

	diccionario_objetos["calculos_texto_kg"] = texto_kg
	diccionario_objetos["calculos_texto_cabeza"] = texto_cabeza
	diccionario_objetos["calculos_texto_lote"] = texto_lote
	diccionario_objetos["calculos_texto_comision"] = texto_comision
	diccionario_objetos["calculos_texto_ivaHacienda"] = texto_ivaHacienda
	diccionario_objetos["calculos_texto_ivaComision"] = texto_ivaComision
	diccionario_objetos["calculos_texto_total"] = texto_total
	diccionario_objetos["calculos_entry_comisionPorcentaje"] = entry_comisionPorcentaje
	diccionario_objetos["calculos_entry_ivaHaciendaPorcentaje"] = entry_ivaHaciendaPorcentaje
	diccionario_objetos["calculos_entry_ivaComisionPorcentaje"] = entry_ivaComisionPorcentaje
	diccionario_objetos["calculos_entry_otros1"] = entry_otros1
	diccionario_objetos["calculos_entry_otros2"] = entry_otros2

	entry_comisionPorcentaje.bind("<Return>", (lambda event: calcularComision()))

	entry_ivaHaciendaPorcentaje.bind("<Return>", (lambda event: calcularImpuestos()))
	entry_ivaComisionPorcentaje.bind("<Return>", (lambda event: calcularImpuestos()))

	entry_otros1.bind("<Return>", (lambda event: calcularFinal()))
	entry_otros2.bind("<Return>", (lambda event: calcularFinal()))
def labelAcciones(lbl_montos):
	lbl_acciones = tk.LabelFrame(lbl_montos, text="Acciones", backgroun="#E0F8F1")
	lbl_acciones.place(x = 1110, y = 10, width = 150, height = 220)

	btn_guardar = tk.Button(lbl_acciones, text="GUARDAR", font=("verdana",15, "bold"), backgroun="#76f5b7", command=guardar)
	btn_guardar.place(x = 10, y = 10, width=130, height=90)

	btn_borrar = tk.Button(lbl_acciones, text="BORRAR", font=("verdana",12, "bold"), backgroun="#e3876d", command=borrarLote)
	btn_borrar.place(x = 10, y = 105, width=130, height=40)

	btn_imprimir = tk.Button(lbl_acciones, text="IMPRIMIR", font=("verdana",12, "bold"), backgroun="#cce388")
	btn_imprimir.place(x = 10, y = 150, width=130, height=40)

#OTROS
def borrarDatosLoteComprador():
	#Borrar Lote
	diccionario_objetos["datosLote_texto_catHacienda"].set("")
	diccionario_objetos["datosLote_texto_catVenta"].set("")
	diccionario_objetos["datosLote_texto_corral"].set("")
	diccionario_objetos["datosLote_texto_cantidad"].set("")
	diccionario_objetos["datosLote_texto_neto"].set("")
	diccionario_objetos["datosLote_texto_promedio"].set("")

	diccionario_objetos["datosLote_txt_observaciones"].configure(state="normal")
	diccionario_objetos["datosLote_txt_observaciones"].delete("1.0", tk.END)
	diccionario_objetos["datosLote_txt_observaciones"].configure(state="disabled")

	#Borrar Vendedor
	diccionario_objetos["texto_aliasVendedor"].set("")
	diccionario_objetos["texto_razonVendedor"].set("")
	diccionario_objetos["texto_cuitVendedor"].set("")
	diccionario_objetos["texto_rucaVendedor"].set("")
	diccionario_objetos["txt_observacionesVendedor"].configure(state="normal")
	diccionario_objetos["txt_observacionesVendedor"].delete("1.0", tk.END)
	diccionario_objetos["txt_observacionesVendedor"].configure(state="disabled")
def borrarDatosComprador():
	#Borrar Comprador
	diccionario_objetos["texto_aliasComprador"].set("")
	diccionario_objetos["texto_razonComprador"].set("")
	diccionario_objetos["texto_cuitComprador"].set("")
	diccionario_objetos["texto_rucaComprador"].set("")
	diccionario_objetos["txt_observacionesComprador"].configure(state="normal")
	diccionario_objetos["txt_observacionesComprador"].delete("1.0", tk.END)
	diccionario_objetos["txt_observacionesComprador"].configure(state="disabled")
def borrarDatosMontosCalculos():
	diccionario_objetos["calculos_texto_kg"].set("")
	diccionario_objetos["calculos_texto_cabeza"].set("")
	diccionario_objetos["calculos_texto_lote"].set("")
	diccionario_objetos["calculos_texto_comision"].set("")
	diccionario_objetos["calculos_texto_ivaHacienda"].set("")
	diccionario_objetos["calculos_texto_ivaComision"].set("")
	diccionario_objetos["calculos_texto_total"].set("")

	diccionario_objetos["entry_kilo"].delete(0, tk.END)
	diccionario_objetos["entry_lote"].delete(0, tk.END)

def guardar():
	lote = diccionario_objetos["ID_LOTE"]
	con = sql_connection()
	condiciones = " WHERE lote = '" + str(lote) + "' AND estado='activo'"
	rows = actualizar_db(con, "compraventa", condiciones)

	if(len(rows) == 1):
		MsgBox = messagebox.askquestion('ATENCION', '¿Desea editar este lote?', icon = 'warning')
		if(MsgBox == 'yes'):
			editarLote()
	else:
		MsgBox = messagebox.askquestion('ATENCION', '¿Desea guardar?', icon = 'warning')
		if(MsgBox == 'yes'):
			guardarLote()

def editarLote():
	lote = diccionario_objetos["ID_LOTE"]
	try:
		x_lote = diccionario_objetos["ID_LOTE_A_EDITAR"]
		x_comprador = str(diccionario_objetos["texto_cuitComprador"].get())
		x_precio = str(float(diccionario_objetos["calculos_texto_kg"].get()))

		entities = [x_comprador,
		x_precio,
		x_lote]

		con = sql_connection()
		cursorObj = con.cursor()
		cursorObj.execute('UPDATE compraventa SET comprador = ?, precio = ? where id = ?', entities)
		con.commit()

		messagebox.showinfo("Éxito", "Lote EDITADO con éxito!")
		diccionario_objetos["ID_LOTE_A_EDITAR"] = "NULL"
		borrarDatosComprador()
		borrarDatosLoteComprador()
		borrarDatosMontosCalculos()

	except:
		messagebox.showerror("ERROR", "Error al cargar a la base de datos")
def guardarLote():
	lote = diccionario_objetos["ID_LOTE"]
	try:
		x_lote = str(lote)
		x_comprador = str(diccionario_objetos["texto_cuitComprador"].get())
		x_precio = str(float(diccionario_objetos["calculos_texto_kg"].get()))
		x_estado = "activo"
		x_remate = rematename
		x_vendedor = str(diccionario_objetos["texto_cuitVendedor"].get())

		entities = [x_lote,
		x_comprador,
		x_precio,
		x_remate,
		x_estado,
		x_vendedor]

		con = sql_connection()
		cursorObj = con.cursor()
		cursorObj.execute("INSERT INTO compraventa VALUES(NULL, ?, ?, ?, ?, ?, ?)", entities)
		con.commit()
		messagebox.showinfo("Éxito", "Productor ingresado con éxito!")
		borrarDatosComprador()
		borrarDatosLoteComprador()
		borrarDatosMontosCalculos()
	except:
		messagebox.showerror("ERROR", "Error al cargar a la base de datos")

def borrarLote():
	lote = diccionario_objetos["ID_LOTE_A_EDITAR"]
	if(lote=="NULL"):
		messagebox.showerror("ERROR", "Primero selecciones un lote cargado para borrar")
		return 0
	else:
		MsgBox = messagebox.askquestion('ATENCION', '¿Desea eliminar los datos de compra de este lote?', icon = 'warning')
		if(MsgBox == 'yes'):
			entities = [lote]
			con = sql_connection()
			cursorObj = con.cursor()
			cursorObj.execute('UPDATE compraventa SET estado = "borrado" where id = ?', entities)
			con.commit()

			messagebox.showinfo("Éxito", "Lote BORRADO con éxito!")
			diccionario_objetos["ID_LOTE_A_EDITAR"] = "NULL"
			borrarDatosComprador()
			borrarDatosLoteComprador()
			borrarDatosMontosCalculos()

#CALCULOS
def calcularKilo(entry_kilo):
	try:
		precio_kilo = float(entry_kilo)
		peso_neto = float(diccionario_objetos["datosLote_texto_neto"].get())
		cantidad_cabezas = float(diccionario_objetos["datosLote_texto_cantidad"].get())
	except:
		messagebox.showerror("ERROR", 'Pruebe seleccionar un lote\nIngresar numeros sin separador de millares\nEl separador decimal es un punto "."')
		return 0
	precioKilo = str(round(precio_kilo, 2))
	precioLote = str(round(precio_kilo*peso_neto, 2))
	precioCabeza = str(round((precio_kilo*peso_neto)/cantidad_cabezas, 2))

	diccionario_objetos["calculos_texto_kg"].set(precioKilo)
	diccionario_objetos["calculos_texto_cabeza"].set(precioCabeza)
	diccionario_objetos["calculos_texto_lote"].set(precioLote)

	calcularComision()
def calcularLote(entry_lote):
	try:
		precio_lote = float(entry_lote)
		peso_neto = float(diccionario_objetos["datosLote_texto_neto"].get())
		cantidad_cabezas = float(diccionario_objetos["datosLote_texto_cantidad"].get())
	except:
		messagebox.showerror("ERROR", 'Pruebe seleccionar un lote\nIngresar numeros sin separador de millares\nEl separador decimal es un punto "."')
		return 0
	precioKilo = str(round(precio_lote/peso_neto, 2))
	precioLote = str(round(precio_lote, 2))
	precioCabeza = str(round(precio_lote/cantidad_cabezas, 2))

	diccionario_objetos["calculos_texto_kg"].set(precioKilo)
	diccionario_objetos["calculos_texto_cabeza"].set(precioCabeza)
	diccionario_objetos["calculos_texto_lote"].set(precioLote)

	calcularComision()
def calcularComision():
	try:
		porcentaje_comision = float(diccionario_objetos["calculos_entry_comisionPorcentaje"].get())
		precio_subtotal = float(diccionario_objetos["calculos_texto_lote"].get())
	except:
		messagebox.showerror("ERROR", 'Pruebe seleccionar un lote\nIngresar numeros sin separador de millares\nEl separador decimal es un punto "."')
		return 0
	comision = str(round(precio_subtotal*porcentaje_comision/100, 2))

	diccionario_objetos["calculos_texto_comision"].set(comision)

	calcularImpuestos()

def calcularImpuestos():
	try:
		porcentaje_comision = float(diccionario_objetos["calculos_entry_ivaComisionPorcentaje"].get())
		porcentaje_hacienda = float(diccionario_objetos["calculos_entry_ivaHaciendaPorcentaje"].get())
	except:
		messagebox.showerror("ERROR", 'Pruebe seleccionar un lote\nIngresar numeros sin separador de millares\nEl separador decimal es un punto "."')
		return 0
	precio_comision = float(diccionario_objetos["calculos_texto_comision"].get())
	precio_subtotal = float(diccionario_objetos["calculos_texto_lote"].get())

	ivaHacienda = str(round(precio_comision*porcentaje_comision/100, 2))
	ivaComision = str(round(precio_subtotal*porcentaje_hacienda/100, 2))

	diccionario_objetos["calculos_texto_ivaHacienda"].set(ivaHacienda)
	diccionario_objetos["calculos_texto_ivaComision"].set(ivaComision)

	calcularFinal()

def calcularFinal():
	precio_subtotal = float(diccionario_objetos["calculos_texto_lote"].get())
	precio_comision = float(diccionario_objetos["calculos_texto_comision"].get())
	precio_ivaHacienda = float(diccionario_objetos["calculos_texto_ivaHacienda"].get())
	precio_ivaComision = float(diccionario_objetos["calculos_texto_ivaComision"].get())

	try:
		otro1 = float(diccionario_objetos["calculos_entry_otros1"].get())
	except:
		otro1 = 0.0
	try:
		otro2 = float(diccionario_objetos["calculos_entry_otros2"].get())
	except:
		otro2 = 0.0

	precio_total = str(round(precio_subtotal + precio_comision + precio_ivaHacienda + precio_ivaComision + otro1 + otro2, 2))

	diccionario_objetos["calculos_texto_total"].set(precio_total)

def remate(window):
	lbl_lote = Label(window, backgroun="#E0F8F1")
	lbl_comprador = Label(window, backgroun="#E0F8F1")
	lbl_montos = Label(window, backgroun="#E0F8F1")

	mod_alt = 0
	var_bajar = 0

	lbl_lote.place(x = 2, y = 2+mod_alt, width = 1281, height = 200)
	lbl_comprador.place(x = 2, y = 204+mod_alt, width = 1281, height = 200)
	lbl_montos.place(x = 2, y = 406+mod_alt, width = 1281, height = 250)

	#EN LOTE:
	if(True):
		tk.Label(lbl_lote, text="LOTES", font=("Helvetica Neue",15, "bold"), anchor="c", backgroun="#E0F8F1", wraplength=1).place(x = 5, y = 0, width = 15, height = 200)
		labelLoteBuscar(lbl_lote)
		labelLoteTabla(lbl_lote)
		labelLoteInfor(lbl_lote)

	#EN COMPRADOR:
	if(True):
		tk.Label(lbl_comprador, text="COMPRADOR", font=("Helvetica Neue",10, "bold"), anchor="c", backgroun="#E0F8F1", wraplength=1).place(x = 5, y = 0, width = 15, height = 200)
		labelCompradorBuscador(lbl_comprador)
		labelLoteDatos(lbl_comprador)
		labelCompradorInfor(lbl_comprador)

	#EN MONTOS:
	if(True):
		tk.Label(lbl_montos, text="MONTOS", font=("Helvetica Neue",15, "bold"), anchor="c", backgroun="#E0F8F1", wraplength=1).place(x = 5, y = 25, width = 25, height = 200)
		labelCompradorMontos(lbl_montos)
		labelCalculosLote(lbl_montos)
		labelAcciones(lbl_montos)

	actualizarProductores()
	actualizarTablaLotes()

window1 = Tk()
window1.title("Remate")
window1.geometry("1285x728")
window1.configure(backgroun="#2C4D4F") #E8F6FA
remate(window1)
window1.mainloop()


import os
import numpy as np
import pandas as pd
import openpyxl as op
import compile_data as cd
from openpyxl import load_workbook

#Define Data Directory
dDir = './test-data/'
rDir = './results-and-plots/'

#Initialize Excel Writer
writer = pd.ExcelWriter(rDir+'Test_Sample.xlsx', engine='openpyxl')

#Read in sp and fp DataFrame
pdf = pd.read_csv('./sp-fp.csv')

for file in os.listdir(dDir):
    fname = dDir + file
    sp    = pdf[pdf['File Name'] == file.strip('.txt')]['sp'].values[0]
    fp    = pdf[pdf['File Name'] == file.strip('.txt')]['fp'].values[0]
    r     = np.arange(0,1,0.1)

    #Initialize DataFrame
    df    = pd.DataFrame(index=r+sp, columns=r+fp)

    #Make and Save plot at initial points
    try:
        cd.fit_data(fname, sp+0.5, fp+0.5, save_name=rDir+file.replace('.txt', '.png'))
    except:
        print('Yo, dude this shit dont want to converge')
        print(file)

    #Fill in DataFrame with Diffusion Lengths
    for i in r:
        for j in r:
            try:
                dl = cd.fit_data(fname, sp+i, fp+j, save_name=False)
            except:
                dl = np.NAN
            df.loc[sp+i, fp+j] = dl

    #Make Excel File
    df.to_excel(writer, sheet_name=file.strip('.txt'))
    img = op.drawing.image.Image(rDir+file.replace('.txt', '.png'))
    ws  = writer.sheets[file.strip('.txt')]
    ws.add_image(img, 'A13')

writer.save()


import sys
input = sys.stdin.readline

### 어떤 타일 오는지 확인하는 함수
def checktile():
    for i in range(1, 6):
        avail[i] = False
    for i in range(6):
        di, dj = dirlst[i]
        nx, ny = sx+di, sy+dj
        val = arr[ny][nx]
        if val != 0:
            avail[val] = True
    maxi = 10000
    idx = 0
    for i in range(1, 6):
        if not avail[i]:
            if num[i] < maxi:
                maxi = num[i]
                idx = i
    arr[sy][sx] = idx
    num[idx] += 1
    number.append(idx)

def cal():
    global level, sx, sy
    while level < 61:
        sx += 1
        sy -= 1
        checktile()
        if cnt == 10001:
            break
        for i in range(level - 1):
            di, dj = dirlst[0]
            sx += di
            sy += dj
            checktile()
            if cnt == 10001:
                break
        for k in range(1, 6):
            for i in range(level):
                di, dj = dirlst[k]
                sx += di
                sy += dj
                checktile()
                if cnt == 10001:
                    break
        level += 1

T = int(input())
arr = [[0] * 301 for _ in range(601)]
number = [0]
level, sx, sy, cnt = 1, 150, 300, 1
dirlst = [(0,-2), (-1,-1), (-1,1), (0,2), (1,1), (1,-1)]
num = [0, 1, 0, 0, 0, 0]
avail = [False] * 6
arr[sy][sx] = 1
number.append(1)

cal()
for _ in range(T):
    target = int(input())
    print(number[target])

백준/Gold/3678. 카탄의 개척자/카탄의 개척자.py


import os

from flask import Flask
from jinja2 import FileSystemLoader
from jinja2 import TemplateNotFound

from pgadmin import VersionedTemplateLoader
from pgadmin.utils.route import BaseTestGenerator

class TestVersionedTemplateLoader(BaseTestGenerator):
    def setUp(self):
        self.loader = VersionedTemplateLoader(FakeApp())

    def runTest(self):
        self.test_get_source_returns_a_template()
        self.test_get_source_when_the_version_is_9_1_returns_9_1_template()
        self.test_get_source_when_the_version_is_9_3_and_there_are_templates_for_9_2_and_9_1_returns_9_2_template()

    def test_get_source_returns_a_template(self):
        expected_content = "Some SQL" \
                           "\nsome more stuff on a new line\n"

        content, filename, up_to_dateness = self.loader.get_source(None, "some_feature/sql/9.1_plus/some_action.sql")

        self.assertEqual(expected_content, content)
        self.assertIn("some_feature/sql/9.1_plus/some_action.sql", filename)

    def test_get_source_when_the_version_is_9_1_returns_9_1_template(self):
        expected_content = "Some SQL" \
                           "\nsome more stuff on a new line\n"

        content, filename, up_to_dateness = self.loader.get_source(None, "some_feature/sql/#90100#/some_action.sql")

        self.assertEqual(expected_content, content)
        self.assertIn("some_feature/sql/9.1_plus/some_action.sql", filename)

    def test_get_source_when_the_version_is_9_3_and_there_are_templates_for_9_2_and_9_1_returns_9_2_template(self):

        content, filename, up_to_dateness = self.loader.get_source(None, "some_feature/sql/#90300#/some_action.sql")

        self.assertEqual("Some 9.2 SQL", content)
        self.assertIn("some_feature/sql/9.2_plus/some_action.sql", filename)

    def test_get_source_when_the_version_is_9_0_and_there_are_templates_for_9_1_and_9_2_returns_default_template(self):

        content, filename, up_to_dateness = self.loader.get_source(None, "some_feature/sql/#90000#/some_action_with_default.sql")

        self.assertEqual("Some default SQL", content)
        self.assertIn("some_feature/sql/default/some_action_with_default.sql", filename)

    def test_raise_not_found_exception_when_postgres_version_less_than_all_available_sql_templates(self):

        try:
            self.loader.get_source(None, "some_feature/sql/#10100#/some_action.sql")
            self.fail("No exception raised")
        except TemplateNotFound:
            return

class FakeApp(Flask):
    def __init__(self):
        super(FakeApp, self).__init__("")
        self.jinja_loader = FileSystemLoader(os.path.dirname(os.path.realpath(__file__)) + "/templates")


import datetime
from PIL import Image
import streamlit as st

def write_life_page():
    st.subheader('하루 기록 서비스 📝')
    breakfast_food = 20
    lunch_food = 20
    dinner_food = 15
    breakfast_water = 50
    lunch_water = 10
    dinner_water = 25
    weight = 15.5
    playtime = 2
    check1 = 1
    check2 = 0
    check3 = 1
    check4 = 0
    check5 = 0
    check6 = 1
    check7 = 0
    check8 = 0
    check9 = 0
    check10 = 1
    memo="밥먹다가 뒤로 넘어짐. 혼자 숨바꼭질함."

# 꾸미기
#     font_css = """
#     <style>
#     button[data-baseweb="tab"] > div[data-testid="stMarkdownContainer"] > p {
#       font-size: 24px;
#     }
#     </style>
#     """
#
#     st.write(font_css, unsafe_allow_html=True)
    font_css = """
    <style>
    button[data-baseweb="tab"]   {
      background: #EAEAEA55;
    }
    </style>
    """

    st.write(font_css, unsafe_allow_html=True)

    listtabs=["일지 보기","오늘의 일지 작성","보고서"]
    whitespace = 15

    tabs = st.tabs([s.center(whitespace, "\u2001") for s in listtabs])
    # tab1, tab2, tab3 = st.tabs(["  일지 보기  ","  오늘의 일지 작성  ","  보고서  "])
    with tabs[0]:
        col1,col2=st.columns([1,2],gap='large')
        with col1:
            now = datetime.datetime.now()
            year=int(now.strftime('%Y'))
            month = int(now.strftime('%m'))
            day = int(now.strftime('%d'))
            st.markdown('###### 👇날짜 선택')
            choose_date=st.date_input('👇날짜 선택',datetime.date(year,month,day),label_visibility='collapsed')
        with col2:
            st.markdown('###### 👇기록 확인')

            with st.expander(f'{choose_date}의 기록'):
            # st.write(f'{choose_date}의 기록')

                subcol13,subcol14,subcol15=st.columns([1,1,3])
                subcol13.markdown('###### ▪ 몸무게')
                kilogram='kg'
                subcol14.text_input('몸무게',value=str(weight) + kilogram, disabled=True,label_visibility='collapsed')

                subcol13,subcol14,subcol15=st.columns([1,1,3])
                subcol13.markdown('###### ▪ 놀이시간')
                hour='hour'
                subcol14.text_input('놀이시간',value=str(playtime) + hour, disabled=True,label_visibility='collapsed')

                st.markdown('###### ▪ 사료급여량')
                gram='gram'
                subcol1,subcol2,subcol3,subcol4,subcol5,subcol6=st.columns([1,2,1,2,1,2],gap='medium')
                subcol1.write('아침')
                subcol2.text_input('아침사료량',value=str(breakfast_food) + gram, disabled=True,label_visibility='collapsed')
                subcol3.write('점심')
                subcol4.text_input('점심사료량',value=str(lunch_food) + gram, disabled=True,label_visibility='collapsed')
                subcol5.write('저녁')
                subcol6.text_input('저녁사료량',value=str(dinner_food) + gram, disabled=True,label_visibility='collapsed')

                st.markdown('###### ▪ 음수량')
                ml = 'ml'
                subcol1,subcol2,subcol3,subcol4,subcol5,subcol6= st.columns([1, 2, 1, 2, 1, 2], gap='medium')
                subcol1.write('아침')
                subcol2.text_input('아침음수량', value=str(breakfast_water) + ml, disabled=True, label_visibility='collapsed')
                subcol3.write('점심')
                subcol4.text_input('점심음수량', value=str(lunch_water) + ml, disabled=True, label_visibility='collapsed')
                subcol5.write('저녁')
                subcol6.text_input('저녁음수량', value=str(dinner_water) + ml, disabled=True, label_visibility='collapsed')
                c_col1,c_col2,c_col3,c_col4,c_col5=st.columns(5)
                c_col1.checkbox(label=":drop_of_blood:",value=bool(check1),disabled=True)
                c_col2.checkbox(label="🪫", value=bool(check2), disabled=True)
                c_col3.checkbox(label="💊", value=bool(check3), disabled=True)
                c_col4.checkbox(label="🌡", value=bool(check4), disabled=True)
                c_col5.checkbox(label="🛁", value=bool(check5), disabled=True)
                st.write("")
                c_col1, c_col2, c_col3, c_col4, c_col5 = st.columns(5)
                c_col1.checkbox(label="👂", value=bool(check6), disabled=True)
                c_col2.checkbox(label="😿", value=bool(check7), disabled=True)
                c_col3.checkbox(label="😺", value=bool(check8), disabled=True)
                c_col4.checkbox(label="😸", value=bool(check9), disabled=True)
                c_col5.checkbox(label="😻", value=bool(check10), disabled=True)
                st.markdown('###### ▪ 메모')
                st.text_area('memo',value=memo,disabled=True, label_visibility="collapsed")
    with tabs[1]:
        st.write('오늘의 일지 작성')

    with tabs[2]:
        st.write("")
        st.write("")
        st.subheader('통계보기 📊')
        col1,col2,col3=st.columns([1,1,2])
        col1.selectbox("기간",("1주일","1개월","6개월","1년"),label_visibility="collapsed")

    # 데이터베이스 연동 후 그래프


#
# Pyserini: Reproducible IR research with sparse and dense representations
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import argparse

import numpy as np
import pandas as pd
from tqdm import tqdm
from transformers import BertModel, BertTokenizer

def encode_query(text, tokenizer, model, device='cpu'):
    max_length = 36  # hardcode for now
    inputs = tokenizer(
        '[CLS] [Q] ' + text + ' [MASK]' * max_length,
        max_length=max_length,
        truncation=True,
        add_special_tokens=False,
        return_tensors='pt'
    )
    inputs.to(device)
    outputs = model(**inputs)
    embeddings = outputs.last_hidden_state.detach().cpu().numpy()
    return np.average(embeddings[:, 4:, :], axis=-2).flatten()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--encoder', type=str, help='encoder name or path', required=True)
    parser.add_argument('--input', type=str, help='query file to be encoded.', required=True)
    parser.add_argument('--output', type=str, help='path to store query embeddings', required=True)
    parser.add_argument('--device', type=str,
                        help='device cpu or cuda [cuda:0, cuda:1...]', default='cpu', required=False)
    args = parser.parse_args()

    tokenizer = BertTokenizer.from_pretrained(args.encoder)
    model = BertModel.from_pretrained(args.encoder)
    model.to(args.device)
    embeddings = {'id': [], 'text': [], 'embedding': []}
    for line in tqdm(open(args.input, 'r').readlines()):
        qid, text = line.rstrip().split('\t')
        qid = qid.strip()
        text = text.strip()
        embeddings['id'].append(qid)
        embeddings['text'].append(text)
        embeddings['embedding'].append(encode_query(text, tokenizer, model, args.device))
    embeddings = pd.DataFrame(embeddings)
    embeddings.to_pickle(args.output)


import numpy as np
import talib
from numba import int32, jit, float64

class Factory:

    """
    横向横盘调整因子值，大部分的值落在（0,100）之间，越靠近0,越是盘整状态。
    """
    @jit(nopython=True)  # jit，numba装饰器中的一种
    def vibrate(close: np.ndarray, open: np.ndarray, period: int32 = 12) -> float64:
        total: float64 = 0.0
        for i in np.arange(-period, 0):
            total += (close[i] + open[i]) / 2
        base_price: float64 = total / period
        total: float64 = 0.0
        for i in np.arange(-period, 0):
            dela = close[i] - base_price
            total += (dela * dela)
        return 100 * np.sqrt(total) / base_price

    """
      改进后的arron指标。 以买方、卖方力量为准
    """
    def arron(period,close:np.ndarray, high: np.ndarray,low:np.ndarray):
        sell = (high + close) / 2
        buy =  (low+ close) / 2
        aroon_down, aroon_up = talib.AROON(sell, buy, period)
        return aroon_down,aroon_up

    """
       参考Arron方式，wave指标统计在一个period周期内的波动率，也就是创新高值的能力。创新高的有create_high个，创新低的有几个create_low。
       返回wave_down,wave_up。[0,100]之间。
    """
    @jit(nopython=True)  # jit，numba装饰器中的一种
    def wave(period, close: np.ndarray, high: np.ndarray, low: np.ndarray):
        sell = (high + close) / 2
        buy = (low + close) / 2

        high_cnt = 0
        low_cnt = 0
        high_value = sell[-period]
        low_value = buy[-period]
        for i in range(-period+1,0):
            if sell[i] >= high_value:
                high_cnt +=1
                high_value = sell[i]
            if buy[i] <= low_value:
                low_cnt+=1
                low_value = buy[i]
        wave_down = 100 * low_cnt / period
        wave_up = 100 * high_cnt / period
        return wave_down, wave_up

    """
     能量波动潮因子。
     wave+obv结合。
    """

    @jit(nopython=True)  # jit，numba装饰器中的一种
    def obv_wave(period, close: np.ndarray, high: np.ndarray, low: np.ndarray,volumn:np.ndarray):

        # assert abs(_high - _low) > 0.008
        # print("why")
        assert  len(close) > period
        obv = np.zeros(period)
        for i in range(-period,0):
            _low = min(close[i-1], low[i])
            _high = max(close[i-1], high[i])
            obv[i] = ((close[i] - _low) - (_high - close[i])) / (_high - _low) * volumn[i]
        ##统计obv创新高和创新低的个数
        high_cnt = 0
        low_cnt = 0
        high_value = obv[-period]
        low_value = obv[-period]
        high_index = -period
        low_index = -period
        for i in range(-period + 1, 0):
            if obv[i] >= high_value:
                high_cnt += 1
                high_index = i
                high_value = obv[i]
            if obv[i] <= low_value:
                low_cnt += 1
                low_index = i
                low_value = obv[i]

        obv_wave_down = 100 * low_cnt / period
        obv_wave_up = 100 * high_cnt / period
        #Aroon(上升) = [(计算期天数 - 最高价后的天数) / 计算期天数] * 100
        #Aroon(下降) = [(计算期天数 - 最低价后的天数) / 计算期天数] * 100

        high_day_prirod = abs(high_index) - 1
        low_day_period = abs(low_index) -1
        arron_up = 100 * (period - high_day_prirod) / period
        arron_down = 100 * (period - low_day_period) / period

        return  arron_down * obv_wave_down /100, arron_up * obv_wave_up / 100

    """

    价格与成交量偏离因子值。(-1到1） 没有验证过。
    """
    def pvb(close: np.ndarray, high: np.ndarray,low:np.ndarray,volumn:np.ndarray, period: int32 = 20)->float:
        ##涨幅与多空成交量对比的相关系数。
        pct_list,volumn_pct_list = Factory.__pbv_inter(close,high,low,volumn,period)
        ret = talib.CORREL(pct_list, volumn_pct_list, timeperiod=period)

        return ret[-1]

    @jit(nopython=True)  # jit，numba装饰器中的一种
    def __pbv_inter(close: np.ndarray, high: np.ndarray,low:np.ndarray,volumn:np.ndarray, period: int32 = 20):
        pct_list = np.full(period, np.nan)
        volumn_pct_list = np.full(period , np.nan)
        # _pre_volumn_lsosc = Indicator.lsosc(close[-2-period],close[-1-period],high[-1-period],low[-1-period]) * volumn[-1-period]
        pre_volum = 0
        for i in range(-period, 0):
            pct_list[i] = close[i]
            _low = min(close[i - 1], low[i])
            _high = max(close[i - 1], high[i])
            assert abs(_high - _low) > 0.008
            # print("why")
            lsosc = ((close[i] - _low) - (_high - close[i])) / (_high - _low)
            # volumn_lsosc = Indicator.lsosc(close[i-1],close[i],high[i],low[i]) * volumn[i]
            volumn_pct_list[i] = pre_volum + lsosc * volumn[i]
            pre_volum = volumn_pct_list[i]
        return pct_list,volumn_pct_list

    """
    第一个元素总是为0
    """
    def ad_diff(close: np.ndarray,high: np.ndarray,low:np.ndarray,volumn:np.ndarray):
        size = len(close)
        ad_diff_list = np.full(size, 0.0)

        for i in range(1,size):
            # 多空对比 = [（收盘价- 最低价） - （最高价 - 收盘价）] / （最高价 - 最低价)
            dk1 = ((close[i] - low[i]) - (high[i] - close[i])) /(high[i] - low[i])

            adj_high = max(high[i],close[i-1])
            adj_low = min(low[i],close[i-1])
            dk2 = ((close[i] - adj_low) - (adj_high - close[i])) /(adj_high - adj_low)

            diff = abs(dk1-dk2)
            ad_diff_list[i] = ad_diff_list[i-1]+ diff * volumn[i]
        return ad_diff_list

    def ad_diff2(close: np.ndarray,high: np.ndarray,low:np.ndarray,volumn:np.ndarray):
        size = len(close)
        ad_diff_list = np.full(size, 0.0)

        for i in range(1,size):
            # 多空对比 = [（收盘价- 最低价） - （最高价 - 收盘价）] / （最高价 - 最低价)
            dk1 = ((close[i] - low[i]) - (high[i] - close[i])) /(high[i] - low[i])

            adj_high = max(high[i],close[i-1])
            adj_low = min(low[i],close[i-1])
            dk2 = ((close[i] - adj_low) - (adj_high - close[i])) /(adj_high - adj_low)

            diff = dk2-dk1
            ad_diff_list[i] = ad_diff_list[i-1]+ diff * volumn[i]
        return ad_diff_list