#capture.py

import cv2

#顔検出器を初期化
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#映像を読み込むオブジェクト
cap= cv2.VideoCapture(0) #0はデフォルトのカメラデバイス

ret,frame = cap.read()
#グレイスケール化
faces = face_cascade.detectMultiScale(cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY))

if len(faces) > 0:
    (x,y,w,h) = faces[0] #顔検出器によって返される位置情報を変数に取る
    track_window = (x,y,w,h) #トラッキングウィンドウの位置とサイズ
    roi = frame[y:y+h, x:x+w] #region of interest. 顔がある部分の領域
    hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV) #BGR色空間からHSV色空間に変換
    mask = cv2.inRange(hsv_roi,(0,60,32),(180,255,255)) #指定範囲内の色は白に、それ以外は黒に変換
    roi_hist = cv2.calcHist([hsv_roi],[0],mask,[180],[0,180]) #指定された色相のヒストグラムを計算
    cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX) #ヒストグラムの正規化とスケーリング
    term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1) #トラッキング処理（後述）の停止基準。10回繰り返したら終了

while True:
    #カメラからフレームを取得
    ret, frame = cap.read()

    #フレームの取得に成功したら
    if ret:
        hsv=cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        dst=cv2.calcBackProject([hsv],[0],roi_hist,[0,180],1) #ヒストグラムの逆投影を行う
        ret, track_window=cv2.meanShift(dst,track_window,term_crit) #トラッキングを行う
        x,y,w,h=track_window
        cv2.rectangle(frame, (x,y),(x+w,y+h),(0,255,0),2)

        #フレームをウィンドウで表示
        cv2.imshow('Camera',frame)
    #qを押したらループ解除
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
#終了動作
cap.release()
cv2.destroyAllWindows()


from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, WebDriverException
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

cred_obj = firebase_admin.credentials.Certificate('firebase-sdk.json')
firebase_admin.initialize_app(cred_obj, {
	'databaseURL': 'https://wise-monitor-price-default-rtdb.asia-southeast1.firebasedatabase.app/'
	})

chrome_path = r"C:\Users\gundu\PycharmProjects\pythonProject\drivers\chromedriver.exe"
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
browser = webdriver.Chrome(chrome_path, options=chrome_options)
ref = db.reference('/')
ref.child('Pacific').delete()

# method for finding product name and price
def findItem():
    product = browser.find_elements_by_xpath(
        './/*[@class="product_grid-item grid__item product_img-crop ratio_1-1 small--one-half medium--one-half large--one-quarter"]')
    product2 = browser.find_elements_by_xpath(
        './/*[@class="product_grid-item grid__item product_img-crop ratio_1-1 small--one-half medium--one-half large--one-quarter on-sale"]')

    for post in product:
        name = post.find_element_by_xpath('.//*[@class="grid-link__title"]').text
        price = post.find_element_by_xpath('.//*[@data-currency="MYR"]').text

        ref = db.reference('Pacific')
        emp_ref = ref.push({
                        'name': name,
                        'price': price
            })

    for post2 in product2:
        name2 = post2.find_element_by_xpath('.//*[@class="grid-link__title"]').text
        price2 = post2.find_element_by_xpath('.//*[@data-currency="MYR"]').text
        ref = db.reference('Pacific')
        emp_ref = ref.push({
            'name': name2,
            'price': price2
            })

    print("new data created")

# delete the # in the list below to retrieve the products' name and price from the link
url = {#'https://www.pacific-online.com.my/collections/groceries',
#'https://www.pacific-online.com.my/collections/toiletries',
#'https://www.pacific-online.com.my/collections/wet-tissues-diapers-napkin',
#'https://www.pacific-online.com.my/collections/beauty',
#'https://www.pacific-online.com.my/collections/toiletries-health-beauty',
#'https://www.pacific-online.com.my/collections/household-1',
#'https://www.pacific-online.com.my/collections/pets-care',
'https://www.pacific-online.com.my/collections/beverages/coffee'}
for link in url:
    browser.get(link)
    print(link)
    findItem()              # scrap first page

                        # move to next page
    while True:
        try:
            browser.execute_script("return arguments[0].scrollIntoView(true);",WebDriverWait(browser, 10).until(
             EC.presence_of_element_located((By.XPATH, "//a[@title = 'Next']"))
                 ))
            browser.find_element_by_xpath("//a[@title = 'Next']").click()

            print("------------------Next Page-----------------")
            # scraping the following pages
            findItem()
        except (TimeoutException, WebDriverException) as e:
            print("Last page reached")
            break


from configparser import ConfigParser
import os.path
import sys
from dotenv import load_dotenv

config_object = ConfigParser()

load_dotenv()

api_key = os.getenv('api_key')
api_secret = os.getenv('api_secret')

if not api_key or not api_secret:
    if not os.path.isfile("config.ini"):
        print("Check config file config.ini for api key parameters")

        config_object.add_section('API_CONFIG')
        config_object.set('API_CONFIG', 'api_key', 'xxxx')
        config_object.set('API_CONFIG', 'api_secret', 'xxxx')

        with open(r"config.ini", 'w') as configfile:
            config_object.write(configfile)

        sys.exit()

    config_object.read("config.ini")

    api_key = config_object['API_CONFIG']['api_key']
    api_secret = config_object['API_CONFIG']['api_secret']


from __future__ import absolute_import, print_function, division, unicode_literals

import os
import io
import sys
import hashlib
import datetime
import logging
import json

from ..app import db

file_types = {
    "jpg": ("images", "image/jpeg"),
    "mp3": ("sounds", "audio/mp3"),
    "mp4": ("videos", "video/mp4"),
    "stl": ("models", "model/mesh")
}

type_dc_type = {
    "images": "StillImage",
    "sounds": "Sound",
    "videos": "MovingImage",
    "models": "InteractiveResource"
}

def check_update(m, p, current_user, guid_type=None):
    h = calcFileHash(p)
    if m.image_hash == h:
        return m
    m.status = "file_changed"
    m.status_date = datetime.datetime.now()
    m.status_detail = m.image_hash
    m.image_hash = h
    m.appuser = current_user
    props = json.loads(m.props)
    config = json.loads(current_user.config)
    props["dc:rights"] = config.get("license", "CC0")
    m.props = json.dumps(props)
    if guid_type == "hash":
        m.file_reference = h
    return m

def calcFileHash(f, op=True, return_size=False, read_size=2048):
    def do_hash(fd):
        md5 = hashlib.md5()
        size = 0

        buf = fd.read(read_size)
        while len(buf) > 0:
            size += len(buf)
            md5.update(buf)
            buf = fd.read(read_size)

        return md5, size

    if op:
        with io.open(f, "rb") as fd:
            md5, size = do_hash(fd)
    else:
        md5, size = do_hash(f)

    if return_size:
        return (md5.hexdigest(), size)
    else:
        return md5.hexdigest()

def process_media(m, update_db=True, api=None):
    try:
        if os.path.exists(m.path):
            h, size = calcFileHash(m.path, return_size=True)
            m.image_hash = h

            for k in file_types:
                if m.path.lower().endswith(k):
                    m.media_type, m.mime = file_types[k]
                    break
            else:
                raise TypeError("Invalid File Type {}".format())

        else:
            raise FileNotFoundError

        # Upload Media File
        if api is None:
            m.status = "uploaded"
            m.status_date = datetime.datetime.now()
            m.status_detail = ""
        else:
            logging.debug("Start post for %r", m.path)
            res = api.upload(m.file_reference, m.path)
            logging.debug("Finished post for %r got back %r", m.path, res)
            if res is None:
                m.status = "failed"
                m.status_date = datetime.datetime.now()
                m.status_detail = ""
            else:
                m.status = "uploaded"
                m.status_date = datetime.datetime.now()
                m.status_detail = ""

        if update_db:
            db.session.add(m)
            db.session.commit()

    except FileNotFoundError:
        e = sys.exc_info()[1]
        m.status = "missing"
        m.status_date = datetime.datetime.now()
        m.status_detail = repr(e)

    return m


import pandas as pd
from pathlib import Path
import subprocess
from bianca import __version__

def get_subject_sessions(bids_dir, flair_acq):
    def _get_suse_from_path(p):
        session = p.parents[1].name.replace("ses-", "")
        subject = p.parents[2].name.replace("sub-", "")
        return subject, session

    flair_files = list(Path(bids_dir).glob(f"sub-*/ses-*/anat/*_acq-{flair_acq}_*_FLAIR.nii.gz"))
    t1w_files = list(Path(bids_dir).glob(f"sub-*/ses-*/anat/*_T1w.nii.gz"))
    flair_suse = set([_get_suse_from_path(p) for p in flair_files])
    t1w_suse = set([_get_suse_from_path(p) for p in t1w_files])
    subject_sessions = list(flair_suse & t1w_suse)
    subject_sessions.sort()
    return subject_sessions

def export_version(out_dir):
    out_dir.mkdir(parents=True, exist_ok=True)
    try:
        version_label = subprocess.check_output(["git", "describe", "--tags"]).strip()
        (out_dir / "pipeline_version.txt").write_text(f"git: {version_label.decode()}")
    except:
        (out_dir / "pipeline_version.txt").write_text(__version__)

def create_masterfile(prep_dir, training_data_dir, bianca_dir, flair_tmpl, t1w_tmpl, manual_mask_tmpl,
                      mat_tmpl):
    bianca_dir.mkdir(exist_ok=True, parents=True)

    # get flair files
    flair_globs = list(prep_dir.glob(flair_tmpl.format(subject="*", session="*")))
    print(f"{len(flair_globs)} flair files found")

    # get remaining files
    df = pd.DataFrame({"flair": [str(f) for f in flair_globs]})
    df["subject"] = df.flair.str.split("sub-").str[1].str.split("/").str[0]
    df["session"] = df.flair.str.split("ses-").str[1].str.split("/").str[0]

    complete_files = {"t1w": str(prep_dir / t1w_tmpl),
                      "manual_mask": str(training_data_dir / manual_mask_tmpl),
                      "mat": str(prep_dir / mat_tmpl)
                      }
    for var in complete_files.keys():
        df[var] = None
    for i in range(len(df)):
        for var in complete_files.keys():
            df[var].iloc[i] = complete_files[var].format(**df.iloc[i])

    df = df[['flair', 't1w', 'manual_mask', 'mat', 'subject', 'session']]

    # only include masks from training subjects
    training_subject_index = df.manual_mask.apply(lambda s: Path(s).is_file())
    df.loc[~training_subject_index, "manual_mask"] = "XXX"
    training_subjects = df[training_subject_index]

    # check if files exist
    files = df[['flair', 't1w', 'manual_mask', 'mat']].melt()["value"].to_list()
    for f in files:
        if f != "XXX":
            assert Path(f).is_file(), f"{f} is missing"

    # save
    df.to_csv(bianca_dir / "masterfile.txt", index=False, header=False, sep=" ")
    df.to_csv(bianca_dir / "masterfile_wHeader.txt", index=False, sep=" ")
    training_subjects.to_csv(bianca_dir / "masterfile_training_subjects.txt", index=False, sep=" ")


import discord
import json
import os
from discord.ext import commands

client = commands.Bot(command_prefix= '!w2g')

os.chdir("path completo")

@client.event
async def on_ready():
    print('Bot is ready.')

@client.event
async def on_member_join(meber):
    with open('users.json', 'r') as f:
        users = json.load(f)

    await update_data(users, member)

    with open('users.json', 'w') as f:
        json.dump(users, f)

@client.event
async def on_message(message):
    with open('users.json', 'r') as f:
        users = json.load(f)

    await update_data(users, message.author)
    await add_experience(users, message.author, 5)
    await level_up(users, message.author, message.channel)

    with open('users.json', 'w') as f:
        json.dump(users, f)

async def update_data(users, users):
    if not user.id in users:
        users[user.id] = {}
        users[user.id]['experience'] = 0
        users[user.id]['level'] = 1

async def add_experience(users, user, exp):
    users[user.id]['experience'] += exp

