from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

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

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

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

def tests1(request):
    sentence = request.GET['scr']
    ls = sentence.split()
    sen_new = ""
    ls1 = ls[::-1]
    for word in ls1:
        sen_new = sen_new + " " + word
    sen_new = sen_new.strip()
    res = "The reversed sentence is : " + sen_new
    print(sentence)
    return render(request, 's1.html', {'result': res})

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

def tests2(request):
    sen = request.GET['scr']
    counter = 0
    for i in sen:
        counter += 1
    res = ("Total chars. : " + str(counter))
    return render(request, 's2.html', {'result': res})

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

def tests3(request):
    sen = request.GET['scr']
    counter = 0
    vowel = ['a', 'e', 'i', 'o', 'u']
    for char in sen:
        for vow in vowel:
            if char.lower() == vow:
                counter += 1
    res = (counter)
    return render(request, 's3.html', {'result': res})

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

def tests4(request):
    sen = request.GET['scr']
    sen1 = ""
    counter = 0
    for i in sen:
        sen1 += i
        counter += 1
    res = "The number of characters copied are : " + str(counter)
    return render(request, 's4.html', {'result': res})

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

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

def testn1(request):
    n = request.GET['scr']
    d = int(n)
    if d % 365 == 0:
        years = int(d / 365)
        days = 0
    else:
        years = int(d / 365)
        days = d % 365
    if days % 30 == 0:
        months = days / 30
        days1 = 0
    else:
        months = int(days / 30)
        days1 = days % 30
    res = ("The value converted to {:} years , {:} months , {:} days".format(years, months, days1))
    return render(request, 'n1.html', {'result': res})

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

def testn2(request):
    ID = request.GET['scr1']
    hrs = request.GET['scr2']
    amt = request.GET['scr3']
    salary = int(hrs) * int(amt)
    res = ("Salary of Employee with id {:} is Rs{:}".format(ID, salary))
    return render(request, 'n2.html', {'result': res})

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

def testn3(request):
    nu1 = int(request.GET['scr1'])
    nu2 = int(request.GET['scr2'])
    nu3 = int(request.GET['scr3'])
    if nu1 > nu2 and nu1 > nu3:
        res = "number1 is the greatest if the three"
    elif nu2 > nu1 and nu2 > nu3:
        res = "number2 is the greatest of the three"
    else:
        res = "number3 is the greatest of the three"
    return render(request, 'n3.html', {'result': res})

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

def testn4(request):
    # Taking 2000,500,100,20,10 Notes

    amt1 = request.GET['scr']
    res1000 = 0
    res500 = 0
    res100 = 0
    res20 = 0
    res10 = 0
    amt = int(amt1)
    if amt % 2000 == 0:
        two1000 = int(amt / 2000)
        res1000 = "Rs 2000 notes :" + str(two1000)

    else:
        two1000 = int(amt / 2000)
        amt = amt % 2000
        res1000 = "Rs 2000 notes :" + str(two1000)

        if amt % 500 == 0:
            five100 = int(amt / 500)
            res500 = "Rs 500 notes :" + str(five100)

        else:
            five100 = int(amt / 500)
            amt = amt % 500
            res500 = "Rs 500 notes :" + str(five100)
            if amt % 100 == 0:
                one100 = int(amt / 100)
                res100 = "Rs 100 notes :" + str(one100)
            else:
                one100 = int(amt / 100)
                amt = amt % 100
                res100 = "Rs 100 notes :" + str(one100)
                if amt % 20 == 0:
                    two10 = int(amt / 20)
                    res20 = "Rs 20 notes :" + str(two10)
                else:
                    two10 = int(amt / 20)
                    amt = amt % 20
                    res20 = "Rs 20 notes :" + str(two10)
                    if amt % 10 == 0:
                        one10 = int(amt / 10)
                        res10 = "Rs 10 notes :" + str(one10)
                    else:
                        one10 = int(amt / 10)
                        amt = amt % 10
                        res10 = "Rs 10 notes :" + str(one10)
    return render(request, 'n4.html',
                  {'result2000': res1000, 'result500': res500, 'result100': res100, 'result20': res20,
                   'result10': res10})

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

def testn5(request):
    sec1 = request.GET['scr']
    sec = int(sec1)
    if sec % 3600 == 0:
        hours = int(sec / 3600)
        sec = 0
    else:
        hours = int(sec / 3600)
        sec = sec % 3600
    if sec % 60 == 0:
        minutes = sec / 60
        sec = 0
    else:
        minutes = int(sec / 60)
        sec = sec % 60
    res = ("The value converted to {:} hours , {:} minutes , {:} seconds".format(hours, minutes, sec))
    return render(request, 'n5.html', {'result': res})

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

def testn6(request):
    num_list = list()
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    for i in [n1, n2, n3, n4, n5]:
        num_list.append(int(i))
    sum1 = 0
    for n in num_list:
        if not int(n) % 2 == 0:
            sum1 = sum1 + int(n)
        else:
            continue
    res = ("Sum of Odd values is :" + str(sum1))
    return render(request, 'n6.html', {'result': res})

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

def testn7(request):
    n1 = request.GET['scr']
    n = int(n1)
    months = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
              'November', 'December']
    res = ("The month resembling the value entered is :", months[n - 1])
    return render(request, 'n7.html', {'result': res})

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

def testn8(request):
    n = []
    for i in range(2):
        n.append(input(request.GET['scr']))
    if not int(n[1]) == 0:
        res = ("The result of division is :", (float(n[0]) / float(n[1])))
    else:
        res = "Division not possible"
    return render(request, 'n8.html', {'result': res})

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

def testn9(request):
    cm1 = request.GET['scr']
    cm = float(cm1)
    inches = cm / 2.54
    res = ("The length in inches is :", inches)
    return render(request, 'n9.html', {'result': res})

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

def testn10(request):
    n1 = int(request.GET['scr1'])
    n2 = int(request.GET['scr2'])
    n3 = 0
    n3 = n1
    n1 = n2
    n2 = n3
    res = ("The swapped values :" + n1 + "," + n2)
    return render(request, 'n10.html', {'result': res})

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

def testn11(request):
    n1 = int(request.GET['scr1'])
    n2 = int(request.GET['scr2'])
    n1 = n1 + n2
    n2 = n1 - n2
    n1 = n1 - n2
    res = ("The number of n1 : {:} & n2 : {:} after swapping ".format(n1, n2))
    return render(request, 'n11.html', {'result': res})

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

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

def testa1(request):
    num_list = []
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    n6 = request.GET['scr6']
    n7 = request.GET['scr7']
    for i in [n1, n2, n3, n4, n5, n6, n7]:
        num_list.append(int(i))
    res1 = ("The value at element number : 1 is {:}".format(n1))
    res2 = ("The value at element number : 2 is {:}".format(n2))
    res3 = ("The value at element number : 3 is {:}".format(n3))
    res4 = ("The value at element number : 4 is {:}".format(n4))
    res5 = ("The value at element number : 5 is {:}".format(n5))
    res6 = ("The value at element number : 6 is {:}".format(n6))
    res7 = ("The value at element number : 7 is {:}".format(n7))
    return render(request, 'a1.html',
                  {'result1': res1, 'result2': res2, 'result3': res3, 'result4': res4, 'result5': res5, 'result6': res6,
                   'result7': res7})

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

def testa2(request):
    num_list = []
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    for i in [n1, n2, n3, n4, n5]:
        num_list.append(int(i))
    num_list1 = []
    for n in num_list:
        counter = 0
        n = int(n)
        for i in range(1, n + 1):
            if n % i == 0:
                counter += 1
        if counter == 2:
            num_list1.append(n)
    res = "List of prime numbers in the entered array is :" + str(num_list1)
    return render(request, 'a2.html', {'result': res})

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

def testa3(request):
    num_list = []
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    for i in [n1, n2, n3, n4, n5]:
        num_list.append(int(i))
    res = []
    i = 1
    for n in num_list:
        n = int(n)
        if n < 5:
            res.append("The element at position {:} whose value is {:} less than 5.".format(i, n))
        i += 1
    return render(request, 'a3.html', {'result': res})

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

def testa4(request):
    num_list = []
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    n6 = request.GET['scr6']
    for i in [n1, n2, n3, n4, n5, n6]:
        num_list.append(i)
    reverse = []
    res1 = "Original list is :" + str(num_list)
    num_list.reverse()
    for n in num_list:
        reverse.append(n)
    res2 = "Reversed list is :" + str(reverse)
    return render(request, 'a4.html', {'result1': res1, 'result2': res2})

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

def testa5(request):
    num_list = []
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    n6 = request.GET['scr6']
    for i in [n1, n2, n3, n4, n5, n6]:
        num_list.append(i)
    small_num = None
    small_pos = None
    i = 1
    for n in num_list:
        n = int(n)
        if small_num is None:
            small_num = n
            small_pos = i
        elif n < small_num:
            small_num = n
            small_pos = i
        i += 1
    res = ("The smallest number is {:} at the position : {:}.".format(small_num, small_pos))
    return render(request, 'a5.html', {'result': res})

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

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

def testl1(request):
    num = []
    n1 = request.GET['scr1']
    n2 = request.GET['scr2']
    n3 = request.GET['scr3']
    n4 = request.GET['scr4']
    n5 = request.GET['scr5']
    n6 = request.GET['scr6']
    n7 = request.GET['scr7']
    n8 = request.GET['scr8']
    n9 = request.GET['scr9']
    n10 = request.GET['scr10']
    for i in [n1, n2, n3, n4, n5, n6, n7, n8, n9, n10]:
        num.append(i)
    sum = 0
    for n in num:
        sum += int(n)
    avg = sum / 10
    res = ("Sum : {:}  &  Average : {:.1f}".format(sum, avg))
    return render(request, 'l1.html', {'result': res})

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

def testl2(request):
    n1 = int(request.GET['scr1'])
    product = 1
    for i in range(3):
        product = product * n1
    res = "The product is : " + str(product)
    return render(request, 'l2.html', {'result': res})

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

def testl3(request):
    n = int(request.GET['scr'])
    num_list = []
    for i in range(10):
        product = 1
        product = n * (i + 1)
        num_list.append("{:>2} * {:<2} = {:>1}  ".format(n, (i + 1), product))

    return render(request, 'l3.html', {'result': num_list})

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

def testl4(request):
    n = int(request.GET['scr'])
    sum = 0
    for i in range(1, (n)):
        if n % i == 0:
            sum = sum + i
    if sum == n:
        res = "Perfect number"
    else:
        res = "Not a Perfect number"
    return render(request, 'l4.html', {'result': res})

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

def testl5(request):
    n1 = int(request.GET['scr1'])
    n2 = int(request.GET['scr2'])
    num_list = []
    for n in range(n1, n2 + 1):
        sum = 0

        for i in range(1, n):
            if n % i == 0:
                sum = sum + i
        if sum == n:
            num_list.append(" {:} is a perfect number.".format(sum))
        else:
            num_list.append(" {:} is not a perfect number.".format(n))

    return render(request, 'l5.html', {'result': num_list})

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

