import subprocess
import wolframalpha
import pyttsx3
import json
import operator
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import pyjokes
import feedparser
import time
import requests
import shutil
from bs4 import BeautifulSoup

class Ben:
    def __init__(self):
        self.engine = pyttsx3.init('sapi5')
        self.voices = self.engine.getProperty('voices')
        self.engine.setProperty('voice', self.voices[1].id)

        self.app_id = "Wolframalpha api id"
        self.client = wolframalpha.Client(self.app_id)

        self.wishMe()
        self.username()

    def speak(audio):
        self.engine.say(audio)
        self.engine.runAndWait()

    def wishMe():
        self.hour = int(datetime.datetime.now().hour)
        if self.hour>= 0 and hour<12:
            speak("Good Morning Sir !")

        elif self.hour>= 12 and hour<18:
            speak("Good Afternoon Sir !")

        else:
            speak("Good Evening Sir !")

        self.ben = "Ben"
        speak("I am your Assistant")
        speak(self.ben)

    def username():
        speak("What should i call you sir")
        self.uname = takeCommand()
        speak("Welcome Mister")
        speak(self.uname)
        self.columns = shutil.get_terminal_size().columns

        print("#####################".center(self.columns))
        print("Welcome Mr.", self.uname.center(self.columns))
        print("#####################".center(self.columns))

        speak("How can I help you, Sir")

    def takeCommand():

        self.r = sr.Recognizer()

        with sr.Microphone() as source:

            print("Listening...")
            self.r.pause_threshold = 1
            audio = self.r.listen(source)

        try:
            print("Recognizing...")
            self.query = self.r.recognize_google(audio, language ='en-in')
            print(f"User said: {self.query}\n")

        except Exception as e:
            print(e)
            print("Unable to Recognize your voice.")
            return "None"

        return self.query

    def main(self):
        self.query = takeCommand().lower()

        if "Ben" in self.query and "wikipedia" in self.query:
            speak('Searching Wikipedia...')
            self.query = self.query.replace("wikipedia", "")
            self.results = wikipedia.summary(self.query, sentences = 3)
            speak("According to Wikipedia")
            print(self.results)
            speak(self.results)

        elif 'Ben' in self.query and "youtube" in self.query:
            speak("Here you go to Youtube\n")
            webbrowser.open("youtube.com")

        elif "Ben" in self.query and "time" in self.query:
            self.strTime = datetime.datetime.now().strftime("% H:% M:% S")
            speak(f"Sir, the time is {self.strTime}")

        elif "Ben" in self.query and "joke" in self.query:
            speak(pyjokes.get_joke())

        elif "Ben" in self.query and "News" in self.query:
            pass
            # not done
            #except Exception as e:
            #    print(str(e))

        elif "Ben where is" in self.query:
            self.query = self.query.replace("where is", "")
            self.location = self.query
            speak("User asked to Locate")
            speak(self.location)
            webbrowser.open("https://www.google.nl / maps / place/" + self.location + "")

        elif "Ben write a note" in self.query:
            speak("What should i write, sir")
            self.note = takeCommand()
            self.file = open('jarvis.txt', 'w')
            speak("Sir, Should i include date and time")
            self.snfm = takeCommand()
            if 'yes' in snfm or 'sure' in snfm:
                self.strTime = datetime.datetime.now().strftime("% H:% M:% S")
                self.file.write(self.strTime)
                self.file.write(" :- ")
                self.file.write(self.note)
            else:
                self.file.write(self.note)

        elif "Ben" in self.query and "show note" in self.query:
            speak("Showing Notes")
            self.file = open("jarvis.txt", "r")
            print(self.file.read())
            speak(self.file.read(6))

        elif "Ben" in self.query and "weather" in self.query:

            # Google Open weather website
            # to get API of Open weather
            api_key = "Api key"
            base_url = "http://api.openweathermap.org / data / 2.5 / weather?"
            speak(" City name ")
            print("City name : ")
            city_name = takeCommand()
            complete_url = base_url + "appid =" + api_key + "&q =" + city_name
            response = requests.get(complete_url)
            x = response.json()

            if x["code"] != "404":
                y = x["main"]
                current_temperature = y["temp"]
                current_pressure = y["pressure"]
                current_humidiy = y["humidity"]
                z = x["weather"]
                weather_description = z[0]["description"]
                print(" Temperature (in kelvin unit) = " +str(current_temperature)+"\n atmospheric pressure (in hPa unit) ="+str(current_pressure) +"\n humidity (in percentage) = " +str(current_humidiy) +"\n description = " +str(weather_description))

            else:
                speak(" City Not Found ")

        elif "send message " in self.query:
                # You need to create an account on Twilio to use this service
                account_sid = 'Account Sid key'
                auth_token = 'Auth token'
                client = Client(account_sid, auth_token)

                message = client.messages \
                                .create(
                                    body = takeCommand(),
                                    from_='Sender No',
                                    to ='Receiver No'
                                )

                print(message.sid)

        elif "i love you" in self.query:
            speak("that's kind of gay not going to lie")

        elif "what is" in self.query or "who is" in self.query:
            self.res = client.self.query(self.query)

            try:
                print (next(self.res.results).text)
                speak (next(self.res.results).text)
            except StopIteration:
                print ("No results")

        elif "Ben calculate" in self.query:
            self.indx = self.query.lower().split().index('calculate')
            self.query = self.query.split()[self.indx + 1:]
            self.res = self.client.self.query(' '.join(self.query))
            self.answer = next(self.res.results).text
            print("The answer is " + self.answer)
            speak("The answer is " + self.answer)


file = open('26-89.txt')
n = int(file.readline())
nums = sorted([int(i) for i in file])
ans = dict()

for i in range(len(nums)):
    last = nums[i]
    count = 1
    for j in range(i + 1, len(nums)):
        if nums[j] - last >= 3:
            last = nums[j]
            count += 1
    if count in ans:
        ans[count].add(nums[i])
    else:
        ans[count] = {nums[i]}
print(max(ans), ans[max(ans)])


import sqlite3
from scrolling import clear

def artistsMainMenu(aid, conn):
    # allows the artist to add songs and find top fans/playlists

    # display options
    print("------Artist Main Menu-------")
    action = input("Enter\n1 add a song\n2 find top fans and playlists\n3 to logout\nAnything else to exit the program\n")

    # do the corresponding action
    if action == '1':
        clear()
        addSong(aid, conn)
        return artistsMainMenu(aid, conn)
    elif action == '2':
        clear()
        displayUsersPlaylists(aid, conn)
        return artistsMainMenu(aid, conn)
    elif action == '3':
        clear()
        print("logged out")
        return '4' # should return to main screen
    else:
        return -1

def displayUsersPlaylists(aid, conn):
    # display top fans and playlists

    # display top three users
    print("------Top Three Users------")
    users = topThreeUsers(aid, conn)
    if users != None:
        for i in range(len(users)):
            print(" | ".join(users[i]))

    # display top three playlists
    print("\n------Top Three Playlists------")
    playlists = topThreePlaylists(aid, conn)
    if playlists!= None:
        for i in range(len(playlists)):
            print(" | ".join(playlists[i]))

    input("press enter to continue")

def topThreeUsers(aid, conn):
    # find top three users

    c = conn.cursor()

    # query for top users
    getTopUsers = f"""
    SELECT u.*
    FROM songs s, listen l, perform p, users u
    WHERE s.sid = l.sid AND s.sid = p.sid
    AND p.aid = ?
    AND l.uid = u.uid
    GROUP BY l.uid
    ORDER BY SUM(s.duration * l.cnt) DESC
    LIMIT 3;
    """

    # execute query and return top users
    c.execute(getTopUsers, (aid,))
    topUsers = c.fetchall()
    return topUsers

def topThreePlaylists(aid, conn):
    # find top three playlists

    c = conn.cursor()

    # query for top playlists
    getTopPlaylists = f"""
    SELECT p.*
    FROM plinclude pl, perform pr, playlists p
    WHERE pl.sid = pr.sid AND p.pid = pl.pid
    AND pr.aid = ?
    GROUP BY pl.pid
    ORDER BY COUNT(pl.sid) DESC
    LIMIT 3
    """

    # execute query and return top playlists
    c.execute(getTopPlaylists, (aid,))
    topPlaylists = c.fetchall()
    topPlaylists = [list(i) for i in topPlaylists]
    topPlaylists = [[str(i[0])] + i[1:] for i in topPlaylists]
    return topPlaylists

def addSong(aid, conn):
    # add new song

    c = conn.cursor()
    print("------Add a new song------")

    # get song title and validate
    title = input("Enter the title of the song: ")
    if title == "":
        print("ERROR: title cannot be empty")
        input("press enter to continue")
        return

    # get duration and validate
    try:
        duration = int(input("Enter the duration: "))
    except:
        print("ERROR: duration must be an integer")
        input("press enter to continue")
        return

    # prompt the user to add or reject new song if title and duration are the same
    if not isNewSong(aid, title, duration, conn):
        print("Song with the same title and duration already exists")
        choice = input("Enter\n1 to proceed with adding the song\nAnything else to reject it\n")
        if choice!= '1':
            return

    # get any additional aids and check that aids do not conflict
    ids = [aid] + input("Enter the aids of any additional artists separated by spaces: ").split()
    if aid in ids[1:]:
        print("ERROR: cannot use own aid as additional aid")
        input("press enter to continue")
        return

    # Add new song into songs table
    sid = getUniqueSid(conn)

    insertSong = f"""
    INSERT INTO songs
    VALUES (?, ?, ?);
    """

    c.execute(insertSong, (sid, title, duration))

    # check that all aids are valid
    if False in [isValidAid(i, conn) for i in ids]:
        print("ERROR: you must enter valid aids")
        addPerformer(ids[0], sid, conn)
        input("press enter to continue")
        return

    # insert all aids into perform table
    for id in ids:
        addPerformer(id, sid, conn)

    conn.commit()
    input("press enter to continue")

def addPerformer(aid, sid, conn):
    # add new entry into perfrom table

    c = conn.cursor()
    insertPerform = f"""
    INSERT INTO perform
    VALUES (?, ?);
    """
    c.execute(insertPerform, (aid, sid))
    conn.commit()

def isValidAid(aid, conn):
    # check that any given aid is in the database

    c = conn.cursor()
    getArtist = f"""
    SELECT *
    FROM artists
    WHERE aid = ?;
    """

    c.execute(getArtist, (aid,))
    return bool(c.fetchone())

def getUniqueSid(conn):
    # get a unique sid different from all the ones in the database

    c = conn.cursor()
    sidQuery = """
    SELECT sid
    FROM songs
    """

    c.execute(sidQuery)
    sids = c.fetchall()
    if sids == []:
        return 1
    return max([i[0] for i in sids]) + 1

def isNewSong(aid, title, duration, conn):
    # check that any given song does not exist in the database

    c = conn.cursor()
    songQuery = f"""
    SELECT *
    FROM artists a, songs s, perform p
    WHERE a.aid = p.aid AND s.sid = p.sid
    AND title = ? AND duration = ?
    AND a.aid = ?;
    """

    c.execute(songQuery, (title, duration, aid))
    return not bool(c.fetchone())

if __name__ == "__main__":
    #db = sqlite3.connect("./new.db")
    #topThreePlaylists("a10", sqlite3.connect("./a2.db"))
    #print(isNewSong("a1", "Applause", 212, sqlite3.connect("./a2.db")))
    #print(type(getAllSids(sqlite3.connect("./new.db"))[0]))
    #print(isValidAid("a10", sqlite3.connect("./new.db")))
    #addSong("a10", sqlite3.connect("./new.db"))
    artistsMainMenu("a10", sqlite3.connect("./new.db"))
    #print(getUniqueSid(sqlite3.connect("./new.db")))
    pass


import requests
from bs4 import BeautifulSoup as BS
import codecs
import time

# session = requests.Session()
# headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:47.0) Gecko/20100101 Firefox/47.0','Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'}
url = 'http://top.bigmir.net/report/16936420/'
# resp = session.get(url, headers=headers)