async def level_up(users, user, chennel):
    experience = users[user.id]['experience']
    lvl_start = users[user.id]['level']
    lvl_end = int(experience ** (1/4))

    if lvl_start < lvl_end:
        await client.send_message(channel, '{} upou de levels'.format(user.mention, lvl_end))
        users[user.id]['level'] = lvl_end
client.run('NzcyNTAxMzYyNjgzNTQzNTYz.X57l9Q.tiBFZwKM02qDv7emjtLBkNVxvFk')


import json

def main():
    input_filename = "data.json"
    output_filename = "result.json"

    with open(input_filename, "r") as input_file:
        data = json.load(input_file)

    unique_part_numbers = set()
    unique_items = []

    for item in data:
        part_number = item.get("partNumber")
        if part_number and part_number not in unique_part_numbers:
            unique_part_numbers.add(part_number)
            unique_items.append(item)

    with open(output_filename, "w") as output_file:
        json.dump(unique_items, output_file, indent=4)

    print(f"Unique part numbers saved in {output_filename}")

if __name__ == "__main__":
    main()


import setuptools

with open("README.md", "r") as f:
	readme_description = f.read()

setuptools.setup(
	name="pytextdist",
	version="0.1.6",
	author="Yifan Wu",
	author_email="yw693@cornell.edu",
	description="A python implementation of a variety of text distance and similarity metrics.",
	long_description=readme_description,
    long_description_content_type="text/markdown",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires=">=3.3"
)


import matplotlib.pyplot as plt
import numpy as np

N = 5000

def solveLoop(x, y):
    xs = []
    ys = []
    time = []

    t = 0.0
    dt = 0.001
    for i in range(N):
        x += dt * (3 - x - 2 * y)
        y += dt * (2 - x - y)
        t += dt

        xs.append(x)
        ys.append(y)
        time.append(t)

    return xs, ys

x = [0, 0, 3, 1, 4, 5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 5]
y = [0, 2, 0, 1, 4, 0, 3, 2, 10, 9, 5, 1.5, 0, 2, 5, 6]

plotNo = len(x)
xsPlot = np.zeros((plotNo, N))
ysPlot = np.zeros((plotNo, N))

for i in range(len(xsPlot)):
    xsPlot[i, :], ysPlot[i, :] = solveLoop(x[i], y[i])

for i in range(len(xsPlot)):
    plt.plot(xsPlot[i, :], ysPlot[i, :], label="(x,y): " + str(x[i]) + "," + str(y[i]))

plt.legend()
plt.grid()
plt.show()


#!/usr/bin/env python3

import re

RE_DEFAULT = re.compile(r"\[D=([TF])\] ")
RE_TRANSITION = re.compile(r"([a-zA-Z0-9 \[\]=#_-]+) *->(.*)")
RE_ASSERTION = re.compile(
    r"\[A S=([a-zA-Z01_]+) SS=([a-zA-Z01_]+) ES=([a-zA-Z01_]+) P=([a-zA-Z_]+) ESP=([a-zA-Z_]+)\]"
)
RE_ASSERTION_SHORTHAND = re.compile(r"\[A#([0-9T]+)\]")

# ======================================================================
# ======================================================================

testnum = 1

def start_test(line):
    global testnum
    output.write(
        """
    def test_{0}(self):
        # {1}...\n""".format(
            testnum, line[0:80]
        )
    )
    testnum += 1

def set_default(d):
    output.write(
        """
        if self.default_is is not {0}:
            return\n""".format(
            "True" if d == "T" else "False"
        )
    )

def enroll(e):
    if e.endswith("-C"):
        e = e[:-2]
        output.write("\n        # Re-set enrollment pref, like Normandy would do\n")
    output.write(
        "        self.set_enrollment_status(ExperimentStatus.ENROLLED_{0})\n".format(
            e.upper()
        )
    )

def set_pref(enabled):
    output.write(
        "\n        self.marionette.set_pref(Prefs.WIN32K, {0})\n".format(str(enabled))
    )

def set_e10s(enable):
    if enable:
        output.write(
            """
        app_version = self.execute_script("return Services.appinfo.version")
        self.restart(env={ENV_DISABLE_E10S: app_version})
        self.set_env(ENV_DISABLE_E10S, "null")\n"""
        )
    else:
        raise Exception("Not implemented")

def set_header(enable):
    if enable:
        output.write(
            """
        self.restart(env={ENV_DISABLE_WIN32K: "1"})\n"""
        )
    else:
        output.write(
            """
        self.set_env(ENV_DISABLE_WIN32K, "")\n"""
        )

def set_bad_requirements(enabled):
    output.write(
        """
        self.marionette.set_pref(Prefs.WEBGL, {0})\n""".format(
            "False" if enabled else "True"
        )
    )

def restart():
    output.write("\n        self.restart()\n")

def print_assertion(assertion):
    if not assertion:
        return
    output.write(
        """
        self.check_win32k_status(
            status=ContentWin32kLockdownState.{0},
            sessionStatus=ContentWin32kLockdownState.{1},
            experimentStatus=ExperimentStatus.{2},
            pref={3},
            enrollmentStatusPref=ExperimentStatus.{4},
        )\n""".format(
            *assertion
        )
    )

# ======================================================================
# ======================================================================

TESTS = open("win32k_tests.txt", "r").readlines()

output = open("test_win32k_enrollment.py", "w", newline="\n")
header = open("test_win32k_enrollment.template.py", "r")
for l in header:
    output.write(l)

mappings = {}
for line in TESTS:
    line = line.strip()
    if not line:
        continue

    if line.startswith("#"):
        continue
    elif line.startswith("> "):
        line = line[2:]
        key, value = line.split(":")
        mappings[key.strip()] = value.strip()
        continue
    elif line.startswith("-"):
        line = line[1:].strip()
    elif line.startswith("+"):
        line = line[1:].strip()
        import pdb

        pdb.set_trace()
    else:
        raise Exception("unknown line type: " + line)

    # We can't handle Safe Mode right now
    if "Safe Mode" in line:
        continue

    # If we have no assertions defined, skip the test entirely
    if "[A" not in line:
        continue

    if not RE_DEFAULT.match(line):
        raise Exception("'{0}' does not match the default regex".format(line))
    default = RE_DEFAULT.search(line).groups(1)[0]

    start_test(line)

    set_default(default)

    line = line[6:]

    while line:
        # this is a horrible hack for the line ending to avoid making the
        # regex more complicated and having to fix it
        if not line.endswith(" ->"):
            line += " ->"

        groups = RE_TRANSITION.search(line).groups()
        start = groups[0].strip()
        end = groups[1].strip()

        if RE_ASSERTION.search(start):
            assertion = RE_ASSERTION.search(start).groups()
            start = start[0 : start.index("[")].strip()
        elif RE_ASSERTION_SHORTHAND.search(start):
            key = RE_ASSERTION_SHORTHAND.search(start).groups()[0]
            assertion = RE_ASSERTION.search(mappings[key]).groups()
            start = start[0 : start.index("[")].strip()
        else:
            assertion = ""

        if start == "Nothing":
            pass
        elif start.startswith("Enrolled "):
            enroll(start[9:])
        elif start == "E10S":
            set_e10s(True)
        elif start == "Header-On":
            set_header(True)
        elif start == "Header-Off":
            set_header(False)
        elif start == "Bad Requirements":
            set_bad_requirements(True)
        elif start == "Restart":
            restart()
        elif start == "On":
            set_pref(True)
        elif start == "Off":
            set_pref(False)
        else:
            raise Exception("Unknown Action: " + start)

        print_assertion(assertion)

        line = end.strip()

    if RE_ASSERTION.match(line):
        print_assertion(RE_ASSERTION.search(line).groups())
    elif RE_ASSERTION_SHORTHAND.search(line):
        key = RE_ASSERTION_SHORTHAND.search(line).groups()[0]
        print_assertion(RE_ASSERTION.search(mappings[key]).groups())


import pickle
import numpy as np
from scipy.io import loadmat
import os
import sys

i = int(sys.argv[1]) if len(sys.argv)>1 else 0

step=1
lion_extended_power_options = np.arange(1, 200+step, step)
lion_extended_power_options = sorted(list(lion_extended_power_options) + [13.8, 16.5, 21.1, 26.6])
#Those are found by cross-validation below. Just want to estimate accuracy at those spots

lion_extended_percentile_options = [90,95,99,100]

ptsne_train_mat = loadmat('mnist_train.mat')
ptsne_test_mat = loadmat('mnist_test.mat')

accuracy_nn = 10

ptsne_mapped = loadmat('mnist_mapped.mat') # We need Y to take as ground truth
ptsne_Y_train = ptsne_mapped['mapped_train_X']
ptsne_Y_test = ptsne_mapped['mapped_test_X']

ptsne_X_train = ptsne_train_mat['train_X']
ptsne_labels_train = ptsne_train_mat['train_labels'].reshape(-1)-1
ptsne_X_test = ptsne_test_mat['test_X']
ptsne_labels_test = ptsne_test_mat['test_labels'].reshape(-1)-1

lion_extended_accuracy_plot_data_file = './lion-processed-samples/lion_extended_accuracy_plot_data_'+str(i)+'.p'

with open('cell_centers.p', 'rb') as f:
    cell_centers = pickle.load(f)

# This cell calculates test set accuracy for each combination of power and radius_x percentile

np.random.seed(111222)

# Leaving it extensible to get smth like "KL vs power" etc. if we need to.
regenerate_extended_lion_accuracy = False

lion_extended_accuracy_plot_data = dict()
lion_extended_precision_30_plot_data = dict()
lion_extended_precision_50_plot_data = dict()
already_tested_keys = dict()

with open('extended_nn_dist.p', "rb") as f:
    nn_x_extended_distance, nn_y_extended_distance = pickle.load(f)

radius_y = np.percentile(nn_y_extended_distance, 100)
radius_y_close = np.percentile(nn_y_extended_distance, 10)
radius_y += radius_y_close

radius_extended_x = dict()
for p in lion_extended_percentile_options:
    radius_extended_x[p] = np.percentile(nn_x_extended_distance, p)

# One at a time, so no such things as outliers overlap, etc.

sample_accuracy = dict()
sample_precision_30 = dict()
sample_precision_50 = dict()

def ptsne_get_nearest_neighbors_in_y(y, ptsne_Y_train, n,i=-1):
    y_distances = np.sum((ptsne_Y_train - y)**2, axis=1)
    if i>=0:
        y_distances[i] = np.inf
    return np.argsort(y_distances)[:n]

print("Processing:", i)

with open('./ExtendedDistanceVectors/test_' + str(i) + '.p', 'rb') as f:
    x_distances_to_all_training_samples = pickle.load(f)

y_result = dict()  # Embeddings in all cases

# If we got exact match, power and percentile does not matter, response is the same
exact_match = np.where(x_distances_to_all_training_samples == 0)[0]
if len(exact_match) > 0:
    print("Exact match!")
    # If we got exact match, power and percentile does not matter, response is the same
    for perc in lion_extended_percentile_options:
        for p in lion_extended_power_options:
            key = str(perc) + ";" + "%.3f" % (p)
            if key not in already_tested_keys:
                y_result[key] = ptsne_Y_train[exact_match[0], :]