def testl6(request):
    n1 = int(request.GET['scr1'])
    n2 = int(request.GET['scr2'])
    sum = 0
    for n in range(n1, n2 + 1):
        if not n % 17 == 0:
            sum += n
    res = ("The sum of numbers in the range not divisible by 17 is {:} .".format(sum))
    return render(request, 'l6.html', {'result': res})

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

def testl7(request):
    num = int(request.GET['scr'])
    counter = 0
    for i in range(1, num + 1):
        if num % i == 0:
            counter += 1
    if counter == 2:
        res = "The entered number is prime."
    else:
        res = "The entered number is not prime."
    return render(request, 'l7.html', {'result': res})

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

def testl8(request):
    num = int(request.GET['scr'])
    product = 1
    for i in range(1, num + 1):
        product *= i
    res = ("The factorial of the entered number is : " + str(product))
    return render(request, 'l8.html', {'result': res})

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

def testl9(request):
    n1 = int(request.GET['scr1'])
    n2 = int(request.GET['scr2'])
    num_list = []
    for num in range(n1, n2 + 1):
        counter = 0
        for i in range(1, num + 1):
            if num % i == 0:
                counter += 1

        if counter == 2:
            num_list.append("The number {:} is prime.  ".format(num))
        else:
            num_list.append("The number {:} is not prime.  ".format(num))
    return render(request, 'l9.html', {'result': num_list})

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

def testl10(request):
    num = int(request.GET['scr'])
    num1 = num
    sum = 0
    while num1 > 0:
        m = num1 % 10
        sum = sum + m ** 3
        num1 = num1 // 10
    if sum == num:
        res = "The entered number is armstrong."
    else:
        res = "The entered number is not armstrong."
    return render(request, 'l10.html', {'result': res})

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

def testl11(request):
    num_list = []
    for n in range(1, 1001):
        sum1 = 0
        m = n
        while m > 0:
            a = m % 10
            sum1 += a ** 3
            m = m // 10
        if sum1 == n:
            num_list.append("The number {:} is armstrong.  ".format(n))
        else:
            num_list.append("The number {:} is not armstrong.  ".format(n))
    return render(request, 'l11.html', {'result': num_list})

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

def testl12(request):
    num_list = []
    n1 = int(request.GET['scr1'])
    n2 = int(request.GET['scr2'])
    for n in range(n1, n2 + 1):
        if n < 7:
            continue
        if not n % 7 == 0:
            if n % 7 == 2 or n % 7 == 3:
                m = n % 7
                num_list.append("{:} being divided by 7 leaves remainder {:}.  ".format(n, m))
    return render(request, 'l12.html', {'result': num_list})

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

def testl13(request):
    n = int(request.GET['scr'])
    num_list = []
    for i in range(1, n + 1):
        if n % i == 0:
            num_list.append("{:} is a divisor for the entered number.  ".format(i))
    return render(request, 'l13.html', {'result': num_list})

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

def testl14(request):
    n = int(request.GET['scr'])
    sum1 = 0
    m = n
    while m > 0:
        a = m % 10
        sum1 = sum1 * 10 + a
        m = m // 10
    res = ("The reverse of the entered number is : " + str(sum1))
    return render(request, 'l14.html', {'result': res})


import itertools
import json
import operator
import re
import warnings

from functools import reduce

polish_json_filename = './static/polish_words.json'
lemko_json_filename = './static/lemko_words.json'

def firstLetterFromSentencesToUpper(sentences):
    return [sent[0].upper() + sent[1:] for sent in sentences]

# does a permutation lists
def listsToSentences(lists):
    sets_of_words = list(itertools.product(*lists))
    sentences = [" ".join(list(sets_of_words[i])) for i in range(0, sets_of_words.__len__() - 1)]
    sentences = firstLetterFromSentencesToUpper(sentences)
    return sentences

def saveLemkosSentences(sentences):
    lem_sentences_file = open("data/lemkos_sentences.txt", 'w', encoding="UTF-8")
    for sent in sentences:
        lem_sentences_file.write(sent + "\n")

def savePolishSentences(sentences):
    pl_sentences_file = open("data/polish_sentences.txt", 'w', encoding="UTF-8")
    for sent in sentences:
        pl_sentences_file.write(sent + "\n")

# l_lem is list of lists of words (noun, verb, etc.)
def createAndSaveToFileSentences(l_lem, l_pl):
    lem_sentences = listsToSentences(l_lem)
    pl_sentences = listsToSentences(l_pl)
    saveLemkosSentences(lem_sentences)
    savePolishSentences(pl_sentences)

def flatten(l: []):
    return reduce(operator.concat, l)

def unnest_list(l: []):
    while True:
        l = flatten(l)
        try:
            if len(l) > 0:
                continue
        except Exception:
            return l
        return l

def get_words(sentence):
    return [word.lower() for word in re.findall(r'\w+', sentence) if word != '']

def format_text(text: str):
    pattern = re.compile(r'\s+')
    formatted = re.sub(pattern, ' ', text).lower()
    return formatted

def remove_none(l: []):
    return list(filter(lambda x: x != None, l))

def get_polish_base_forms_from_json_file():
    polish_dict = {}
    with open("data/polish_words.json", "r", encoding="utf8") as file:
        polish_dict = json.load(file)
    return list(polish_dict.keys())

def zip_nums_with_values(values):
    n = len(values) + 1
    return dict(list(zip(range(0, n), values)))

def get_values_from_index(table: [], indx: []):
    res = []
    try:
        for i in indx:
            res.append(table[i])
    except IndexError as e:
        print('Index error')
        return res
    return res

# it additionally reload polish_dict variable from polish_json_file_worker file
def save_polish_word_to_file(polish_word):
    if polish_word != {}:
        with open(polish_json_filename, "r", encoding="utf8") as file:
            polish_dict = json.load(file)
        polish_dict.update(polish_word)
        with open(polish_json_filename, 'wb') as file:
            file.write(json.dumps(polish_dict, indent=2, sort_keys=True, ensure_ascii=False).encode('utf8'))
            return True

def save_lemko_word_to_file(lemko_word):
    with open("data/lemko_words.json", "r", encoding="utf8") as file:
        lemko_dict = json.load(file)
    lemko_dict.update(lemko_word)
    with open('data/lemko_words.json', 'wb') as file:
        file.write(json.dumps(lemko_dict, indent=2, sort_keys=True, ensure_ascii=False).encode('utf8'))
        return True

def is_node_set(node: {}):
    return node != {} and node != ''

def get_node_key(node: {}):
    if is_node_set(node):
        return list(node.keys())[0]
    else:
        warnings.warn('Pusty node')
        return None

def get_node_val(node: {}):
    if is_node_set(node):
        return list(node.values())[0]
    else:
        return None

def get_keys(node: {}):
    if is_node_set(node):
        return list(node.keys())
    else:
        warnings.warn('Pusty node')
        return None

def get_values(node: {}):
    if is_node_set(node):
        return list(node.values())
    else:
        warnings.warn('Pusty node')
        return None


from datetime import date, timedelta
from decimal import *
import pdb

"""
Module construct
---------------------
class InvalidOperationError
    custom build exception class that contains a message
class UserQuitException
    custom build exception class that contains a message
class Accountant
    Transaction _transactions[]
    Trip _tdy

    method __init__()
    method get_transaction_value(variable_name, transaction_index)
    method get_trip_value(variable_name)
    static method convert_to_date(d)
    method trip_parameters_set()
    method load_data()
    method save_data()
    method set_per_diem_data(begin_date, end_date, travel_per_diem, daily_per_diem)
    method calculate_trip_duration()
    method calculate_per_diem_total()
    method add_transaction(name, transaction_date, amount, remarks)
    method find_transaction(find_me)
    method calculate_total_spent()
    method calculate_earned_per_diem()
    method modify_transaction(transaction_number, name, transaction_date, amount, remarks)
    method num_transactions()
class Transaction
    String name
    Date transaction_date
    Decimal amount
    String remarks

    method __init__(name, transaction_date, amount, remarks)
class Trip
    Date _begin_date
    Date _end_date
    Decimal _daily_per_diem
    Devimal _travel_per_diem

    method set_per_diem(daily_per_diem, travel_per_diem)
    method set_dates(begin_date, end_date)
    method retrieve_values()
    method dates_set()
    method per_diem_values_set()
    method calculate_duration()
    method calculate_per_diem_total()
    method calculate_earned_per_diem()
"""

class InvalidOperationError(Exception):  # exception class
    def __init__(self, message):
        self.message = message

class UserQuitException(Exception): # exception class
    def __init__(self, message):
        self.message = message