data = ''
handle = codecs.open('bigmir_.html','r', 'utf-8')
data = handle.read()
handle.close()
stat = {}
stat['bigmir'] = {}
stat['bigmir']['xls_url'] = url + '?ver=&format=xls'
if True: # resp.status_code == 200:
    # bsObj = BS(resp.content, "html.parser")
    bsObj = BS(data, "html.parser")
    tables = bsObj.find_all('table', attrs={'class':'small'})
    general_stat = tables[0]
    detail_stat = tables[1]
    raw_data = general_stat.find_all('tr')
    general = []
    for tr in raw_data:
        value = tr.find('td', attrs={'class':'text_right'}).text.replace('\n', '').strip()
        title = tr.find('td', attrs={'class':'large'}).text.replace('\n', '').strip()
        general.append({'title': title, 'value': value})
    stat['bigmir']['general'] = general
    detail = []
    raw_data = detail_stat.find_all('tr')
    size = len(raw_data)
    for i in range(1, size):
        tr = raw_data[i]
        v = tr.find_all('td', attrs={'class': False})
        # print(v)
        title = tr.find('td', attrs={'class':'large'}).text.replace('\n', '').strip()
        values = {}
        values['today'] = v[0].text.replace('\n', '').strip()
        if i < size - 1:
            values['1_day_ago'] = v[1].text.replace('\n', '').strip()
            values['2_days_ago'] = v[2].text.replace('\n', '').strip()
            values['7_days_ago'] = v[3].text.replace('\n', '').strip()
            values['30_days_ago'] = v[4].text.replace('\n', '').strip()
        detail.append({'title': title, 'values': values})
    stat['bigmir']['detail'] = detail

# data = bsObj.prettify()#.encode('utf8')
handle = codecs.open('bigmir_stat.txt', "w", 'utf-8')
handle.write(str(stat))
handle.close()
# data = str(groups)
# handle = codecs.open('bigmir_groups.txt', "w", 'utf-8')
# handle.write(str(data))
# handle.close()


import shutil

from sentence_transformers import SentenceTransformer, InputExample, losses, evaluation, \
    LoggingHandler
from torch.utils.data import DataLoader
import torch
import random

import math

import sys
import numpy as np

from myDataset import *
from src.utils import KNNOverGenBatchBleuEvaluator

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

logging.basicConfig(format='%(asctime)s - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    level=logging.INFO,
                    handlers=[LoggingHandler()])
logger = logging.getLogger(__name__)

import torch

# Set random seed.
seed = 42

torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)

def process_data(path, overgen_score_path, greedy_score_path, context_window=3):
    f = open(path)
    dataset = json.load(f)
    f.close()

    f = open(overgen_score_path)
    scores = json.load(f)
    f.close()

    f = open(greedy_score_path)
    greedy_scores = json.load(f)
    f.close()

    assert len(scores) == len(dataset)
    assert len(dataset[0]["over_gen"]) == len(scores[0])

    lex_delex_utt_map = load_damd_lex_delex_map()

    data_samples = []

    for entry, score, greedy_score in zip(dataset[:], scores[:],
                                        greedy_scores[:]):

        gold_delex = entry["resp_text"]
        over_gen_list_delex = entry["over_gen"]
        context_lex = entry["context_text"]

        context_delex = list(map(lambda x: lex_delex_utt_map[x], context_lex))
        sentc = str(" <turn_sep> ".join(context_delex[0 if context_window is None else -context_window:]))
        sentr = gold_delex
        sentn_list = list(map(lambda x: x.replace(" <eos_r>", ""), over_gen_list_delex))

        positive_list = []
        negative_list = []

        for i in range(len(sentn_list)):
            if (score[i] >= greedy_score):
                positive_list.append(InputExample(texts=[sentc + " <turn_sep> " + sentn_list[i]], label=1))
            else:
                negative_list.append(InputExample(texts=[sentc + " <turn_sep> " + sentn_list[i]], label=0))
        num_to_added = min(len(positive_list), len(negative_list))

        data_samples.extend(positive_list[:num_to_added])
        data_samples.extend(negative_list[:num_to_added])

    return data_samples

def process_anchors(path, overgen_score_path, greedy_score_path, context_window=3, num_of_anchors=1000):
    f = open(path)
    dataset = json.load(f)
    f.close()

    f = open(overgen_score_path)
    scores = json.load(f)
    f.close()

    greedy_score_path = greedy_score_path
    f = open(greedy_score_path)
    greedy_scores = json.load(f)
    f.close()

    assert len(scores) == len(dataset)
    assert len(dataset[0]["over_gen"]) == len(scores[0])

    assert len(dataset) > num_of_anchors

    lex_delex_utt_map = load_damd_lex_delex_map()

    anchor_samples = []

    for entry, score, greedy_score in zip(dataset[-num_of_anchors:], scores[-num_of_anchors:],
                                        greedy_scores[-num_of_anchors:]):

        gold_delex = entry["resp_text"]
        over_gen_list_delex = entry["over_gen"]
        context_lex = entry["context_text"]

        context_delex = list(map(lambda x: lex_delex_utt_map[x], context_lex))
        sentc = str(" <turn_sep> ".join(context_delex[0 if context_window is None else -context_window:]))
        sentr = gold_delex
        sentn_list = list(map(lambda x: x.replace(" <eos_r>", ""), over_gen_list_delex))

        positive_list = []
        negative_list = []

        for i in range(len(sentn_list)):
            if (score[i] >= greedy_score):
                positive_list.append((sentc + " <turn_sep> " + sentn_list[i], 1))
            else:
                negative_list.append((sentc + " <turn_sep> " + sentn_list[i], 0))
        num_to_added = min(len(positive_list), len(negative_list))

        anchor_samples.extend(positive_list[:num_to_added])
        anchor_samples.extend(negative_list[:num_to_added])

    return anchor_samples

'''
Main function here
'''

def run_experiment():

    context_window = 3

    knn_k = [500, 1000, 5000]

    num_of_anchors = [5000, 10000]

    anchor_sample_list = []

    batch_size = 128

    train_samples = process_data(path="./data/0.7_train.json",
                                 overgen_score_path="./data/sim_score_mpnet_train_0.7.json",
                                 greedy_score_path="./data/sim_score_mpnet_train_0.7_greedy.json",
                                 context_window=context_window)

    assert len(train_samples) > 0

    for num_anchor in num_of_anchors:
        anchor_samples = process_anchors(path="./data/0.7_train.json",
                                         overgen_score_path="./data/sim_score_mpnet_train_0.7.json",
                                         greedy_score_path="./data/sim_score_mpnet_train_0.7_greedy.json",
                                          context_window=context_window, num_of_anchors=num_anchor)

        assert len(anchor_samples) > 0
        anchor_sample_list.append((num_anchor, anchor_samples))

    init_model_path = "./output/selection-bert-base-uncased-mintl-ct3-e3-bs64-20_sysonly_delex/"

    epochs = 5
    note = "0.7_mpnet"

    model = SentenceTransformer(init_model_path)
    model.max_seq_length = 128

    # Adding the special tokens.
    word_embedding_model = model._first_module()
    special_tokens = Vocab().special_tokens
    word_embedding_model.tokenizer.add_tokens(special_tokens, special_tokens=True)
    word_embedding_model.auto_model.resize_token_embeddings(len(word_embedding_model.tokenizer))

    train_loss = losses.BatchAllTripletLoss(model=model)

    train_dataloader = DataLoader(train_samples, shuffle=True, batch_size=batch_size)

    all_evaluator_list = []
    for anchor_num, anchor_sample in anchor_sample_list:
        evaluator_test = KNNOverGenBatchBleuEvaluator(data_path="./data/0.7_test.json", context_window=context_window,
                                                     anchor_samples=anchor_sample,
                                                     knn_k=knn_k, num_of_anchors=anchor_num)

        all_evaluator_list.append(evaluator_test)
        evaluator_dev = KNNOverGenBatchBleuEvaluator(data_path="./data/0.7_dev.json", context_window=context_window,
                                                     anchor_samples=anchor_sample,
                                                     knn_k=knn_k, num_of_anchors=anchor_num)

        all_evaluator_list.append(evaluator_dev)

    evaluator = evaluation.SequentialEvaluator(all_evaluator_list, main_score_function=lambda scores: np.max(scores))

    warmup_steps = math.ceil(len(train_dataloader) * epochs / batch_size * 0.1)

    loss_str = train_loss.__str__()
    loss_str = loss_str[:loss_str.index("(")]
    output_path = "./output/similarity-mintl-" + "ct-" + str(context_window) + "-" + loss_str \
                  + "-e" + str(epochs) + "-bs" + str(batch_size) + "-seed" + str(seed) + "-" + note + "/"

    model.fit(train_objectives=[(train_dataloader, train_loss)], epochs=epochs, evaluator=evaluator,
              warmup_steps=warmup_steps, output_path=output_path)

    shutil.copyfile(sys.argv[0], output_path + "/code.py")

def main():
    run_experiment()

if __name__ == '__main__':
    main()


from PIL import Image, ImageDraw, ImageFont
import random

def plural(action):
    if len(action.split()) > 1:
        return ' '.join([f"{action.split()[0]}s", action.split()[1]])
    else:
        return f"{action}s"

def random_phrase() -> list:
    nouns = open("nouns.txt", "r").readlines()
    actions = open("actions.txt", "r").readlines()

    ret = f"When the {random.choice(nouns)[:-1]} {plural(random.choice(actions)[:-1])} you"

    return [[(0, 0), ret]]

def random_nouns(count, x, spacing) -> list:
    nouns = open("nouns.txt", "r").readlines()

    return [[(x, spacing * i), random.choice(nouns)] for i in range(count)]

def generate_meme(meme) -> list:
    verb = random.choice(open('verbs.txt', 'r').readlines())[:-1]
    noun = random.choice(open('nouns.txt', 'r').readlines())[:-1]
    noun2 = random.choice(open('nouns.txt', 'r').readlines())[:-1]
    action = random.choice(open('actions.txt', 'r').readlines())[:-1]
    noun3 = random.choice(open('nouns.txt', 'r').readlines())[:-1]
    adjective = random.choice(open('adjs.txt', 'r').readlines())[:-1]

    texts = {
        "peace": random_phrase(),
        "uno": [[(100, 150), f"{verb} {noun}s"], [(300, 20), f"{noun2}s"]],
        "incredible": [[(50, 150), f"Me when I {action} the {noun}"], [(600, 150), f"It's {adjective}"]],
        "joey": [[(0, 0), f"Me when I {action} the {noun}"]],
        "crying": [[(0, 0), f"Me when I {action} the {adjective} {noun}"]],
        "monkey": [[(0, 0), f"Me when I {action} the {noun}"]]
    }

    return texts[meme]

def main():
    meme = random.choice(["peace", "uno", "incredible", "joey", "crying", "monkey"])
    caption = generate_meme(meme)

    img = Image.open(f"formats/{meme}.png")
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype('impact.ttf', size=24)
    print(caption)

    for l in caption:
        print(l[0])
        draw.text((l[0][0] - 1, l[0][1] - 1), l[1], 'black', font)
        draw.text((l[0][0] + 1, l[0][1] - 1), l[1], 'black', font)
        draw.text((l[0][0] - 1, l[0][1] + 1), l[1], 'black', font)
        draw.text((l[0][0] + 1, l[0][1] + 1), l[1], 'black', font)

        draw.text(l[0], l[1], 'white', font)

    img.save('out.png')

    with open("caption", "w") as f:
        for i in caption:
            f.write(i[1])
            f.write('.\n')

if __name__ == '__main__':
    main()


from django.urls import path, re_path, include

from .ajax_util import get_all_ajax_functions
from .views import (
    get_boxes_codes,
    get_clerk_codes,
    get_counter_commands,
    checkout_view,
    overseer_view,
    vendor_view,
    accept_terms,
    get_items,
    all_to_print,
    item_add,
    item_hide,
    item_to_printed,
    item_to_not_printed,
    item_update_name,
    item_update_type,
    item_update_price,
    remove_item_from_receipt,
    get_boxes,
    box_add,
    box_content,
    box_hide,
    box_print,
    stats_view,
    type_stats_view,
    statistical_stats_view,
    lost_and_found_list,
    adjust_box_size,
)
from .views import access_signup
from .views import accounting
from .views import event_management
from .views.frontpage import front_page
from .checkout_api import checkout_js
from .views.mobile import index as mobile_index, logout as mobile_logout
from .views.vendors import change_vendor, create_vendor
from .views.item_dump import dump_items_view