else:
    # Not an exact match. Need to go further.
    for perc in lion_extended_percentile_options:
        # print(perc)
        # This part depends only on radius_x
        cur_neighbor_indices = np.where(x_distances_to_all_training_samples <= radius_extended_x[perc])[0]
        local_interpolation_distances = x_distances_to_all_training_samples[cur_neighbor_indices]
        # print(cur_neighbor_indices)
        # print(local_interpolation_distances)
        if len(local_interpolation_distances) == 0:  # Outlier handling does not depend on power.
            # print(perc, 0)
            for p in lion_extended_power_options:
                key = str(perc) + ";" + "%.3f" % (p)
                # No need to pop. Each sample is independent anyway
                if key not in already_tested_keys:
                    y_result[key] = cell_centers[np.random.randint(0, len(cell_centers)), :]
        elif len(local_interpolation_distances) == 1:  # Single-neighbor handling does not depend on power
            # print(perc, 1)
            # Now a single neighbor
            single_neighbor_index = cur_neighbor_indices[0]
            single_neighbor_nn_dist = nn_x_extended_distance[single_neighbor_index]
            if single_neighbor_nn_dist <= radius_extended_x[perc]:
                # Treat as outliers
                for p in lion_extended_power_options:
                    key = str(perc) + ";" + "%.3f" % (p)
                    # No need to pop. Each sample is independent anyway
                    if key not in already_tested_keys:
                        y_result[key] = cell_centers[np.random.randint(0, len(cell_centers)), :]
            else:
                for p in lion_extended_power_options:
                    key = str(perc) + ";" + "%.3f" % (p)
                    if key not in already_tested_keys:
                        random_dist = np.random.uniform(low=0, high=radius_y_close)
                        random_angle = np.random.uniform(low=0, high=2 * np.pi)
                        y_result[key] = ptsne_Y_train[single_neighbor_index, :].copy()
                        y_result[key][0] += random_dist * np.cos(
                            random_angle)  # Considering 0 is X. DOes not matter, really
                        y_result[key][1] += random_dist * np.sin(random_angle)
        else:
            # print(perc, 2)
            for p in lion_extended_power_options:
                key = str(perc) + ";" + "%.3f" % (p)
                # weights = 1 / np.array([decimal.Decimal(i) for i in local_interpolation_distances]) ** p
                if key not in already_tested_keys:
                    weights = 1 / local_interpolation_distances ** p
                    weights = weights / np.sum(weights)
                    y_result[key] = weights.dot(ptsne_Y_train[cur_neighbor_indices, :])

print("Got results")

# TODO Got results for all cases
for perc in lion_extended_percentile_options:
    for p in lion_extended_power_options:
        key = str(perc) + ";" + "%.3f" % (p)
        print(perc, p, key)

        expected_label = ptsne_labels_test[i]
        result = y_result[key]
        nn_indices = ptsne_get_nearest_neighbors_in_y(result, ptsne_Y_train, n=accuracy_nn)
        obtained_labels = ptsne_labels_train[nn_indices]
        sample_accuracy[key] = sum(obtained_labels == expected_label) / len(obtained_labels)

        nn_x_indices = ptsne_get_nearest_neighbors_in_y(ptsne_X_test[i,:], ptsne_X_train, n=30)
        nn_y_indices = ptsne_get_nearest_neighbors_in_y(result, ptsne_Y_train, n=30)
        matching_indices = len([k for k in nn_x_indices if k in nn_y_indices])
        sample_precision_30[key] = (matching_indices / 30)

        nn_x_indices = ptsne_get_nearest_neighbors_in_y(ptsne_X_test[i,:], ptsne_X_train, n=50)
        nn_y_indices = ptsne_get_nearest_neighbors_in_y(result, ptsne_Y_train, n=50)
        matching_indices = len([k for k in nn_x_indices if k in nn_y_indices])
        sample_precision_50[key] = (matching_indices / 50)

        print("\t", sample_accuracy[key], sample_precision_30[key], sample_precision_50[key])

with open(lion_extended_accuracy_plot_data_file, 'wb') as f:
    pickle.dump((y_result, sample_accuracy, sample_precision_30,
                 sample_precision_50), f)


#!/usr/bin/python3

from pathlib import Path
import argparse
import hashlib
import json
import os
import re
import subprocess
import urllib.request, urllib.parse, urllib.error

HOME = Path.home()
# Paths.
LOOKUP_DATA_DIR = HOME / ".goto_build"
LOOKUP_DATA_PATH = LOOKUP_DATA_DIR / "build_lookup.json"
CUSTOM_BUILDOZER_PATH = LOOKUP_DATA_DIR / "buildozer"
# Buildozer details.
CUSTOM_BUILDOZER_URL = "https://github.com/kentsommer/buildtools/releases/download/4.2.0-1/buildozer"
CUSTOM_BUILDOZER_SHA = "9a9193b77f51dcff416cdc5039a7a78e7b7ace7b019c1c952ab8028e6ee3303f"

def sha256sum(path):
    """Calculates sha256sum of the file at the given path."""
    h = hashlib.sha256()
    b = bytearray(128 * 1024)
    mv = memoryview(b)
    with open(path, mode="rb", buffering=0) as f:
        for n in iter(lambda: f.readinto(mv), 0):
            h.update(mv[:n])
    return h.hexdigest()

def make_executable(path):
    """Makes the file at the given path executable."""
    mode = os.stat(path).st_mode
    mode |= (mode & 0o444) >> 2  # copy R bits to X
    os.chmod(path, mode)

def fetch_buildozer():
    """Download custom buildozer."""
    # Prepare our directory if it doesn't exist.
    os.makedirs(LOOKUP_DATA_DIR, exist_ok=True)
    # Download buildozer binary.
    buildozer_binary = urllib.request.urlopen(CUSTOM_BUILDOZER_URL).read()
    with open(CUSTOM_BUILDOZER_PATH, mode="wb") as fp:
        fp.write(buildozer_binary)
    make_executable(CUSTOM_BUILDOZER_PATH)

def maybe_fetch_buildozer():
    """Download custom buildozer if not downloaded already."""
    if os.path.isfile(CUSTOM_BUILDOZER_PATH):
        if sha256sum(CUSTOM_BUILDOZER_PATH) != CUSTOM_BUILDOZER_SHA:
            fetch_buildozer()
    else:
        fetch_buildozer()

def build_lookup_data():
    """Build map from file path to corresponding BUILD file and target."""
    lookup_data = subprocess.check_output(
        [
            CUSTOM_BUILDOZER_PATH,
            "print startline path srcs hdrs",
            "//...:*",
        ],
        stderr=subprocess.DEVNULL,
    ).decode("utf-8")
    pattern = re.compile(
        r"^(\d*) (\/.*?BUILD).*?(?:\[(.*?)\]|glob\((.*?)\)|(\(missing\))).*?(?:\[(.*?)\]|glob\((.*?)\)|(\(missing\)))",
        re.DOTALL + re.MULTILINE,
    )
    matches = pattern.findall(lookup_data)
    result = {}
    for match in matches:
        line = match[0]
        BUILD = match[1]
        prefix = BUILD.split("BUILD")[0]
        srcs = [f"{prefix}{src}" for src in match[2].split(" ")] if match[2] else []
        hdrs = [f"{prefix}{hdr}" for hdr in match[5].split(" ")] if match[5] else []
        for src in srcs:
            result[src] = f"{BUILD}:{line}"
        for hdr in hdrs:
            result[hdr] = f"{BUILD}:{line}"
    # Prepare our directory if it doesn't exist.
    os.makedirs(LOOKUP_DATA_DIR, exist_ok=True)
    # Save our file so we can potentially reuse the map for future queries.
    with open(LOOKUP_DATA_PATH, mode="w+", encoding="utf-8") as fp:
        json.dump(result, fp, indent=2)
    return result

def get_corresponding_build_info(args):
    """Load (build if does not exist) the lookup_data map from and return corresponding BUILD file and target.

    Will rebuild the map if src file is not found in the map and file was loaded.
    """
    did_build = False
    # Try to load lookup_data.
    if os.path.isfile(LOOKUP_DATA_PATH):
        with open(LOOKUP_DATA_PATH, mode="r", encoding="utf-8") as fp:
            try:
                lookup_data = json.load(fp)
            # If we have issues loading the json file, build it.
            except json.decoder.JSONDecodeError as ex:
                lookup_data = build_lookup_data()
    # If lookup data does not exist, build it.
    else:
        lookup_data = build_lookup_data()
        did_build = True

    # If our file exists in the map, return the BUILD and target information.
    if args.input in lookup_data:
        return lookup_data[args.input]
    else:
        # If the file does not exist and we did not build, rebuild the map.
        if not did_build:
            lookup_data = build_lookup_data()
        # If the file exists in the newly built map, return the BUILD and target information.
        if args.input in lookup_data:
            return lookup_data[args.input]
    return None

def main(args):
    # Ensure our custom buildozer binary exists.
    maybe_fetch_buildozer()
    # Fetch build info.
    build_info = get_corresponding_build_info(args)
    if build_info:
        print(build_info)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(__doc__)
    parser.add_argument(
        "-i", "--input", required=True, type=str, help="Input file for which to find the corresponding BUILD file"
    )
    args = parser.parse_args()
    main(args)


from __future__ import unicode_literals

from django.test import TestCase

from nose.plugins.attrib import attr

from candidates.models import PersonExtra, SiteSettings
from candidates.tests import factories
from candidates.tests.uk_examples import UK2015ExamplesMixin

@attr(country='uk')
class CSVTests(UK2015ExamplesMixin, TestCase):

    def setUp(self):
        super(CSVTests, self).setUp()
        # The second person's name (and party name) have diacritics in
        # them to test handling of Unicode when outputting to CSV.
        self.gb_person_extra = factories.PersonExtraFactory.create(
            base__id=2009,
            base__name='Tessa Jowell',
            base__honorific_suffix='DBE',
            base__honorific_prefix='Ms',
            base__email='jowell@example.com',
            base__gender='female',
        )
        camberwell_area_extra = self.camberwell_post_extra.base.area.extra
        camberwell_area_extra.base.other_identifiers.create(
            scheme='mapit-area-url',
            identifier='http://mapit.mysociety.org/area/65913',
        )
        camberwell_area_extra.base.other_identifiers.create(
            scheme='gss',
            identifier='E14000615',
        )
        dulwich_area_extra = self.dulwich_post_extra.base.area.extra
        dulwich_area_extra.base.other_identifiers.create(
            scheme='mapit-area-url',
            identifier='http://mapit.mysociety.org/area/65808',
        )
        dulwich_area_extra.base.other_identifiers.create(
            scheme='gss',
            identifier='E14000673',
        )
        factories.CandidacyExtraFactory.create(
            election=self.election,
            base__person=self.gb_person_extra.base,
            base__post=self.camberwell_post_extra.base,
            base__on_behalf_of=self.labour_party_extra.base
        )
        factories.CandidacyExtraFactory.create(
            election=self.earlier_election,
            base__person=self.gb_person_extra.base,
            base__post=self.dulwich_post_extra.base,
            base__on_behalf_of=self.labour_party_extra.base
        )
        self.gb_person_extra.base.identifiers.create(
            identifier='uk.org.publicwhip/person/10326',
            scheme='uk.org.publicwhip',
        )
        self.labour_party_extra.base.identifiers.create(
            identifier='PP53',
            scheme='electoral-commission',
        )

    def test_as_list_single_dict(self):
        person_extra = PersonExtra.objects \
            .joins_for_csv_output().get(pk=self.gb_person_extra.id)
        # So that we predictably do need to perform the settings query
        # below, make sure it isn't cached:
        SiteSettings.objects.clear_cache()
        # After the select_related and prefetch_related calls
        # PersonExtra there should two more queries - that to
        # find the complex fields mapping and another for settings:
        with self.assertNumQueries(2):
            person_dict_list = person_extra.as_list_of_dicts(self.election)
        self.assertEqual(len(person_dict_list), 1)
        person_dict = person_dict_list[0]
        self.assertEqual(len(person_dict), 35)
        self.assertEqual(person_dict['id'], 2009)

        # Test the extra CSV fields:
        self.assertEqual(person_dict['gss_code'], 'E14000615')
        self.assertEqual(person_dict['parlparse_id'], 'uk.org.publicwhip/person/10326')
        self.assertEqual(person_dict['theyworkforyou_url'], 'http://www.theyworkforyou.com/mp/10326')
        self.assertEqual(person_dict['party_ec_id'], 'PP53')


#!/usr/bin/env python3

import tensorflow as tf
import tensorflow_addons as tfa
import einops