class Accountant:
    # Class contains transaction and perdiem data and performs operations on them

    def __init__(self):
        self._transactions = []
        self._tdy = Trip() # create Trip object with dummy values (values will be set later)

    def get_transaction_value(self, variable_name, transaction_index):
        """
        This function is a one stop shop for necessary variable data
        Input
            variable_name - name of the variable caller wants a value for
                possibilities include: "begin date", "end date" "daily per diem" "travel per diem"
            transaction_index = 0 - which transaction the caller wants values for
        Return
            value of variable requested
        Throws
            value error if name is incorrect
        """
        # step 1: create a check to ensure transaction_index is not out of bounds of existing transactions
        in_list_bounds = transaction_index < len(self._transactions)

        # step 2: if not in bounds, raise an exception
        if not in_list_bounds:
            raise ValueError("Debug Error: Accountant.get_transaction_value requested transaction does not exist")

        # step 3: check which variable to caller is asking for and return that value
        if variable_name == "name":
            return self._transactions[transaction_index].name
        elif variable_name == "date":
            return self._transactions[transaction_index].transaction_date
        elif variable_name == "amount":
            return self._transactions[transaction_index].amount
        elif variable_name == "remarks":
            return self._transactions[transaction_index].remarks
        else: # step 4: if none of the previous checks are correct, the caller isn't asking for a valid variable
            raise ValueError("Debug error: Accountant.get_transaction_value variable does not exist")

    def get_trip_value(self, variable_name):
        """
        This function is a one stop shop for necessary variable data
        Input
            variable_name - name of the variable caller wants a value for
            possibilities include: "begin date", "end date" "daily per diem" "travel per diem"
            trip_index = 0 - which trip the caller wants values for
        Return
            value of variable requested
        Throws
            value error if name is incorrect
        """

        # step 1: pull dictionary variable containing trip's values from Trip method
        pulled_values = self._tdy.retrieve_values()

        # step 2: determine what caller is asking for and return that value
        try:
            if variable_name == "begin date":
                return pulled_values['begin_date']
            elif variable_name == "end date":
                return pulled_values['end_date']
            elif variable_name == "daily per diem":
                return pulled_values['daily_per_diem']
            elif variable_name == "travel per diem":
                return pulled_values['travel_per_diem']
            else: # step 3: handle error scenarios
                raise InvalidOperationError("Debug error: Accountant.get_trip_values: trip variable does not exist")
        except InvalidOperationError as e:
            raise e

    @staticmethod  # This means we can call the method without initializing an object
    def convert_to_date(d):
        """
        This function accepts a date and attempts to convert it to date object
        Input
            d - the date string to convert to a date object.  Must be military time
        Returns
            date object
        Throws
            value error if date can't be converted
        """

        # step 1: ensure method parameter is an integer
        try:
            begging_value = int(d)
        except ValueError as e:
            raise e

        # step 2: convert the method parameter to a string
        working_value = str(begging_value)

        # step 3: cut up string into year, month and day segments
        try:
            result = date(int(working_value[:4]), int(working_value[4:6]), int(working_value[6:]))
        except ValueError as e:  # step 4: raise value error if number can't be parsed into a date
            raise e

        # step 5: return resulting date object
        return result

    def trip_parameters_set(self):
        """
    Determines whether a trip's date and per diem values have been set
    Input
        none
    Returns
        answer - boolean value indicating whether the trip has values
    Throws
        none
        """
        # step 1: combine dates_set() and per_diem_values_set() with "and".  If either is false, method returns false.
        return self._tdy.dates_set() and self._tdy.per_diem_values_set()

    def load_data(self):
        """
        This function loads data from the file ledger.txt
        Input
            none
        Returns
            none
        Throws
            Invalid operation error if ledger.txt is not found
        """

        # step 1: open the file in read only mode
        try:
            file = open("ledger.txt", "r")
        except IOError:  # todo: incorporate better "file missing" logic
            raise InvalidOperationError("Ledger.txt not found")

        # step 2: read each line of the file into an array
        file_data = []  # this is the array we will read all data into

        for line in file:
            file_data.append(line)

        # step 3: close the file
        file.close()

        # todo: check file inputs for bad data and raise ValueError exception if necessary
        # todo: parse all file data before loading any of it into accountant object
        try:
            temp = file_data[0]
            begin_date = date(int(temp[0:4]), int(temp[4:6]), int(temp[6:]))

            temp = file_data[1]
            end_date = date(int(temp[0:4]), int(temp[4:6]), int(temp[6:]))

            travel_per_diem = Decimal(file_data[2])
            daily_per_diem = Decimal(file_data[3])

            # step 5: set per diem and dates values in default TDY
            self._tdy.set_per_diem(daily_per_diem, travel_per_diem)
            self._tdy.set_dates(begin_date, end_date)

            # step 6: iterate through each transaction pulled from the file
            i = 4  # index number,starts after previous reads for trip data is done
            while i + 4 <= len(file_data):  # continue until file_data is out of records
                # store next transaction's name and increment index
                name = file_data[i]
                name = name[:-1]  # this cuts off the newline character
                i += 1

                # store transaction date and increment index
                temp = file_data[i]
                transaction_date = date(int(temp[0:4]), int(temp[4:6]), int(temp[6:]))
                i += 1

                # store transaction amount and increment index
                amount = Decimal(file_data[i])
                i += 1

                # store transaction remarks and increment index
                remarks = file_data[i]
                remarks = remarks[:-1]  # this cuts off the newline character
                i += 1

                # step 7: add pulled transaction data to new transaction
                self.add_transaction(name, transaction_date, amount, remarks)
        except IndexError as e:
            raise e

    def save_data(self):
        """
        This function saves data to the file ledger.txt
        Input
            none
        Returns
            none
        Throws
            Invalid Operation error if tdy is not initialized
        """

        # step 1: open file ledger.txt in write mode
        file = open("ledger.txt", "w")

        # step 2: write beginning and end date along with per diem values
        try:
            pulled_values = self._tdy.retrieve_values()
            file.write(pulled_values['begin_date'].strftime("%Y%m%d") + "\n")
            file.write(pulled_values['end_date'].strftime("%Y%m%d") + "\n")
            file.write(str(pulled_values['travel_per_diem']) + "\n")
            file.write(str(pulled_values['daily_per_diem']) + "\n")
        except InvalidOperationError as e:  # Trip.retrieve values can throw exception if object is not initialized
            raise e

        # step 3: loop through each transaction and write their values
        i = 0
        while True:
            if i >= len(self._transactions):
                break

            file.write(self._transactions[i].name + "\n")
            file.write(str(self._transactions[i].transaction_date.strftime("%Y%m%d")) + "\n")
            file.write(str(self._transactions[i].amount) + "\n")
            file.write(str(self._transactions[i].remarks) + "\n")

            i += 1

        # step 4: close the file
        file.close()

    def set_per_diem_data(self, begin_date, end_date, travel_per_diem, daily_per_diem):
        """
        Function sets per diem data for a trip
        Input
            date and per diem values to pass to Trip object
        Returns
            none
        Throws
            Value errors if bad data is passed to the program
        """
        # step 1: sanitize date values
        if not isinstance(begin_date, date) or not isinstance(end_date, date):
            raise InvalidOperationError("Debug error: dates provided to Bank.setperdiemdata are not correct type")
        if end_date <= begin_date:
            raise InvalidOperationError("Debug error: Bank.setperdiemdata: end date is <= to begin date")

        # step 2: sanitize per diem values
        if not isinstance(travel_per_diem, Decimal) or not isinstance(daily_per_diem, Decimal):
            raise InvalidOperationError("Debug error: Bank.setperdiemdata: per_diem data provided are not Decimal")
        if travel_per_diem < 0 or daily_per_diem < 0:
            raise InvalidOperationError("Debug error: Bank.setperdiemdata: per_diem data not valid")

        # step 3: set tdy values by calling Trip object methods
        try:
            self._tdy.set_per_diem(daily_per_diem, travel_per_diem)
            self._tdy.set_dates(begin_date, end_date)
        except ValueError as e:
            raise e

    def calculate_trip_duration(self):
        """
        Function returns the duration of the TDY
        Input
            none
        Returns
            duration of trip
        Throws
            Invalid Operation Error if trip is not initialized
        """

        # step 1: call upon Trip object to calculate own duration
        try:
            result = self._tdy.calculate_duration()
        except InvalidOperationError as e:  # this exception occurs if Trip object's dates have not been set
            raise e

        # step 2: return the result
        return result

    def calculate_per_diem_total(self):
        """
        Method returns the amount of per diem for the a Trip object
        Input
            trip_index=0 - indicates which Trip object to perform calculations on
        Returns
            total per diem for trip
        Throws
            Invalid Operation Error dates or per diem totals have not been set
        """

        # step 1: call on Trip object to calculate its own per diem total
        try:
            total = self._tdy.calculate_per_diem_total()
        except InvalidOperationError as e: # exception occurs if Trip object date or per diem values not set
            raise e

        # step 2: return the total per diem
        return total

    def add_transaction(self, name, transaction_date, amount, remarks):
        """
        Adds a single transaction to Transaction array
        Input
            name - the name of the transaction
            transaction_date - the date of the transaction
            amount - the amount of the transaction
            remarks - remarks for the transaction
        Returns
            index of new transaction's location
        Throws
            Invalid Operation Error if parameters are not valid
            Value Error if attempted duplicate transaction
        """
        # step 1: create new Transaction object and append to Transaction array
        try:
            new_transaction = Transaction(name, transaction_date, amount, remarks)

            # detect duplicate transaction
            self.find_transaction(new_transaction)

            self._transactions.append(new_transaction)

            # step 2: sort the transactions by date
            self._transactions = sorted(self._transactions, key=lambda Transaction: Transaction.transaction_date)

            return self.find_transaction(new_transaction)

        except InvalidOperationError as e: # most likely a duplicate transaction
            raise e

    def find_transaction(self, find_me):
        """
        Finds a transaction and returns it's location in the list
        params: find_me -- the transaction object to find
        returns: location as an integer
        Throws: ValueError if param is not transaction or transaction is not found
        """
        # todo: test function

        # initialize variables
        result = -1 # stores find_me's location
        temp_index = 0 # keeps track of our location in the list

        # check find_me is valid Transaction object
        if not isinstance(find_me, Transaction):
            raise ValueError("Accountant.find_transaction param not valid")

        # iterate over list of transactions to find find_me
        for transaction in self._transactions:
            amount_same = transaction.amount == find_me.amount
            date_same = transaction.transaction_date == find_me.transaction_date
            amount_same = transaction.amount == find_me.amount
            remarks_same = transaction.remarks == find_me.remarks

            if amount_same and date_same and amount_same and remarks_same:
                if not result == -1: # case that we have already found the transaction
                    raise InvalidOperationError("Error: duplicate transactions exist")
                result = temp_index
                temp_index += 1
            else:
                temp_index += 1

        return result

    def calculate_total_spent(self):
        """
        Sums the amount parameter in all transactions and returns the result
        Input
            none
        Returns
            sum of all Transactions amount
        Throws
            none
        """

        # step 1: initialize placeholder for result
        total = 0

        # step 2: iterate through each transaction and add each amount to the total
        for t in self._transactions:
            total = total + t.amount

        # step 3: return the total
        return total

    def calculate_earned_per_diem(self):
        """
        Calls Trip object to calculate how much per diem we have earned based on the current date
        Input
            none
        Returns
            earned per diem
        Throws
            none
        """

        # step 1: have the Trip object do the calculation and return the result
        return self._tdy.calculate_earned_per_diem()

    def modify_transaction(self, transaction_number, name, transaction_date, amount, remarks):
        """
        Changes a transaction
        Input
            transaction_numer - index of transaction we want to modify
            name - new transaction name
            transaction_date - new transaction date
            amount - new transaction amount
            remarks - new transaction remarks
        Returns
            none
        Throws
            InvalidOperationError if transaction object index is out of range of current transaction array
        """
        # todo: function testing

        # step 1: check that transaction index number is not out of array range
        if len(self._transactions) < transaction_number:
            raise InvalidOperationError("transaction number out of range")

        # step 1.1: check for duplicate transaction
        new_transaction = Transaction(name, transaction_date, amount, remarks) # this will throw an exception if duplicate

        try:
            self.find_transaction(new_transaction) # find where the current transaction is
        except InvalidOperationError as e:
            raise e

        # Step 2: remove old transaction
        self._transactions.remove(self._transactions[transaction_number - 1])

        # Step 3: use bank's own add_transaction function to add transaction
        self.add_transaction(new_transaction.name, new_transaction.transaction_date, new_transaction.amount, new_transaction.remarks)

        # Step 4: sort with the new transactions
        self._transactions = sorted(self._transactions, key=lambda Transaction: Transaction.transaction_date)

        return self.find_transaction(new_transaction)

    def num_transactions(self):
        return len(self._transactions)

class Transaction:
    # Class contains data for individual _transactions
    # Data: date, name, amount, remarks
    def __init__(self, name, transaction_date, amount, remarks):
        # first step: sanitize input
        # todo: change InvalidOperationErrors to ValueErrors
        if isinstance(amount, int): # if amount is an integer, we can convert it to a Decimal
            amount = Decimal(amount)

        if not isinstance(name, str) or not isinstance(amount, Decimal) or not isinstance(remarks, str):
            raise InvalidOperationError("Debug error: Transaction init; values passed not valid type")
        if not isinstance(transaction_date, date):
            raise InvalidOperationError("Debug error: Transaction init; values passed not valid type")

        if not amount > 0:
            raise InvalidOperationError("Debug error: Transaction init; amount not greater than 0")

        # set object values
        self.name = name
        self.transaction_date = transaction_date
        self.amount = amount
        self.remarks = remarks