app_name = "kirppu"

event_urls = [
    path(r'accounting/', accounting.accounting_receipt_view, name="accounting"),
    path(r'accounting/live', accounting.live_accounts, name="live_accounts"),
    path(r'itemdump/', dump_items_view, name="item_dump"),
    path(r'clerks/', get_clerk_codes, name='clerks'),
    path(r'boxes/', get_boxes_codes, name="box_codes"),
    path(r'checkout/', checkout_view, name='checkout_view'),
    path(r'overseer/', overseer_view, name='overseer_view'),
    path(r'stats/', stats_view, name='stats_view'),
    path(r'stats/type/<str:type_id>', type_stats_view, name='type_stats_view'),
    path(r'stats/statistical/', statistical_stats_view, name='statistical_stats_view'),
    path(r'', vendor_view, name='vendor_view'),
    path(r'vendor/', vendor_view),
    path(r'vendor/accept_terms', accept_terms, name='accept_terms'),
    path(r'vendor/items/', get_items, name='page'),
    path(r'vendor/items/move_to_print', all_to_print, name='all_to_print'),
    path(r'vendor/item/', item_add, name='item_add'),
    path(r'vendor/item/<str:code>/to_printed', item_to_printed, name='item_to_printed'),
    path(r'vendor/item/<str:code>/price', item_update_price, name='item_update_price'),
    path(r'vendor/item/<str:code>/name', item_update_name, name='item_update_name'),
    path(r'vendor/item/<str:code>/type', item_update_type, name='item_update_type'),
    path(r'vendor/item/<str:code>/to_not_printed', item_to_not_printed, name='item_to_not_printed'),
    path(r'vendor/item/<str:code>/hide', item_hide, name='item_hide'),
    path(r'remove_item', remove_item_from_receipt, name='remove_item_from_receipt'),
    path(r'lost_and_found/', lost_and_found_list, name='lost_and_found'),
    path(r'vendor/boxes/', get_boxes, name='vendor_boxes'),
    path(r'vendor/box/', box_add, name='box_add'),
    path(r'vendor/box/<str:box_id>/content', box_content, name='box_content'),
    path(r'vendor/box/<str:box_id>/hide', box_hide, name='box_hide'),
    path(r'vendor/box/<str:box_id>/print', box_print, name='box_print'),

    path(r'vendor/status/', mobile_index, name='mobile'),
    path(r'vendor/status/logout/', mobile_logout, name='mobile_logout'),

    path('vendor/change', change_vendor, name="change_vendor"),
    path('vendor/create', create_vendor, name="create_vendor"),

    path('api/checkout.js', checkout_js, name='checkout_js'),
    path(r'commands/', get_counter_commands, name='commands'),

    path('manage/', event_management.index, name='manage_event'),
    path('manage/people', event_management.PeopleManagement.as_view(), name='people_manage'),

    path('signup', access_signup.signup, name='signup'),

    path("adjust_box", adjust_box_size, name="adjust_box_size"),
]

common_urls = [
    path(r'', front_page, name="front_page"),
]

event_urls.extend([
    re_path(func.url, func.func, name=func.view_name)
    for _, func in get_all_ajax_functions()
])

urlpatterns = [path(r'<slug:event_slug>/', include(event_urls))] + common_urls


import maya
from maya import cmds as mc
import pymel.core as pm

from .. import utils

## ----------------------------------------------------------------------
'''

	MODULE_BASE.PY

	Base class for all rig modules.  If you know C++, consider this a
	virtual class with functions that need to be overridden in order to
	instantiate and build rig parts.

	The following are the main functions you might want to override:

	build():	The least you need to do is to override the build() method.  This
				is where you'll do the bulk of the module's setup.

	calculateDefaults():	When setting params for the first time, this allows you
							to specify the default values of the params based on the
							chain being tagged.

	createParams():	Used to specify rig parameters, settings that change how the
					rig is built.

	postbuild(): 	This is run by automatedBuild after all modules are complete,
					making it easier to connect modules together that need to rely
					on each other.  This function can assume that build() ran
					successfully.

	seamGoal():		Used to perform connections between modules when you've specified
					a parent for the IK Goal of the current module in another.

	seamRoot():		Used to perform connections between modules when you've specified
					a parent for the root of the current module in another.

	validate():		If your module requires certain pre-conditions be extant before
					build can run, you can check for those conditions here.

'''

## ----------------------------------------------------------------------

class ModuleBaseException(Exception):
	pass

## constants
PARAM_PREFIX = 'WT'

## ----------------------------------------------------------------------