def get_pixel_value(
        img, x, y, data_format=None):
    """
    Utility function to get pixel value for coordinate
    vectors x and y from a  4D tensor image.
    Input
    -----
    - img: tensor of shape (B, H, W, C)
    - x: flattened tensor of shape (B*H*W, )
    - y: flattened tensor of shape (B*H*W, )
    Returns
    -------
    - output: tensor of shape (B, H, W, C)
    """
    if data_format is None:
        data_format = tf.keras.backend.image_data_format()

    if data_format == 'channels_first':
        axis = -3
    else:
        axis = -1

    batch_dims = tf.rank(img) - 3

    # NOTE(ycho): HAS TO BE -1 due to tensorflow constraints.
    # indices[-1]
    indices = tf.stack([y, x], axis=-1)

    if data_format == 'channels_first':
        img = einops.rearrange(img, '... c h w -> ... h w c')
    out = tf.gather_nd(img, indices, batch_dims=batch_dims)
    if data_format == 'channels_first':
        out = einops.rearrange(out, '... h w c -> ... c h w')

    #print(x.shape) # 1,256,512
    #print(y.shape) # 1,256,512
    #print(indices.shape) # 1,256,512,2
    #print(img.shape) #1,3,256,512
    #out = tf.gather_nd(img, indices, batch_dims=batch_dims)
    return out
    #shape = tf.shape(x)
    #batch_size = shape[0]
    #height = shape[1]
    #width = shape[2]

    # batch_idx = tf.range(0, batch_size)[:, None, None, None]  # B111
    # if axis == 1:
    #    b = tf.tile(batch_idx, (1, 1, height, width))  # B1HW
    # else:
    #    b = tf.tile(batch_idx, (1, height, width, 1))  # BHW1

    #indices = tf.stack([b, ALL, y, x], axis)
    # return tf.gather_nd(img, indices)

def tf_warp(img, flow, data_format=None):
    if data_format is None:
        data_format = tf.keras.backend.image_data_format()
    # 3D pattern
    if data_format == 'channels_first':
        pattern = '_ h w'
        axis = -3
    else:
        pattern = 'h w _'
        axis = -1

    # Check if batched ...
    if tf.rank(flow) >= 4:
        print('is_batch')
        is_batch = True

    if is_batch:
        pattern = '_ ' + pattern

    shape = einops.parse_shape(img, pattern)
    W, H = shape['w'], shape['h']
    print('w={}, h={}'.format(W, H))

    # Compute grid coordinates.
    x, y = tf.meshgrid(tf.range(W), tf.range(H))

    # Add channel dims
    x = tf.expand_dims(x, axis=axis)
    y = tf.expand_dims(y, axis=axis)

    # Add batch dims
    if is_batch:
        x = tf.expand_dims(x, axis=0)
        y = tf.expand_dims(y, axis=0)

    x = tf.cast(x, tf.float32)
    y = tf.cast(y, tf.float32)
    grid = tf.concat([x, y], axis=axis)

    flows = grid + flow
    max_y = tf.cast(H - 1, tf.int32)
    max_x = tf.cast(W - 1, tf.int32)
    zero = tf.constant(0, dtype=tf.int32)

    # Deal with individual components
    if data_format == 'channels_first':
        x, y = einops.rearrange(flows, 'n c h w -> c n h w', c=2)
    else:
        x, y = einops.rearrange(flows, 'n h w c -> c n h w', c=2)

    x0 = x
    y0 = y
    x0 = tf.cast(x0, tf.int32)
    x1 = x0 + 1
    y0 = tf.cast(y0, tf.int32)
    y1 = y0 + 1

    # clip to range [0, H/W] to not violate img boundaries
    x0 = tf.clip_by_value(x0, zero, max_x)
    x1 = tf.clip_by_value(x1, zero, max_x)
    y0 = tf.clip_by_value(y0, zero, max_y)
    y1 = tf.clip_by_value(y1, zero, max_y)

    # get pixel value at corner coords
    Ia = get_pixel_value(img, x0, y0, data_format)
    Ib = get_pixel_value(img, x0, y1, data_format)
    Ic = get_pixel_value(img, x1, y0, data_format)
    Id = get_pixel_value(img, x1, y1, data_format)

    # recast as float for delta calculation
    x0 = tf.cast(x0, tf.float32)
    x1 = tf.cast(x1, tf.float32)
    y0 = tf.cast(y0, tf.float32)
    y1 = tf.cast(y1, tf.float32)

    # calculate deltas
    wa = (x1 - x) * (y1 - y)
    wb = (x1 - x) * (y - y0)
    wc = (x - x0) * (y1 - y)
    wd = (x - x0) * (y - y0)

    # add dimension for addition
    wa = tf.expand_dims(wa, axis=axis)
    wb = tf.expand_dims(wb, axis=axis)
    wc = tf.expand_dims(wc, axis=axis)
    wd = tf.expand_dims(wd, axis=axis)

    # compute output
    out = tf.add_n([wa * Ia, wb * Ib, wc * Ic, wd * Id])

    return out

def dense_image_warp(image, flow, name=None) -> tf.Tensor:
    """Image warping using per-pixel flow vectors.
    Apply a non-linear warp to the image, where the warp is specified by a
    dense flow field of offset vectors that define the correspondences of
    pixel values in the output image back to locations in the source image.
    Specifically, the pixel value at output[b, j, i, c] is
    images[b, j - flow[b, j, i, 0], i - flow[b, j, i, 1], c].
    The locations specified by this formula do not necessarily map to an int
    index. Therefore, the pixel value is obtained by bilinear
    interpolation of the 4 nearest pixels around
    (b, j - flow[b, j, i, 0], i - flow[b, j, i, 1]). For locations outside
    of the image, we use the nearest pixel values at the image boundary.
    PLEASE NOTE: The definition of the flow field above is different from that
    of optical flow. This function expects the negative forward flow from
    output image to source image. Given two images `I_1` and `I_2` and the
    optical flow `F_12` from `I_1` to `I_2`, the image `I_1` can be
    reconstructed by `I_1_rec = dense_image_warp(I_2, -F_12)`.
    Args:
      image: 4-D float `Tensor` with shape `[batch, height, width, channels]`.
      flow: A 4-D float `Tensor` with shape `[batch, height, width, 2]`.
      name: A name for the operation (optional).
      Note that image and flow can be of type tf.half, tf.float32, or
      tf.float64, and do not necessarily have to be the same type.
    Returns:
      A 4-D float `Tensor` with shape`[batch, height, width, channels]`
        and same type as input image.
    Raises:
      ValueError: if height < 2 or width < 2 or the inputs have the wrong
        number of dimensions.
    """
    with tf.name_scope(name or "dense_image_warp"):
        image = tf.convert_to_tensor(image)
        flow = tf.convert_to_tensor(flow)
        batch_size, height, width, channels = (
            tf.shape(image)[0],
            tf.shape(image)[1],
            tf.shape(image)[2],
            tf.shape(image)[3],
        )

        # The flow is defined on the image grid. Turn the flow into a list of query
        # points in the grid space.
        grid_x, grid_y = tf.meshgrid(tf.range(width), tf.range(height))
        stacked_grid = tf.cast(tf.stack([grid_y, grid_x], axis=2), flow.dtype)
        batched_grid = tf.expand_dims(stacked_grid, axis=0)
        query_points_on_grid = batched_grid + flow
        query_points_flattened = tf.reshape(
            query_points_on_grid, [batch_size, height * width, 2]
        )
        # Compute values at the query points, then reshape the result back to the
        # image grid.
        interpolated = tfa.image.interpolate_bilinear(
            image, query_points_flattened)
        interpolated = tf.reshape(
            interpolated, [batch_size, height, width, channels])
        return interpolated


import time,random,sqlite3

conn = sqlite3.connect('scores.db')
c = conn.cursor()

# Create the table if it doesn't exist
c.execute('CREATE TABLE IF NOT EXISTS scores (username TEXT, score INTEGER)')

difficulty,players,hints,category,username=[0,0,0,0,0]

# all the words that will pop up for hangman
words = {
    'Animals': {
        'Easy': ['zebra', 'tiger', 'snake', 'shark', 'whale', 'otter', 'panda', 'koala', 'chimp', 'puppy', 'eagle', 'hippo', 'raven', 'stork', 'hyena', 'skunk', 'rhino', 'goose'],
        'Medium': ['panther', 'gazelle', 'penguin', 'buffalo', 'giraffe', 'elephant', 'octopus', 'chicken', 'jaguar', 'hamster', 'seagull', 'sparrow', 'badgers', 'kangaro',  'platypu', 'lobster', 'wallaby'],
        'Hard': ['crocodile', 'porcupine', 'rhinoceros', 'alligator', 'kangaroos', 'jellyfish', 'chameleons', 'hummingbird', 'butterfly', 'orangutans', 'dolphinews', 'porpoises', 'hippopotam', 'woodpecker', 'platypuses', 'cheetahs', 'anteaters', 'squirrels', 'flamingoes', 'chinchilla']
    },
    'Countries': {
        'Easy': ['japan', 'china', 'india', 'spain', 'italy', 'chile', 'kenya', 'egypt', 'nepal','sudan', 'nepal', 'yemen',  'libya', 'malta'],
        'Medium': ['belgium', 'morocco', 'ireland', 'germany', 'colombi', 'bahrain', 'pakistan', 'romania', 'mongolia', 'nigeria', 'denmark', 'haiti', 'oman', 'brazil', 'namibia', 'jamaica', 'thailand', 'india', 'kazakhs', 'mongoli'],
        'Hard':  ['zimbabwean', 'azerbaijan', 'czechoslov', 'bangladesh', 'guadeloupe', 'macedonian', 'mauritania', 'afghanista', 'micronesia', 'montserrat', 'vietnamese', 'azerbaijan', 'argentinia', 'kyrgyzstan']
    },
    'Fruits': {
        'Easy': ['grape', 'apple', 'mango', 'peach', 'melon', 'lemon', 'berry','olive', 'pears', 'grape', 'avoca', 'pears', 'dates', 'guava', 'pawpaw', 'prune'],
        'Medium': ['mangoes', 'apricot', 'avocado', 'coconut', 'kiwifruit', 'mangost', 'papayas', 'peaches', 'plumcot', 'soursop', 'bananas'],
        'Hard': ['blackberry', 'pomegranat', 'honeycrisp',  'persimmons', 'bloodorang', 'tamarillos', 'boysenberr', 'ackeefruit', 'watermelon', 'kiwiberrie',  'cantaloupe', 'clementine',  'guavafruit']}}

def hint(gussedletters,Secretword):
    # finds a letter thats part of the secret word and shows it
    valid_letters = [letter for letter in Secretword if letter not in gussedletters]
    gussed_letter=random.choice(valid_letters)
    print(f"Hint {gussed_letter} has been added!")
    gussedletters.append(gussed_letter)
    return gussed_letter