class Trip:
    # Class contains beginning and end dates of a trip, per diem info and calculations
    def __init__(self, begin_date = date(1950, 1, 1) , end_date = date(1950, 1, 1), daily_per_diem = -1, travel_per_diem = -1):
        self._begin_date = begin_date
        self._end_date = end_date
        self._daily_per_diem = daily_per_diem
        self._travel_per_diem = travel_per_diem

    def set_per_diem(self, daily_per_diem, travel_per_diem):
        """
        Function used to set optional per diem values
        parameters: Decimal daily_per_diem and travel_per_diem
        throws Value error if parameters are not Decimal
        returns: none
        """
        # step 1: make sure per diem values provided to function are integers or Decimal
        if (not isinstance(daily_per_diem, Decimal) and not isinstance(daily_per_diem, int)) or (not isinstance(travel_per_diem, Decimal) and not isinstance(travel_per_diem, int)):
            raise ValueError('Debug error: Trip.set_per_diem; values passed not Decimal or int')

        # step 2: make sure the per diem values provided to function make sense (not negative)
        if daily_per_diem < 0 or travel_per_diem < 0:
            raise ValueError('Debug error: Trip.set_per_diem; values passed must be positive')

        # step 3: store per diem values as Decimals
        self._daily_per_diem = Decimal(daily_per_diem)
        self._travel_per_diem = Decimal(travel_per_diem)

    def set_dates(self, begin_date, end_date):
        """
        Function used to set begin and end dates
        parameters: Date objects for the beggining and end dates of trip
        throwns: ValueError if parameters are not date objects
        returns: none
        """
        # step 1: ensure that parameters provided are Date objects
        if not isinstance(begin_date, date) or not isinstance(end_date, date):
            raise ValueError('Debug error: Trip.set_dates; error: parameters provided not date objects')

        # step 2: ensure that begin_date and end_dates make sense
        if end_date <= begin_date:
            raise ValueError('Debug error: Trip.set_dates; error: trip end date should be after begin date')

        # step 3: set begin and end dates to provided values
        self._begin_date = begin_date
        self._end_date = end_date

    def retrieve_values(self):
        """
        Function used to retrieve all values from the Trip.
        parameters: none
        returns: dictionary containing all values.  These values can be modified without affecting object's variables
        throws: none
        """
        # step 1: make sure Trip object has been initialized (provided legit values for)
        if not self.dates_set():
            raise InvalidOperationError('Debug error: Trip.retrieve_values; error:attempted to retrieve vales before '
                                        'object is initialized')

        # step 2: create a dictionary with date objects belonging to Trip object
        values = {'begin_date': self._begin_date, 'end_date': self._end_date}

        # step 2: if per diem values are set, include those as well
        if self.per_diem_values_set():
             values['daily_per_diem'] = self._daily_per_diem
             values['travel_per_diem'] = self._travel_per_diem

        # step 3: return dictionary to caller
        return values

    def dates_set(self):
        """
        Function used to determine whether Trip object has been provided proper dates
        parameters: none
        returns: boolean indicating if object is initialized
        throws: none
        """
        # step 1: check all mandatory variables against the default values to make sure some value has been provided to it
        # the only mandatory variables are the begin_date and the end_date, as of right now
        if self._begin_date == date(1950, 1, 1) or self._end_date == date(1950, 1, 1):
            return False

        # step 2: if you make it past that first check, values are good and we return true
        return True

    def per_diem_values_set(self):
        """
        Function check per diem values to see if they have been set
        parameters: none
        returns: boolean indicating if per diem values have been set
        throws: none
        """
        # step 1: check per diem values against defaults
        if self._daily_per_diem == -1 or self._travel_per_diem == -1:
            return False

        # step 2: if we got past the first check, we must be good
        return True

    def calculate_duration(self):
        """
        Method returns the duration of this TDY
        Input
            none
        Returns
            duration of trip
        Throws
            Invalid Operation Error if object is not initialized
        """
        # step 1: check if trip object is initialized
        if not self.dates_set():
            raise InvalidOperationError("Debug error: Trip.calculate_duration() trip dates not set")

        # Create timedelta object that is the difference between two dates
        result = self._end_date - self._begin_date

        # Result will be short one day, so we create a timedelta object of one day
        modification = timedelta(days=1)

        # Finally, we add modification to result
        result = result + modification

        return result

    def calculate_per_diem_total(self):
        """
        Method returns the amount of per diem for a trip object
        Input
            none
        Returns
            total per diem for trip
        Throws
            Invalid Operation Error dates or per diem totals have not been set
        """
        # step 1: ensure dates and per diem values have been set
        if not self.dates_set() or not self.per_diem_values_set():
            raise InvalidOperationError("Debug Error: Trip.calculate_per_diem_total() dates/perdiem not set")

        # step 2: double the travel per diem total
        total = self._travel_per_diem * 2

        # step 3: calculate the duration of the trip
        duration = self.calculate_duration().days

        # step 4: multiply the duration by the daily per diem
        total += (duration - 2) * self._daily_per_diem

        # step 5: return the total per diem
        return total

    def calculate_earned_per_diem(self):
        """
        Calculates how much per diem we have earned based on the current date
        Params:
            none
        Returns:
            earned per diem as double
        Throws: InvalidOperationError if trip not initialized correctly
        """

        # check if tdy is in a valid state
        if not self.dates_set() or not self.per_diem_values_set():
            raise InvalidOperationError("Debug Error: Trip.calculate_earned_per_diem -- trip object not in valid state")

        # initialize variabels
        total = 0

        # if tdy hasn't started yet, return 0
        if date.today() < self._begin_date:
            return 0

        # if the entire tdy has passed, return the total
        if date.today() >= self._end_date:
            return self.calculate_per_diem_total()

        # based on our previous checks, today must be on, or after, the first travel day
        total += self._travel_per_diem

        # calculate how many days have transpired (not including the first travel day)
        time_spent = date.today() - self._begin_date
        # note: because of the way dates are subtracted, it will be short 1 day. In this function, that
        # missing day is treated as the first travel day, making the calculations work.
        days = time_spent.days

        # multiple days by daily_per_diem and add to total
        total += (self._daily_per_diem * days)

        return total


#! /usr/bin/env python3

from PIL import Image
import os
import argparse

parser = argparse.ArgumentParser(description = "Convert all png files to a gif animation, reserve the transparent attribute.")

parser.add_argument("--duration", type = float, default = 0.1, help = "Duration of each frame, in unit s, should be a multiple of 0.01")
parser.add_argument("--reverse", type = bool, default = False, help = "Whether reverse the animation or not")
parser.add_argument("--loop", type = int, default = 0, help = "Loop how many times, 0 for infinite")
parser.add_argument("--output", type = str, default = "out.gif", help = "Output file name")

args = parser.parse_args()

def gen_frame(path):
    im = Image.open(path)
    alpha = im.getchannel('A')

    # Convert the image into P mode but only use 0xFF colors in the palette out of 0x100
    im = im.convert('RGB').convert('P', palette = Image.ADAPTIVE, colors = 0xFF)

    # Set all pixel values below 128 to 0xFF , and the rest to 0
    mask = Image.eval(alpha, lambda _: 0xFF if _ <= 0x80 else 0x00)

    # Paste the color of index 0xFF and use alpha as a mask
    im.paste(0xFF, mask)

    # The transparency index is 0xFF
    im.info['transparency'] = 0xFF

    return im

images = [gen_frame(filename) for filename in sorted([fn for fn in os.listdir(".") if fn.endswith(".png")], reverse = args.reverse)]
images[0].save(args.output if args.output.endswith(".gif") else ".".join([args.output, "gif"]), \
    save_all = True, append_images = images[1:], loop = args.loop, duration = int(1E3 * args.duration), disposal = 2) # disposal should be 2 or 3
for _ in images: _.close()


import itertools
import string

#chars = string.digits

chars = input("Entre com a string a ser permutada: ex(luis123@) \n")

resultado = itertools.permutations(chars, len(chars))

for i in resultado:
    print(''.join(i))
    if 'sanethay@' == ''.join(i):
        break
    if 'teste123' == ''.join(i):
        break


import tensorflow as tf
import numpy as np
import cv2
import os
from tqdm import tqdm
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from random import shuffle

in_data = '/Users/ibneetkaur/Desktop/coding/image_recognizer/train'

def refining_img():
    labeled_images = []
    for i in tqdm(os.listdir(in_data)):
        path = os.path.join(in_data,i)
        img = cv2.imread(path)
        if img is not None:
            img = cv2.resize((cv2.cvtColor(img,cv2.COLOR_BGR2RGB)),(100, 100))
       #    img = cv2.resize(img,(100,100))
            labeled_images.append([np.array(img), img_label(i)])
        else:
            print('Image not loaded')
        shuffle(labeled_images)
    return labeled_images

def img_label(img):
    img_lbl = []
    label = img.split('.')[0]
    if label == 'Ibneet':
        img_lbl = np.array([1,0])
    elif label == 'Gurjot':
        img_lbl = np.array([0,1])
    return img_lbl

from keras.models import Sequential
from keras.layers import *
from keras.optimizers import *
from keras.models import Model
from keras.utils import print_summary

images_with_label = np.asarray(refining_img())

images = np.array([i[0] for i in images_with_label]).reshape(-1,100,100,3)
label = np.array([i[1] for i in images_with_label])

train_img, test_img, train_lbl, test_lbl = train_test_split(images, label, test_size=0.2,
                                                    random_state=42)

input_img = Input(shape=(100, 100, 3))

x1 = Conv2D(64, (3, 3), activation='relu', padding='same')(input_img)
x2 = MaxPooling2D((2, 2), padding='same')(x1)
x3 = Conv2D(32, (3, 3), activation='relu', padding='same')(x2)
x4 = MaxPooling2D((2, 2), padding='same')(x3)
x5 = Conv2D(32, (3, 3), activation='relu', padding='same')(x4)
encoded = MaxPooling2D((2, 2), padding='same')(x5)

y1 = Flatten()(x5)
y2 = Dense(1024, activation='relu')(y1)
y3 = Dropout(0.2)(y2)
y4 = Dense(2, activation='softmax')(y3)

#x6 = Conv2D(32, (3, 3), activation='relu', padding='same')(encoded)
#x7 = UpSampling2D((2, 2))(x6)
#x8 = Conv2D(32, (3, 3), activation='relu', padding='same')(x7)
#x10 = Conv2D(64, (3, 3), activation='relu')(x9)
#x11 = UpSampling2D((2, 2))(x10)
#decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x11)

autoencoder = Model(input_img, y4)

encoder = Model(input_img, encoded)

autoencoder.compile(optimizer='adam', loss='categorical_crossentropy',metrics=['accuracy'])

print_summary(autoencoder)

train_img = train_img.astype('float32')
train_img /= 255

test_img = test_img.astype('float32')
test_img /= 255

autoencoder.fit(train_img, train_lbl,
                epochs=50,
                batch_size=20,
                shuffle=True)

predicted_imgs = autoencoder.predict(test_img)

plt.figure(figsize=(40, 40))
for i in range(10):
    # display original images
    ax = plt.subplot(3, 20, i + 1)
    plt.imshow(train_img[i])
    plt.title(train_lbl[i])
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