class ModuleBase(object):
	_defaultToken = 'MODULEBASE'
	_module_type = 'ModuleBase'
	_minChainLength = 0
	_maxChainLength = 0
	_defaultControllerColor = utils.colors.indexForColor('green')
	_defaultControllerSubColor = utils.colors.indexForColor('yellow')
	_defaultControllerType = 'box'
	_defaultRotationOrder = 'zxy'
	_isIkFk = False
	_usesRoot = True		## this is turned off for special modules, like GOD
	_usesGoal = False

	## ----------------------------------------------------------------------
	## python-y methods
	def __init__(self, *args):
		self._message = None

		## different types of controls with their own Param collections
		self._controllerCategories = []

		## these are targets for constraints
		self._inputs = {}

		## these are automatically populated if the module author uses
		## the createControl function in the module and not in utils
		## these are sorted into list bins by category, IE, self._controlers['fk']
		self._controllers = {}
		self._controllerZeros = {}

		self.module = self.rig = self.controls = self.extras = None

		## grab the chain
		oblist = utils.makeList(args, type='joint')
		if not len(oblist):
			raise ModuleBaseException('Tried to create module instance without a chain of joints.')
		self.chain = utils.getChain(oblist[0])

		self.segmentScaleCompensateDisable( self.chain )

		self.rigRoot = utils.addRigRoot( self.chain[0] )

		## this has to happen before defaults and params creation
		self.calculateSide()

		self.calculateDefaults()
		self.createParams()

		##!FIXME: If the module already exists, pull info from the extant nodes
		## If it doesn't exist, create the base parts

	def __str__(self):
		joints = 's' if self.chainLength > 1 else ''
		return("<< Witch Rig Module Instance: %s (%d joint%s)." % (self.__class__, self.chainLength, joints) )

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

	def __getitem__(self, key):
		## This returns None if the lookup fails
		## Is that the right decision?
		result = self.getParam(key)
		return(result)

	def __setitem__(self, key, value):
		## if the parameter was already created in createParams, then you can set it
		## otherwise, kick up an error
		if self.hasAttr(PARAM_PREFIX+"_"+key):
			self.setParam(key, value)
		else:
			raise ValueError("ModuleBase: param '%s' does not exist -- cannot set." % key)

	def getControl(self, category, index):
		return(self._controllers[category][index])

	def getZero(self, category, index):
		return(self._controllerZeros[category][index])

	def numControls(self, category):
		if category in self._controllers.keys():
			return(len(self._controllers[category]))
		else:
			return(0)

	## ----------------------------------------------------------------------
	## "virtual" methods
	def build(self, **kwargs):
		raise ModuleBaseException('Invalid subclass-- build() virtual function not implemented.')

	def calculateDefaults(self):
		## Calculate default colors here if necessary.
		## This is an example; they're set above in the class variables.
		#self._defaultControllerColor = 6
		#self._defaultControllerSubColor = 9

		## default controller types
		self.registerControllerCategory('fk')
		if self._isIkFk:
			self.registerControllerCategory('ik')

	def createParams(self):
		defaultParams = [
			{ 'name':'type', 'type':'string', 'value':self._module_type },
			{ 'name':'token', 'type':'string', 'value':self._defaultToken },
			{ 'name':'hideModule', 'type':'bool', 'value':False },
		]

		## This is the simplest way to identify rig module chain roots in the scene
		## without doing something like adding a custom locator shape: add a special
		## attribute to it, and sort by that attribute
		if not self.root.hasAttr('MODULEROOT'):
			self.root.addAttr('MODULEROOT', at='bool', dv=True, k=True)
			self.root.MODULEROOT.lock()

		for param in defaultParams:
			name = param.pop('name')
			self.setParam(name, preserveValue=True, **param)

		self.createControllerParams()

	def postbuild(self):
		## default: no postbuild
		pass

	def seamGoal(self):
		goalParent = utils.getParentAttr(self.root, 'goal')
		if goalParent is not None and self['goalInput'] is not None:
			##!FIXME: 	offer other types of constraining apart from parent / scale?
			##			This could mean that the constraint listing below wouldn't
			##			work if the constraint were more exotic

			## clean out prior constraints
			oldCnsts = self['goalInput'].getChildren(type='constraint')
			for item in oldCnsts:
				pm.delete(item)

			self.constrain(goalParent, self['goalInput'], mo=True, type='parent')
			self.constrain(goalParent, self['goalInput'], mo=True, type='scale')

	def seamRoot(self):
		rootParent = utils.getParentAttr(self.root, 'root')
		if rootParent is not None and self['rootInput'] is not None:
			##!FIXME: 	Offer other types of constraining apart from parent / scale?
			##			This could mean that the constraint listing below wouldn't
			##			work if the constraint were more exotic, and I'll have to
			##			keep track of constraint nodes

			## clean out prior constraints
			oldCnsts = self['rootInput'].getChildren(type='constraint')
			for item in oldCnsts:
				pm.delete(item)

			self.constrain(rootParent, self['rootInput'], mo=True, type='parent')
			self.constrain(rootParent, self['rootInput'], mo=True, type='scale')

	def validate(self):
		if not self._minChainLength == 0 and self.chainLength < self._minChainLength:
			self._message = 'Chain is shorter than min chain length (found %d; requires %d).' % (self.chainLength, self._minChainLength)
			return(False)

		if not self._maxChainLength == 0 and self.chainLength > self._maxChainLength:
			self._message = 'Chain is longer than max chain length (found %d; requires %d).' % (self.chainLength, self._maxChainLength)
			return(False)

		return( True )

	## ----------------------------------------------------------------------
	## properties
	@property ## readonly
	def debug(self):
		## Blake Stone, anyone? God I'm old.
		result = True if mc.optionVar(q='DEBUGLEVEL1') else False
		return(result)

	@property ## readonly
	def chainLength(self):
		return len(self.chain)

	@property ## readonly
	def root(self):
		if self.chainLength:
			return(self.chain[0])
		else:
			return(None)

	## ----------------------------------------------------------------------
	## utility functions
	def addModuleAttr(self, *args):
		if self.module is None:
			raise ModuleBaseException('Module is not created.')

		oblist = utils.makeList(args)
		for ob in oblist:
			if not ob.hasAttr('module'):
				ob.addAttr('module', at='message')
			self.module.message >> ob.module

	def calculateSide(self):
		if self.root is None:
			raise ModuleBaseException('calculateSide: no root joint.')

		side = self.getParam('side', None) or utils.determineSide(self.root)
		data = { 'type':'enum', 'enumName':'cn:lf:rt','value':side }
		self.setParam('side', **data)

	def connectChains(self, *args, **kwargs):
		## pass in the roots to connect
		## arguments to args are expected to be lists or tuples

		chains = []
		for arg in args:
			if isinstance(arg, list) or isinstance(arg, tuple):
				chains.append(utils.makeList(arg))
				root = chains[-1][0].getParent()
				if not root.type() == 'transform' or not root.endswith('_rigRoot'):
					raise ModuleBaseException('connectChains: Passed in chain has no rig root.')
			else:
				raise ModuleBaseException('connectChains: Only lists of joints may be passed in.')

		if len(chains) < 2:
			raise ModuleBaseException('connectChains: need at least two chain roots.')

		targetChain = chains.pop(-1)

		if len(chains) == 1:
			## direct connection
			for source, target in zip(chains[0], targetChain ):
				for attr in 'translate','rotate','scale':
					for axis in 'XYZ':
						source.attr(attr+axis) >> target.attr(attr+axis)

			## because we checked earlier the rigRoots should be present at this point
			sourceRoot = chains[0][0].getParent()
			targetRoot = targetChain[0].getParent()

			pm.parentConstraint(sourceRoot, targetRoot, mo=True)
			pm.scaleConstraint(sourceRoot, targetRoot, mo=True)

		else:
			raise NotImplementedError("Multiple chains aren't finished yet, sorry.")

	def constrain(self, *args, **kwargs):
		cType = kwargs.pop('type', None)

		## I want to be able to provide more than the standard Maya constraints in the
		## at some point, while also offering the module creator the ease of use of specifying
		## names through these strings if the system is ported to another DCC in the future.
		validConstraints = ['point','orient','pointorient','parent','normal','axis','scale']

		if not cType in validConstraints:
			raise ValueError('constraint type invalid -- must be one of ' ', '.join(validConstraints) + '.')

		oblist = utils.makeList(args)

		results = []
		if cType == 'point' or cType == 'pointorient':
			results.append( pm.pointConstraint(*oblist, **kwargs) )
		elif  cType == 'orient' or cType == 'pointorient':
			results.append( pm.orientConstraint(*oblist, **kwargs) )
		elif cType == 'parent':
			results.append( pm.parentConstraint(*oblist, **kwargs) )
		elif cType == 'scale':
			results.append( pm.scaleConstraint(*oblist, **kwargs) )
		else:
			raise NotImplementedError('Constraint type not yet implemented.')

		if len(results) == 1:
			return(results[0])
		else:
			return(results)

	def createControl(self, category, name, target=None, constrain=None, **kwargs):
		data = self.loadControllerParams(category)

		data['name'] = self['token']+"__"+name+"_#s_#d_CON"

		zero, con = utils.createControl(target, **data)[0]
		pm.parent(zero, self.controls)

		if constrain is not None and target is not None:
			if not (isinstance(constrain, tuple) or isinstance(constrain, list)):
				constrain = [constrain]
			for cType in constrain:
				self.constrain(con, target, type=cType, mo=True)

		self._controllers[category].append(con)
		self._controllerZeros[category].append(zero)

		## this is for introspection
		utils.setAttrSpecial(con, 'con_index', len(self._controllers[category])-1 , channelBox=False)

		##!FIXME: setAttrSpecial's channelBox flag
		con.con_index.set(k=False, cb=False)
		con.con_index.lock()

		return(con)

	def createControllerParams(self):
		for controlType in self._controllerCategories:
			params = [
				{ 'name':'%sControllerType' % controlType, 'type':'string', 'value':self._defaultControllerType, },
				{ 'name':'%sControllerColor' % controlType, 'type':'enum', 'enumName':utils.colors.enumNames(), 'value':self._defaultControllerColor, },
				{ 'name':'%sControllerAddSub' % controlType, 'type':'bool', 'value':False, },
				{ 'name':'%sControllerSubColor' % controlType, 'type':'enum', 'enumName':utils.colors.enumNames(), 'value':self._defaultControllerSubColor, },
				{ 'name':'%sControllerScale' % controlType, 'type':'float', 'value':1.0, 'min':0.1 },
				{ 'name':'%sControllerSubScale' % controlType, 'type':'float', 'value':0.9, 'min':0.1 },
				{ 'name':'%sControllerTranslation' % controlType, 'type':'float3', 'value':(0,0,0) },
				{ 'name':'%sControllerRotation' % controlType, 'type':'float3', 'value':(0,0,0) },
				{ 'name':'%sControllerRotateOrder' % controlType, 'type':'enum', 'enumName':'xyz:yzx:zxy:xzy:yxz:zyx', 'value':self._defaultRotationOrder },
				{ 'name':'%sControllerAim' % controlType, 'type':'enum', 'enumName':'x:y:z:-x:-y:-z', 'value':'x' },
				{ 'name':'%sControllerUp' % controlType, 'type':'enum', 'enumName':'x:y:z:-x:-y:-z', 'value':'y' },
			]

			for param in params:
				name = param.pop('name')
				self.setParam(name, preserveValue=True, **param)

	def createModule(self):
		moduleName = self.makeName('#t_#s_MODULE', upper=True)
		if pm.objExists(moduleName):
			raise ModuleBaseException('Cannot create module %s: already exists.' % moduleName)

		self.module = pm.createNode('transform', name=moduleName)
		utils.snap(self.module, self.root)
		self.module.addAttr('nodes', at='float', multi=True)

		for groupName in 'controls','rig','extras':
			group = pm.createNode( 'transform', name='_'.join([moduleName, groupName]) )
			utils.snap(group, self.module)
			pm.parent(group, self.module)

		controls, rig, extras = self.module.getChildren()
		self.controls = controls
		self.rig = rig
		self.extras = extras

		self.extras.inheritsTransform.set(0)

		## addModuleAttr adds a message connection to each node in the module
		## this way, you can find the module from any node which belongs to it
		self.addModuleAttr(self.chain)
		self.addModuleAttr(self.controls, self.rig, self.extras)

		## moduleConnect goes the opposite direction: all nodes have a
		## connection to the module's nodes attribute so that all
		## required nodes can be found for removal and rebuilds

		self.moduleConnect(self.controls, self.rig, self.extras)

		## for all other introspection, setAttrSpecial does message
		## connections.  Here we're not using a prefix.
		utils.setAttrSpecial(self.module, 'controls', self.controls)
		utils.setAttrSpecial(self.module, 'rig', self.rig)
		utils.setAttrSpecial(self.module, 'extras', self.extras)
		utils.setAttrSpecial(self.module, 'chain', self.chain, multi=True)

		for item in self.rig, self.extras:
			item.v.set(0)

		## create default inputs
		## in mose cases you won't need more than this, but
		## the machinery is there for adding extras as needed
		if self._usesRoot:
			self.registerInput('root')
		if self._usesGoal:
			self.registerInput('goal')

	def createJoint(self, name, target=None):
		name = utils.makeName(name)
		joint = pm.createNode('joint', name=name)
		if target is not None:
			utils.snap(joint, target)
		return( joint )

	def createRigChain(self, prefix='RIG', radius=1.0):
		if self.chain is None or len(self.chain) == 0:
			## probably don't need this error check at this point, but ...
			raise ModuleBaseException('createRigChain: no source chain.')

		radius = 0.01 if radius < 0.01 else radius

		rigChain = []
		for item in self.chain:
			name = '_'.join([prefix, str(item)])
			joint = self.createJoint(name, item)
			if len(rigChain):
				pm.parent(joint, rigChain[-1])
			joint.radius.set(radius)
			rigChain.append(joint)

		rigChainRoot = utils.addRigRoot(rigChain[0])
		pm.parent(rigChainRoot, self.rig)

		pm.makeIdentity(rigChain, a=True, r=True, s=True)

		self.segmentScaleCompensateDisable( rigChain )

		return(rigChain)

	def getParam(self, param, defaultValue=None):
		result = utils.getAttrSpecial(self.root, param, defaultValue, prefix=PARAM_PREFIX)
		return(result)

	def loadControllerParams(self, category):
		data = {
			'type': 		self.getParam('%sControllerType' % category),
			'color': 		self.getParam('%sControllerColor' % category),
			'subColor': 	self.getParam('%sControllerSubColor' % category),
			'scale': 		self.getParam('%sControllerScale' % category),
			'subScale': 	self.getParam('%sControllerSubScale' % category),
			'aim': 			self.getParam('%sControllerAim' % category),
			'up': 			self.getParam('%sControllerUp' % category),
			'rotateOrder': 	self.getParam('%sControllerRotateOrder' % category),
			'translation': 	self.getParam('%sControllerTranslation' % category),
			'rotation': 	self.getParam('%sControllerRotation' % category),
		}

		return(data)

	def makeName(self, name, **kwargs):
		result = utils.makeName(name, token=self['token'], side=self['side'], **kwargs)
		return(result)

	def moduleConnect(self, *args):
		utils.setAttrSpecial( self.module, 'nodes', args, multi=True, append=True )

	def popState(self):
		pass

	def pushState(self):
		pass

	def registerControllerCategory(self, key):
		self._controllerCategories.append(key)
		self._controllers[key] = []
		self._controllerZeros[key] = []

	def registerInput(self, key):
		key = key.lower()
		group = pm.createNode('transform', name=self.makeName("#t_"+key+"_#s_#d_INPUT", upper=True))
		utils.snap(group, self.module)
		pm.parent(group, self.module)
		utils.addZero(group)
		self._inputs[key] = group

		## allow the input to be picked up in the same
		## manner as the other module params

		self.setParam(key+"Input", group)

		## root is a special input
		## when registered, set it up to move the controls group
		if key == 'root':
			self.constrain(group, self.controls, type='parent', mo=True)
			self.constrain(group, self.controls, type='scale', mo=True)

	def segmentScaleCompensateDisable(self, *args):
		oblist = utils.makeList(args, type='joint')
		for item in oblist:
			item.segmentScaleCompensate.set(False)

	def segmentScaleCompensateEnable(self, *args):
		oblist = utils.makeList(args, type='joint')
		for item in oblist:
			item.segmentScaleCompensate.set(True)

	def setParam(self, param, value, **kwargs):
		if self.debug:
			print(">> Setting Param: %s (value %s)" % (param, str(value)))

		utils.setAttrSpecial(self.root, param, value, prefix=PARAM_PREFIX, **kwargs)


# coding: utf-8

from json import load
from os import path

import logging
log = logging.getLogger('justine')

def cargar_credenciales():
    token = 'eyJyb2wiOiAiYWRtaW5pc3RyYWRvciIsICJkaXJlY2Npb24iOiAiYWxvcnRpeiJ9.3wR/qMGedccms7xFXN+GCbxlhbTknXGaBrtK3byOzJ0='
    cabecera = 'WWW-Authorization'
    return {cabecera: token}

def cargar_datos(ente):
    directorio = path.dirname(__file__)
    ruta = directorio.split('tests')[0] + 'tests/'

    archivo = ruta + 'datos.json'
    fichero = open(archivo, 'rb')
    contenido = load(fichero)

    return contenido[ente]