def play(difficulty,hints,category):
    global list,username
    # number of lives
    Lives=6
    gussedletters=[]
    # number of hints per difficulty
    guesses={"Easy":3, "Medium":2, "Hard":1}
    if category ==0:
        category= random.choice(["Animals","Countries","Fruits"])
        print(f"No category selected. Choosing {category} instead.")
    if difficulty==0:
        difficulty=random.choice(["Easy","Medium","Hard"])
        print(f"No difficulty selected. Choosing {difficulty} instead.")
    word = words[category][difficulty]
    Secretword=random.choice(word).lower()
    length=len(Secretword)
    blanks=length*"_"
    # incase a costume hint is chosen in the main menue
    if hints==0:
        guesses=guesses[difficulty]
    else:
        guesses=hints
    print("The Game has begun!")
    print("\nDuring any point of the game, you may type 'hint' in order to use any of your remaining hints!\n")
    print("During any point of the game, you may type the word!\n")
    print(f"You've got {guesses} hints!\n")
    print(f"the word has {length} letters!")

    # runs till the word is found or the player runs out of lives
    while Lives>=1:
        if blanks==Secretword:
            print(f"You got it right with {Lives} lives remaning!")
            time.sleep(3)
            # Score calculation
            score=Lives*100+hints*100
            if difficulty=="Hard":
                score+=1000
            elif difficulty=="Medium":
                score+=500
            print(f"{username} has completed {difficulty} difficulty having {guesses} hints available and having {Lives} lives remaining.\nOverall score: {score} points!")
            # Adds it to the database
            c.execute('INSERT INTO scores (username, score) VALUES (?, ?)', (username, score))
            conn.commit()
            main()
        # prints the blanks including the found letters
        print(blanks)
        try:
            letterguess=str(input("\nGuess a letter:")).lower()
            # if there are hints avalible and the player would like to use them
            if letterguess=="hint" and guesses>0:
                guessedletter=hint(gussedletters,Secretword)
                positions = [i for i, letter in enumerate(Secretword) if letter in guessedletter]
                for i in positions:
                    blanks = blanks[:i] + guessedletter + blanks[i+1:]
                guesses-=1
                continue
            # if there are no hints available and the player would like to use them
            if letterguess=="hint" and guesses==0:
                print("\nyou've ran out of hints!:(")
                continue
            # incase the user guesses the word
            if letterguess==Secretword:
                blanks=Secretword
                print("Congragulations! you've got it right!")
                continue
            # incorrect input
            elif len(letterguess)<1 or len(letterguess)>1:
                raise
            # repetition of guesses
            elif letterguess in gussedletters:
                print("you've already gussed this letter!")
                continue
        except:
            print("Thats not a valid input!")
            continue
        # guessed letter correctly
        if letterguess in Secretword:
            print(letterguess,"Is in the secret word!")
            positions = [i for i, letter in enumerate(Secretword) if letter in letterguess]
            for i in positions:
                blanks = blanks[:i] + letterguess + blanks[i+1:]
        else:
            print("thats not correct")
            Lives-=1
            print(f"You've got {Lives} Lives left!")
        gussedletters.append(letterguess)
    if Lives==0:
        print(f"The secret word was {Secretword}!!")

def difficulty_choice():
    # option to choose difficulty
    while True:
        print("========================================")
        print("|        Choose Difficulty Level       |")
        print("========================================")
        print("| 1. Easy (5 letter words, 6 guesses)  |")
        print("| 2. Medium (7 letter words, 4 guesses)|")
        print("| 3. Hard (10 letter words, 2 guesses) |")
        print("| 4. Back to Main Menu                 |")
        print("========================================")
        playerschoice=input("Enter your choice: ")
        # makes sure the input is correct
        if playerschoice.isdigit() and int(playerschoice) in [1,2,3,4]:
            break
        else:
            print("Please pick a digit between 1-4!")
            time.sleep(2)
    playerschoice=int(playerschoice)
    if playerschoice==1:
        return("Easy")

    elif playerschoice==2:
        return("Medium")
    elif playerschoice==3:
        return("Hard")
    elif playerschoice==4:
        main()

def hint_choice():
    # option to choose hint difficulty level
    while True:
        print("==================================")
        print("|          Hint System           |")
        print("==================================")
        print("| 1. Easy (2 hints per game)     |")
        print("| 2. Medium (1 hint per game)    |")
        print("| 3. Hard (no hints)             |")
        print("| 4. Back to Main Menu           |")
        print("==================================")
        playerschoice=input("Enter your choice: ")
        # makes sure the input is correct
        if playerschoice.isdigit() and int(playerschoice) in [1,2,3,4]:
            break
        else:
            print("Please pick a digit between 1-4!")
            time.sleep(2)
    playerschoice=int(playerschoice)
    if playerschoice==1:
        return(2)
    elif playerschoice==2:
        return(1)
    elif playerschoice==3:
        return(0)
    elif playerschoice==4:
        main()

def categories_choice():
    # option to chosse what category of words
    while True:
        print("==================================")
        print("|         Word Categories        |")
        print("==================================")
        print("| 1. Animals                     |")
        print("| 2. Countries                   |")
        print("| 3. Fruits                      |")
        print("| 4. Back to Main Menu           |")
        print("==================================")
        playerschoice=input("Enter your choice: ")
        # makes sure the input is correct
        if playerschoice.isdigit() and int(playerschoice) in [1,2,3,4]:
            break
        else:
            print("Please pick a digit between 1-4!")
            time.sleep(2)
    playerschoice=int(playerschoice)
    if playerschoice==1:
        return("Animals")
    elif playerschoice==2:
        return("Countries")
    elif playerschoice==3:
        return("Fruits")
    elif playerschoice==4:
        main()

def scoreboard():
    # option to show or clear the score board
    while True:
        print("==================================")
        print("|      High Score Tracking       |")
        print("==================================")
        print("| 1. View High Scores            |")
        print("| 2. Clear High Scores           |")
        print("| 3. Back to Main Menu           |")
        print("==================================")
        playerschoice=input("Enter your choice: ")
        # makes sure the input is correct
        if playerschoice.isdigit() and int(playerschoice) in [1,2,3]:
            break
        else:
            print("Please pick a digit between 1-4!")
            time.sleep(2)
    playerschoice=int(playerschoice)
    if playerschoice==1:
        # Retrieve the scores from the database and display them
        c.execute('SELECT * FROM scores ORDER BY score DESC')
        sorted_items = c.fetchall()
        if sorted_items:
            print("Leaderboard:")
            for rank, (username, score) in enumerate(sorted_items, start=1):
                print(f"{rank}. {username}: {score}")
        else:
            print("no one has played yet!")
    elif playerschoice==2:
        # deletes the score board data
        c.execute('DELETE FROM scores')
        conn.commit()
        print("Leaderboard has been cleared!\n")
    elif playerschoice==3:
        main()

def main():
    # shows main menue and checks to see if the username is taken
    global difficulty,hints,category,username
    while True:
        username = input("Please enter your name: ")
        rand_num = str(random.randint(0, 9999)).zfill(4)
        username=(f"{username}#{rand_num}")
        c.execute('SELECT * FROM scores WHERE username=?', (username,))
        result = c.fetchone()
        if result is not None or username=='':
            print("Sorry, that username is unavailable. Please choose another.")
            username=0
            continue
        break

    print(f"Hello, {username}!")
    while True:
        print("==================================")
        print("|       Welcome to Hangman!      |")
        print("==================================")
        print("| 1. Play Game                  |")
        print("| 2. Choose Difficulty Level    |")
        print("| 3. Hint System                |")
        print("| 4. Word Categories            |")
        print("| 5. High Score Tracking        |")
        print("| 6. Exit                       |")
        print("==================================")
        # checks to see if input is correct
        try:
            playerschoice=int(input("Enter your choice: "))
            if playerschoice not in [1,2,3,4,5,6]:
                raise
        except:
            print("Please pick a digit between 1-7!")
            time.sleep(2)
            continue
        if playerschoice==1:
            play(difficulty,hints,category)
        elif playerschoice==2:
            difficulty=difficulty_choice()
            print(f"\nDifficulty {difficulty} has been chosen!\n")
        elif playerschoice==3:
            hints=hint_choice()
            print(f"\n{hints} hints has been given!\n")
        elif playerschoice==4:
            category=categories_choice()
            print(f"\n{category} category has been chosen!\n")
        elif playerschoice==5:
            scoreboard()
        elif playerschoice==6:
            break
main()
conn.close()


import torch
import torch.nn as nn
from espnet.nets.pytorch_backend.backbones.modules.resnet import ResNet, BasicBlock
from espnet.nets.pytorch_backend.transformer.convolution import Swish

def threeD_to_2D_tensor(x):
    n_batch, n_channels, s_time, sx, sy = x.shape
    x = x.transpose(1, 2)
    return x.reshape(n_batch * s_time, n_channels, sx, sy)

class Conv3dResNet(torch.nn.Module):
    """Conv3dResNet module
    """

    def __init__(self, backbone_type="resnet", relu_type="swish"):
        """__init__.

        :param backbone_type: str, the type of a visual front-end.
        :param relu_type: str, activation function used in an audio front-end.
        """
        super(Conv3dResNet, self).__init__()
        self.frontend_nout = 64
        self.trunk = ResNet(BasicBlock, [2, 2, 2, 2], relu_type=relu_type)
        self.frontend3D = nn.Sequential(
            nn.Conv3d(1, self.frontend_nout, (5, 7, 7), (1, 2, 2), (2, 3, 3), bias=False),
            nn.BatchNorm3d(self.frontend_nout),
            Swish(),
            nn.MaxPool3d((1, 3, 3), (1, 2, 2), (0, 1, 1))
        )

    def forward(self, xs_pad):
        B, C, T, H, W = xs_pad.size()
        xs_pad = self.frontend3D(xs_pad)
        Tnew = xs_pad.shape[2]
        xs_pad = threeD_to_2D_tensor(xs_pad)
        xs_pad = self.trunk(xs_pad)
        return xs_pad.view(B, Tnew, xs_pad.size(1))


from collections import Counter

def solution(k, tangerine):
    counter = Counter(tangerine)
    lst = list(counter.values())
    lst.sort(reverse=True)

    answer = 0
    value = 0
    for count in lst:
        if value >= k:
            break
        answer += 1
        value += count
    return answer

print(solution(6, [1, 3, 2, 5, 4, 5, 2, 3]))


import pygame, sys
import pyautogui

# initialize the pygame
mainClock = pygame.time.Clock()
from pygame.locals import *
pygame.init()
pygame.display.set_caption("C:/Users/daant/PycharmProjects/Eindwerkstuk-P3.6/Skin/Main/Gideon assistant")
icon = pygame.image.load("C:/Users/daant/PycharmProjects/Eindwerkstuk-P3.6/Skin/Main/waveform icon - Copy.png")
pygame.display.set_icon(icon)
screen = pygame.display.set_mode((420, 280),0,32)

font = pygame.font.SysFont(None, 20)

Duo = pygame.image.load("C:/Users/daant/PycharmProjects/Eindwerkstuk-P3.6/Skin/Main/Google-Duo-3 - Copy.png").convert()
vol_up = pygame.image.load("C:/Users/daant/PycharmProjects/Eindwerkstuk-P3.6/Skin/Main/volume up.png").convert()
vol_down = pygame.image.load("C:/Users/daant/PycharmProjects/Eindwerkstuk-P3.6/Skin/Main/volume down.png").convert()
vol_mute = pygame.image.load("C:/Users/daant/PycharmProjects/Eindwerkstuk-P3.6/Skin/Main/volume mute.png").convert()
setings = pygame.image.load("C:/Users/daant/PycharmProjects/Eindwerkstuk-P3.6/Skin/Main/settings.png").convert()

def draw_text (text, font, color, surface, x, y):
    textobj = font.render(text, 1, color)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

click = False

def Google_Duo():
    print("Duo Button pressed")
    pyautogui.hotkey("Alt", "Tab")

def volume_up():
    pyautogui.press("volumeup")

def volume_down():
    pyautogui.press("volumedown")

def volume_mute():
    pyautogui.press("volumemute")

def settings():
    import Database

while True:

    screen.fill((0, 130, 255))

    mx, my = pygame.mouse.get_pos()

    button_1 = pygame.Rect(20, 20, 175, 100)
    button_2 = pygame.Rect(30, 150, 100, 100)
    button_3 = pygame.Rect(160, 150, 100, 100)
    button_4 = pygame.Rect(290, 150, 100, 100)
    button_5 = pygame.Rect(260, 20, 100, 100)
    if button_1.collidepoint((mx, my)):
        if click:
            Google_Duo()
    if button_2.collidepoint((mx, my)):
        if click:
            volume_down()
    if button_3.collidepoint((mx, my)):
        if click:
            volume_mute()
    if button_4.collidepoint((mx, my)):
        if click:
            volume_up()
    if button_5.collidepoint((mx, my)):
        if click:
            settings()
    pygame.draw.rect(screen, (0, 222, 200), button_1)
    pygame.draw.rect(screen, (0, 222, 200), button_2)
    pygame.draw.rect(screen, (0, 222, 200), button_3)
    pygame.draw.rect(screen, (0, 222, 200), button_4)
    pygame.draw.rect(screen, (0, 222, 200), button_5)
    screen.blit(Duo, [20, 20])
    screen.blit(vol_down, [30, 150])
    screen.blit(vol_mute, [160, 150])
    screen.blit(vol_up, [290, 150])
    screen.blit(setings, [260, 20])

    click = False
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
        if event.type == MOUSEBUTTONDOWN:
            if event.button == 1:
                click = True

    pygame.display.update()
    mainClock.tick(60)