plt.figure(figsize=(40, 40))
for i in range(20):
    # display original images
    ax = plt.subplot(3, 20, i + 1)
    plt.imshow(test_img[i])
    if np.argmax(predicted_imgs[i]) == 1:
        lbl = 'Gurjot'
    else:
        lbl = 'Ibneet'
    plt.title(lbl)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

#############################################################################################
from playsound import playsound

def detect():
    faceCascade = cv2.CascadeClassifier('/Users/ibneetkaur/Downloads/haarcascade_frontalface_default.xml')
    cap = cv2.VideoCapture(0)
    cap.set(3,640)
    cap.set(4,480)

    font = cv2.FONT_HERSHEY_SIMPLEX

    while True:
        ret, img = cap.read()
        img = cv2.flip(img, 1)
        img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        faces = faceCascade.detectMultiScale(
                img_rgb,
                scaleFactor=1.2,
                minNeighbors=5,
                minSize=(100, 100)
                )
        if len(faces) > 0:
            for (x,y,w,h) in faces:
                cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

                image = cv2.resize(img[y:y+h,x:x+w],(100,100))
#                image = img_rgb[y:y+h,x:x+w]
                image = np.reshape(image,(-1,100,100,3))
                image = image.astype('float32')
                image /= 255

                predicted_imgs = autoencoder.predict(image)

                if predicted_imgs[:,1] > 0.7:
                    lbl = 'Gurjot'
                    wel = playsound("welcome1.mp3")
                elif predicted_imgs[:,0] > 0.7 :
                    lbl = 'Ibneet'
                    wel = playsound("welcome2.mp3")
                else:
                    lbl = 'Unkown'

                id = lbl
                print(predicted_imgs)

                cv2.putText(
                    img,
                    str(id),
                    (x+5,y-5),
                    font,
                    1,
                    (255,255,255),
                    2
                   )
                wel
                cv2.imshow('Input',img)
                k = cv2.waitKey(10) & 0xff
                if k == 27: # press 'ESC' to quit
                    break
    cap.release()
    cv2.destroyAllWindows()
    cv2.waitKey(1)

enter = input('Press a to start webcam predictions.')

if enter == 'a':
    detect()

from gtts import gTTS

message1 = gTTS(text='Hi Gurjot! How are you.', lang='en', slow=False)
message2 = gTTS(text='Hi Ibneet! How are you.', lang='en', slow=False)

message1.save("welcome1.mp3")
message2.save("welcome2.mp3")


import psycopg2
import time
from configparser import ConfigParser

config = ConfigParser()
config.read(['/etc/flant-testcase.conf'])

db_url = config.get('main', 'database')
db = psycopg2.connect(db_url)

def save_hit(url):
    crs = db.cursor()
    crs.execute('insert into hit (url) values (%(url)s)',
                {'url': url})
    crs.close()
    db.commit()

def application(env, start_response):
    url = env["PATH_INFO"]
    save_hit(url)
    start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
    return ["That's what we've got: {0}@{1}".format(url, unicode(time.time()))]


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.support.ui import WebDriverWait

drive_path = '/home/jhomani/projects/python/geckodriver'
uri = "https://www.bing.com/translator"

def config():
  driver = webdriver.Firefox(service=Service(executable_path=drive_path))

  driver.get(uri)
  driver.implicitly_wait(0.5)

  src_options = driver.find_element(by=By.ID, value="tta_srcsl")
  src_options.click()
  option = src_options.find_element(by=By.CSS_SELECTOR, value="option[value=es]")
  option.click()

  src_options = driver.find_element(by=By.ID, value="tta_tgtsl")
  src_options.click()
  option = src_options.find_element(by=By.CSS_SELECTOR, value="option[value=en]")
  option.click()

  return driver

wait_translation = lambda d : d.find_element(
  By.CSS_SELECTOR,
  "div[class=tta_playc]"
)

def translate_phrases(phrases = []):
  translated = []

  driver = config()

  text_box = driver.find_element(by=By.ID, value="tta_input_ta")
  target_box = driver.find_element(by=By.ID, value="tta_output_ta")
  clear_btn = driver.find_element(by=By.ID, value="tta_clear")

  for item in phrases:
    text_box.send_keys(item)

    WebDriverWait(driver, timeout=5).until(wait_translation)

    translated.append(target_box.get_attribute('value'))

    clear_btn.click()

  driver.quit()

  return translated

target_list = [
  "En ese ejemplo, pasamos una función anónima.",
  "Esto no es ejemplo, pasamos una función anónima.",
  "Amo los ejemplo, pasamos una función anónima.",
]

print(translate_phrases(target_list))


# Stdlib imports
# Core Django imports
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _

# Third-party app imports
# Imports from my app

class StationsPlotsConfig(AppConfig):
    name = "src.plots"
    verbose_name = _("StationsPlots")

class DomainsPlotsConfig(AppConfig):
    name = "src.plots"
    verbose_name = _("DomainsPlots")


import requests
import random
import asyncio
import os

progress = [
"""
┳━━━━━━━━━━┓
┃         🏮
┃         /|\\
┃
┃
┃
┃
┃
┃
"""
,
"""
┳━━━━┿━━━━━┓
┃         🏮
┃         /|\\
┃
┃
┃
┃
┃
┃
"""
,
"""
┳━━━━┿━━━━━┓
┃    │    🏮
┃         /|\\
┃
┃
┃
┃
┃
┃
"""
,
"""
┳━━━━┿━━━━━┓
┃    │    🏮
┃    │    /|\\
┃
┃
┃
┃
┃
┃
"""
,

"""
┳━━━━┿━━━━━┓
┃    │    🏮
┃    │    /|\\
┃   🎩
┃
┃
┃
┃
┃
"""
,
"""
┳━━━━┿━━━━━┓
┃    │    🏮
┃    │    /|\\
┃  ╭🎩╮
┃  ╰👴╯
┃
┃
┃
┃
"""
,
"""
┳━━━━┿━━━━━┓
┃    │    🏮
┃    │    /|\\
┃  ╭🎩╮
┃  ╰👴╯
┃   👔
┃
┃
┃
"""
,
"""
┳━━━━┿━━━━━┓
┃    │    🏮
┃    │    /|\\
┃  ╭🎩╮
┃  ╰👴╯
┃  /👔
┃
┃
┃
"""
,
"""
┳━━━━┿━━━━━┓
┃    │    🏮
┃    │    /|\\
┃  ╭🎩╮
┃  ╰👴╯
┃  /👔\\
┃
┃
┃
"""
,
"""
┳━━━━┿━━━━━┓
┃    │    🏮
┃    │    /|\\
┃  ╭🎩╮
┃  ╰👴╯
┃  /👔\\
┃   👖
┃
┃
"""
,
"""
┳━━━━┿━━━━━┓
┃    │    🏮
┃    │    /|\\
┃  ╭🎩╮
┃  ╰👴╯
┃  /👔\\
┃   👖
┃  /
┃
"""
,
"""
┳━━━━┿━━━━━┓
┃    │    🏮
┃    │    /|\\
┃  ╭🎩╮
┃  ╰👴╯
┃  /👔\\
┃   👖
┃  /  \\
┃
"""
]
gameOver = False
site = "https://www.mit.edu/~ecprice/wordlist.10000"
Response = requests.get(site)
words = [i for i in Response.content.decode().split("\n") if len(i) >= 5]

Loop = asyncio.get_event_loop()

async def Preview(Text, Length):
    def Render(Countdown):
        os.system("cls||clear")
        print(f"{Text}\n\nPreview countdown in {Length - Countdown}\n[{''.join(Progress)}]")
    Progress = ["🟥" for i in range(Length)]
    Render(0)
    for i in range(1, Length + 1):
        Progress[i - 1] = "🟩"
        await asyncio.sleep(1)
        Render(i)
    await asyncio.sleep(1)
    os.system("cls||clear")

while not gameOver:
    word = random.choice(words).lower()
    guess = []
    Counter = 0
    os.system("cls||clear")
    start = input("Do you want to play Hangman game?\nPlease enter y(yes) or n(no): ")
    while start != "y" and start != "n":
        start = input("Do you want to play Hangman game?\nPlease enter y(yes) or n(no): ")
    if start == "n":
        break
    while not gameOver:
        os.system("cls||clear")
        Counter += 1
        if Counter >= len(progress):
            print(progress[Counter - 1].strip())
            Loop.run_until_complete(Preview(f"Game over! You died! The word is `{word}`", 10))
            break
        print(progress[Counter - 1].strip())
        key = ["_" for i in range(len(word))]
        for i in range(len(word)):
            if list(word)[i] in guess:
                key[i] = list(word)[i]
        if "_" not in key:
            print(" ".join(key))
            Loop.run_until_complete(Preview("You won the game!", 5))
            break
        print(" ".join(key))
        userInput = input("Please enter a letter: ").lower()
        if userInput.isalpha() and len(userInput) == 1 and userInput in word:
            if userInput not in guess:
                guess.append(userInput)
                if Counter > 0:
                    Counter -= 1
        continue
os.system("cls||clear")


import importlib
from django.db import migrations

original_migration_module = importlib.import_module("evap.evaluation.migrations.0123_evaluation_state_fsm_int")

class Migration(migrations.Migration):
    """
    Initially, we forgot to migrate logentries in 0123, so this migration cleans this up.
    Note that 0123 is now modified to also take care of the logentries in the first place.
    """

    dependencies = [
        ("evaluation", "0126_add_textanswer_review_email_template"),
    ]

    operations = [
        migrations.RunPython(original_migration_module.logentries_str_to_int, migrations.RunPython.noop),
    ]


# my task solution
def thirt(n):

    loop = [1, 10, 9, 12, 3, 4]
    sum = 0
    while True:
        current_sum = 0
        for index, digit in enumerate(str(n)[::-1]):
            current_index = index % len(loop)
            current_sum += int(digit) * loop[current_index]
        if sum == current_sum:
            return sum

        sum = current_sum
        n = current_sum

print(thirt(123456789))

# codewars task best solution
array = [1, 10, 9, 12, 3, 4]

def thirt(n):
    total = sum(
        [int(c) * array[i % 6] for i, c in enumerate(reversed(str(n)))])
    if n == total:
        return total
    return thirt(total)

# codewars task best solution
import itertools as it

def thirt(n):
    if n < 100: return n

    pattern = it.cycle([1, 10, 9, 12, 3, 4])

    return thirt(sum(d * n for d, n in zip(map(int, str(n)[::-1]), pattern)))

# codewars task best solution
def thirt(n):
    seq = [1, 10, 9, 12, 3, 4]
    s = str(n)
    t = sum(seq[i % 6] * int(s[-i - 1]) for i in range(len(s)))
    return t if t == n else thirt(t)

# codewars task best solution
from itertools import cycle

def thirt(n):
    c = cycle([1, 10, 9, 12, 3, 4])
    m = sum(int(l) * next(c) for l in str(n)[::-1])
    return m if m == n else thirt(m)

# codewars task best solution
def thirt(n):
    ans = sum(
        [int(val) * ((10**key) % 13) for key, val in enumerate(str(n)[::-1])])
    return n if ans == n else thirt(ans)

Task 225 A Rule of Divisibility by 13/A Rule of Divisibility by 13.py


from django.shortcuts import render
import requests
from bs4 import BeautifulSoup
import pandas as pd
import csv
from matplotlib import pyplot as plt
from io import StringIO
# Create your views here.