#https://leetcode.com/problems/minimum-time-to-make-array-sum-at-most-x/
#You are given two 0-indexed integer arrays nums1 and nums2 of equal length. Every second, for all indices 0 <= i < nums1.length, value of nums1[i] is incremented by nums2[i]. After this is done, you can do the following operation:
#	Choose an index 0 <= i < nums1.length and make nums1[i] = 0.
#You are also given an integer x.
#Return the minimum time in which you can make the sum of all elements of nums1 to be less than or equal to x, or -1 if this is not possible.
#
#Example 1:
#Input: nums1 = [1,2,3], nums2 = [1,2,3], x = 4
#Output: 3
#Explanation:
#For the 1st second, we apply the operation on i = 0. Therefore nums1 = [0,2+2,3+3] = [0,4,6].
#For the 2nd second, we apply the operation on i = 1. Therefore nums1 = [0+1,0,6+3] = [1,0,9].
#For the 3rd second, we apply the operation on i = 2. Therefore nums1 = [1+1,0+2,0] = [2,2,0].
#Now sum of nums1 = 4. It can be shown that these operations are optimal, so we return 3.
#Example 2:
#Input: nums1 = [1,2,3], nums2 = [3,3,3], x = 4
#Output: -1
#Explanation: It can be shown that the sum of nums1 will always be greater than x, no matter which operations are performed.
#
#Constraints:
#	1 <= nums1.length <= 103
#	1 <= nums1[i] <= 103
#	0 <= nums2[i] <= 103
#	nums1.length == nums2.length
#	0 <= x <= 106
class Solution(object):
    def minimumTime(self, nums1, nums2, x):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :type x: int
        :rtype: int
        """
        #Two pointers
        #Time:  O(n)
        #Space: O(1)
        i = 0
        j = len(nums1) - 1
        while i <= j and x > 0:
            x -= nums1[i] + nums2[j]
            i += 1
            j -= 1
        return i + j + 1 if x >= 0 else -1


from Pyxis.ModSupport import *
from Pyxides import im
register_pyxis_module(superglobals="MS LSM DESTDIR");
v.define("LSM","lsm.lsm.html","""current local sky model""");

# external tools
define('IMAGER','lwimager','Imager to user. Default is lwimager.');
define('LWIMAGER_PATH','lwimager','path to lwimager binary. Default is to look in the system PATH.');
define('WSCLEAN_PATH','{im.WSCLEAN_PATH}','path to lwimager binary. Default is to look in the system PATH.');
define('MORESANE_PATH','{im.MORESANE_PATH}','path to lwimager binary. Default is to look in the system PATH.');

define('COLUMN','CORRECTED_DATA','default column to image');

# standard imaging options
ifrs=""
npix=2048
cellsize="8arcsec"
mode="channel"
stokes="IQUV"
weight="briggs"
robust=0
wprojplanes=0
cachesize=4096
niter=1000
gain=.1
threshold=0
fixed=0

# rescale images by factor
flux_rescale=1

# use velocity rather than frequency
velocity = False;

no_weight_fov = False

# filenames for images
define("BASENAME_IMAGE_Template","${OUTFILE}${-<IMAGER}","default base name for all image filenames below");
define("DIRTY_IMAGE_Template", "${BASENAME_IMAGE}.dirty.fits","output filename for dirty image");
define("PSF_IMAGE_Template", "${BASENAME_IMAGE}.psf.fits","output filename for psf image");
define("RESTORED_IMAGE_Template", "${BASENAME_IMAGE}.restored.fits","output filename for restored image");
define("RESIDUAL_IMAGE_Template", "${BASENAME_IMAGE}.residual.fits","output filename for deconvolution residuals");
define("MODEL_IMAGE_Template", "${BASENAME_IMAGE}.model.fits","output filename for deconvolution model");
define("FULLREST_IMAGE_Template", "${BASENAME_IMAGE}.fullrest.fits","output filename for LSM-restored image");
define("MASK_IMAGE_Template", "${BASENAME_IMAGE}.mask.fits","output filename for CLEAN mask");

# How to channelize the output image. 0 for average all, 1 to include all, 2 to average with a step of 2, etc.
# None means defer to 'imager' module options
define("IMAGE_CHANNELIZE",0,"image channels selection: 0 for all, 1 for per-channel cube")
# passed to tigger-restore when restoring models into images. Use e.g. "-b 45" for a 45" restoring beam.
define("RESTORING_OPTIONS","","extra options to tigger-restore for LSM-restoring")
# default clean algorithm
define("CLEAN_ALGORITHM","clark","CLEAN algorithm (clark, hogbom, csclean, etc.)")

def fits2casa (input,output):
    """Converts FITS image to CASA image."""
    im.argo.fits2casa(input,output)

def make_image (msname="$MS",column="$COLUMN",imager='$IMAGER',
                dirty=True,restore=False,restore_lsm=True,psf=False,
                dirty_image="$DIRTY_IMAGE",
                restored_image="$RESTORED_IMAGE",
                residual_image="$RESIDUAL_IMAGE",
                psf_image="$PSF_IMAGE",
                model_image="$MODEL_IMAGE",
                algorithm="$CLEAN_ALGORITHM",
                fullrest_image='${FULLREST_IMAGE}',
                restoring_options='${RESTORING_OPTIONS}',
                channelize=None,lsm="$LSM",**kw0):
    """Makes image(s) from MS. Set dirty and restore to True or False to make the appropriate images. You can also
    set either to a dict of options to be passed to the imager. If restore=True and restore_lsm is True and 'lsm' is set,
    it will also make a full-restored image (i.e. will restore the LSM into the image) with tigger-restore. Use this when
    deconvolving residual images. Note that RESTORING_OPTIONS are passed to tigger-restore.

    'channelize', if set, overrides the IMAGE_CHANNELIZE setting. If both are None, the options in the 'imager' module take effect.

    'algorithm' is the deconvolution algorithm to use (hogbom, clark, csclean, multiscale, entropy)

    'dirty_image', etc. sets the image names, with defaults determined by the globals DIRTY_IMAGE, etc.
    """

    global IMAGER
    IMAGER =  II(imager)
    imager,msname,column,lsm,dirty_image,psf_image,restored_image,residual_image,model_image,algorithm,fullrest_image,restoring_options = \
interpolate_locals("imager msname column lsm dirty_image psf_image \
restored_image residual_image model_image algorithm fullrest_image restoring_options")

    makedir('$DESTDIR')
    if imager in ['lwimager','wsclean']:
        __import__('im.%s'%imager.lower());
        call_imager = getattr(getattr(im, imager.lower()), "make_image")
#        call_imager = eval( 'im.%s.make_image'%(imager.lower()) )
    else:

        abort('Uknown imager: $imager')
    if MORESANE_PATH != '{im.MORESANE_PATH}':
       im.MORESANE_PATH = MORESANE_PATH
    if WSCLEAN_PATH != '{im.WSCLEAN_PATH}':
       im.WSCLEAN_PATH = WSCLEAN_PATH
    # make dict of imager arguments that have been specified globally or locally
    args_to_parse = 'npix weight robust stokes field no_weight_fov ifrs gain niter cachesize mode wprojplanes threshold cellsize'.split()
    kw = dict([ (arg,globals()[arg]) for arg in args_to_parse if arg in globals() and globals()[arg] is not None ])
    kw.update( pol=stokes,scale=im.argo.toDeg(cellsize),size='%d %d'%(npix,npix) )
    if imager == 'wsclean':
        kw.update(weight='%s %.2f'%(weight,robust) if weight=='briggs' else weight)
        if isinstance(threshold,str):
            kw.update(threshold=im.argo.toJy(threshold))
    kw.update([ (arg,kw[arg]) for arg in args_to_parse if arg in kw0 ])
    kw.update(**kw0)

    call_imager(msname,column=column,dirty=dirty,restore_lsm=restore_lsm,restore=restore,
                psf=psf,dirty_image=dirty_image,restored_image=restored_image,
                psf_image=psf_image,model_image=model_image,algorithm=algorithm,
                channelize=channelize,lsm=lsm,fullrest_image=fullrest_image,
                restoring_options=restoring_options,**kw)

document_globals(make_image,"*_IMAGE IMAGER COLUMN IMAGE_CHANNELIZE MS RESTORING_OPTIONS CLEAN_ALGORITHM ms.IFRS ms.DDID ms.FIELD ms.CHANRANGE")

def make_threshold_mask (input="$RESTORED_IMAGE",threshold=0,output="$MASK_IMAGE",high=1,low=0):
    """Makes a mask image by thresholding the input image at a given value. The output image is a copy of the input image,
    with pixel values of 'high' (1 by default) where input pixels are >= threshold, and 'low' (0 default) where pixels are <threshold.
    """
    input,output = interpolate_locals("input output");
    im.argo.make_threshold_mask(input=input,threshold=threshold,output=output,high=high,low=low)

document_globals(make_threshold_mask,"RESTORED_IMAGE MASK_IMAGE")

def predict_vis (msname="$MS",image="$MODEL_IMAGE",column="MODEL_DATA",channelize=None,
  copy=False,copyto="$COPY_IMAGE_TO",**kw0):
    """Converts image into predicted visibilities"""

    import im.lwimager

    msname,image,column,copyto = interpolate_locals("msname image column copyto")

    im.lwimager.predict_vis(msname=msname,image=image,column=column,channelize=channelize,
                            copy=copy,copyto=copyto,**kw0)

document_globals(predict_vis,"MS MODEL_IMAGE COPY_IMAGE_TO ms.IFRS ms.DDID ms.FIELD ms.CHANRANGE");

define("COPY_IMAGE_TO_Template", "${MS:BASE}.imagecopy.fits","container for image copy")
def make_empty_image (msname="$MS",image="${COPY_IMAGE_TO}",channelize=None,**kw0):
    msname,image = interpolate_locals("msname image")
    im.argo.make_empty_image(msname=msname,imagename=image,channelize=channelize,**kw0)

def make_psf (msname="$MS",**kw):
    """Makes an image of the PSF. All other arguments as per make_image()."""

    make_image(msname,dirty=False,psf=True,**kw)


import sys, json, ctypes, os, math, shutil, subprocess, time
import win32com.client
from pathlib import Path
from szipper import szip

def pretty(tgt='', sym='-', length=55):
	length = length - 2
	result = ''
	result += math.ceil((length - len(tgt))/2)*sym
	result += ' '
	result += tgt
	result += ' '
	result += math.floor((length - len(tgt))/2)*sym
	return result

def drop(amt=1):
	for d in range(amt):
		print('')

drop()
print("""
=======================================================
=======================================================
              KICKBOXER 3000 INSTALLING