#Importa bibliotecas
import smbus2 as smbus
import time

#Inicia SMbus
bus = smbus.SMBus(1)

#Define endereço do arduino
slaveAddress = 0x08

#Funcao que faz o request dos valores do arduino
def RequestArduinoData():
	#le valor do arduino
	data_received_Arduino = bus.read_byte ( slaveAddress)
	print(data_received_Arduino)

while 1:
	#Requisita valor do arduino e aguarda 250ms
	RequestArduinoData()
	time.sleep(0.25)


from gpiozero import Button
from signal import pause
import pygame, pygame.mixer
import os

pygame.mixer.init()

def say_hello():
    pygame.mixer.music.stop()
    print("hi")
def say_goodbye():
    print("bye")
    pygame.mixer.music.load(os.path.join("/home/pi/Doorcode/opendoor.mp3"))
    pygame.mixer.music.play()

button1 = Button(3)
button1.when_pressed = say_hello
button1.when_released = say_goodbye

button2 = Button(4)
button2.when_pressed = say_hello
button2.when_released = say_goodbye

button3 = Button(17)
button3.when_pressed = say_hello
button3.when_released = say_goodbye

button4 = Button(27)
button4.when_pressed = say_hello
button4.when_released = say_goodbye
pause()


from rest_framework import serializers
from rest_framework.fields import SlugField

from api.models import (
    TrainingConfiguration,
    TrainingTask
)

class TrainingConfigurationSerializer(serializers.ModelSerializer):
    class Meta:
        model = TrainingConfiguration
        fields = (
            'id', 'algorithm', 'dockerfile', 'created_on',
        )

    algorithm = SlugField(label='name', required=False)
    dockerfile = SlugField(label='name', required=False)

class TrainingTaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = TrainingTask
        fields = (
            'training_configuration',
            'id',
            'status',
            'created_on',
            'started_on',
            'terminated_on',
            'failure_message',
            'test_loss',
            'test_accuracy',
            'docker_id',
        )

    docker_id = serializers.CharField(allow_null=True)
    failure_message = serializers.CharField(allow_blank=True)
    id = serializers.IntegerField(read_only=True)
    training_configuration = serializers.PrimaryKeyRelatedField(read_only=True)
    started_on = serializers.DateTimeField(allow_null=True)
    terminated_on = serializers.DateTimeField(allow_null=True)


'''
109. Convert Sorted List to Binary Search Tree
Medium
6.6K
141
Companies
Given the head of a singly linked list where elements are sorted in ascending order, convert it to a
height-balanced
 binary search tree.

Example 1:

Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Example 2:

Input: head = []
Output: []

Constraints:

The number of nodes in head is in the range [0, 2 * 104].
-105 <= Node.val <= 105
Accepted
461.3K
Submissions
771.2K
Acceptance Rate
59.8%
'''

# Definition for singly-linked list.
from typing import Optional

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def getArrayFromLinkedList(self, head):
        cursor = head
        arr = []
        while cursor:
            arr.append(cursor.val)
            cursor = cursor.next
        return arr

    def getBST(self, arr, node):
        if len(arr) == 0:
            return None
        mid = (len(arr) - 1) // 2
        node.val = arr[mid]
        node.left = self.getBST(arr[:mid], TreeNode())
        node.right = self.getBST(arr[mid + 1:], TreeNode())
        return node

    def sortedListToBST(self, head: Optional[ListNode]) -> Optional[TreeNode]:
        return self.getBST(self.getArrayFromLinkedList(head), TreeNode())


from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.flatpages import views

urlpatterns = [
    path('auth/', include('users.urls')),
    path('auth/', include('django.contrib.auth.urls')),
    path('admin/', admin.site.urls),
    path('about/', views.flatpage, {'url': '/about/'}, name='about'),
    path('tech/', views.flatpage, {'url': '/tech/'}, name='tech'),
    path('', include('api.urls')),
    path('', include('recipes.urls')),
]

if settings.DEBUG:

    import debug_toolbar
    urlpatterns += (path('__debug__/', include(debug_toolbar.urls)),)
    urlpatterns += static(
        settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(
        settings.STATIC_URL, document_root=settings.STATIC_ROOT)


import pandas as pd
import numpy as np
from sklearn.metrics import r2_score
import statsmodels.api as sm

pizza = pd.read_csv("pizza.csv")

X = pizza['Promote']
X = sm.add_constant(X)
y = pizza['Sales']
model = sm.OLS(y,X)
results = model.fit()

print(results.params)
print(results.summary())

### Credit Approval
import os
os.chdir(r"C:\Training\Academy\Business Analytics 3e Resources\Excel Datasets\eba3e_datasets_xls")
cred = pd.read_excel("CreditApprovalDecisions.xlsx",sheet_name="Data",
                     usecols="A:F",skiprows=2)
X = cred[['Years of Credit History',
          'Revolving Balance', 'Revolving Utilization']]
y = cred['Credit Score']

X = sm.add_constant(X)

model = sm.OLS(y,X)
results = model.fit()

print(results.params)
print(results.summary())

StudetDataBackup/8. Covariance Correlation & Regression/sm_ols.py


# libs
import os
from dotenv import load_dotenv

# carrega variáveis de ambiente no script
load_dotenv()

# carrega a variável da chave de api no script
API_KEY_LEADS_SIGA = os.environ.get("API_KEY_LEADS_SIGA")
URL_SIGA = os.environ.get("URL_SIGA")
def get_siga(chave:str = API_KEY_LEADS_SIGA):
    import requests
    #Conexão com api siga.
    params={
        "chave_abrasel":chave,
        "accept" : "*",
        }
    response = requests.get(URL_SIGA,headers=params, verify=False)
    data = response.json()
    base = []
    for d in data:
        base.append({
            "SEC_REG": d.get("S/R", "não informado").upper(),
            "NOME_FANTASIA": d.get("Nome Fantasia", ""),
            "CNPJ": d.get("CNPJ", "não informado"),
            "ENDERECO": f"{d.get('Logradouro', '')}, {d.get('Numero', 'SN')} {d.get('Comp.', '')}".upper(),
            "BAIRRO": d.get("Bairro", "não informado"),
            "CEP": d.get("CEP", "não informado"),
            "CIDADE": d.get("Cidade", "não informado"),
            "UF": d.get("UF", "não informado"),
            "ASSOCIADO": d["Status"].upper(),
            "SOU_ABRASEL": d["Status_SouAbrasel"].upper()
        })

    return base

#Visualizar dados.
def visualizar_associados_ativos():
    import pandas as pd
    import duckdb as db
    associados=pd.DataFrame(get_siga())
    return db.query("""select * from associados """).to_df()


# Lambda function to build scheduler as a AWS CloudWatch Event rule
# Trigger: API Gateway POST request with job config

import json

import boto3

cw = boto3.client('events')
s3 = boto3.resource('s3')

BUCKET_CONFIG = 'aws-od-configs'

LAMBDA_ROLE = ''
LAMBDA_TRIGGER = ''

def lambda_handler(event, context):
    try:
        config = json.loads(event['body'])
        job_id = config.get('id')

        s3.Bucket(
            BUCKET_CONFIG
        ).put_object(
            Body=event['body'].encode(),
            Key=f'{job_id}.json'
        )

        rule = cw.put_rule(
            Name=job_id,
            ScheduleExpression=f'cron({config.get("cron")})',
            State='ENABLED',
            RoleArn=LAMBDA_ROLE
        )

        target = cw.put_targets(
            Rule=job_id,
            Targets=[{
                'Arn': LAMBDA_TRIGGER,
                'Id': 'InitPipelineJob', # ID of the target for this specific rule
                'Input': json.dumps({'id': job_id})
            }]
        )

        return build_response(200, f'successfully created scheduler with ARN {rule["RuleArn"]}')
    except Exception as e:
        return build_response(500, e)

def build_response(code, message=''):
    response = {
        'statusCode': code,
        'headers': {
            'Access-Control-Allow-Origin': '*'
        }
    }

    if message:
        response['body'] = message

    return response


from django.shortcuts import render, get_object_or_404
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, Group

from proyecto.decorators import *
from .forms import *
from actividades.funciones import *
from proyecto.models import RegistroPerfil, ProyectoDeGrado
from .funciones import *
from proyecto.funciones import comprobar

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente','tutor','tribunal'])
def revisiones(request, pk):
    usuario = request.user
    grupo = usuario.groups.get().name
    equipo = get_object_or_404(Equipo, id=pk)

    if comprobar(grupo, equipo, usuario):
        return HttpResponse('error')

    salas_documentos = SalaDocumentoDoc.objects.filter(revisor=usuario, equipo=equipo)

    is_perfil_habilitado = isActividad(equipo, "imprimir carta tutoria")
    is_perfil_terminado = isActividad(equipo, "imprimir formulario")
    is_proyecto_terminado = isActividad(equipo, "nota docente proyecto")
    is_vb_proyecto_tutor = isActividad(equipo, "visto bueno proyecto tutor")
    is_vb_perfil_tutor = isActividad(equipo, "visto bueno perfil tutor")

    context = {
        'grupo': grupo,
        'equipo': equipo,
        'salas_documentos': salas_documentos,
        'is_perfil_habilitado': is_perfil_habilitado,
        'is_perfil_terminado': is_perfil_terminado,
        'is_proyecto_terminado': is_proyecto_terminado,
        'is_vb_proyecto_tutor': is_vb_proyecto_tutor,
        'is_vb_perfil_tutor': is_vb_perfil_tutor,
    }
    return render(request, 'revisar_documentos/revisiones.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente','tutor'])
def configurar(request, pk):
    revisor = request.user
    grupo = revisor.groups.get().name
    equipo = get_object_or_404(Equipo, id=pk)

    if grupo=='docente':
        docente = revisor.datosdocente
        if not Equipo.objects.filter(docente=docente):
            return HttpResponse('error')

    configuracion, created = ConfiguracionSala.objects.get_or_create(usuario=revisor)
    salas = RevisarDocPersonalizado.objects.filter(usuario=revisor).order_by('orden')
    salas_pre = RevisarDocPredeterminado.objects.all().order_by('orden')
    suma_max = 0
    for sala in salas:
        suma_max += sala.nota_max

    context = {
        'grupo': grupo,
        'revisor': revisor,
        'equipo': equipo,
        'salas': salas,
        'salas_pre': salas_pre,
        'configuracion': configuracion,
        'suma_max': suma_max
    }
    if grupo == 'docente':
        return render(request, 'revisar_documentos/configurar.html', context)
    else:
        return render(request, 'revisar_documentos/configurar_revisor.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente', 'tutor'])
def cambiarPredeterminado(request, pk):
    revisor = request.user
    grupo = revisor.groups.get().name
    equipo = get_object_or_404(Equipo, id=pk)
    configuracion = ConfiguracionSala.objects.get(usuario=revisor)

    if grupo=='docente':
        docente = revisor.datosdocente
        if not Equipo.objects.filter(docente=docente):
            return HttpResponse('error')

    if request.method == 'POST':
        if configuracion.is_predeterminado == False:
            configuracion.is_predeterminado = True
            configuracion.save()
        else:
            configuracion.is_predeterminado = False
            configuracion.save()
        return redirect('revisar_documentos:configurar', pk=equipo.id)

    context = {
        'grupo': grupo,
        'revisor': revisor,
        'equipo': equipo,
    }

    return render(request, 'revisar_documentos/cambiar_predeterminado.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente','tutor','tribunal'])