def scrapper(url):
    page = requests.get(url)
    htmlContent = page.content

    soup = BeautifulSoup(htmlContent,'html.parser')

    # WEB SCRAPPING
    name = []
    for n in soup.find_all("div",class_="_4rR01T"):
        name.append(n.string.strip())

    price = []
    for p in soup.find_all('div',class_='_30jeq3 _1_WHN1'):
        pdash = p.string.strip()
        pdash = pdash.replace('₹','')
        pdash = pdash.replace(',','')
        price.append(int(pdash))

    rating = []
    for rate in soup.find_all('div',class_='_3LWZlK'):
        if len(rating)<24:
            r = rate.get_text()
            rating.append(float(r))

    return {'name':name,'price':price,'rating':rating}

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

def iphone(request):
    url = "https://www.flipkart.com/search?q=iphones&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off&as-pos=1&as-type=HISTORY&as-backfill=on"

    return render(request,'iphone.html',scrapper(url))

def ipad(request):
    url = "https://www.flipkart.com/search?q=IPAD&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off"

    return render(request,'ipad.html',scrapper(url))

def macbook(request):
    url = "https://www.flipkart.com/search?q=macbook&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off"

    return render(request,'ipad.html',scrapper(url))

def downloadIphone(request):
    url = "https://www.flipkart.com/search?q=iphones&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off&as-pos=1&as-type=HISTORY&as-backfill=on"
    df = pd.DataFrame(scrapper(url))
    df.to_csv('ihone.csv',index=True)
    return render(request,'home.html',{})

def downloadIpad(request):
    url = "https://www.flipkart.com/search?q=IPAD&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off"
    df = pd.DataFrame(scrapper(url))
    df.to_csv('ipad.csv',index=True)
    return render(request,'home.html',{})

def downloadMac(request):
    url = "https://www.flipkart.com/search?q=macbook&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off"
    df = pd.DataFrame(scrapper(url))
    df.to_csv('macbook.csv',index=True)
    return render(request,'home.html',{})

def graph():
    url = "https://www.flipkart.com/search?q=iphones&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off&as-pos=1&as-type=HISTORY&as-backfill=on"
    di = scrapper(url)
    y = di['rating']
    x = di['price']
    fig = plt.figure()
    plt.plot(x,y)
    # plt.bar(x,y)
    # plt.xlabel("Rating's of iphone")
    # plt.ylabel("Price's of iphone")
    imgdata = StringIO()
    fig.savefig(imgdata, format='svg')
    imgdata.seek(0)

    data = imgdata.getvalue()
    return data

def graphIphone(request):
    context = {}
    context['graph'] = graph()
    return render(request, 'graph.html', context)


import argparse
from glob import glob
import os
from pathlib import Path
import re

from aicsimageio import AICSImage
import numpy as np
import pandas as pd
from scipy.ndimage import affine_transform
import skimage.io as skio
import yaml
from yaml.loader import SafeLoader

overwrite = True

import registration_utils

def os_swap(x):
    out = "/" + ("/".join(x.split("\\"))).replace("//", "/")
    return out

parser = argparse.ArgumentParser()
parser.add_argument(
    "--output_path",
    type=str,
    required=True,
    help="output dir of all processing steps. This specifies where to find the yml_configs too",
)
parser.add_argument(
    "--barcode", type=str, required=True, help="specify barcode to analyze"
)

parser.add_argument(
    "-p",
    "--position_list",
    nargs='*',
    type=str,
    required=False,
    help="specify positions to process. E.g. -p P1 P2"
)

parser.add_argument("--method",
            choices=['cross_cor', 'ORB', 'merged']
)

if __name__ == "__main__":
    args = parser.parse_args()

    # Open the file and load the file
    # Open the file and load the file
    barcode = args.barcode

    yaml_dir = os.path.join(args.output_path, "yml_configs")

    yaml_list = [x for x in os.listdir(yaml_dir) if "_confirmed" in x]
    yaml_list = [x for x in yaml_list if barcode in x]
    dflist = []
    for y in yaml_list:
        print(y)
        yml_path = yaml_dir + os.sep + y
        with open(yml_path) as f:
            data = yaml.load(f, Loader=SafeLoader)
            for round_dict in data["Data"]:
                dfsub = pd.DataFrame(round_dict.values(), index=round_dict.keys()).T
                dfsub["barcode"] = data["barcode"]
                dfsub["scope"] = data["scope"]
                dfsub["output_path"] = data["output_path"]
                dflist.append(dfsub)

    dfconfig = pd.concat(dflist)
    dfconfig.set_index(["barcode", "round"], inplace=True)

    mag = "20x"

    output_dir = dfconfig["output_path"][0]
    csv_dir = output_dir + os.sep + "csvs"
    csv_name = barcode + "cleanedup_match_csv.csv"
    csv_path = csv_dir + os.sep + csv_name
    print("\n\n" + csv_path + "\n\n")
    # dfall = pd.read_csv(csv_path)
    dfall = pd.read_csv(csv_path)

    output_dir = dfconfig["output_path"][0]
    align_csv_dir = output_dir + os.sep + "alignment_csvs_each_" + args.method
    align_csv_name_glob = f"{barcode}*alignment_csv_each.csv"
    print(align_csv_name_glob)
    globlist = glob(align_csv_dir + os.sep + align_csv_name_glob)
    dfalign_list = []
    for align_csv_path in globlist:
        # align_csv_path = align_csv_dir + os.sep + align_csv_name
        df = pd.read_csv(align_csv_path)
        dfalign_list.append(df)
    dfalign = pd.concat(dfalign_list)

    dfall["parent_file"] = dfall["parent_file"].apply(lambda x: os_swap(x))

    # merge both dataframes so that you only try to align the positions that can be aligned.
    dfall = pd.merge(
        dfalign,
        dfall,
        on=["key", "template_position"],
        suffixes=("_align", ""),
        how="left",
    )

    keylist = dfall["key"].unique()
    # for Position in ['P2']:

    if args.position_list is not None:
        template_position_list = [x for x in np.sort(dfall["template_position"].unique()) if x in args.position_list]
        print('choosing subset of positions = ', args.position_list)
    else:
        template_position_list = np.sort(dfall["template_position"].unique())

    print(template_position_list)
    # go one position by position, since you need offsets per position
    for Position in template_position_list:

        print("POSITION = ", Position)

        # need to define the keylist for each position, since some positions may not be imaged every round
        keylist = dfall.set_index("template_position").loc[Position, "key"].unique()
        # keylist = [x for x in keylist if "Time" not in x]
        # print(testing_keylist)
        # for ki, key in enumerate(testing_keylist):
        key = '20x_Timelapse'
        if key not in keylist:
            key = 'Round 1'
            print('no timelapse present: choosing round 1 instead')

        print(key)

        # first thing that needs to be found is the reference image (i.e. timelapse image) details

        if args.method == "merged":
            alignment_offset = eval(
                dfall.set_index(["key", "template_position"]).loc[
                    pd.IndexSlice[key, Position], "best_alignment_params"
                ]
            )
        else:
            alignment_offset = eval(
                dfall.set_index(["key", "template_position"]).loc[
                    pd.IndexSlice[key, Position], "alignment_offsets_zyx"
                ]
            )

        print(alignment_offset)

        # then the shape of the aligned images needs to be determined
        initial_shape = [45,1248,1848]

        zpad = 20
        xypad = 300
        final_shape = np.uint16(
            np.asarray(
                [
                    initial_shape[0] + zpad*2,
                    initial_shape[1] + xypad*2,
                    initial_shape[2] + xypad*2,
                ]
            )
        )

        # initial image size as mimic. The goal is to shift an image of ones in the same way the reference image was shifted so this becomes a mask for cropping
        blank_image = np.ones(initial_shape,dtype='uint16')

        #now compute the alignment transform for the reference image
        align_matrix = registration_utils.get_align_matrix(alignment_offset)
        shift_to_center_matrix = registration_utils.get_shift_to_center_matrix(
            blank_image.shape, final_shape
        )
        combo = shift_to_center_matrix @ align_matrix

        # now perform the alignment transform to shift the ones
        transformed_blank = affine_transform(
            blank_image,
            np.linalg.inv(combo),
            output_shape=final_shape,
            order=0,  # order = 0 means no interpolation...juust use nearest neighbor
        )

        # now perform max intensity projection since the upcoming crop will be performed on the max intensity projection exports.
        transformed_blank_mip = np.max(transformed_blank,axis=0)

        # now identify the crop ROI

        crops = [0,0,0] #gap between edge of label and edge of roi z,y,x
        py, px = np.nonzero(transformed_blank_mip)
        roi=[]
        for pi,p in enumerate([py,px]):
            roi.extend( [np.max( (p.min()-crops[pi], 0) ),
                        np.min( (p.max() + crops[pi], transformed_blank_mip.shape[pi]) )] )

        # this index epxression can now be applied to all the images for a given position (rounds and timepoints and channels) to crop
        crop_expression = np.index_exp[roi[0]:roi[1],roi[2]:roi[3]]
        print(crop_expression)

        dfr = dfall.set_index(["template_position", "key"])
        dfsub = dfr.loc[pd.IndexSlice[[Position], [key]], :]
        parent_file = dfsub["parent_file"][0]
        scene = dfsub["Scene"][0]

        # # 3 get variables for file name
        # # round_num0 = re.search("time|Round [0-9]+", parent_file, re.IGNORECASE).group(0)
        # search_out = re.search("time|Round [0-9]+", parent_file, re.IGNORECASE)
        # assert search_out is not None  # necessary for passing mypy type errors
        # round_num0 = search_out.group(0)

        scene_num = str(scene).zfill(2)
        position_num = Position[1::].zfill(2)
        well = dfsub["Well_id"][0]

        position = Position
        si = int(scene) - 1  # scene_index

        # mip_exportstest_v3_merged
        sep = os.sep
        globdir = (
            f"{output_dir}{sep}mip_exportstest_v3_merged{sep}{barcode}-export{sep}"
        )

        # now search for the images to crop
        fovid = f"{barcode}_R*_P{position_num}"
        globname = (
            f"{fovid}-mip-c*_T*.tif"
        )
        globpath = os.path.abspath(f"{globdir}{sep}{globname}")

        # now find all files associated with that position and round number (should be multiple channels and potentially multiple timepoints)
        globlist = glob(globpath)
        # [print(x) for x in globlist]
        print(len(globlist))

        # now iterate through all the files and perform the cropping.
        for imgi,img_path in enumerate(globlist):
            reader = AICSImage(img_path)
            img = np.squeeze(reader.get_image_data())
            crop_img = img[crop_expression]

            # now determine where to save the cropped image
            savedir = (
            f"{output_dir}{sep}mip_exports_tcropped_v3{sep}{barcode}{sep}"
            )

            savename = Path(img_path).name
            savepath = savedir + os.sep + savename

            if not os.path.exists(savedir):
                os.makedirs(savedir)
                print("making", os.path.abspath(savedir))

            file_name_stem = Path(dfsub["parent_file"].iloc[0]).stem

            assert os.path.abspath(savepath) is not os.path.abspath(img_path)

            skio.imsave(
                savepath, np.uint16(crop_img), check_contrast=False
            )

            if imgi==0:
                print(os.path.abspath(savepath))


# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

class WebcrawlerPipeline(object):
    def process_item(self, item, spider):
        return item

from scrapy.exceptions import DropItem

class PricePipeline(object):

    def process_item(self, item, spider):
        if item.get('price'):
        	item['price'] = '$' + item['price']
        	return item
        else:
            raise DropItem("Missing price in %s" % item)

    # def process_item(self, item, spider):
    #     if item.get('tags'):
    #     	item['tags'] = item['tags'].split(',')
    #     	return item
    #     else:
    #         raise DropItem("Missing tags in %s" % item)


from torch import nn
import torch
from utils.misc import Accumulator, Timer

def accuracy(y_hat, y):
    """
    计算训练正确的样本的个数
    :param y_hat: 预测值
    :param y: 真实值
    :return:
    """
    # 如果是二维的数据的话，就按行取最大值的索引
    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
        y_hat = y_hat.argmax(axis=1)
    # 按位运算，获取正确的个数
    cmp = y_hat.type(y.dtype) == y
    return float(cmp.type(y.dtype).sum())

def accuracy_gpu(net, data_iter, ae=None, device=None):
    """
    使用device计算精度
    :param ae:
    :param net:
    :param data_iter:
    :param device:
    :return:
    """
    if isinstance(net, nn.Module):
        net.eval()  # 设置为评估模式
        if not device:
            device = next(iter(net.parameters())).device
    # 正确预测的数量，总预测的数量
    metric = Accumulator(2)
    with torch.no_grad():
        if ae:
            for X, y in data_iter:
                X = X.to(device)
                X_rec = ae(X)
                y = y.to(device)
                metric.add(accuracy(net(X), y), y.numel())
                metric.add(accuracy(net(X_rec), y), y.numel())
        else:
            for X, y in data_iter:
                X = X.to(device)
                y = y.to(device)
                metric.add(accuracy(net(X), y), y.numel())
    return metric[0] / metric[1]

def loss_gpu(net, data_iter, loss_fn, device=None):
    """使用GPU计算自编器在数据集上的精度
    """
    if isinstance(net, nn.Module):
        net.eval()  # 设置为评估模式
        if not device:
            device = next(iter(net.parameters())).device

    # loss，总预测的数量
    metric = Accumulator(2)
    with torch.no_grad():
        for X, y in data_iter:
            X = X.to(device)
            X_R = net(X)
            metric.add(X.shape[0] * loss_fn(X_R, X).item(), y.numel())
    return metric[0] / metric[1]

def jenson_shannon_divergence(net_1_logit, net_2_logit):
    from torch.functional import F
    net_1_probs = F.softmax(net_1_logit, dim=1)
    net_2_probs = F.softmax(net_2_logit, dim=1)

    total_m = 0.5 * (net_1_probs + net_2_probs)
    loss = 0.0
    loss += F.kl_div(F.log_softmax(net_1_logit, dim=1), total_m, reduction="none")
    loss += F.kl_div(F.log_softmax(net_2_logit, dim=1), total_m, reduction="none")
    return 0.5 * loss.sum(dim=1)


import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import  time
# 测试浏览导航 back forword
class baiduSearch(unittest.TestCase):
    def setUp(self):
        # self.driver = webdriver.PhantomJS(executable_path="C:\\phantomjs.exe")
        self.driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
        self.driver.set_window_size(1920,1080)

    def test_search_in_baidu(self):
        driver =self.driver

        driver.get("http://www.baidu.com")

        self.assertIn("百度",driver.title)
        elem = driver.find_element_by_name('wd')
        elem.send_keys("pycon")
        elem.send_keys(Keys.RETURN)
        time.sleep(1)

    def test_back_in_chrome(self):
        driver = self.driver
        driver.get("https://www.sina.com.cn/")

        driver.get("https://mil.news.sina.com.cn/")
        driver.back()   #回退
        driver.forward()  #前进
        driver.refresh()  #刷新

    def tearDown(self):
        self.driver.quit()
        print("quit ____________________")
if  __name__ == "__main__":
    unittest.main()


#!/usr/local/bin/python3
import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None
import geopandas as gpd

# pygeos sjoin gives widely inaccurate results, so force using rtree instead
#import pygeos
gpd.options.use_pygeos = False

from geopandas import GeoSeries
from geopandas.tools import sjoin
from shapely.geometry import Polygon

import argparse
argparser = argparse.ArgumentParser(description='generate contour polygons with prominence information from elevation-labelled contour lines')
argparser.add_argument('-o', '--out', default='prominence.shp', help='output filename')
argparser.add_argument('file', help='input file of elevation-labelled contour linestrings (any format supported by geopandas)')
#argparser.add_argument('--attribute', default='elevation', help='name of the elevation attribute')
args = argparser.parse_args()

ct = gpd.read_file(args.file)
ct['poly'] = GeoSeries([Polygon(g) for g in ct.geometry])
ct['area'] = ct.poly.area

# sorting by area as secondary is important for two reasons:
# 1. assume larger areas of the same elevation are actually a little higher, so are assigned prominence first
# 2. when selecting basin containers we want to stick to the smallest containing one,
# (so we aggregate using .max(), maybe .last() also ok)
ct.sort_values(['elevation', 'area'], ascending=[False, False], inplace=True, na_position='first')
ct.reset_index(drop=True, inplace=True)
ct.reset_index(inplace=True)

# now that contour lines have been re-sorted, make dedicated polygon dataframe for spatial joins
polys = gpd.GeoDataFrame(geometry=ct.poly)
# FIXME get proj from input file
polys = polys.set_crs(epsg=31297, inplace=True)
# and put in an appropriate projection
print("Reprojecting...")
#polys.to_crs('ESRI:102030', inplace=True)
polys.to_crs('EPSG:31297', inplace=True)

centroids = gpd.GeoDataFrame(geometry=polys.geometry.centroid)

els = list(ct.elevation.unique())
interval = els[0] - els[1]

# index of the 'parent' (containing) contour line
ct['parent'] = np.repeat(-1, len(ct))

for ele in els:
  left = sum(ct.elevation == ele)
  descentparents = sjoin(centroids[ct.elevation == ele], polys[ct.elevation == ele - interval], predicate='within', how='left') # or within or intersects
  # if there's no direct descent parent, maybe it is a basin within a
  # (usually much wider) contour line of the same elevation
  orphans = descentparents[np.isnan(descentparents.index_right)].index
  basins = 0
  if len(orphans):
    # TODO only keep polygons larger than the smallest orphan as candidates
#    largestorphan = max(ct.area)
    basinparents = sjoin(centroids.loc[orphans], polys[ct.elevation == ele], predicate='within', how='left')
    # FIXME drop multiple matches! also group by but select largest (=first/min)
    basinparents.dropna(inplace = True)
    basins = sum(basinparents.index != basinparents.index_right)

  # if there's multiple, only keep smallest (because that will be the direct parent)
  descentparents.dropna(inplace=True)
  groups = descentparents[['index_right']].groupby(descentparents.index, sort=False)
  # because we originally sorted like this, we know it's the highest index! yesss!
  descentparents = groups.max()

  # using pygeos' sjoin I found that I got many incorrect results, basd on this check:
  # p.geometry.within(polys.geometry[p.index_right])]
#  invalid = [i for i, p in descentparents.iterrows() if np.isnan(p.index_right)]
#  print(invalid)
#  descentparents.drop(invalid, inplace=True)

  # actual matches found
  print(ele)
  print(left)
  print(len(descentparents) + basins)
  ct.parent[descentparents.index] = descentparents.index_right
  # now that known parents have been assigned, we can use this information to correctly
  # assign the lower parent of basins
  if basins:
    print("found basin(s)")
    # FIXME there might be recursive basin-parenting happening here which would require a loop
    ct.parent[basinparents.index] = ct.parent[basinparents.index_right]
#    print(ct.parent[basinparents.index])
  print()

ct['prominence'] = np.repeat(None, len(ct))
for i in range(len(ct)):
  if ct.prominence[i] != None or ct.parent[i] == -1:
    continue
#  print(i)
  parent = ct.parent[i]
  print(f'{i} @ {ct.elevation[i]}: ', end = '')
  while ct.prominence[parent] == None:
    print('.', end = '')
    ct.prominence[parent] = 0
    if ct.parent[parent] == -1 or np.isnan(ct.parent[parent]):
      break
    parent = ct.parent[parent]
  # ok, compute prominence
  ct.prominence[i] = ct.elevation[i] - ct.elevation[parent]
  print(f'{parent} @ {ct.elevation[parent]}')

peaks = [i for i, p in enumerate(ct.prominence > 0) if p]
peaks = gpd.GeoDataFrame({ 'elevation': ct.elevation[peaks], 'prominence': pd.to_numeric(ct.prominence[peaks]), 'geometry': polys.geometry[peaks] }, crs='ESRI:102030')

# TODO filter only positive prominence
peaks.to_file(args.out)


from django.urls import path
from . import views

app_name = 'spendings'

urlpatterns = [
    path("", views.index, name="index"),
    path("all_spendings/", views.SpendingsView.as_view(), name="all_spendings"),
    path("<int:pk>/", views.SpendingDetailView.as_view(), name="spending_details"),
    path("spending/", views.SpendingCreateView.as_view(), name="add"),
]


# building a system that will tell the user what to watch next based on the word vector similarity of the description of movies.

import numpy as np
import spacy

nlp = spacy.load('en_core_web_md')

with open('movies.txt', 'r') as f:
    descriptions = f.readlines()

def suggest_movie(description):
    # Tokenise the input description and remove stop words
    doc = nlp(description.lower())
    words1 = [token.text for token in doc if token.is_alpha and not token.is_stop]
    # Find the similarity between the input document and movies.txt
    similarity = [nlp(desc.lower()).similarity(doc) for desc in descriptions]
    # Find the index of the most similar movie
    sim_index = np.argmax(similarity)
    # Return the title of the most similar movie
    return descriptions[sim_index]

description = "Will he save their world or destroy it? When the Hulk becomes too dangerous for the Earth, the Illuminati trick Hulk into a shuttle and launch him into space to a planet where the Hulk can live in peace. Unfortunately, Hulk lands on the planet Sakaar where he is sold into slavery and trained as a gladiator."
suggested_movie = suggest_movie(description)
print(f"We recommend: [{suggested_movie} ]for your next watch.")


from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import object

from tkinter import *
from scipy.interpolate import UnivariateSpline
import os, sys
from xymath.splines import Spline