=======================================================
=======================================================
""")
drop(5)

def main():

	print(pretty('Spinning Earth...'))

	drop()
	print(pretty('Discovering LV-426...'))

	bin_root = Path(__file__).parent
	exe_dir = Path(sys.executable).parent

	drop()
	print(pretty('Sending Chuck Norris...'))

	szipper = szip(bin_root / '7z.exe')

	# ========================================
	#   Unpack controller to the current dir
	# ========================================
	szipper.unpack(
		bin_root / 'kb_data.7z',
		exe_dir,
	)

	drop(4)
	print(pretty('Mission Status: No survivors...'))
	drop(1)

	# ========================================
	# Move 7zip executable to the bins folder inside controller
	# ========================================
	(exe_dir / 'KickBoxer3000-win32-x64' / 'resources' / 'app' / 'src' / 'bins' / '7z').mkdir(parents=True, exist_ok=True)
	shutil.move(
		bin_root / '7z.exe',
		exe_dir / 'KickBoxer3000-win32-x64' / 'resources' / 'app' / 'src' / 'bins' / '7z' / '7z.exe',
	)
	shutil.move(
		bin_root / '7z.dll',
		exe_dir / 'KickBoxer3000-win32-x64' / 'resources' / 'app' / 'src' / 'bins' / '7z' / '7z.dll',
	)

	# ========================================
	#       Important: create a lock file
	# ========================================
	(exe_dir / 'KickBoxer3000-win32-x64' / 'resources' / 'app' / 'src' / 'raw_base_is.bad').write_text('Achtung')

	# ========================================
	#            Create a shortcut
	# ========================================
	shotcut_loc = str(exe_dir / 'KickBoxer3000.lnk')
	shotcut_target = str(exe_dir / 'KickBoxer3000-win32-x64' / 'KickBoxer3000.exe')
	# icon = r'C:\path\to\icon\resource.ico'

	shell = win32com.client.Dispatch('WScript.Shell')
	shortcut = shell.CreateShortCut(shotcut_loc)
	shortcut.Targetpath = shotcut_target
	# shortcut.IconLocation = icon
	# shortcut.WindowStyle = 7
	shortcut.save()

	print(pretty('... among Aliens.'))
	drop(4)

	# ========================================
	#            Reload Icons
	# ========================================
	subprocess.call([r'C:\Windows\System32\ie4uinit.exe', '-show'])

	print(pretty('Installation Complete. No Errors.'))
	drop(5)

	time.sleep(5)

if __name__ == '__main__':
	main()


from __future__ import annotations

import asyncio
import datetime
import unittest

from tvaf import ltpy
from tvaf import services

from . import lib

class FormatTest(lib.AppTest, lib.TestCase):
    async def test_invalid_info_hash(self) -> None:
        r = await self.client.get("/torrents/a")
        self.assertEqual(r.status_code, 422)
        self.assert_golden_json(r.json(), suffix="short.json")

        r = await self.client.get("/torrents/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
        self.assertEqual(r.status_code, 422)
        self.assert_golden_json(r.json(), suffix="long.json")

        r = await self.client.get("/torrents/zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz")
        self.assertEqual(r.status_code, 422)
        self.assert_golden_json(r.json(), suffix="not_hex.json")

class StatusTest(lib.AppTestWithTorrent, lib.TestCase):
    @unittest.skip("flaky")
    async def test_get(self) -> None:
        r = await self.client.get(f"/torrents/{self.torrent.sha1_hash}")
        self.assertEqual(r.status_code, 200)
        # some fields are unstable, so content-length is unstable
        headers = dict(r.headers)
        headers.pop("content-length")
        self.assert_golden_json(headers, suffix="headers.json")

        status_dict = r.json()
        # test unstable parts
        self.assertIsInstance(status_dict.pop("added_time"), int)
        self.assertIsInstance(status_dict.pop("completed_time"), int)
        datetime.datetime.fromisoformat(status_dict.pop("last_download"))
        self.assertEqual(status_dict.pop("save_path"), self.tempdir.name)
        self.assert_golden_json(status_dict, suffix="body.json")

class GetPiecePrioritiesTest(lib.AppTestWithTorrent, lib.TestCase):
    async def test_get(self) -> None:
        r = await self.client.get(
            f"/torrents/{self.torrent.sha1_hash}/piece_priorities"
        )
        self.assertEqual(r.status_code, 200)
        self.assert_golden_json(dict(r.headers), suffix="headers.json")
        self.assert_golden_json(r.json(), suffix="body.json")

class RemoveTest(lib.AppTestWithTorrent, lib.TestCase):
    @unittest.skip("flaky")
    async def test_delete(self) -> None:
        r = await self.client.delete(f"/torrents/{self.torrent.sha1_hash}")
        self.assertEqual(r.status_code, 200)
        self.assertFalse(
            await asyncio.to_thread(
                ltpy.handle_in_session,
                self.handle,
                await services.get_session(),
            )
        )

class TorrentListTest(lib.AppTestWithTorrent, lib.TestCase):
    @unittest.skip("flaky")
    async def test_torrent_list(self) -> None:
        r = await self.client.get("/torrents")
        self.assertEqual(r.status_code, 200)
        # some fields are unstable, so content-length is unstable
        headers = dict(r.headers)
        headers.pop("content-length")
        self.assert_golden_json(headers, suffix="headers.json")

        statuses = r.json()
        # test unstable parts
        self.assertIsInstance(statuses[0].pop("added_time"), int)
        self.assertIsInstance(statuses[0].pop("completed_time"), int)
        datetime.datetime.fromisoformat(statuses[0].pop("last_download"))
        self.assertEqual(statuses[0].pop("save_path"), self.tempdir.name)
        self.assert_golden_json(statuses, suffix="body.json")


import requests
from pprint import pprint

import datetime
import time
import csv
import json
import os

# start time
start_time = datetime.datetime.now()

# read questions form a file
file_question_topics = open("topic_list_answers.txt", mode="r", encoding="utf-8")
topics = file_question_topics.readlines()

def get_voteCount(contents, upvote_index):
    end_index = []
    for index in upvote_index:
        end = index
        while contents[end] != "," and contents[end] != "}":
            end +=1
        end_index.append(end)
    return end_index

def save_data_as_json(data, path,ensure_ascii=True):
    with open(path, "w") as f:
        json.dump(data, f, ensure_ascii=ensure_ascii)

for topic in topics:
    quora_question_answers = {}
    topic = topic.replace("\n","")
    quora_question_answers[topic] = []

    questions_list = open("./questions/" + topic + ".txt", "r",encoding="utf-8")
    urls = questions_list.readlines()

    total = len(urls)

    count = 0
    for url in urls:
        question_answer_pair = {}
        question_answer_pair["url"] = url.replace('\n','')
        question_answer_pair["question"] = url.replace("https://www.quora.com/","").replace("-"," ").replace('\n','')
        res = requests.get(url)
        contents = res.text

        text_index = []
        upvote_index = []

        for i in range(len(contents)-14):
            text_flag = contents[i:i+7]
            upvote_flag = contents[i:i+14]
            url_flag = contents[i:i+6]

            if text_flag == '"text":':
                text_index.append(i+7)
            if upvote_flag == '"upvoteCount":':
                upvote_index.append(i+14)

        end_index = get_voteCount(contents, upvote_index)

        answers = []
        for i in range(len(text_index)-1):
            answer = {}
            answer["upvote"] = int(contents[upvote_index[i]+1:end_index[i]])
            answer["content"] = contents[text_index[i]+2:upvote_index[i]-17]
            answers.append(answer)

        question_answer_pair["answers"] = answers
        quora_question_answers[topic].append(question_answer_pair)

        count +=1
        if count%20 ==0:
            print(str(count) + "/"+ str(total) + " "+ str(datetime.datetime.now() - start_time))

    # save data as json format
    path = "./results/" + topic + ".json"
    save_data_as_json(quora_question_answers,path)

# display processing time
end_time = datetime.datetime.now()
print(end_time - start_time)


"""
 # -*- coding:utf-8 -*-
 # @Author：xiabo
 # @File : report.py
 # @Date ：2022/4/11 下午4:56