def crearSalaPersonal(request, pk):
    revisor = request.user
    grupo = revisor.groups.get().name
    equipo = get_object_or_404(Equipo, id=pk)

    if grupo=='docente':
        docente = revisor.datosdocente
        if not Equipo.objects.filter(docente=docente):
            return HttpResponse('error')

    if grupo=='tutor':
        tutor = revisor.datostutor
        if not Equipo.objects.filter(tutor=tutor):
            return HttpResponse('error')

    if grupo=='docente':
        form = crearRevisarDocPersonalizadoForm()
    else:
        form = crearRevisarDocPersonalizadoRevisorForm()

    if request.method == 'POST':
        if grupo=='docente':
            form = crearRevisarDocPersonalizadoForm(request.POST)
        else:
            form = crearRevisarDocPersonalizadoRevisorForm(request.POST)
        if form.is_valid():
            form.instance.usuario = revisor
            form.instance.tipo = "proyecto"
            form.save()
            return redirect('revisar_documentos:configurar', pk=equipo.id)

    salas = RevisarDocPersonalizado.objects.filter(usuario=revisor, tipo='proyecto')
    suma_max = 0
    for sala in salas:
        suma_max += sala.nota_max

    context = {
        'grupo': grupo,
        'revisor': revisor,
        'equipo': equipo,
        'suma_max': suma_max,
        'form': form,
    }
    return render(request, 'revisar_documentos/crear_sala_personalizado.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente','tutor','tribunal'])
def eliminarSalaPersonal(request, pk_equipo, pk):
    revisor = request.user
    grupo = revisor.groups.get().name
    sala = get_object_or_404(RevisarDocPersonalizado, id=pk)
    equipo = get_object_or_404(Equipo, id=pk_equipo)

    if not RevisarDocPersonalizado.objects.filter(usuario=revisor):
        return HttpResponse('error')

    if request.method == 'POST':
        sala.delete()
        return redirect('revisar_documentos:configurar', pk=equipo.id)

    context = {
        'grupo': grupo,
        'revisor': revisor,
        'equipo': equipo,
    }
    return render(request, 'revisar_documentos/eliminar_sala.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente','tutor','tribunal'])
def modificarSalaPersonal(request, pk_equipo, pk):
    revisor = request.user
    grupo = revisor.groups.get().name
    sala = get_object_or_404(RevisarDocPersonalizado, id=pk)
    equipo = get_object_or_404(Equipo, id=pk_equipo)

    if not RevisarDocPersonalizado.objects.filter(usuario=revisor):
        return HttpResponse('error')

    if grupo=='docente':
        form = crearRevisarDocPersonalizadoForm(instance=sala)
    else:
        form = crearRevisarDocPersonalizadoRevisorForm(instance=sala)

    if request.method == 'POST':
        if grupo=='docente':
            form = crearRevisarDocPersonalizadoForm(request.POST, instance=sala)
        else:
            form = crearRevisarDocPersonalizadoRevisorForm(request.POST, instance=sala)
        if form.is_valid():
            form.save()
        return redirect('revisar_documentos:configurar', pk=equipo.id)

    salas = RevisarDocPersonalizado.objects.filter(usuario=revisor, tipo='proyecto')
    suma_max = 0
    for sala in salas:
        suma_max += sala.nota_max

    context = {
        'grupo': grupo,
        'revisor': revisor,
        'equipo': equipo,
        'suma_max': suma_max,
        'form': form,
    }
    return render(request, 'revisar_documentos/modificar_sala_personal.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['estudiante'])
def revisarDocumentoEstudiante(request, documento, id_revisor):
    usuario = request.user
    grupo = usuario.groups.get().name
    revisor = User.objects.get(id=id_revisor)
    estudiante = request.user.datosestudiante
    grupo_revisor = revisor.groups.get()
    sala_doc = SalaDocumentoDoc.objects.filter(revisor=revisor, grupo_revisor=grupo_revisor, equipo=estudiante.equipo, tipo=documento).first()
    salas_revisar = SalaRevisarDoc.objects.filter(sala_documento=sala_doc).order_by('-fecha_creacion')
    dicc_salas = {}
    for sala in salas_revisar:
        mensajes = MensajeRevisarDoc.objects.filter(sala=sala).exclude(usuario=usuario)
        no_visto = 0
        for mensaje in mensajes:
            if not mensaje.visto:
                no_visto += 1
        dicc_salas[sala] = no_visto
    suma = 0
    if grupo_revisor.name == 'docente' and sala_doc.tipo == 'proyecto' and salas_revisar.count() > 0:
        suma = 0
        for sala in salas_revisar:
            suma += sala.nota
    context = {
            'sala_doc':sala_doc,
            'dicc_salas':dicc_salas,
            'suma': suma,
            'grupo':grupo}
    return render(request, 'revisar_documentos/revisar_documento_estudiante.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['tutor','docente','tribunal'])
def revisarDocumentoRevisor(request, documento, id_equipo):
    grupo = request.user.groups.get().name
    revisor = request.user
    equipo = get_object_or_404(Equipo, id=id_equipo)
    grupo_revisor = revisor.groups.get()

    if documento=='proyecto' and not isActividad(equipo, "imprimir formulario"):
        return HttpResponse('error')
    if documento=='perfil' and not isActividad(equipo, "imprimir carta tutoria"):
        return HttpResponse('error')
    if documento=='proyecto' and grupo=="docente" and not isActividad(equipo, "visto bueno proyecto tutor"):
        return HttpResponse('error')

    sala_doc, created = SalaDocumentoDoc.objects.get_or_create(revisor=revisor, grupo_revisor=grupo_revisor, equipo=equipo, tipo=documento)
    salas_revisar = SalaRevisarDoc.objects.filter(sala_documento=sala_doc).order_by('-fecha_creacion')

    dicc_salas = {}
    for sala in salas_revisar:
        mensajes = MensajeRevisarDoc.objects.filter(sala=sala).exclude(usuario=request.user)
        no_visto = 0
        for mensaje in mensajes:
            if not mensaje.visto:
                no_visto += 1
        dicc_salas[sala] = no_visto
    suma = 0
    suma_max = 0
    if grupo_revisor.name == 'docente' and sala_doc.tipo == 'proyecto' and salas_revisar.count() > 0:
        suma = 0
        for sala in salas_revisar:
            suma += sala.nota

        # suma de nota max
        suma_max = 0
        for sala in salas_revisar:
            suma_max += sala.nota_max

    context = {
            'sala_doc':sala_doc,
            'dicc_salas':dicc_salas,
            'equipo':equipo,
            'suma': suma,
            'suma_max': suma_max,
            'grupo':grupo}

    return render(request, 'revisar_documentos/revisar_documento_revisor.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['tutor','docente','tribunal'])
def modificarNotaMax(request, id_sala):
    grupo = request.user.groups.get().name
    revisor = request.user
    sala_revisar = get_object_or_404(SalaRevisarDoc, id=id_sala)
    if sala_revisar.is_calificado:
        return HttpResponse('error')
    documento = sala_revisar.sala_documento.tipo
    equipo = sala_revisar.sala_documento.equipo

    salas_revisar = sala_revisar.sala_documento.salarevisardoc_set.all()
    # suma de nota max
    suma_max = 0
    for sala in salas_revisar:
        suma_max += sala.nota_max

    form = NotaMaxForm(instance=sala_revisar)
    if request.method == 'POST':
        form = NotaMaxForm(request.POST, instance=sala_revisar)
        if form.is_valid():
            form.save()
            return redirect('revisar_documentos:revisar_documento_revisor', documento=documento, id_equipo=equipo.id)
    context = {
            'form': form,
            'suma': suma_max,
            'grupo': grupo,}

    return render(request, 'revisar_documentos/modificar_nota_max.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente', 'tutor', 'tribunal'])
def crearSalaRevisar(request, documento, id_sala_doc):
    sala_doc = SalaDocumentoDoc.objects.get(id=id_sala_doc)
    equipo = sala_doc.equipo
    primer_estudiante = equipo.datosestudiante_set.first()
    grupo = request.user.groups.get().name
    salas_revisar = sala_doc.salarevisardoc_set.all()
    form = SalaRevisarDocForm
    if request.method == 'POST':
        form = SalaRevisarDocForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.sala_documento = sala_doc
            form.save()
            return redirect('revisar_documentos:revisar_documento_revisor', documento=sala_doc.tipo, id_equipo=equipo.id)
    suma_max = 0
    for sala in salas_revisar:
        suma_max += sala.nota_max

    context = {'form':form,
            'suma_max': suma_max,
            'grupo': grupo}
    return render(request, 'revisar_documentos/crear_sala_revisar.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente', 'tutor', 'tribunal'])
def crearSalaSinNota(request, documento, id_sala_doc):
    sala_doc = SalaDocumentoDoc.objects.get(id=id_sala_doc)
    equipo = sala_doc.equipo
    primer_estudiante = equipo.datosestudiante_set.first()
    grupo = request.user.groups.get().name
    form = SalaRevisarDocSinNotaForm
    if request.method == 'POST':
        form = SalaRevisarDocSinNotaForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.sala_documento = sala_doc
            form.save()
            return redirect('revisar_documentos:revisar_documento_revisor', documento=sala_doc.tipo, id_equipo=equipo.id)

    context = {'form':form,
            'grupo': grupo}

    return render(request, 'revisar_documentos/crear_sala_sin_nota.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente', 'tutor', 'tribunal'])
def eliminarSalaRevisar(request, id_sala_rev):
    sala_rev = SalaRevisarDoc.objects.get(id=id_sala_rev)
    if not sala_rev.sala_documento.revisor == request.user:
        return HttpResponse('error')
    if sala_rev.is_calificado:
        return HttpResponse('error')
    documento = sala_rev.sala_documento.tipo
    id_equipo = sala_rev.sala_documento.equipo.id
    grupo = request.user.groups.get().name
    if request.method == 'POST':
        sala_rev.delete()
        return redirect('revisar_documentos:revisar_documento_revisor', documento=documento, id_equipo=id_equipo)
    context = {
            'grupo': grupo}
    return render(request, 'revisar_documentos/eliminar_sala.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente', 'tutor', 'tribunal'])
def cerrarSalaRevisar(request, id_sala_rev):
    sala_rev = SalaRevisarDoc.objects.get(id=id_sala_rev)

    if not sala_rev.sala_documento.revisor == request.user:
        return HttpResponse('error')
    if sala_rev.is_calificado:
        return HttpResponse('error')

    documento = sala_rev.sala_documento.tipo
    id_equipo = sala_rev.sala_documento.equipo.id
    grupo = request.user.groups.get().name

    if request.method == 'POST':
        sala_rev.is_calificado = True
        sala_rev.save()
        return redirect('revisar_documentos:revisar_documento_revisor', documento=documento, id_equipo=id_equipo)

    context = {
        'grupo': grupo,
        'sala': sala_rev,
    }

    return render(request, 'revisar_documentos/cerrar_sala.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['estudiante'])
def subirDocumento(request, pk):
    sala_revisar = SalaRevisarDoc.objects.get(id=pk)
    estudiante = request.user.datosestudiante
    documento = sala_revisar.sala_documento.tipo
    revisor = sala_revisar.sala_documento.revisor
    grupo_revisor = sala_revisar.sala_documento.grupo_revisor.name
    equipo = estudiante.equipo
    if sala_revisar.sala_documento.equipo != equipo:
        return HttpResponse('error')
    grupo = request.user.groups.get().name
    form = SubirDocumentoForm(instance=sala_revisar)
    if request.method == 'POST':
        form = SubirDocumentoForm(request.POST, request.FILES, instance=sala_revisar)
        if form.is_valid():
            form.save()
            if grupo_revisor == "tribunal":
                tribunales = equipo.tribunales.all()
                if revisor.datostribunal == tribunales[0]:
                    numero = '1'
                else:
                    numero = '2'
                agregarAviso('revisar '+ documento + ' ' + numero, equipo, revisor)
                agregarActividadEquipo('revisar ' + documento + ' ' + numero, equipo)
            else:
                agregarAviso('revisar '+ documento + ' ' + grupo_revisor, equipo, revisor)
                agregarActividadEquipo('revisar ' + documento + ' ' + grupo_revisor, equipo)
            return redirect('revisar_documentos:revisar_documento_estudiante', documento=documento, id_revisor=revisor.id)
    context = {'form':form,
            'grupo': grupo}
    return render(request, 'revisar_documentos/subir_documento.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente'])