class SplinePage(object):

    def leavePageCallback(self):
        '''When leaving page, tidy up any issues.'''
        print('Leaving SplinePage')

    def selectPageCallback(self):
        '''When entering page, do a little setup'''
        print('Entering SplinePage')

    def __init__(self, guiObj, pageFrame):

        self.guiObj = guiObj
        self.pageFrame = pageFrame

        # make frames
        self.main_frame = Frame(pageFrame)
        self.top_f = Frame(self.main_frame)
        self.top_left_f = Frame(self.top_f)
        self.top_right_f = Frame(self.top_f)

        self.selected_spline_nameL = []
        self.guiObj.selected_spline_objL = []
        self.selected_smoothing = 0.0

        self.Label_1 = Label(self.top_left_f,text="Select Spline(s)", width="15")
        self.Label_1.pack(anchor=NW, side=TOP)  #.place(x=36, y=6, width=200, height=22)

        lbframe = Frame( self.top_left_f )
        self.Listbox_1_frame = lbframe
        scrollbar = Scrollbar(lbframe, orient=VERTICAL)
        self.Listbox_1 = Listbox(lbframe, width="40", selectmode="extended", exportselection=0,
            yscrollcommand=scrollbar.set, height="7")
        scrollbar.config(command=self.Listbox_1.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.Listbox_1.pack(side=LEFT, fill=BOTH, expand=1)

        self.Listbox_1_frame.pack(anchor=NW, side=TOP)  #.place(x=24, y=30, width=200, height=300)
        self.Listbox_1.bind("<ButtonRelease-1>", self.Listbox_1_Click)

        self.k_valueD = {} # holds polynomial order
        CONTROLS = [
            ("Linear Interpolation", 1),
            ("Quadratic Spline", 2),
            ("Cubic Spline", 3),
            ("Quartic Spline", 4),
            ("Quintic Spline", 5),
            ]
        for text, k in CONTROLS:
            self.Listbox_1.insert(END, text)
            self.k_valueD[text] = k

        # put smoothing control in place
        self.SmoothValLabel = Label(self.top_right_f, text="Smoothing (0=None)", justify=LEFT, anchor=W)
        self.SmoothValStringVar = StringVar(value="0")
        self.SmoothValSpinbox = Spinbox(self.top_right_f, from_=0, to=9, increment=0.1, textvariable=self.SmoothValStringVar)

        self.SmoothValStringVar_traceName = \
            self.SmoothValStringVar.trace_variable("w", self.SmoothValStringVar_Callback)

        self.SmoothValLabel2 = Label(self.top_right_f, text="Must Be >= 0.0", justify=LEFT, anchor=W)

        self.SmoothValLabel.pack(anchor=NW, side=TOP) #.place(x=240, y=30, width=160  )
        self.SmoothValSpinbox.pack(anchor=NW, side=TOP) #.place(x=240, y=60, width=100  )
        self.SmoothValLabel2.pack(anchor=NW, side=TOP)

        # ShowHelp Button
        self.ShowHelp_Button = Button(self.top_f,text="Show Help", width="15")
        self.ShowHelp_Button.bind("<ButtonRelease-1>", self.ShowHelp_Button_Click)

        # make text results area
        lbframe = Frame( self.main_frame )
        self.Messages_Text_frame = lbframe
        scrollbar = Scrollbar(lbframe, orient=VERTICAL)
        self.Messages_Text = Text(lbframe,  yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.Messages_Text.yview)
        self.Messages_Text.pack(anchor=NW, side=LEFT, fill=BOTH, expand=1)
        scrollbar.pack(side=RIGHT, fill=Y)

        self.top_left_f.pack(anchor=NW, side=LEFT)
        self.top_right_f.pack(anchor=NW, side=LEFT, padx=18, pady=18)
        self.ShowHelp_Button.pack(anchor=SE, side=RIGHT)

        self.top_f.pack(anchor=NW, side=TOP, fill=X, expand=1)
        self.Messages_Text_frame.pack(anchor=NW, side=TOP, fill=BOTH, expand=1)

        self.main_frame.pack(anchor=NW, side=LEFT, fill=BOTH, expand=1)

        self.ShowHelp_Button_Click()

    def SmoothValStringVar_Callback(self, varName, index, mode):
        #print "SmoothValStringVar_Callback varName, index, mode",varName, index, mode
        #print "    new StringVar value =",self.SmoothValStringVar.get()
        self.put_splines_on_plot()

    def put_splines_on_plot(self):

        XY = self.guiObj.XYjob
        self.guiObj.selected_spline_objL = []

        try:
            self.selected_smoothing = float( self.SmoothValStringVar.get() )
        except:
            self.selected_smoothing = 0.0

        if self.selected_smoothing < 0.0:
            self.selected_smoothing = 0.0

        curveL = []
        descStr = '' # description string of spline(s)

        if (XY.dataset and XY.dataset.N > 1) or len(self.selected_spline_nameL)>0:
            for n,spline_name in enumerate(self.selected_spline_nameL):
                k = self.k_valueD[ spline_name ]

                if XY.dataset.N > 1 + k:
                    s = Spline( XY.dataset, order=k, smoothing=self.selected_smoothing)
                    self.guiObj.selected_spline_objL.append( s )
                    curveL.append( s )
                    if descStr:
                        descStr +=  '\n' + '='*44 + '\n'
                    descStr += s.get_full_description()

            if self.selected_smoothing==0:
                mytitle = 'Spline Interpolation'
            else:
                mytitle = 'Smoothed Spline Interpolation\n(StdDev=%g, %% StdDev=%g%%, CorrCoeff=%g)'%(s.std, s.pcent_std, s.corrcoef)

            self.guiObj.PlotWin.make_new_plot(dataset=XY.dataset, curveL=curveL,
                title_str=mytitle)

        if descStr:
            self.new_message( descStr )
            self.ShowHelp_Button.configure(state=NORMAL,text="Show Help",width="18",relief=RAISED)

    def ShowHelp_Button_Click(self, event=None):
        #print 'Pressed ShowHelp Button'
        self.new_message('''Fit Spline Curve to Data.

1) Select the desired spline, or splines (order 1 to 5, Linear to Quintic)
2) Select any desired "smoothing"

If smoothing is equal to zero, the spline will go through all data points.

With smoothing added, the curve will go near the data points, but not necessarily through them. Click the Smoothing spin box to change the amount of smoothing.

Standard deviation and percent standard deviation will be calculated for smoothed splines along with their correlation coefficient.

Note that multiple splines can be fitted to the data simply by selecting more than one spline in the listbox.
''')
        self.ShowHelp_Button.configure(state=DISABLED,text="",width="1",relief=FLAT)

    def clear_messages(self):
        self.Messages_Text.delete(1.0, END)
        self.Messages_Text.update_idletasks()
        self.ShowHelp_Button.configure(state=NORMAL,text="Show Help",width="15",relief=RAISED)

    def add_to_messages(self, s):
        self.Messages_Text.insert(END, s)
        self.Messages_Text.update_idletasks()
        self.ShowHelp_Button.configure(state=NORMAL,text="Show Help",width="15",relief=RAISED)

    def new_message(self, s):
        self.clear_messages()
        self.Messages_Text.insert(END, s)
        self.Messages_Text.update_idletasks()
        self.ShowHelp_Button.configure(state=NORMAL,text="Show Help",width="15",relief=RAISED)

    def Listbox_1_Click(self, event): #click method for component ID=2
        #print "executed method Listbox_1_Click"
        #print "current selection(s) =",self.Listbox_1.curselection()
        self.selected_spline_nameL = []
        for i in self.Listbox_1.curselection():
            self.selected_spline_nameL.append( self.Listbox_1.get(i) )
            #self.selected_spline_nameL.append( self.k_valueD[self.Listbox_1.get(i)] )
        #print 'self.selected_spline_nameL =',self.selected_spline_nameL

        self.put_splines_on_plot()


import hashlib
import json
from time import time
from urllib.parse import urlparse
import requests

#区块链类
class Blockchain(object):
    def __init__(self):
        self.chain = []
        self.current_transactions = []
        self.nodes = set() #初始化节点,set()防止节点重复

        #创建创世块
        self.new_block(previous_hash=1,proof=100)

    def new_block(self,proof,previous_hash = None):
        # Creates a new Block and adds it to the chain
        """
        生成新块
        :param proof: <int> The proof given by the Proof of Work algorithm
        :param previous_hash: (Optional) <str> Hash of previous Block
        :return: <dict> New Block
        """
        block = {
            'index':len(self.chain) + 1,
            'timestamp':time(),
            'transactions':self.current_transactions,
            'proof':proof,
            'previous_hash':previous_hash or self.hash(self.chain[-1])
        }
        #重置当前的交易链
        self.current_transactions = []
        self.chain.append(block)
        return block

    def new_transaction(self,sender,recipient,amount):
        # Adds a new transaction to the list of transactions
        """
        生成新交易信息，信息将加入到下一个待挖的区块中
        :param sender: <str> Address of the Sender
        :param recipient: <str> Address of the Recipient
        :param amount: <int> Amount
        :return: <int> The index of the Block that will hold this transaction
        """
        self.current_transactions.append({
            'sender':sender,
            'recipient':recipient,
            'amount':amount
        })

        return self.last_block['index'] + 1

    @staticmethod
    def hash(block):
        # Hashes a Block
        # 生成sha-256 hash
        block_string = json.dumps(block,sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()

    @property
    def last_block(self):
        # Returns the last Block in the chain
        return self.chain[-1]

    def proof_of_work(self,last_proof):
        """
              简单的工作量证明:
              """
        proof = 0
        while self.valid_proof(last_proof, proof) is False:
            proof += 1
        return proof

    @staticmethod
    def valid_proof(last_proof, proof):
        """
        验证证明: 是否hash(last_proof, proof)以4个0开头?
        :param last_proof: <int> Previous Proof
        :param proof: <int> Current Proof
        :return: <bool> True if correct, False if not.
        """

        guess = f'{last_proof}{proof}'.encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        return guess_hash[:4] == "0000"

    def register_node(self,address):
        """
                Add a new node to the list of nodes
                :param address: <str> Address of node. Eg. 'http://192.168.0.5:5000'
                :return: None
                """
        parsed_url = urlparse(address)
        self.nodes.add(parsed_url.netloc)

    #实现共识算法：最长链才是有效链
    def valid_chain(self,chain):
        last_block = chain[0]
        current_index = 1

        while current_index < len(chain):
            block = chain[current_index]
            print(f'{last_block}')
            print(f'{block}')

            #检查块的哈希值是正确的
            if block['previous_hash'] != self.hash(last_block):
                return False
            #检查POW的正确性
            if not self.valid_proof(last_block['proof'],block['proof']):
                return False

            last_block = block
            current_index += 1
        return True

    def resolve_conflicts(self):
        """
        共识算法解决冲突
        使用网络中最长的链.
        :return: <bool> True 如果链被取代, 否则为False
        """
        neighbours = self.nodes
        new_chain = None

        max_length = len(self.chain)

        # Grab and verify the chains from all the nodes in our network
        for node in neighbours:
            response = requests.get(f'http://{node}/chain')

            if response.status_code == 200:
                length = response.json()['length']
                chain = response.json()['chain']

                # Check if the length is longer and the chain is valid
                if length > max_length and self.valid_chain(chain):
                    max_length = length
                    new_chain = chain

        # Replace our chain if we discovered a new, valid chain longer than ours
        if new_chain:
            self.chain = new_chain
            return True

        return False
'''
    #块结构
    block = {
        #索引
        'index': 1,
        'timestamp': 1506057125.900785,
        #交易列表
        'transactions': [
            {
                'sender': "8527147fe1f5426f9dd545de4b27ee00",
                'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",
                'amount': 5,
            }
        ],
        #工作量证明
        'proof': 324984774000,
        #前一块hash
        'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
    }
'''