"""
import re
import json

import curlify
from django.core.exceptions import ObjectDoesNotExist
from django.shortcuts import render
from django.utils.decorators import method_decorator
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from Summer_TestingPlatform import pagination
from summertest import serializers, models
from summertest.utils.decorator import request_log
from summertest.utils import response

class Report2Curl(object):
    @staticmethod
    def to_curl(request_meta_dict: dict):
        class RequestMeta(object):
            ...

        req = RequestMeta()
        setattr(req, 'method', request_meta_dict['method'])
        setattr(req, 'url', request_meta_dict['url'])
        setattr(req, 'headers', request_meta_dict['headers'])
        body = request_meta_dict.get('body') or request_meta_dict.get('data')
        setattr(req, 'body', body)
        return curlify.to_curl(req, compressed=True, verify=False)

    @classmethod
    def generate_curl(cls, report_details):
        for detail in report_details:
            for record in detail['records']:
                meta_data = record['meta_data']
                curl = cls.to_curl(meta_data['request'])
                record['meta_data']['curl'] = curl

class ReportView(GenericViewSet):
    """报告视图"""
    queryset = models.Report.objects
    serializer_class = serializers.ReportSerializer
    pagination_class = pagination.MyPageNumberPagination

    def get_authenticators(self):
        # 查看报告详情不需要鉴权
        # self.request.path = '/api/fastrunner/reports/3053/'
        pattern = re.compile(r'/api/fastrunner/reports/\d+/')
        if self.request.method == 'GET' and re.search(pattern, self.request.path) is not None:
            return []
        return super().get_authenticators()

    @method_decorator(request_log(level='DEBUG'))
    def list(self, request):
        """报告列表
        """

        project = request.query_params['project']
        search = request.query_params["search"]
        report_type = request.query_params["reportType"]
        report_status = request.query_params["reportStatus"]
        only_me = request.query_params["onlyMe"]

        queryset = self.get_queryset().filter(project__id=project).order_by('-update_time')

        # 前端传过来是小写的字符串，不是python的True
        if only_me == 'true':
            queryset = queryset.filter(creator=request.user)

        if search != '':
            queryset = queryset.filter(name__contains=search)

        if report_type != '':
            queryset = queryset.filter(type=report_type)

        if report_status != '':
            queryset = queryset.filter(status=report_status)

        page_report = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page_report, many=True)
        return self.get_paginated_response(serializer.data)

    @method_decorator(request_log(level='INFO'))
    def delete(self, request, **kwargs):
        """删除报告
        """
        """
           删除一个报告pk
           删除多个
           [{
               id:int
           }]
        """
        try:
            if kwargs.get('pk'):  # 单个删除
                models.Report.objects.get(id=kwargs['pk']).delete()
            else:
                for content in request.data:
                    models.Report.objects.get(id=content['id']).delete()

        except ObjectDoesNotExist:
            return Response(response.REPORT_NOT_EXISTS)

        return Response(response.REPORT_DEL_SUCCESS)

    @method_decorator(request_log(level='INFO'))
    def look(self, request, **kwargs):
        """查看报告
        """
        pk = kwargs["pk"]
        report = models.Report.objects.get(id=pk)
        report_detail = models.ReportDetail.objects.get(report_id=pk)
        summary = json.loads(report.summary, encoding="utf-8")
        summary['details'] = eval(report_detail.summary_detail)
        Report2Curl.generate_curl(summary['details'])
        summary["html_report_name"] = report.name
        # return render_to_response('report_template.html', summary)

        return render(request, template_name='report_template.html', context=summary)

    def download(self, request, **kwargs):
        """下载报告
        """
        pass


import matplotlib.pyplot as plt

line_lyr = QgsProject.instance().mapLayersByName('New scratch layer')[0]
rl = QgsProject.instance().mapLayersByName('S17E130')[0]

line_geom = [f.geometry() for f in line_lyr.getFeatures()][0]

line_length = line_geom.length()

num_profile_pts = 25

interp_dist = line_length/num_profile_pts

total_dist = interp_dist

sample_geoms = []

while total_dist < line_length:
    sample_geoms.append(line_geom.interpolate(total_dist))
    total_dist+=interp_dist

#print(sample_pts)

plot_vals = [rl.dataProvider().sample(geom.asPoint(), 1)[0] for geom in sample_geoms]

#print(plot_vals)

plt.plot(plot_vals, label='Profile', color='brown', linewidth=2)

plt.show()


import csv
import numpy as np
import math
import random
# split data into training and test sets

TRAIN_RATIO = 0.6

#train = csv.DictReader(open('creditcard.csv'), fieldnames=('Time','V1','V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19', 'V20', 'V21', 'V22', 'V23', 'V24', 'V25', 'V26', 'V27', 'V28', 'Amount', 'Class'))
data = csv.reader(open('creditcard.csv', newline=''), delimiter=',')

num_frauds = 0
num_txn = 0

fraud = []
legitimate = []

# sort them into fraud and legitimate
for entry in data:
    if (entry[30] == '1'):
        fraud.append(entry)
    else:
        legitimate.append(entry)

# make training and test sets
train_fraud = []
train_legitimate = []

print(legitimate.pop(0))

num_train_fraud = math.floor(TRAIN_RATIO * len(fraud))
train_fraud_idx = random.sample(range(len(fraud)), num_train_fraud)
num_train_legitimate = math.floor(TRAIN_RATIO * len(legitimate))
train_legitimate_idx = random.sample(range(len(legitimate)), num_train_legitimate)

train_fraud = [fraud[i] for i in train_fraud_idx]
train_legitimate = [legitimate[i] for i in train_legitimate_idx]

#test_fraud = [fraud[i] for i in range(len(fraud)) if i not in train_fraud_idx]
#test_legitimate = [legitimate[i] for i in range(len(legitimate)) if i not in train_legitimate_idx]

train_fraud_idx.sort(reverse=True)
train_legitimate_idx.sort(reverse=True)

for i in train_fraud_idx:
    fraud.pop(i)

for i in train_legitimate_idx:
    legitimate.pop(i)

np.save('train_fraud', np.asarray(train_fraud, dtype='float32'))
np.save('train_legitimate', np.asarray(train_legitimate, dtype='float32'))
np.save('test_fraud', np.asarray(fraud, dtype='float32'))
np.save('test_legitimate', np.asarray(legitimate, dtype='float32'))


import nltk
from nltk.corpus import wordnet

sentence = "A high level Israeli army official has said today Saturday that Israel believes Iran is set to begin " \
           "acquiring nuclear capability for military purposes from 2005."

tokens = nltk.tokenize.word_tokenize(sentence)
print("tokens: ", tokens)

tagged = nltk.pos_tag(tokens)
print("tagged: ", tagged[:6])

synonyms = []
for syn in wordnet.synsets("computer"):
    for lemma in syn.lemmas():
        synonyms.append(lemma.name())
print(synonyms)


# Zachary Hoover || Find and Replace
# 11-4-22

import os

folders = [
    "Unit 3",
    "Unit 4",
    "Unit 5",
    "Unit 6",
    "Unit 7-8",
    "Unit 9",
    "Other"
]
find = '# call auto menu function\nautoMenu()'
replace = r'if __name__ == "__main__": autoMenu();'

for folder in folders:
    for filename in os.listdir(folder):
        try:
            with open(f"{folder}/{filename}", 'r') as file :
                filedata = file.read()
            filedata = filedata.replace(find, replace)
            with open(f"{folder}/{filename}", 'w') as file:
                file.write(filedata)
            print(f"{folder}/{filename}")
        except:
            continue

print("Done!")


#!usr/bin/env/python3
# Message protocol: read and write

from asyncio import StreamWriter, StreamReader

async def read_msg(stream: StreamReader) -> bytes:
    size_bytes = await stream.readexactly(4)
    size = int.from_bytes(size_bytes, byteorder='big')
    data = await stream.readexactly(size)
    return data

async def send_msg(stream: StreamWriter, data: bytes):
    size_bytes = len(data).to_bytes(4, byteorder='big')
    stream.writelines([size_bytes, data])
    await stream.drain()


import cv2

cam_front = cv2.VideoCapture(0)
problem_signal = False # a signal for problem indication

while True:
    # get the frame from the front camera
    bool, front_frame = cam_front.read()

    # show the frame
    if(bool):
        problem_signal = False

        cv2.imshow("Camera Input", front_frame)
    else:
        if(not problem_signal):
            print ("Frame from the front CAM is missing")
            problem_signal = True

    # to break the main loop press ESC
    key = cv2.waitKey(1)
    if key == 27:
        break

# release controls
cam_front.release()
cv2.destroyAllWindows()


import numpy as np
from scipy.io.wavfile import write

samples = []
with open("samples.txt", "r") as f:
	for line in f:
		if len(line.strip()) == 0:
			continue
		samples.append(-2000 + 4000 * int(line))

rate = 6250
write('test.wav', rate, np.int16(samples))


from AccessControl import Unauthorized
from Acquisition import aq_inner
from Products.Five.browser import BrowserView
from Products.statusmessages.interfaces import IStatusMessage
from zope.component import getMultiAdapter

from collective.polls import MessageFactory as _

class PollView(BrowserView):

    def __init__(self, context, request):
        self.context = context
        self.request = request

    def __call__(self):
        self.update()
        return self.index()

    def update(self):
#        super(PollView, self).update()
        messages = IStatusMessage(self.request)
        context = aq_inner(self.context)
        self.context = context
        self.state = getMultiAdapter(
            (context, self.request), name=u'plone_context_state')
        self.wf_state = self.state.workflow_state()
        self.utility = context.utility
        # Handle vote
        form = self.request.form
        self.errors = []
        self.messages = []

        if 'poll.submit' in form:
            self._handleSubmit(form)
        # Update status messages
        for error in self.errors:
            messages.addStatusMessage(error, type="warn")
        for msg in self.messages:
            messages.addStatusMessage(msg, type="info")

    def _handleSubmit(self, form):
        INVALID_OPTION = _(u'Invalid option')
        options = form.get('options', '')
        if isinstance(options, list):
            self.errors.append(INVALID_OPTION)
        elif isinstance(options, str):
            if not options.isdigit():
                self.errors.append(INVALID_OPTION)
            else:
                options = int(options)
        if not self.errors:
            # Let's vote
            try:
                self.context.setVote(options, self.request)
                self.messages.append(_(u'Thanks for your vote'))
                # We do this to avoid redirecting anonymous user as
                # we just sent them the cookie
                self._has_voted = True
            except Unauthorized:
                self.errors.append(_(u'You are not authorized to vote'))

    @property
    def can_vote(self):
        if hasattr(self, '_has_voted') and self._has_voted:
            # This is mainly to avoid anonymous users seeing the form again
            return False
        try:
            return self.utility.allowed_to_vote(self.context, self.request)
        except Unauthorized:
            return False

    @property
    def can_edit(self):
        utility = self.utility
        return utility.allowed_to_edit(self.context)

    @property
    def has_voted(self):
        ''' has the current user voted in this poll? '''
        if hasattr(self, '_has_voted') and self._has_voted:
            return True
        utility = self.utility
        voted = utility.voted_in_a_poll(self.context, self.request)
        return voted

    def poll_uid(self):
        ''' Return uid for current poll '''
        utility = self.utility
        return utility.uid_for_poll(self.context)

    def getOptions(self):
        ''' Returns available options '''
        return self.context.getOptions()

    def getResults(self):
        ''' Returns results so far if allowed'''
        show_results = False
        if self.wf_state == 'open':
            show_results = show_results or self.context.show_results
        elif self.wf_state == 'closed':
            show_results = True
        return (show_results and self.context.getResults()) or None


import unittest

from scidownl.db.entities import get_engine, create_tables, ScihubUrl
from scidownl.log import get_logger

logger = get_logger()

class TestEntities(unittest.TestCase):

    def test_create_tables(self):
        create_tables(test=True)

    def test_orm(self):
        from sqlalchemy.orm import sessionmaker

        create_tables(test=True)
        engine = get_engine(echo=False, test=True)
        Session = sessionmaker(bind=engine)

        # Add
        items = [
            ScihubUrl(url="http://sci-hub.se"),
            ScihubUrl(url="https://sci-hub.sd"),
        ]
        session = Session()
        for item in items:
            try:
                session.add(item)
                session.commit()
            except Exception as e:
                session.rollback()
        session.close()

        # Query
        exist_url = ScihubUrl(url="http://sci-hub.se")
        non_exist_url = ScihubUrl(url="http://sci-hub.non-exist")
        session = Session()
        exist_rec = session.query(ScihubUrl).filter_by(url=exist_url.url).first()
        self.assertEqual(exist_url.url, exist_rec.url)
        non_exist_rec = session.query(ScihubUrl).filter_by(url=non_exist_url.url).first()
        self.assertIsNone(non_exist_rec)
        session.close()

        # Modify
        modify_url = ScihubUrl(url="http://sci-hub.se")
        session = Session()
        session.query(ScihubUrl).filter_by(url=modify_url.url).update({
            ScihubUrl.success_times: ScihubUrl.success_times + 1
        })
        session.commit()
        modified_success_times = session.query(ScihubUrl).filter_by(url=modify_url.url).first().success_times
        self.assertGreaterEqual(modified_success_times, 1)
        session.close()

        # Delete
        session = Session()
        urls = session.query(ScihubUrl).all()
        for url in urls:
            session.delete(url)
        session.commit()
        self.assertEqual(0, len(session.query(ScihubUrl).all()))
        session.close()

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


def isOdd(n):
    return n % 2

def DA_solve(num_list, O, D):
    L = 0
    R = 0
    length = len(num_list)
    maxsum = -99999
    sums = [0 for i in range(length)]
    odds = [0 for i in range(length)]

    odds[0] = isOdd(num_list[0])
    sums[0] = num_list[0]
    for i in range(1, length):
        odds[i] = odds[i - 1] + isOdd(num_list[i])
        sums[i] = sums[i - 1] + num_list[i]

    def os(l, r):
        if 0 < l:
            totalodd = odds[r] - odds[l - 1]
            return totalodd
        else:
            return odds[r]

    def ss(l, r):
        if 0 < l:
            totals = sums[r] - sums[l - 1]
            return totals
        else:
            return sums[r]

    for R in range(length):
        if L > R:
            continue

        while os(L, R) > O or ss(L, R) > D:
            L += 1
            if L > R:
                break

        if L > R:
            continue

        tmpsum = ss(L, R)
        if tmpsum > maxsum:
            maxsum = tmpsum

    # while R < length:
    #     while os(L, R) > O:
    #         L += 1
    #         if L>R:
    #             R+=1
    #             break
    #     #then below will be os(L, R) <= O

    #     while ss(L, R) > D:
    #         L += 1
    #         if L>R:
    #             R+=1
    #             break
    #     #then below will be ss(L, R) <= D

    #     tmpsum = ss(L, R)
    #     if tmpsum > maxsum:
    #         maxsum = tmpsum

    #     R += 1

    if maxsum == -99999 or maxsum > D:
        print('IMPOSSIBLE')
    else:
        print(maxsum)

    return 0

def main():
    T = int(input())

    for n in range(T):
        tmp = input().split()
        tmp = list(map(int, tmp))
        N, O, D = tmp

        tmp = input().split()
        tmp = list(map(int, tmp))
        x1, x2, A, B, C, M, L = tmp

        X = [x1, x2]
        S = [x1 + L, x2 + L]

        for i in range(2, N):
            X.append((A * X[i - 1] + B * X[i - 2] + C) % M)
            S.append(X[i] + L)

        print('Case #' + str(n + 1) + ': ', end='')
        DA_solve(tuple(S), O, D)

if __name__ == '__main__':
    main()


import pyttsx3
import os

pyttsx3 .speak("welcome in my tools")

while True:
    pyttsx3.speak("chat with me your requirement")
    print("chat with me your requirement : ", end='')
    p=input()
    if("dont" in p):
        print("cant open application")
    elif (("run" in p) or ("execute" in p) or ("open" in p)) and ("chrome" in p):
        pyttsx3.speak("yes, here is chrome")
        os.system("chrome")
    elif (("run" in p) or ("execute" in p) or ("open" in p)) and (("notepad" in p) or ("editor" in p)):
        pyttsx3.speak("yes, here is notepad")
        os.system("notepad")
    elif (("run" in p) or ("execute" in p) or ("open" in p)) and ("vlc" in p):
        pyttsx3.speak("yes, here is vlc")
        os.system("vlc")
    elif (("run" in p) or ("execute" in p) or ("open" in p)) and (("player" in p) or ("media" in p)):
        pyttsx3.speak("yes, here is wmplayer")
        os.system("wmplayer")
    elif (("run" in p) or ("execute" in p) or ("open" in p)) and (("Arduino" in p) or ("program" in p)):
        pyttsx3.speak("yes, here is Arduino")
        os.system("Arduino")
    elif (("run" in p) or ("launch" in p) or ("launch" in p) ) and (("paint" in p)):
        pyttsx3.speak("yes, here is paint")
        os.system("paint")
    elif ("exit" in p) or ("quit" in p):
        break
    else:
        print("dont support")


import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import  confusion_matrix,accuracy_score,roc_auc_score
from sklearn.preprocessing import LabelEncoder

csvPath = r"C:\Users\YSK\Documents\GitHub\pattern-recognition-with-dataset\otu.csv"
dataset = pd.read_csv(csvPath)
X = dataset.iloc[1:, :].T
y = dataset.iloc[:1, :].T
le=LabelEncoder()
y=le.fit_transform(y)
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.30,random_state=100)

model=LogisticRegression()

model.fit(X_train,y_train)
print("Test Score", model.score(X_test,y_test))
print("Train Score", model.score(X_train,y_train))

prediction=model.predict(X_test)
cm=confusion_matrix(y_test,prediction)
print("Accuracy",accuracy_score(y_test,prediction))
print('Sensitivity : ', cm[0,0]/(cm[0,0]+cm[0,1]))
print('Specificity : ', cm[1,1]/(cm[1,0]+cm[1,1]))
print("auc:",roc_auc_score(y_test,prediction))


#!/usr/bin/env python3
# c-basic-offset: 4; tab-width: 8; indent-tabs-mode: nil
# vi: set shiftwidth=4 tabstop=8 expandtab:
# :indentSize=4:tabSize=8:noTabs=true:
#
# SPDX-License-Identifier: GPL-3.0-or-later
"""
Creation of a vocabulary dataset
"""

vocabs = {'programming':['The activity or job of writing computer programs','______mming'],
    'python':['A very large snake that kills animals','____hon'],
    'fun':['Pleasure, enjoyment or entretainment','__n']}

def list_all_words():
    print('Your Vocab List\n')
    for key, value in vocabs.items():
        print('  {} ({})\n    - {}\n'.format(key, value[1], value[0]))

def new_word():
    try:
        word, definition, hint=input('Enter your new word(word|meaning|hint):\n').split('|')
        if word in vocabs:
            print('{} is already in the Vocaob builder'.format(word))
        else:
            vocabs[word]= [definition, hint]
            print('word {} added.'.format(word))
    except ValueError:
        print('Please make sure the format is correct')
    except:
        print('Unexpected Error!')

def remove_a_word():
    word = input('Enter a word to remove: ')
    if word in vocabs:
        del(vocabs[word])
        print('{} has been removed.'.format(word))
    else:
        print('Cannot find the word {} in your Vocab builder.'.format(word))

def test_yourself():
    points =0
    incorrect_word_list=[]
    want_to_quit=False

    for key, value in vocabs.items():
        while True:
            answer=input('\nWhat is {}\n or [p]ass, [h]int, [q]uit\n'.format(value[0]))
            if answer==key :
                print('Correct!!')
                points +=1
                break
            elif answer == 'p':
                print('The correct answer is {}'.format(key))
                incorrect_word_list.append(key)
            elif answer=='h':
                print(value[1])
            elif answer =='q':
                want_to_quit = True
                break
            else:
                print('It\'s not correct :(')
                incorrect_word_list.append(key)
        if want_to_quit:
            break

    print('\Score: {}/{}'.format(points, len(vocabs)))
    print('Incorrect word list:')
    for key in incorrect_word_list:
        values=vocabs[key]
        print('  {}\n'.format(key, values[0]))

def main():
    """
    Calling the functions
    """
    while True:
        cmd = input("""\nWelcome to Vocab Builder!
        1)Test yourself!
        2)Add a new word
        3)Remove a word
        4)List all words
        5)Exit\n""")

        if cmd =='1':
            test_yourself()
        elif cmd== '2':
            new_word()
        elif cmd == '3':
            remove_a_word()
        elif cmd=='4':
            list_all_words()
        elif cmd == '5':
            break

if __name__ == "__main__":
    main()


from django.shortcuts import get_object_or_404, render, redirect
from .models import Blog, News, BlogComment
# Create your views here.

def blogandnews(request):
    blogs = Blog.objects.all()
    newss = News.objects.all()
    return render(request, "blogandnews.html", {
        'blogs': blogs,
        'newss': newss,
    })

def blog(request, blogId):
    blog = get_object_or_404(Blog, id=blogId)
    comments = BlogComment.objects.filter(blog=blog)
    context = {'blog': blog, 'comments': comments}
    return render(request, 'blog.html', context)

def blog_like(request, blogId):
    blog = get_object_or_404(Blog, id=blogId)
    blog.likes = blog.likes + 1
    blog.save()

    return redirect("blog", blogId=blogId)

def comments(request, blogId):
    if request.method == "POST":
        comment = request.POST.get("comment")
        mail = request.POST.get("mail")
        blog = Blog.objects.get(id=blogId)

        comment = BlogComment(comment=comment, blog=blog, mail=mail)
        comment.save()

    return redirect("blog", blogId=blogId)  # to be changed


def group_by_city(scores_dataset):
    cities = {}
    for entries in scores_dataset:
        city = entries["City"]
        name = entries["Name"]
        if city not in cities:
            cities[city] = []

        cities[city].append(name)

    return cities

def busy_cities(scores_dataset):
    maxi = 0
    busyc = []
    cities = group_by_city(scores_dataset)
    for city, students in cities.items():
        if len(students) > maxi:
            maxi = len(students)
            busyc = [city]
        elif len(students) == maxi:
            busyc.append(city)

    return busyc


with open('bingo.txt') as f:
    bingo_input = [l.strip() for l in f.readlines()]

draws = [int(i) for i in bingo_input.pop(0).split(',')]

boards = []
new_board = []

for l in bingo_input:
    if l:
        new_board.append([int(d) for d in l.split()])
    elif new_board:
        boards.append(new_board)
        new_board = []

print('board_count', len(boards))
removed = 0

def check_winner(board):
    for row in board:
        if not any(d != -1 for d in row):
            return True
    for i in range(len(board[0])):
        if not any(row[i] != -1 for row in board):
            return True

    return False

def sum_board(board):
    winning_sum = 0
    for row in board:
        for i in row:
            winning_sum += i if i != -1 else 0
    return winning_sum

first_winner = None
winning_draw = None
final_winner = None
final_draw = None

for d in draws:
    for b in [unwon for unwon in boards if not check_winner(unwon)]:
        for row in b:
            if d in row:
                row[row.index(d)] = -1

        if check_winner(b):
            if not first_winner:
                first_winner = b
                winning_draw = d
            removed += 1

        if removed == 100:
            final_winner = b
            final_draw = d

    if final_draw:
        break

winning_sum = sum_board(first_winner)
print('part 1 answer is', winning_draw * winning_sum)

final_winning_sum = sum_board(final_winner)
print('part 2 answer is', final_draw * final_winning_sum)


import csv
import pandas as pd
import datetime as Time
import os
a = Time.datetime.now()
print("This script is convert Data in CSV to column separate by epoch.")
path =input("Enter path of CSV file :")
infile = [f for f in os.listdir(path) if f.endswith(".csv")]
for i in range(len(infile)):
    print(i,infile[i])
NumberOfFile = (int)(input("Enter number File :"))
print("open file: ",path+"\\"+infile[NumberOfFile])
fullPathOpen =path+"\\"+infile[NumberOfFile]
outPath =input("Enter path to save it :")
outfile = input("Enter file output name : ")+".csv"
fullPathOut = outPath+'\\'+outfile

with open(fullPathOpen, newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
    data =[]
    countRow=0
    for read in spamreader:
        data.append(read)

    #print(len(data))
    #print(len(data[1]))
    temp=[]
    #person=[]
    perEpoch=[]
    for row in range(1,len(data)):
        epoch=1
        for col in range(1,len(data[row])):
            if col%71==0:
                temp.append(round((float)(data[row][col]),10))
                person=[data[row][0],epoch]+temp
                perEpoch.append(person)
                person=[]
                temp=[]
                epoch+=1

            else:temp.append(round((float)(data[row][col]),10))

    Signal = ['subject', 'epoch',
              'SaO2_min', 'SaO2_max', 'SaO2_avg', 'SaO2_SD', 'SaO2_kurtosis',
              'PR_min', 'PR_max', 'PR_avg', 'PR_SD', 'PR_kurtosis',
              'position_min', 'position_max', 'position_avg', 'position_SD', 'position_kurtosis',
              'light_min', 'light_max', 'light_avg', 'light_SD', 'light_kurtosis',
              'ox_stat_min', 'ox_stat_max', 'ox_stat_avg', 'ox_stat_SD', 'ox_stat_kurtosis',
              'airflow_min', 'airflow_max', 'airflow_avg', 'airflow_SD', 'airflow_kurtosis',
              'ThorRes_min', 'ThorRes_max', 'ThorRes_avg', 'ThorRes_SD', 'ThorRes_kurtosis',
              'AbdoRes_min', 'AbdoRes_max', 'AbdoRes_avg', 'AbdoRes_SD', 'AbdoRes_kurtosis',
              'EOG(L)_min', 'EOG(L)_max', 'EOG(L)_avg', 'EOG(L)_SD', 'EOG(L)_kurtosis',
              'EOG(R)_min', 'EOG(R)_max', 'EOG(R)_avg', 'EOG(R)_SD', 'EOG(R)_kurtosis',
              'EEG(sec)_min', 'EEG(sec)_max', 'EEG(sec)_avg', 'EEG(sec)_SD', 'EEG(sec)_kurtosis',
              'EEG_min', 'EEG_max', 'EEG_avg', 'EEG_SD', 'EEG_kurtosis',
              'ECG_min', 'ECG_max', 'ECG_avg', 'ECG_SD', 'ECG_kurtosis',
              'EMG_min', 'EMG_max', 'EMG_avg', 'EMG_SD', 'EMG_kurtosis',
              'stage']
    #print(len(perEpoch))
    Frame = pd.DataFrame(perEpoch,columns=Signal)
    Frame.to_csv(fullPathOut, encoding='utf-8',index=False)
print(fullPathOut)


import os

import tkinter as tk
import customtkinter as ctk
import openai

from ui_components import Scene1, Scene2
from utils.api_utils import load_api_data
from utils.file_utils import get_icon

OPENAI_APIKEY = ""
GPT_MODEL = ""

if os.path.exists(os.path.join(os.getcwd(), "config.json")):
    api_data = load_api_data()
    OPENAI_APIKEY = api_data["API_KEY"]
    GPT_MODEL = api_data["MODEL"]

openai.api_key = OPENAI_APIKEY

# System settings
ctk.set_appearance_mode("System")
ctk.set_default_color_theme("blue")

class App(ctk.CTk):
    """Main class for the Anki cards creator application."""

    def __init__(self):
        super().__init__()
        self.geometry("900x600")
        self.title("Anki cards creator")

        self.api_keys_scene = None
        self.scenes_params = dict(row=0, column=1, sticky=tk.NSEW)

        self.left_frame = ctk.CTkFrame(self, corner_radius=0)
        self.left_frame.grid(row=0, column=0, sticky="NS")

        self.manage_api = ctk.CTkButton(self.left_frame,
                                        text="Manage API key",
                                        command=self.change_to_api_scene,
                                        width=150,
                                        height=35,
                                        fg_color="gray20",
                                        hover_color="gray25",
                                        image=get_icon("key.png", (18, 18)))

        self.manage_api.pack(padx=10, pady=10)

        self.createing_flashcards = ctk.CTkButton(self.left_frame,
                                                  text="Create flashcards",
                                                  width=150,
                                                  height=35,
                                                  fg_color="gray20",
                                                  hover_color="gray25",
                                                  image=get_icon("plus.png", (20, 20)),
                                                  command=self.change_to_flashcard_scene)

        self.createing_flashcards.pack(padx=10, pady=10)

        self.quit_btn = ctk.CTkButton(self.left_frame,
                                      text="Quit",
                                      width=150,
                                      fg_color="gray20",
                                      hover_color="gray25",
                                      image=get_icon("leave.png", (15, 15)),
                                      command=self.quit)
        self.quit_btn.pack(pady=10, side=tk.BOTTOM)

        self.flash_card_scene = Scene1(self, fg_color="#f7f7f8", corner_radius=0)
        self.flash_card_scene.grid(**self.scenes_params)

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)

    def change_to_api_scene(self):
        """Switch the displayed scene to the API key management scene."""

        self.flash_card_scene.forget()
        self.api_keys_scene = Scene2(self, fg_color="#f7f7f8", corner_radius=0)
        self.api_keys_scene.grid(**self.scenes_params)

    def change_to_flashcard_scene(self):
        """Switch the displayed scene to the flashcard creation scene."""

        self.api_keys_scene.forget()
        self.flash_card_scene = Scene1(self, fg_color="#f7f7f8", corner_radius=0)
        self.flash_card_scene.grid(**self.scenes_params)

def main():
    app = App()
    app.mainloop()

if __name__ == '__main__':
    main()


# Number Ladder

# 2023-01-03 Marking (1 right, 0 wrong, * bug):
# 11100000 = 5/23

from collections import deque
from functools import lru_cache

DIGIT_WORDS = ["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"]
for i in range(len(DIGIT_WORDS)):
    # To list of letter indices
    DIGIT_WORDS[i] = list(map(lambda letter: ord(letter)-65, DIGIT_WORDS[i]))

@lru_cache(maxsize=None) # Memoise
def int2letterCounts(num:str):
    # print(num)
    letter_counts = [0 for _ in range(26)]
    for char in num:
        digit = ord(char)-48 # To int
        for letter_ind in DIGIT_WORDS[digit]:
            letter_counts[letter_ind] += 1
    return tuple(letter_counts)

@lru_cache(maxsize=None)
def isTransformation(num1:tuple, num2:tuple): # Both letter counts
    letter_changes = 0
    for i in range(26):
        if num1[i] != num2[i]:
            # Letter added/deleted
            if letter_changes == 5:
                return False # Too many changes

            # print("Changed", chr(i+65), abs(num1[i]-num2[i]))
            letter_changes += abs(num1[i]-num2[i])
    return True

def getTransformations(num1:tuple): # In and Out as letter counts
    transformations = []
    # "only uses numbers between 1 and 999 inclusive"
    for i in range(1, 1000):
        num2 = int2letterCounts(str(i))
        if isTransformation(num1, num2):
            transformations.append(num2)
    return transformations

def bfsShortestLadder(num1:str, num2:str):
    num1 = int2letterCounts(num1)
    num2 = int2letterCounts(num2)
    q = deque([(num1,0)]) # Each letter count, dist

    visited = set()
    while(q):
        node, dist = q.popleft()
        for neighbour in getTransformations(node):
            if neighbour == num2:
                return dist+1
            if not neighbour in visited:
                visited.add(neighbour)
                q.append((neighbour, dist+1))

# Main
start1, finish1 = input().split() # Strings
start2, finish2 = input().split() # Strings
start3, finish3 = input().split() # Strings
print(bfsShortestLadder(start1, finish1))
print(bfsShortestLadder(start2, finish2))
print(bfsShortestLadder(start3, finish3))