def calificarSalaRevision(request, pk):
    usuario = request.user
    grupo = usuario.groups.get().name
    sala_revisar = get_object_or_404(SalaRevisarDoc, id=pk)
    if sala_revisar.is_calificado:
        return HttpResponse('error')
    documento = sala_revisar.sala_documento
    equipo = documento.equipo
    equipo = sala_revisar.sala_documento.equipo
    form = NotaSalaRevisarDocForm(instance=sala_revisar)
    if request.method == 'POST':
        form = NotaSalaRevisarDocForm(request.POST, instance=sala_revisar)
        if form.is_valid():
            form.instance.is_calificado = True
            form.save()
            # return redirect('progreso_estudiante',pk=equipo.pk)
            return redirect('revisar_documentos:revisar_documento_revisor', documento=documento.tipo, id_equipo=equipo.id)
    sala_documento = SalaDocumentoDoc.objects.get(revisor=usuario, equipo=equipo, tipo='proyecto')
    numero_salas = sala_documento.salarevisardoc_set.count()
    salas_revisar = sala_documento.salarevisardoc_set.all()
    suma = 0
    for sala in salas_revisar:
        suma += sala.nota

    context = {
            'grupo':grupo,
            'sala_revisar': sala_revisar,
            'equipo': equipo,
            'form': form,
            'suma': suma,
            }
    return render(request, 'revisar_documentos/calificar_sala_revision.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['tutor','docente','tribunal','estudiante'])
def mensajes(request, id_sala_rev):
    usuario = request.user
    grupo = usuario.groups.get()
    sala = SalaRevisarDoc.objects.get(id=id_sala_rev)
    ultima_sala = sala.sala_documento.salarevisardoc_set.all().last()
    is_ultima_sala = sala == ultima_sala
    form = MensajeRevisarDocForm
    if request.method == "POST":
        form= MensajeRevisarDocForm(request.POST)
        if form.is_valid():
            file = form.save(commit=False)
            file.sala = sala
            file.usuario = usuario
            file.save()
        return redirect('revisar_documentos:mensajes', id_sala_rev=id_sala_rev)
    mensajes = MensajeRevisarDoc.objects.filter(sala=sala).order_by('-fecha_creacion')
    mensajes_no_vistos = MensajeRevisarDoc.objects.filter(sala=sala, visto=False).exclude(usuario=usuario)
    for mensaje in mensajes_no_vistos:
        mensaje.visto = True
        mensaje.save()
    context = {
            'form':form,
            'mensajes':mensajes,
            'sala':sala,
            'grupo':grupo.name,
            'is_ultima_sala':is_ultima_sala,
            }
    return render(request, 'revisar_documentos/mensajes.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['tutor','docente','tribunal'])
def darVistoBueno(request, id_sala_doc):
    sala_doc = get_object_or_404(SalaDocumentoDoc, id=id_sala_doc)
    salas_revisar = SalaRevisarDoc.objects.filter(sala_documento=sala_doc)
    grupo_revisor = sala_doc.revisor.groups.get().name
    grupo = request.user.groups.get().name
    equipo = sala_doc.equipo
    # suma de nota max
    suma_max = 0
    for sala in salas_revisar:
        suma_max += sala.nota_max
    # calificacion
    for sala in salas_revisar:
        if sala.nota == 0:
            is_calificacion_todo = False
        else:
            is_calificacion_todo = True

    # cerrados, utilizare el is_calificado para este fin.
    vector_is_calificado = [v.is_calificado for v in salas_revisar]
    is_cerrado = all(vector_is_calificado)

    if grupo_revisor == 'tribunal':
        if actividadRealizadaEstudiante("visto bueno tribunal 1", sala_doc.equipo.datosestudiante_set.first()):
            texto_actividad = f"visto bueno {sala_doc.tipo} 2"
        else:
            texto_actividad = f"visto bueno {sala_doc.tipo} 1"
    else:
        texto_actividad = f"visto bueno {sala_doc.tipo} {sala_doc.revisor.groups.get()}"

    if request.method == 'POST':
        # if grupo_revisor == 'docente':
            # if sala_doc.tipo == 'perfil':
                # RegistroPerfil.objects.create(
                    # equipo = sala_doc.equipo,
                    # perfil = sala_doc.salarevisardoc_set.last().archivo_corregir,
                # )
            # elif sala_doc.tipo == 'proyecto':
                # suma = 0
                # for sala in salas_revisar:
                    # suma += sala.nota
                # proyecto, created = ProyectoDeGrado.objects.get_or_create(equipo=equipo)
                # proyecto.nota_informes_trabajo = suma
                # proyecto.archivo = sala_doc.salarevisardoc_set.last().archivo_corregir
                # proyecto.save()
        # agregarActividadEquipo('revisar proyecto', equipo)
        if grupo_revisor == 'docente' and sala_doc.tipo == "proyecto":
            suma = 0
            for sala in salas_revisar:
                suma += sala.nota
            proyecto, created = ProyectoDeGrado.objects.get_or_create(equipo=equipo)
            proyecto.nota_informes_trabajo = suma
            proyecto.save()
        sala_doc.visto_bueno = True
        sala_doc.save()
        agregarActividadEquipo(texto_actividad, sala_doc.equipo)
        return redirect('progreso_estudiante', pk=sala_doc.equipo.id)
    registro_perfil, created = RegistroPerfil.objects.get_or_create(
        equipo=sala_doc.equipo)
    registro_proyecto, created = ProyectoDeGrado.objects.get_or_create(
        equipo=sala_doc.equipo)
    context = {'sala_doc': sala_doc,
            'suma_max': suma_max,
            'is_calificacion_todo': is_calificacion_todo,
            'is_cerrado': is_cerrado,
            'registro_perfil': registro_perfil,
            'registro_proyecto': registro_proyecto,
            'grupo': grupo,
            }
    return render(request, 'revisar_documentos/dar_visto_bueno.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['tutor','docente','tribunal'])
def registrarDocumento(request, id_sala_doc):
    sala_doc = get_object_or_404(SalaDocumentoDoc, id=id_sala_doc)
    grupo = request.user.groups.get().name
    equipo = sala_doc.equipo
    if sala_doc.tipo == "perfil":
        perfil = RegistroPerfil.objects.get(equipo=equipo)
        form = RegistroPerfilForm(instance=perfil)
        if request.method == 'POST':
            form = RegistroPerfilForm(request.POST, request.FILES, instance=perfil)
            if form.is_valid():
                form.save()
                if grupo == 'docente':
                    agregarActividadEquipo('registro perfil', equipo)
                return redirect('revisar_documentos:dar_visto_bueno', id_sala_doc=sala_doc.id)
    elif sala_doc.tipo == "proyecto":
        proyecto = ProyectoDeGrado.objects.get(equipo=equipo)
        form = RegistroProyectoDeGradoForm(instance=proyecto)
        if request.method == 'POST':
            form = RegistroProyectoDeGradoForm(request.POST, request.FILES, instance=proyecto)
            if form.is_valid():
                form.save()
                if grupo == 'docente':
                    agregarActividadEquipo('registro proyecto', equipo)
                return redirect('revisar_documentos:dar_visto_bueno', id_sala_doc=sala_doc.id)

    context = {
            'sala_doc': sala_doc,
            'form': form,
            'grupo': grupo,
            }
    return render(request, 'revisar_documentos/registrar_documento.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente',])
def calificarSeminario(request, pk):
    grupo = request.user.groups.get().name
    equipo = get_object_or_404(Equipo, id=pk)
    proyecto, created = ProyectoDeGrado.objects.get_or_create(equipo=equipo)
    nota = proyecto.nota_expos_seminarios
    context = {
        'grupo':grupo,
        'nota': nota,
        'pk':pk,
    }
    return render(request, 'revisar_documentos/calificar_seminario.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente',])
def registrarParticipacionSeminario(request, pk):
    grupo = request.user.groups.get().name
    equipo = get_object_or_404(Equipo, id=pk)
    proyecto, created = ProyectoDeGrado.objects.get_or_create(equipo=equipo)
    nota = proyecto.nota_expos_seminarios
    if nota == 6:
        return redirect('revisar_documentos:calificar_seminario', pk=pk)
    if request.method == 'POST':
        proyecto.nota_expos_seminarios = nota + 2
        proyecto.save()
        return redirect('revisar_documentos:calificar_seminario', pk=pk)
    context = {
        'grupo':grupo,
        'nota': nota,
        'pk':pk,
    }
    return render(request, 'revisar/registrar_seminario.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente',])
def calificarCronograma(request, pk):
    grupo = request.user.groups.get().name
    equipo = get_object_or_404(Equipo, id=pk)
    proyecto, created = ProyectoDeGrado.objects.get_or_create(equipo=equipo)
    nota = proyecto.nota_cumplimiento_cronograma
    context = {
        'grupo':grupo,
        'nota': nota,
        'pk':pk,
    }
    return render(request, 'revisar_documentos/calificar_cronograma.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['docente',])
def registrarCumplimientoCronograma(request, pk):
    grupo = request.user.groups.get().name
    equipo = get_object_or_404(Equipo, id=pk)
    proyecto, created = ProyectoDeGrado.objects.get_or_create(equipo=equipo)
    nota = proyecto.nota_cumplimiento_cronograma
    if nota == 3:
        return redirect('revisar_documentos:calificar_cronograma', pk=pk)
    if request.method == 'POST':
        proyecto.nota_cumplimiento_cronograma = nota + 1
        proyecto.save()
        return redirect('revisar_documentos:calificar_cronograma', pk=pk)
    context = {
        'grupo':grupo,
        'nota': nota,
        'pk':pk,
    }
    return render(request, 'revisar_documentos/registrar_cronograma.html', context)


# 27. 移除元素
# 给你一个数组 nums 和一个值 val，你需要 原地 移除所有数值等于 val 的元素，并返回移除后数组的新长度。

# 不要使用额外的数组空间，你必须仅使用 O(1) 额外空间并 原地 修改输入数组。

# 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

# 来源：力扣（LeetCode）
# 链接：https://leetcode-cn.com/problems/remove-element
# 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

from typing import List

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        fast = slow = 0
        while fast < len(nums):
            if nums[fast] != val:
                nums[slow] = nums[fast]
                slow += 1
            fast += 1
        return slow

class Solution2:
    def removeElement(self, nums: List[int], val: int) -> int:
        left = 0
        right = len(nums)-1
        while left <= right:
            if nums[left] == val:
                nums[left] = nums[right]
                right -= 1
            else:
                left += 1
        return left


from setuptools import setup, find_packages
from glob import glob

def find_scripts(pkgs):
    ret = []
    for pkgname in pkgs:
        ret.extend(glob(pkgname + '/scripts/*.py'))
    return ret

pkgs = find_packages()
scripts = find_scripts(pkgs)

setup(
    name='a107',
    packages=find_packages(),
    include_package_data=True,
    version='21.07.23.0',
    license='GNU GPLv3',
    platforms='any',
    description='A multi-purpose API in Python',
    author='Julio Trevisan',
    author_email='juliotrevisan@gmail.com',
    url='https://github.com/trevisanj/a107',
    keywords= ['debugging', 'introspection', 'file', 'search',
               'conversion', 'datetime', 'config', 'text', 'cryptography'
               ],
    install_requires=["colored", "numpy", "tabulate", "configobj", "python-dateutil"],
    python_requires = '>=3',
    scripts=scripts
)