# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('courseevaluations', '0008_freeformquestionanswer_question'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='evaluationset',
            options={'permissions': (('can_view_status_reports', 'Can view status reports'), ('can_view_student_links', 'Can view student links'))},
        ),
    ]


# Missing number
def getMissingNum(A):
    n = len(A)
    total = (n + 1) * (n + 2) / 2
    sum_A = sum(A)
    return total - sum_A

arr1 = [1, 3, 4, 5, 6]
miss_no = getMissingNum(arr1)
print(int(miss_no))

#
arr2 = [1, 2, 3, 4, 5, 6, 7, 9]
missing_num = []
for num in range(arr2[0], arr2[-1] + 1):
    if num not in arr2:
        missing_num.append(num)
print(missing_num)

# Min and Max values
def minMax():
    num = [2, 3, 4, 1, 5, 6, 10, 9]
    min_num = min(num)
    max_num = max(num)
    return min_num, max_num

print(minMax())

# Remove Duplicates
arr5 = [1, 2, 1, 2, 5, 6, 4, 9, 3, 2, 8]
dup = []
for num in arr5:
    if num not in dup:
        dup.append(num)
print(dup)

# Find Duplicates
def fun5(A):
    duplicates = [num for num in numbers if numbers.count(num) > 1]
    res = list(set(duplicates))
    print(res)

numbers = [0, 1, 2, 1, 2, 5, 6, 4, 9, 3, 2, 8, 0, 1]
fun5(numbers)

# Number of occurrences:
n = [1,2,3,1,2,3,4,5,6,7,8,9]
p = n.count(1)
print(p)

np = [1,-1,-5,6,5,9]
np.sort()
print(np)


#!/usr/bin/python

import random
import json
import datetime

def handler(event,context):

    words_file="words"
    words_fh = open(words_file,'r')
    all_words = words_fh.read().split('\n')

    output_text = ""

    for i in xrange(50):
        output_text += random.choice(all_words) + " "

    api_output = {}
    api_output['random_text'] = output_text.rstrip(" ")
    api_output['generated_at'] = str(datetime.datetime.now())
    json_out = json.dumps(api_output)

    response = {
        "statusCode": 200,
        "headers": {
           'Content-type': 'application/json',
        },
        "body": json_out,
    }

    return response


import numpy as np

def func(X: np.ndarray) -> np.ndarray:
    """
    The data generating function.
    Do not modify this function.
    """
    return 0.3 * X[:, 0] + 0.6 * X[:, 1] ** 2

def noisy_func(X: np.ndarray, epsilon: float = 0.075) -> np.ndarray:
    """
    Add Gaussian noise to the data generating function.
    Do not modify this function.
    """
    return func(X) + np.random.randn(len(X)) * epsilon

def get_data(n_train: int, n_test: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    """
    Generating training and test data for
    training and testing the neural network.
    Do not modify this function.
    """
    X_train = np.random.rand(n_train, 2) * 2 - 1
    y_train = noisy_func(X_train)
    X_test = np.random.rand(n_test, 2) * 2 - 1
    y_test = noisy_func(X_test)

    return X_train, y_train, X_test, y_test

class Neural_network():

    ##Lager en klasse som inneholder alle funksjonene som skal brukes i det nevrale nettverket
    def __init__(self, X_train, y_train, X_test, y_test):
        self.X_train = X_train
        self.y_train = y_train
        self.X_test = X_test
        self.y_test = y_test

        self.input_lag = [0.0, 0.0]
        self.hidden_layer = [0.0, 0.0]
        self.ouput_lag = [0.0]

        self.error = 0
        self.lærings_rate = 0.1
        self.bias = 1

        self.vekt_input_hidden = [np.random.random(), np.random.random(), np.random.random(), np.random.random()]
        self.vekt_hidden_output = [np.random.random(), np.random.random()]

    ##Sigmoid funksjonen
    def sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

    ##Funksjon for trene på treningsdataen, går over alle dataene og kjører gjennom det nevrale nettverket
    def train(self):
        for x, y in zip(self.X_train, self.y_train):
            # Sender input fremover i det nevrale nettverket
            self.input_lag = x
            self.hidden_layer[0] = self.sigmoid(np.dot(self.input_lag, self.vekt_input_hidden[:2]) + self.bias)
            self.hidden_layer[1] = self.sigmoid(np.dot(self.input_lag, self.vekt_input_hidden[2:]) + self.bias)
            self.ouput_lag[0] = np.dot(self.hidden_layer, self.vekt_hidden_output)

            ## Sender tilbake og oppdaterer vektene til nodene
            self.error = y - self.ouput_lag[0]
            self.vekt_hidden_output[0] += self.lærings_rate * self.error * self.hidden_layer[0]
            self.vekt_hidden_output[1] += self.lærings_rate * self.error * self.hidden_layer[1]
            self.vekt_input_hidden[0] += self.lærings_rate * self.error * self.vekt_hidden_output[0] * self.hidden_layer[0] * (1 - self.hidden_layer[0]) * self.input_lag[0]
            self.vekt_input_hidden[1] += self.lærings_rate * self.error * self.vekt_hidden_output[0] * self.hidden_layer[0] * (1 - self.hidden_layer[0]) * self.input_lag[1]
            self.vekt_input_hidden[2] += self.lærings_rate * self.error * self.vekt_hidden_output[1] * self.hidden_layer[1] * (1 - self.hidden_layer[1]) * self.input_lag[0]
            self.vekt_input_hidden[3] += self.lærings_rate * self.error * self.vekt_hidden_output[1] * self.hidden_layer[1] * (1 - self.hidden_layer[1]) * self.input_lag[1]

    def predict(self):
        ## Gjør det samme som tidligere bare med test data
        for (x,y) in zip(self.X_test, self.y_test):
            self.input_lag = x
            self.hidden_layer[0] = self.sigmoid(self.input_lag[0] * self.vekt_input_hidden[0] + self.input_lag[1] * self.vekt_input_hidden[1])
            self.hidden_layer[1] = self.sigmoid(self.input_lag[0] * self.vekt_input_hidden[2] + self.input_lag[1] * self.vekt_input_hidden[3])
            self.ouput_lag[0] = self.hidden_layer[0] * self.vekt_hidden_output[0] + self.hidden_layer[1] * self.vekt_hidden_output[1]
            self.error = y - self.ouput_lag[0]
        print("Test error: ", self.error)

    def mse(self):
        self.error = 0
        for (x,y) in zip(self.X_test, self.y_test):
            self.input_lag = x
            self.hidden_layer[0] = self.sigmoid(self.input_lag[0] * self.vekt_input_hidden[0] + self.input_lag[1] * self.vekt_input_hidden[1])
            self.hidden_layer[1] = self.sigmoid(self.input_lag[0] * self.vekt_input_hidden[2] + self.input_lag[1] * self.vekt_input_hidden[3])
            self.ouput_lag[0] = self.hidden_layer[0] * self.vekt_hidden_output[0] + self.hidden_layer[1] * self.vekt_hidden_output[1]
            self.error += (y - self.ouput_lag[0])**2
        self.error = self.error / len(self.X_test)
        print("MSE: ", self.error)

    ##Funksjon som kjører alle funksjonene
    def run(self):
        self.train()
        self.mse()
        self.predict()

if __name__ == "__main__":
    np.random.seed(0)
    X_train, y_train, X_test, y_test = get_data(n_train=280, n_test=120)

    nn = Neural_network(X_train, y_train, X_test, y_test)
    nn.run()


import mcpi.minecraft as minecraft
import mcpi.block as block
import time
import countdown_mac as countdown

#import RPi.GPIO as GPIO  # Raspberry Pi
import anyio.GPIO as GPIO # Arduino

BUTTON = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON, GPIO.IN)

mc = minecraft.Minecraft.create()
mc.postToChat("PRESS THE BUTTON!")

def bomb(x, y, z):
	mc.setBlock(x+1, y, z+1, block.TNT.id)

	for a in range(5, 0, -1):
		mc.postToChat(str(a))
		time.sleep(1)
	####countdown.count()

	mc.postToChat("BANG!")
	mc.setBlocks(x-10, y-5, z-10, x+10, y+10, z+10, block.AIR.id)
	####mc.player.setTilePos(x, y+40, z)
	####countdown.bang()

try:
	while True:
		time.sleep(0.1)
		if GPIO.input(BUTTON) == False:
			pos = mc.player.getTilePos()
			bomb(pos.x, pos.y, pos.z)

finally:
	GPIO.cleanup()


#!/usr/bin/env python

# https://xkcd.com/208/

# https://github.com/deadlockempire/deadlockempire.github.io
# https://medium.com/nerd-for-tech/simple-react-quiz-application-b9ac808e6100
# https://regex101.com/

# Allow sed for even more complicated replacements?
# Try for multiple paths. Either explicitly, by allowing some easier solutions, allowing flexibility, or through "secrets"

#Ave regex, gratia plena

import re
from typing import Optional
import urllib.parse

'''
Some people, when confronted with a problem, think
"I know, I'll use regular expressions."

Now they have two problems.
'''

'''

You are the newly born god of online messaging.  Your current calling is to respond to the prayers of those that hit the "send" button, but were immediately filled with regret.

You are a minor diety with limited power. Rather then directly stopping or editing these messages, you can only alter them with the arcane language of regular expression substitution.

While answering prayers look for more that might help your supplicants to increase their devotion. Extra honors are bestowed for the use of the smallest Regex pattern.
'''

'''
Levels of puzzles:
 * Straight match
 * Basic wildcard
 * Basic repetition
 * Set/negetive sets
 * Anchors
 * groups for replacement
 * groups for matching
 * `|` operator
 * look a heads https://www.rexegg.com/regex-lookarounds.html

 Use more complicated regex library for recursion/Atomic? https://stackoverflow.com/questions/26385984/recursive-pattern-in-regex

Additional Challenge:
 * Limited # of characters
'''

# Message 2

# The fool

# Explanation of sets of characters.

# He gave week estimates but needs them removed.

# Optional solve task? Sorting, checking passwords, formatting?

# Secret information in task data to format.

# Message 3

# Justice

#  wildcards

# Antagonist god of online drama?

# Have response shown and change based on solving sexond

data = [
    {
        'title': 'The Lovers',
        'original_text': 'Hey Susie! What time should I come over their and pick you up?',
        'prompt': '''AAAAAH!!! I just sent a message to Lisa calling her my Ex's name!''',
        'goal': 'Replace instances of "Susie" with "Lisa".',
        'hint': '''A Regex can be as simple as a basic find and replace. Aside from some reserved characters, a basic regex will just directly match the characters entered.''',
        'answer1': ('Susie', 'Lisa'),
        # Shorter if assuming no other capital S "S\w+"
        'response1': '''I'm free after 5. Pretty brave sending a typo to an editor though : p''',
        'answer2': ('Susie! What time should I come over their', 'Lisa! What time should I come over there'),
        'response2': '''I'm free after 5.''',
        'secret': '''Well that's boring.''',
    },
    {   'title': 'The Fool',
        'original_text': '''\
Hi Dave,

I should have the initial draft of the project to you in 3 days.
I'll be able to get the finished version in 2 additional days.

-
Joe Marwin
Yes2You LLC
''',
        'prompt': '''Ugh, I shouldn't have given firm dates. I have no idea how long this will actually take, and now I'll have to go crawling back a second time.''',
        'goal': 'Replace instances of the numbers with "a few".',
        'hint': '''Regex patterns can contain special characters that match to groups of letters. Square brackets \[\] can be used to specify a set of characters to match against https://plainenglish.io/blog/regular-expressions-brackets-f2d6f69ffe13#- ''',
        'answer1': ('\d', 'a few'),
        'response1': '''Uh, sure Dave. What's up with your signature?''',
        'answer2': ('\d ', 'a few '),
        'response2': '''No problem, just get it to me as soon as it's ready.''',
        'secret': '''Those too weak to stand up for themselves should receive no pity.''',
    },
    {   'title': 'Justice',
        'original_text': 'Hey Susie! What time should I come over their and pick you up?',
        'prompt': '''AAAAAH!!! I just sent a message to Lisa calling her my Ex's name!''',
        'goal': 'Replace instances of "Susie" with "Lisa".',
        'hint': '''A Regex can be as simple as a basic find and replace. Aside from some reserved characters, a basic regex will just directly match the characters entered.''',
        'answer1': ('Susie', 'Lisa'),
        # Shorter if assuming no other capital S "S\w+"
        'response1': '''I'm free after 5. Pretty brave sending a typo to an editor though : p''',
        'answer2': ('Susie! What time should I come over their', 'Lisa! What time should I come over there'),
        'response2': '''I'm free after 5.''',
    },
    {
        'original_text': '''\
[425, 57, 3027, 8242, 7072, 5, 9166, 12, 8732, 4007, 71, 465, 2523, 4406, 7626, 959, 3539, 305, 2866, 0, 1000]
''',
        'prompt': '''\
The missile detection system in a secret underground bunker is acting up! When birds fly by it's triggering the missile
detection threshold! Unfortunately, changing too many values will also trigger a tamper detection.

[Goal]: Given a in a comma separated list of integers. Divide values greater then 999 by 10 rounding down.
''',
        'answer': (r'(\d{3,})\d', r'\1')
        # Longer "(\d+\d{2})\d"
    },

]

def find_diff(a: str, b: str) -> Optional[int]:
    min_len = min(len(a), len(b))
    for i in range(min_len):
        if a[i] != b[i]:
            return i

    if len(a) != len(b):
        return min_len
    else:
        return None

def print_section(string: str, index: int, ellipse=True, before=10, after=10) -> str:
    ret = ''
    start = max(index-before, 0)
    end = index + after
    if ellipse and start != 0:
        ret += '...'
    ret += string[start:end]
    if ellipse and end < len(string) - 1:
        ret += '...'
    return ret

def run(level_data):
    print(level_data['prompt'])
    print(f"[Goal] {level_data['prompt']}")
    while True:
        find_re = input("Enter the Regex to find: ")
        replace_re = input("Enter the replacement string: ")

        substituted_text = re.sub(
            find_re, replace_re, level_data['original_text'])
        answer_text = re.sub(
            level_data['answer'][0], level_data['answer'][1], level_data['original_text'])

        answer_diff = find_diff(substituted_text, answer_text)

        if answer_diff is not None:
            start = max(answer_diff-10, 0)
            print('Original:', print_section(
                level_data['original_text'], answer_diff))
            print('Expected:', print_section(answer_text, answer_diff))
            print('Submitted:', print_section(substituted_text, answer_diff))
            print(
                f"Explanation: https://regex101.com/?regex={urllib.parse.quote(find_re)}&testString={urllib.parse.quote(print_section(level_data['original_text'], answer_diff, False))}&substitution={replace_re}")
            print('Try again.')
        else:
            print('Correct!')
            break

run(data[1])


import itertools

def map_structure(operation, *param_groups):
    """ Expects a pair of list of lists of identical structure representing
    two sets of parameter states. This will apply the desired operation to
    each element in the two groups
    :param param_groups_1: The first parameter group
    :param param_groups_2: The second parameter group
    :return: A list of lists which is the result of the operation applied to
    each pair of elements in the inputs
    """

    param_groups_return = []

    for groups in zip(*param_groups):
        group_grads = []
        for ps in zip(*groups):
            group_grads.append(operation(*ps))
        param_groups_return.append(group_grads)

    return param_groups_return

def reduce_structure(reduce, accumulate, param_groups):
    """ Applies an operation to the elements of a parameter group and accumulates
    the result via specificed functions
    :param reduce: The reducing operation
    :param accumulate: The accumulating operation
    :param param_groups: The
    :return: The accumulated result
    """

    result = None

    for group in param_groups:
        for p in group:
            if result:
                result = accumulate(reduce(p), result)
            else:
                result = reduce(p)

    return result

def flatten(param_groups):
    """ Flattens out a pair of list of lists representing a param_group into
    a single list
    :param param_groups: The group to flatten
    :return: The flattened list
    """
    return itertools.chain(*param_groups)

def parameters_to_tensor_groups(parameter_groups, attribute):
    """ Function to reduce a parameter group from an optimizer to tensor_group with
    the same structure and just the requested parameter
    :param parameter_groups: The parameter group to extract from
    :param attribute: The attribute from the parameter to extrect, e.g. data or grad
    :return: a tensor_group of the same shape ocnting the requested attribute
    """

    tensor_group_return = []

    for group in parameter_groups:
        group_attrs = []
        for ps in group["params"]:
            group_attrs.append(ps.__getattribute__(attribute))
            tensor_group_return.append(group_attrs)

    return tensor_group_return


"""
2 St. Vols conditions
"""
from bsbetl import g
from bsbetl.g_helpers import load_prepare_2StVols_conditions, sync_2stVols_conditions_audit_structure

''' DEFAULT CONDITIONS HERE '''
# NOTE all the dict objects below MUST have a 'cond['name']' key!!!!

# region Condition a
_2StVols_cond_a1 = {
    "name": "Con_a1",
    "group": "Con_a",
    "description": "DVFf3D > C2Vca1 AND DHPGrDifD-1 < C2Vca1D AND DHPGrAvshD > C2Vca1A",
    "notes": "C2Vca1 = 1.0 ... 20; C2Vca1Di = 0.000 ... 0.050; C2Vca1A = 0.9500 ... 1.0500",
    "C2Vca1": 2.0,
    "C2Vca1_min": 1.0,
    "C2Vca1_max": 20.0,
    "C2Vca1D": 0.01,
    "C2Vca1D_min": 0.0,
    "C2Vca1D_max": 0.05,
    "C2Vca1A": 1.0,
    "C2Vca1A_min": 0.95,
    "C2Vca1A_max": 1.05,
    "audit_list": [
        "DVFf3",
        "DHPGrDiF.D-1",
        "DHPGrAvSh"
    ],
    "document_ref": "2 Vols 210524.odt: 2. St. Vls. Con a1)"
}
_2StVols_cond_a2 = {
    "name": "Con_a2",
    "group": "Con_a",
    "description": "DVD / SDVBfD-2 > C2Vca2 AND  DHPGrDifD-1 < C2Vca1D AND DHPGrAvshD > C2Vca1A",
    "notes": "C2Vca2 = 1.0 ... 20; C2Vca1Di = 0.000 ... 0.050; C2Vca1A = 0.9500 ... 1.0500",
    "C2Vca2": 2.0,
    "C2Vca2_min": 1.0,
    "C2Vca2_max": 20.0,
    "C2Vca1D": 0.001,
    "C2Vca1D_min": 0.0,
    "C2Vca1D_max": 0.05,
    "C2Vca1A": 0.96,
    "C2Vca1A_min": 0.95,
    "C2Vca1A_max": 1.05,
    "audit_list": [
        "DV",
        "SDVBf.D-2",
        "DHPGrDiF.D-1",
        "DHPGrAvSh"
    ],
    "document_ref": "2 Vols 210524.odt: 2. St. Vls. Con a2)"
}
#endregion

# region Condition b
_2StVols_cond_b = {
    "name": "Con_b",
    "group": "Con_b",
    "description": "DVFf1D > C2Vcb AND DHPGrDifD-1 < C2Vca1D  AND DHPGrAvshD > C2Vca1A",
    "notes": "C2Vcb = 1.0 ... 10; C2Vca1Di = 0.000 ... 0.050; C2Vca1A = 0.9500 ... 1.0500",
    "C2Vcb": 2.0,
    "C2Vcb_min": 1.0,
    "C2Vcb_max": 10.0,
    "C2Vca1D": 0.01,
    "C2Vca1D_min": 0.0,
    "C2Vca1D_max": 0.05,
    "C2Vca1A": 0.96,
    "C2Vca1A_min": 0.95,
    "C2Vca1A_max": 1.05,
    "audit_list": [
        "DVFf1",
        "DHPGrDiF.D-1",
        "DHPGrAvSh"
    ],
    "document_ref": "2 Vols 210524.odt: 2. St. Vls. Con b)"
}
# endregion

#region Condition c
_2StVols_cond_c = {
    "name": "Con_c",
    "group": "Con_c",
    "description": "DVFmD > C2Vcc AND DHPGrDislD-1 < C2VccD AND DHPGrAvmiD > C2VccA",
    "notes": "C2Vcc = 1.00 ... 3.00; C2VccD = 0.0000 ...  0.0500; C2Vcc = 0.9500 ... 1.0500;",
    "C2Vcc": 1.1,
    "C2Vcc_min": 1.0,
    "C2Vcc_max": 3.0,
    "C2VccD": 0.01,
    "C2VccD_min": 0.0,
    "C2VccD_max": 0.05,
    "C2VccA": 0.96,
    "C2VccA_min": 0.95,
    "C2VccA_max": 1.05,
    "audit_list": [
        "DVFm",
        "DHPGrDiSl.D-1",
        "DHPGrAvMi"
    ],
    "document_ref": "2 Vols 210524.odt: 2. St. Vls. Con c)"
}
#endregion

#region Condition d
_2StVols_cond_d = {
    "name": "Con_d",
    "group": "Con_d",
    "description": "DVFsl D > C2Vcd  AND DHPGrDislD-1 < C2VcdD AND DHPGrAvloD > C2VcdA",
    "notes": "C2Vcd = 1.00 ...1.50; C2VcdD = 0.0000 ...  0.0500; C2VcdA = 0.9500 ... 1.0500",
    "C2Vcd": 1.1,
    "C2Vcd_min": 1.0,
    "C2Vcd_max": 1.5,
    "C2VcdD": 0.001,
    "C2VcdD_min": 0.0,
    "C2VcdD_max": 0.05,
    "C2VcdA": 0.96,
    "C2VcdA_min": 0.95,
    "C2VcdA_max": 1.05,
    "audit_list": [
        "DVFsl",
        "DHPGrDiSl.D-1",
        "DHPGrAvLo"
    ],
    "document_ref": "2 Vols 210524.odt: 2. St. Vls. Con d)"
}
#endregion

#region Condition e
_2StVols_cond_e = {
    "name": "Con_e",
    "group": "Con_e",
    "description": "{100} * DVFf2D *  [(DHPD + DHPD-1) / (DHPD-2 + DHPD-3) -1 ] > {3}",
    "notes": "NO PARAMETERS",
    "audit_list": [
        "DVFf2",
        "DHP",
        "DHP.D-1",
        "DHP.D-2",
        "DHP.D-3"
    ],
    "adjustors": [
        100,
        3
    ],
    "document_ref": "2 Vols 210524.odt: 2. St. Vls. Con e)"
}
#endregion

#region Condition f
_2StVols_cond_f = {
    "name": "Con_f",
    "group": "Con_f",
    "description": "{100} * DVD / SDVCf2 D-1 * (DHPD / DHPD-1 - 1)  > {3}",
    "notes": "NO PARAMETERS",
    "audit_list": [
        "DV",
        "SDVCf2.D-1",
        "DHP",
        "DHP.D-1"
    ],
    "adjustors": [
        100,
        3
    ],
    "document_ref": "2 Vols 210524.odt: 2. St. Vls. Con f)"
}
#endregion

# place all the above individual conditions here
default_2StVols_conditions = [
    _2StVols_cond_a1,
    _2StVols_cond_a2,
    _2StVols_cond_b,
    _2StVols_cond_c,
    _2StVols_cond_d,
    _2StVols_cond_e,
    _2StVols_cond_f,
]

def _2StVols_min_max_value_condition(cond :dict) ->list:
    ''' retrieve the min,max,current value and setting_name as a tuple from the dp_init_conditions '''

    # giant case statement
    # temp clipboard:
    #(cond['_min'],cond['_max'],cond[''],'')

    if cond['name'] == 'Con_a1':
        return [(cond['C2Vca1_min'],cond['C2Vca1_max'],cond['C2Vca1'],'C2Vca1'),
                (cond['C2Vca1D_min'],cond['C2Vca1D_max'],cond['C2Vca1D'],'C2Vca1D'),
                (cond['C2Vca1A_min'],cond['C2Vca1A_max'],cond['C2Vca1A'],'C2Vca1A')
                ]
    if cond['name'] == 'Con_a2':
        return [(cond['C2Vca2_min'],cond['C2Vca2_max'],cond['C2Vca2'],'C2Vca2'),
                (cond['C2Vca1D_min'],cond['C2Vca1D_max'],cond['C2Vca1D'],'C2Vca1D'),
                (cond['C2Vca1A_min'],cond['C2Vca1A_max'],cond['C2Vca1A'],'C2Vca1A')
                ]
    if cond['name'] == 'Con_b':
        return [(cond['C2Vcb_min'],cond['C2Vcb_max'],cond['C2Vcb'],'C2Vcb'),
                (cond['C2Vca1D_min'],cond['C2Vca1D_max'],cond['C2Vca1D'],'C2Vca1D'),
                (cond['C2Vca1A_min'],cond['C2Vca1A_max'],cond['C2Vca1A'],'C2Vca1A')
                ]
    if cond['name'] == 'Con_c':
        return [(cond['C2Vcc_min'],cond['C2Vcc_max'],cond['C2Vcc'],'C2Vcc'),
                (cond['C2VccD_min'],cond['C2VccD_max'],cond['C2VccD'],'C2VccD'),
                (cond['C2VccA_min'],cond['C2VccA_max'],cond['C2VccA'],'C2VccA')
                ]
    if cond['name'] == 'Con_d':
        return [(cond['C2Vcd_min'],cond['C2Vcd_max'],cond['C2Vcd'],'C2Vcd'),
                (cond['C2VcdD_min'],cond['C2VcdD_max'],cond['C2VcdD'],'C2VcdD'),
                (cond['C2VcdA_min'],cond['C2VcdA_max'],cond['C2VcdA'],'C2VcdA')
                ]
    # the rest
    return [(0,0,0,'?')]

_2StVols_conditions = load_prepare_2StVols_conditions(g._2STVOLS_CONDITIONS_FQ, default_2StVols_conditions)

# force sync the assoc audit structure
sync_2stVols_conditions_audit_structure(_2StVols_conditions)


import torch
import torch.nn as nn
import torch.nn.functional as F
import math

from functools import partial
from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau

import constants as c
import util

def get_criterion(name):
    if name in ('cross_entropy', 'ce'):
        return nn.CrossEntropyLoss()
    elif name in ('plate_cross_entropy', 'pce'):
        return PlateCrossEntropyLoss()
    elif name in ('arc_face_loss', 'afl'):
        return ArcFaceLoss()
    elif name in ('focal_loss', 'fl'):
        return partial(focal_loss, alpha=0.5)
    elif name in ('label_smoothing', 'ls'):
        return LabelSmoothingLoss(label_smoothing=0.025)

def focal_loss(logits, labels, gamma=2.0, alpha=0.5):
    epsilon = 1.e-9
    gamma = torch.tensor(gamma).to(logits.device)

    input_soft = F.softmax(logits, dim=1) + epsilon
    target_one_hot = torch.zeros_like(logits, dtype=logits.dtype)
    target_one_hot[torch.arange(labels.size(0)), labels] = 1.0

    weight = torch.pow(torch.tensor(1.) - input_soft, gamma.to(logits.dtype))
    focal = -alpha * weight * torch.log(input_soft)
    loss_tmp = torch.sum(target_one_hot * focal, dim=1)
    loss = torch.mean(loss_tmp)
    return loss

class ArcFaceLoss(nn.modules.Module):
    def __init__(self, s=32.0, m=0.5):
        super(ArcFaceLoss, self).__init__()
        self.s = s
        self.easy_margin = False
        self.cos_m = math.cos(m)
        self.sin_m = math.sin(m)
        self.th = math.cos(math.pi - m)
        self.mm = math.sin(math.pi - m) * m

    def forward(self, logits, labels):
        cosine = logits
        sine = torch.sqrt(1.0 - torch.pow(cosine, 2))
        phi = cosine * self.cos_m - sine * self.sin_m
        if self.easy_margin:
            phi = torch.where(cosine > 0, phi, cosine)
        else:
            phi = torch.where(cosine > self.th, phi, cosine - self.mm)

        one_hot = torch.zeros_like(cosine)
        one_hot.scatter_(1, labels.view(-1, 1).long(), 1)
        output = (one_hot * phi) + ((1.0 - one_hot) * cosine)
        output *= self.s
        loss = nn.CrossEntropyLoss()(output, labels)
        return loss

class ContrastiveLoss(nn.Module):
    """
    Contrastive loss function.
    Based on: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf
    """

    def __init__(self, margin=2.0):
        super(ContrastiveLoss, self).__init__()
        self.margin = margin

    def forward(self, output, label):
        output1, output2 = output
        euclidean_distance = F.pairwise_distance(output1, output2, keepdim=True)
        margin_distance = torch.clamp(self.margin - euclidean_distance, min=0.0)
        loss_contrastive = torch.mean(
            (1 - label).float() * torch.pow(euclidean_distance, 2) + label.float() * torch.pow(margin_distance, 2))
        return loss_contrastive

class LabelSmoothingLoss(nn.Module):
    """
    Modified from https://github.com/jadore801120/attention-is-all-you-need-pytorch/blob/master/train.py#L33
    With label smoothing,
    """
    def __init__(self, label_smoothing):
        # label_smoothing=0.1 from bag of tricks from image classification with CNN
        assert 0.0 < label_smoothing <= 1.0
        super(LabelSmoothingLoss, self).__init__()

        # smooth by plate
        self.smoothing_value = label_smoothing / (c.N_CLASS // 4 - 1)
        self.confidence = 1.0 - label_smoothing
        self.g2rna, self.masks = util.get_g2rna()

    def forward(self, output, target):
        """
        output (FloatTensor): batch_size x n_classes
        target (LongTensor): batch_size
        """
        log_output = F.log_softmax(output, dim=1)
        target = target.contiguous().view(-1)
        one_hot = torch.zeros_like(output).scatter(1, target.view(-1, 1), 1)
        one_hot = one_hot * self.confidence + (1 - one_hot) * self.smoothing_value

        for i, val in enumerate(target.cpu().numpy()):
            group = -1
            for j in range(4):
                if val in self.g2rna[j]:
                    group = j
                    break
            one_hot[i, self.masks[group]] = 0.0

        loss = -(one_hot * log_output).sum(dim=1)
        return torch.mean(loss)

class PlateCrossEntropyLoss(nn.Module):
    def __init__(self):
        super(PlateCrossEntropyLoss, self).__init__()
        self.g2rna, _ = util.get_g2rna()
        self.masks = []
        for val in self.g2rna:
            self.masks.append(torch.tensor(sorted(val)))

    def forward(self, output, target):
        """
        output (FloatTensor): batch_size x n_classes
        target (LongTensor): batch_size
        """
        target = target.contiguous().view(-1)
        one_hot = torch.zeros_like(output).scatter(1, target.view(-1, 1), 1)

        new_output = []
        new_one_hot = []
        for i, val in enumerate(target.cpu().numpy()):
            group = -1
            for j in range(4):
                if val in self.g2rna[j]:
                    group = j
                    break
            new_output.append(output[i, self.masks[group]])
            new_one_hot.append(one_hot[i, self.masks[group]])

        new_output = torch.stack(new_output)
        new_one_hot = torch.stack(new_one_hot)
        log_output = F.log_softmax(new_output, dim=1)
        loss = -(new_one_hot * log_output).sum(dim=1)
        return torch.mean(loss)

class GradualWarmupScheduler(_LRScheduler):
    """
    Copy from: https://github.com/ildoonet/pytorch-gradual-warmup-lr/blob/master/warmup_scheduler/scheduler.py
    Gradually warm-up(increasing) learning rate in optimizer.
    Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour'.
    Args:
        optimizer (Optimizer): Wrapped optimizer.
        multiplier: target learning rate = base lr * multiplier
        total_epoch: target learning rate is reached at total_epoch, gradually
        after_scheduler: after target_epoch, use this scheduler(eg. ReduceLROnPlateau)

    Testing code:
    v = torch.zeros(10)
    optimizer = torch.optim.Adam([v], lr=0.001)
    scheduler_cosine = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 100, eta_min=1e-6)
    scheduler_warmup = lb.GradualWarmupScheduler(optimizer, multiplier=5, total_epoch=5, after_scheduler=scheduler_cosine)

    for epoch in range(1, 50):
        print(epoch, optimizer.param_groups[0]['lr'])
        scheduler_warmup.step(epoch)
    print(epoch, optimizer.param_groups[0]['lr'])
    """

    def __init__(self, optimizer, multiplier, total_epoch, after_scheduler=None):
        self.multiplier = multiplier
        if self.multiplier <= 1.:
            raise ValueError('multiplier should be greater than 1.')
        self.last_epoch = None
        self.total_epoch = total_epoch
        self.after_scheduler = after_scheduler
        self.finished = False
        super().__init__(optimizer)

    def get_lr(self):
        if self.last_epoch > self.total_epoch:
            if self.after_scheduler:
                if not self.finished:
                    self.after_scheduler.base_lrs = [base_lr * self.multiplier for base_lr in self.base_lrs]
                    self.finished = True
                return self.after_scheduler.get_lr()
            return [base_lr * self.multiplier for base_lr in self.base_lrs]

        return [base_lr * ((self.multiplier - 1.) * self.last_epoch / self.total_epoch + 1.) for base_lr in self.base_lrs]

    def step_ReduceLROnPlateau(self, metrics, epoch=None):
        if epoch is None:
            epoch = self.last_epoch + 1
        # ReduceLROnPlateau is called at the end of epoch, whereas others are called at beginning
        self.last_epoch = epoch if epoch != 0 else 1
        if self.last_epoch <= self.total_epoch:
            warmup_lr = [base_lr * ((self.multiplier - 1.) * self.last_epoch / self.total_epoch + 1.) for base_lr in self.base_lrs]
            for param_group, lr in zip(self.optimizer.param_groups, warmup_lr):
                param_group['lr'] = lr
        else:
            if epoch is None:
                self.after_scheduler.step(metrics, None)
            else:
                self.after_scheduler.step(metrics, epoch - self.total_epoch)

    def step(self, epoch=None, metrics=None):
        if type(self.after_scheduler) != ReduceLROnPlateau:
            if self.finished and self.after_scheduler:
                if epoch is None:
                    self.after_scheduler.step(None)
                else:
                    self.after_scheduler.step(epoch - self.total_epoch)
            else:
                return super(GradualWarmupScheduler, self).step(epoch)
        else:
            self.step_ReduceLROnPlateau(metrics, epoch)

    def state_dict(self):
        state_dict = {key: value for key, value in self.__dict__.items() if key != 'optimizer'}
        return state_dict

    def load_state_dict(self, state_dict):
        self.__dict__.update(state_dict)


from collections import OrderedDict
from typing import OrderedDict

import torch
from rich.console import Console
from utils.util import clone_parameters

from .base import ClientBase

class pFedLAClient(ClientBase):
    def __init__(
        self,
        backbone: torch.nn.Module,
        dataset: str,
        batch_size: int,
        valset_ratio: float,
        testset_ratio: float,
        local_epochs: int,
        local_lr: float,
        logger: Console,
        gpu: int,
    ):
        super(pFedLAClient, self).__init__(
            backbone,
            dataset,
            batch_size,
            valset_ratio,
            testset_ratio,
            local_epochs,
            local_lr,
            logger,
            gpu,
        )

    def train(
        self,
        client_id: int,
        model_params: OrderedDict[str, torch.Tensor],
        verbose=True,
    ):
        self.client_id = client_id
        self.set_parameters(model_params)
        self.get_client_local_dataset()
        self.model.to(self.device)
        res, stats = self._log_while_training(evaluate=True, verbose=verbose)()
        self.model.cpu()
        return res, stats

    def _train(self):
        self.model.train()
        frz_model_params = clone_parameters(self.model)
        for _ in range(self.local_epochs):
            for x, y in self.trainset:
                x, y = x.to(self.device), y.to(self.device)

                logits = self.model(x)

                loss = self.criterion(logits, y)

                self.optimizer.zero_grad()
                loss.backward()
                self.optimizer.step()
        delta = OrderedDict(
            {
                k: p1 - p0
                for (k, p1), p0 in zip(
                    self.model.state_dict(keep_vars=True).items(),
                    frz_model_params.values(),
                )
            }
        )
        return delta

    def test(
        self, client_id: int, model_params: OrderedDict[str, torch.Tensor],
    ):
        self.client_id = client_id
        self.set_parameters(model_params)
        self.get_client_local_dataset()
        self.model.to(self.device)
        loss, acc = self.evaluate()
        dummy_diff = OrderedDict(
            {
                name: torch.zeros_like(param)
                for name, param in self.model.state_dict().items()
            }
        )
        self.model.cpu()
        stats = {"loss": loss, "acc": acc}
        return dummy_diff, stats


'''
Failed to solve without taking a look at solution here: https://github.com/hyper-neutrino/advent-of-code/tree/main/2022
Mainly struggled with finding the optimal path in the first part.
Basically implemented method from second part in the beginning. This solution doesn't recognize a 'faster' path to S tho.
'''
from collections import deque

def load_data(file: str) -> list:
    with open(file, 'r', encoding='utf-8') as fhandle:
        return [list(line) for line in fhandle.read().strip().splitlines()]

def find_pos(content: list, letter: str) -> tuple:
    x, y = [(y_idx, y.index(letter)) for y_idx, y in enumerate(content) if letter in y][0]
    if letter == 'S':
        content[x][y] = 'a'
    if letter == 'E':
        content[x][y] = 'z'
    return (x, y)

def find_path(content: list) -> int:
    starting_position = find_pos(content, 'S')
    E = find_pos(content, 'E')
    q = deque()
    q.append((0, starting_position[0], starting_position[1]))
    vis = {(starting_position[0], starting_position[1])}

    while q:
        steps, x, y = q.popleft()
        for n_x, n_y in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
            if n_x < 0 or n_y < 0 or n_x >= len(content) or n_y >= len(content[0]):
                # checking if neighbor is on grid
                continue
            if (n_x, n_y) in vis:
                # checking if neighbor has been visited
                continue
            if ord(content[n_x][n_y]) - ord(content[x][y]) > 1:
                # checking if the height-difference is climable
                continue
            if n_x == E[0] and n_y == E[1]:
                # checking if neighbor is end
                return steps + 1
            vis.add((n_x, n_y))
            q.append((steps + 1, n_x, n_y))

def find_fastest_path(content: list) -> int:
    E = find_pos(content, 'E')
    q = deque()
    q.append((0, E[0], E[1]))
    vis = {(E[0], E[1])}

    while q:
        steps, x, y = q.popleft()
        for n_x, n_y in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
            if n_x < 0 or n_y < 0 or n_x >= len(content) or n_y >= len(content[0]):
                # checking if neighbor is on grid
                continue
            if (n_x, n_y) in vis:
                # checking if neighbor has been visited
                continue
            if ord(content[n_x][n_y]) - ord(content[x][y]) < -1:
                # checking if the height-difference is climable (backwards)
                continue
            if content[n_x][n_y] == 'a':
                # checking if neighbor is a
                return steps + 1
            vis.add((n_x, n_y))
            q.append((steps + 1, n_x, n_y))

def first_task(file: str) -> int:
    content = load_data(file)
    steps = find_path(content)
    return steps

def second_task(file: str) -> int:
    content = load_data(file)
    steps = find_fastest_path(content)
    return steps

steps = first_task('input.txt')
print('First task:', steps)

ans = second_task('input.txt')
print('Second task:', ans)


import xml.etree.ElementTree as ET
from rdkit import Chem, DataStructs
from rdkit.Chem import rdChemReactions as Reactions
from rdkit.Chem import AddHs, AllChem
from rdkit.Chem.MolStandardize import rdMolStandardize
from rdkit.Chem.rdmolops import *                                                                       #is needed
from rdkit.Chem.rdMolDescriptors import CalcNumRings
from rdkit.Chem.Descriptors import *
from rdkit.Chem.rdMolDescriptors import *
from rdkit.Chem.Crippen import MolLogP
import datetime, os, time, random, re, resource, sys
from multiprocessing import Process, Queue
from collections import Counter

def readMol(smiles):
    try:
        targetMol = Chem.MolFromSmiles(smiles)
        RemoveStereochemistry(targetMol)
    except:
        if "[nH]" in smiles:
            modifiedSmiles = smiles.replace("[nH]", "n", 1)

        elif "n" in smiles:
            modifiedSmiles = smiles.replace("n", "[nH]", 1)
        elif "[B]" in smiles:
            modifiedSmiles = smiles.replace("[B]", "[B-]")
        else:
            modifiedSmiles = smiles
        try:
            targetMol = Chem.MolFromSmiles(modifiedSmiles)
        except:
            if "[nH]" in modifiedSmiles:
                try:
                    modifiedSmiles = smiles.replace("[nH]", "n")
                    targetMol = Chem.MolFromSmiles(modifiedSmiles)
                    RemoveStereochemistry(targetMol)
                except:
                    print(smiles + " was not processed by rdkit")
            else:
                print(smiles + " was not processed by rdkit")
    else:
        if targetMol == None:
            if "[nH]" in smiles:
                modifiedSmiles = smiles.replace("[nH]", "n", 1)
            elif "n" in smiles:
                modifiedSmiles = smiles.replace("n", "[nH]", 1)
            elif "[B]" in smiles:
                modifiedSmiles = smiles.replace("[B]", "[B-]")
            else:
                modifiedSmiles = smiles
            try:
                targetMol = Chem.MolFromSmiles(modifiedSmiles)
                RemoveStereochemistry(targetMol)
            except:
                if "[nH]" in modifiedSmiles:
                    try:
                        modifiedSmiles = smiles.replace("[nH]", "n")
                        targetMol = Chem.MolFromSmiles(modifiedSmiles)
                        RemoveStereochemistry(targetMol)
                    except:
                        print(smiles + " was not processed by rdkit")
                else:
                    print(smiles + " was not processed by rdkit")
    if targetMol != None:
        return targetMol
    else:
        return None

def countLines(file):
    lines = 0
    f = open(file, "rb")
    buf_size = 1024*1024
    read_f = f.raw.read
    buf = read_f(buf_size)
    while buf:
        lines += buf.count(b'\n')
        buf = read_f(buf_size)
    f.close()
    return lines

def splitFileByLines(inpFile, outName, linesPerFile):
    n = 0
    smallFile = None
    outNamesList = []
    for ind, line in enumerate(open(inpFile)):
        if ind % linesPerFile == 0:
            if smallFile:
                smallFile.close()
            n+=1
            smallFile = open(outName + "_" + str(n), "w")
            outNamesList.append(outName + "_" + str(n))
        smallFile.write(line)
    if smallFile:
        smallFile.close()
    return outNamesList

def listDir(path):
    d_names = []
    f_names = []
    for a, b, c in os.walk(path):
        main_dir = str(a)
        d_names = b
        f_names = c
        break
    return d_names, f_names, main_dir

def Ro2Filtration(synthonSmiles):
    mol = Chem.MolFromSmiles(synthonSmiles)
    functionality = synthonSmiles.count(":")
    Bivalent_electrophilic = synthonSmiles.count(":30")
    Bivalent_nucleophilic = synthonSmiles.count(":40")
    Bivalent_neutral = synthonSmiles.count(":50")
    MolW = ExactMolWt(mol) - functionality - Bivalent_electrophilic - Bivalent_nucleophilic - Bivalent_neutral
    LogP = MolLogP(mol)
    HDC = CalcNumHBD(mol)
    HAC = CalcNumHBA(mol)
    if "[NH:20]" in synthonSmiles or "[OH:20]" in synthonSmiles or "[SH:20]" in synthonSmiles:
        marksForCount = ["[NH:20]", "[OH:20]", "[SH:20]"]
        count = 0
        for m in marksForCount:
            count += synthonSmiles.count(m)
        HDC -= count
    if MolW > 200 or LogP > 2 or HDC > 2 or HAC > 4:
        return False, ["MolW=" + str(MolW), "LogP=" + str(LogP), "HDC=" + str(HDC), "HAC=" + str(HAC)]
    else:
        return True, ["MolW=" + str(MolW), "LogP=" + str(LogP), "HDC=" + str(HDC), "HAC=" + str(HAC)]

def CheckMolStructure(goodValenceSmiles, label):
    vallences = {"C": 4, "N": 3, "N+": 4, "O": 2, "S:10": 6, "S:20": 2}
    try:
        mol = Chem.MolFromSmiles(goodValenceSmiles)
    except:
        return False
    else:
        if mol:
            for atom in mol.GetAtoms():
                if atom.GetAtomMapNum() != 0:
                    symbol = atom.GetSymbol()
                    if symbol == "C" or symbol == "O" or (symbol == "N" and "+" not in label):
                        if atom.GetTotalValence() < vallences[symbol]:
                            return False
                    elif symbol == "S":
                        if atom.GetTotalValence() < vallences[symbol + ":" + str(atom.GetAtomMapNum())]:
                            return False
                    elif atom.GetTotalValence() < vallences["N+"]:
                            return False
            return True
        else:
            return False

def generateMajorTautFromSynthonSmiles(initSmiles):
    enumerator = rdMolStandardize.TautomerEnumerator()
    initMol = Chem.MolFromSmiles(initSmiles)
    nHinit = []
    for atom in initMol.GetAtoms():
        if atom.GetAtomMapNum() != 0:
            nHinit.append(atom.GetTotalNumHs())
    initMol.UpdatePropertyCache()
    Chem.GetSymmSSSR(initMol)
    tautMol = enumerator.Canonicalize(initMol)
    tautSmiles = Chem.MolToSmiles(tautMol, canonical=True)
    initSmiles = Chem.MolToSmiles(Chem.MolFromSmiles(initSmiles), canonical=True)
    if tautSmiles == initSmiles:
        return tautSmiles
    nHtaut = []
    for atom in tautMol.GetAtoms():
        if atom.GetAtomMapNum() != 0:
            nHtaut.append(atom.GetTotalNumHs())
    if nHinit == nHtaut:
        return tautSmiles
    else:
        return initSmiles

def checkLable(productSmiles:str, Label:str):
        goodValenceSmiles = None
        if Label.split("->")[0][1] == "S":
            hCount = 1
            out = productSmiles.replace(Label.split("->")[0],
                                            "[" + Label.split("->")[1].split(":")[0] + "H" + str(hCount) + ":" +
                                            Label.split("->")[1].split(":")[1] + "]")
            goodValenceSmiles = out
        else:
            for hCount in range(1, 5):
                if hCount == 1:
                    if "+" in Label and "H" not in Label:
                        out = productSmiles.replace(Label.split("->")[0],
                                                    "[" + Label.split("->")[1].split(":")[0] + "+:" +
                                                    Label.split("->")[1].split(":")[1] + "]")

                    else:
                        out = productSmiles.replace(Label.split("->")[0],
                                                    "[" + Label.split("->")[1].split(":")[0] + ":" +
                                                    Label.split("->")[1].split(":")[1] + "]")

                    check = CheckMolStructure(out, Label)
                    if check:
                        goodValenceSmiles = out
                        break
                if "+" in Label and "H" not in Label:
                    out = productSmiles.replace(Label.split("->")[0],
                                                "[" + Label.split("->")[1].split(":")[0] + "H" + str(hCount) + "+:" +
                                                Label.split("->")[1].split(":")[1] + "]")
                else:
                    out = productSmiles.replace(Label.split("->")[0],
                                                "[" + Label.split("->")[1].split(":")[0] + "H" + str(hCount) + ":" +
                                                Label.split("->")[1].split(":")[1] + "]")

                newMol = Chem.MolFromSmiles(out)
                if not newMol:
                    break
                else:
                    goodValenceSmiles = out
                    check = CheckMolStructure(goodValenceSmiles, Label)
                    if check:
                        break
        if not goodValenceSmiles:
            print("Problem with structure check: " + productSmiles + " " + out)
        else:
            return generateMajorTautFromSynthonSmiles(goodValenceSmiles)

def readSyntonLib(synthLibFile, Ro2Filtration=False, FindAnaloguesOfMissingBBs=False):
    fragBegTime = datetime.datetime.now()
    availableBBs = {}
    pat = re.compile("\[\w*:\w*\]")
    for line in open(synthLibFile):
        sline = line.strip()
        if sline:
            mol = Chem.MolFromSmiles(sline.split()[0])
            if Ro2Filtration:
                mol = AddHs(mol)
                MolW = ExactMolWt(mol)
                LogP = MolLogP(mol)
                HDC = CalcNumHBD(mol)
                HAC = CalcNumHBA(mol)
                if MolW>200 or LogP > 2 or HDC > 2 or HAC > 4:
                    continue
            availableBBs[sline.split()[0]] = {}
            availableBBs[sline.split()[0]]["BBs"] = sline.split()[1]
            if FindAnaloguesOfMissingBBs:
                availableBBs[sline.split()[0]]["fp_b"] = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, nBits=2048)
            availableBBs[sline.split()[0]]["n_atoms"] = mol.GetNumAtoms()
            availableBBs[sline.split()[0]]["n_rings"] = CalcNumRings(mol)
            availableBBs[sline.split()[0]]["marks"] = sorted(
                [sline.split()[0][m.start():m.start() + 2] + sline.split()[0][m.end() - 4:m.end()] for m in
                 re.finditer(pat, sline.split()[0])])
            availableBBs[sline.split()[0]]["marksVallences"] = "+".join(sorted([atom.GetSymbol() + ":" +
                        str(atom.GetTotalDegree()) for atom in mol.GetAtoms() if atom.GetAtomMapNum() != 0]))
    print("Lib BB reading time:")
    print(datetime.datetime.now() - fragBegTime)
    return availableBBs


import sys
n = int(input())
ln = []

for i in range(n):
    ln.append(list(map(int, sys.stdin.readline().split())))

num = dict()
for i in range(-1, 2):
    num[i] = 0

def sol(scale, x_start, y_start):
    done = False
    start = ln[y_start][x_start]
    for y in range(scale):
        for x in range(scale):
            if start != ln[y_start + y][x_start + x]:
                done = True
                break
        if done:
            break

    if done:
        if scale == 1:
            num[ln[x_start][y_start]] += 1
        else:
            next_scale = scale//3
            for i in range(3):
                for j in range(3):
                    sol(next_scale, x_start + next_scale * i, y_start + next_scale * j)
    else:
        num[ln[y_start][x_start]] += 1
sol(n, 0, 0)
for i in range(-1, 2):
    print(num[i])


from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from models_demo.hr.views import home, show_employees, show_departments, show_positions, delete_employee, \
    details_employee, details_by_slug_employee, show_test_form, show_edit_employee_form, show_success, show_upload_image, show_validation_form

urlpatterns = [
    path('', home, name='home'),
    path('employees/', show_employees, name='show-employees'),
    path('delete/<int:pk>', delete_employee, name='delete-employee'),
    path('details/<int:pk>', details_employee, name='details-employee'),
    path('detailsbyslug/<slug:slug>', details_by_slug_employee, name='details-by-slug-employee'),
    path('departments/', show_departments, name='show-departments'),
    path('positions/', show_positions, name='show-positions'),
    path('forms/', show_test_form, name='show-forms'),
    path('validation-forms/', show_validation_form, name='show-validation-forms'),
    path('edit-employee/<slug:slug>', show_edit_employee_form, name='edit-employee'),
    path('upload-image/', show_upload_image, name='show-upload-image'),
    path('success/', show_success, name='success'),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import random,sys
sys.setrecursionlimit(5000)

#INSTRUCTIONS

#With "checking_cols" and "checking_rows" i'm doing the following rules:
#~ RULE 1 = Each row and column contains an equal number of 0s and 1s.	  	  				RULE 1
#~ RULE 2 = There is no more than two identical numbers adjacent to each other.				RULE 2

#Now with "identical_rows" and "identical_cols" i'm doing the following rule:
#~ RULE 3 = There is no identical row or column.											RULE 3

#~ 1) I start from checking_rows, and i modify my grid(if needed) to respect RULE1 AND RULE2 for my rows. If my rows aren't modified i
#~ go to checking_cols,if they are modified i recall checking_rows again.

#~ 2) Now i am in checking_cols, and i modify my grid(if needed) to respect RULE1 AND RULE2 for my cols. If my cols aren't modified i
#~ go to identical_rows, if they are modified i recall checking_rows AGAIN.

#~ 3) Now i am in identical_rows, and i am checking if RULE3 is respected for my rows. If my grid has same rows, i randomize that row and
#~ i call back checking_rows again. If they are not modified i call identical_cols.

#~ 4) Now i am in identical_cols, and i am checking if RULE3 is respected for my cols. If my grid has same cols, i randomize that column and
#~ i call back checking_rows (starting from the beginning again). If they are not modified i have finished and i'm ready to play!

#################################################################################################################################
def checking_cols(create_grid,num):
	flag = False #it becomes true when cols are modified. If cols are not modified i don't need to recall checking_rows

	for y in range(0,num): #this "for" check all cols and put 0s and 1s where it is needed
		for x in range(1, num-1): #~ RULE 2 = There is no more than two identical numbers adjacent to each other.
			if create_grid[x][y] == create_grid[x-1][y] and create_grid[x][y] == create_grid[x+1][y] and create_grid[x][y] == 1:
				create_grid[x][y] = 0
				flag = True
			elif create_grid[x][y] == create_grid[x-1][y] and create_grid[x][y] == create_grid[x+1][y] and create_grid[x][y] == 0:
				create_grid[x][y] = 1
				flag = True
		C1 = 0 #it will count 1s in my cols
		for i in range(0,num): #i use this to count how many 1s i have in a column
			if create_grid[i][y] == 1:
				C1 = C1 + 1
		while C1 < num/2: #~ RULE 1 = Each row and column contains an equal number of 0s and 1s.
			var = random.randint(0,num-1)
			if 	create_grid[var][y] == 0:
				create_grid[var][y] = 1
				C1 = C1 + 1
				flag = True
		while C1 > num/2: #~ RULE 1 = Each row and column contains an equal number of 0s and 1s.
			var = random.randint(0,num-1)
			if 	create_grid[var][y] == 1:
				create_grid[var][y] = 0
				C1 = C1 - 1
				flag = True

	try:	#sometimes, some grids create an infinite loop, so i need to use try_except to avoid run time error!
		if flag == True:
			checking_rows(create_grid,num)
		elif flag == False:
			identical_rows(create_grid,num)
	except:
		for x in range(0,num):
			for y in range(0,num):
				create_grid[x][y] = random.randint(0,1) #i randomize again all numbers
		checking_rows(create_grid,num)

#################################################################################################################################
def checking_rows(create_grid,num):
	flag = False #it becomes true when rows are modified.

	for x in range(0,num): #this "for" check all rows and put 0s and 1s where needed
		for y in range(1, num-1):  #~ RULE 2 = There is no more than two identical numbers adjacent to each other.
			if create_grid[x][y] == create_grid[x][y-1] and create_grid[x][y] == create_grid[x][y+1] and create_grid[x][y] == 1:
				create_grid[x][y] = 0
			elif create_grid[x][y] == create_grid[x][y-1] and create_grid[x][y] == create_grid[x][y+1] and create_grid[x][y] == 0:
				create_grid[x][y] = 1
		R1 = 0 #it will count 1s in my row
		for i in range(0,num): #i use this to count how many 1s i have in a row
			if create_grid[x][i] == 1:
				R1 = R1 + 1
		while R1 < num/2: #~ RULE 1 = Each row and column contains an equal number of 0s and 1s.
			var = random.randint(0,num-1)
			if 	create_grid[x][var] == 0:
				create_grid[x][var] = 1
				R1 = R1 + 1
				flag = True
		while R1 > num/2: #~ RULE 1 = Each row and column contains an equal number of 0s and 1s.
			var = random.randint(0,num-1)
			if 	create_grid[x][var] == 1:
				create_grid[x][var] = 0
				R1 = R1 - 1
				flag = True

	try:	#sometimes, some grids create an infinite loop, so i need to use try_except to avoid run time error!
		if flag == True:
			checking_rows(create_grid,num)
		elif flag == False:
			checking_cols(create_grid,num)
	except:
		for x in range(0,num):
			for y in range(0,num):
				create_grid[x][y] = random.randint(0,1) #i randomize again all numbers
		checking_rows(create_grid,num)

#################################################################################################################################
def identical_rows(create_grid,num): #~ RULE 3 = There is no identical row or column.
	flag = False
	for x in range(0,num): #checking identical rows
		for y in range(x+1,num):
			if create_grid[x] == create_grid[y]: #if there is an identical row i randomize that row and i recall "checking_rows"
				flag = True
				for i in range(0,num):
					create_grid[x][i] = random.randint(0,1)
	if flag == True:
		checking_rows(create_grid,num)
	elif flag == False:
		identical_cols(create_grid,num)

#################################################################################################################################
def identical_cols(create_grid,num): #~ RULE 3 = There is no identical row or column.
	flag = False

	for x in range(0,num-1):
		for z in range(x+1, num):
			count_identical_num = 0 #if this var is == num, 2 columns are identical and i need to change it.
			for y in range(0,num):
				if create_grid[y][x] == create_grid[y][z]:
					count_identical_num = count_identical_num + 1
				if count_identical_num == num:
					flag = True
					for b in range(0,num):
						create_grid[b][z] = random.randint(0,1)

	if flag == True:
		checking_rows(create_grid,num)
	elif flag == False:
		print("Tabella soluzioni takuzu ")
		for z in range(0,num):
			print (create_grid[z]) #print final result
		return create_grid

#################################################################################################################################
#This function got random position to show on the grid to help gamer to start his game!
#I'll get with randint random position and put it on my hide_grid some values from my solution grid(create_grid) to print it on the screen.
def hide_part_of_the_grid(num,create_grid):
	hide_grid = [[2]*num for i in range(num)] #create a filled multidimensional list.
	cont = 0

	if num == 4:
		help_on_the_grid = 7
	elif num == 6:
		help_on_the_grid = 11
	elif num == 8:
		help_on_the_grid = 18
	elif num == 10:
		help_on_the_grid = 30

	while cont < help_on_the_grid:
		x = random.randint(0,num-1)
		y = random.randint(0,num-1)
		if hide_grid[x][y] == 2:
			hide_grid[x][y] = create_grid[x][y]
			cont = cont +1

	return hide_grid
#################################################################################################################################


from typing import Any, List, Mapping

from pydantic import BaseModel
from slack_bolt import App
from slack_sdk import WebClient
from slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandler
from slack_sdk.models.blocks import Block, SectionBlock
import structlog

from config import config
from emoji import EmojiInfo, get_emoji

logger: structlog.stdlib.BoundLogger = structlog.get_logger(__name__)

# Setup our Slack Webhook Handler
slack_app = App()
slack_app.client.retry_handlers.append(
    # Ensure we follow the backoff instructions
    RateLimitErrorRetryHandler(
        # But strong prefer not to drop these, lol
        max_retry_count=5
    )
)

@slack_app.event({"type": "emoji_changed", "subtype": "add"})
def emoji_changed(
    client: WebClient,
    event: Mapping[str, Any],
    payload: Mapping[str, Any],
) -> Mapping[str, Any]:
    """{
        'event_ts': '1671070007.348400',
        'name': 'test-emoji-pls-ignore-1',
        'subtype': 'add',
        'type': 'emoji_changed',
        'value': 'https://emoji.slack-edge.com/EXAMPLE/test-emoji-pls-ignore-1/0da8457a872dfe8a.png',
    }"""
    log = logger.bind(
        event=event,
        payload=payload,
        type=payload["type"],
        subtype=payload["subtype"],
        emoji_name=payload["name"],
        emoji_url=payload["value"],
    )
    log.info("New Emoji Added!")

    emoji = get_emoji(client, payload["name"], payload["value"])

    # TODO: Figure out if we should do something more to special case aliase,
    # e.g. batch/debounce the alias posts
    if emoji.is_alias and not config.slack_app.should_report_alias_changes:
        log.info("Skipping alias post")
        return {"ok": True}

    update = EmojiUpdateMessage(emoji=emoji)

    resp = client.chat_postMessage(
        channel=config.slack_app.channel,
        text=update.message(),
        blocks=update.blocks(),
    )
    log.info(
        "Posted to channel",
        channel=config.slack_app.channel,
        status_code=resp.status_code,
        data=resp.data,
    )

    return {"ok": True}

class EmojiUpdateMessage(BaseModel):
    emoji: EmojiInfo

    def message(self) -> str:
        emoji_or_alias = (
            f"alias of `{self.emoji.alias_of}`" if self.emoji.is_alias else "emoji"
        )

        if self.emoji.author is not None:
            return f"New {emoji_or_alias} added by @{self.emoji.author}!"
        else:
            return f"New {emoji_or_alias} added!"

    # TODO: Type this at some point
    def blocks(self) -> List[Block]:
        primary_block = SectionBlock(
            text={
                "text": self.message(),
                "type": "mrkdwn",
            },
            fields=[
                {"type": "mrkdwn", "text": "*Name*"},
                {"type": "mrkdwn", "text": "*Emoji*"},
                {"type": "mrkdwn", "text": f"`{self.emoji}`"},
                {"type": "mrkdwn", "text": str(self.emoji)},
            ],
            accessory={
                "type": "image",
                "image_url": self.emoji.image_url,
                "alt_text": str(self.emoji),
            },
        )

        return [primary_block]


from kanaria.core.service.brain.mind_types import DecisionType
from kanaria.core.environment import Environment
from kanaria.core.service.brain import Brain
from kanaria.core.model.letter import Letter

class Action(object):

    def __init__(self, decision_type_text, order, message=""):
        self.decision_type_text = ""
        self.order = order
        self.message = message

        text = decision_type_text
        if isinstance(decision_type_text, DecisionType):
            text = decision_type_text.value
        self.decision_type_text = text

    def make_reply(self, subject="", message="", from_user=""):
        msg = message if message else self.message
        if not msg:
            return None

        sub = subject if subject else "Re: " + self.order.letter().subject
        env = Environment()
        letter = self.order.letter()
        admin_address = Brain.MY_USER_NAME + "@" + env.mail_domain
        from_address = from_user + "@" + env.mail_domain if from_user else admin_address
        to_addresses = [a for a in letter.to_addresses + [letter.from_address] if a != from_address]
        to_addresses = [a for a in to_addresses if not a.startswith(Brain.MY_USER_NAME) and not a.endswith(env.mail_domain)]
        letter = Letter(subject=sub, body=msg, from_address=from_address, to_addresses=to_addresses)
        return letter

    def decision_type(self):
        return DecisionType(self.decision_type_text)


from models.row import Row
from models.tagset.pronoun_tagset import PronounTagset

from lxml import etree

class PToken:
    def __init__(self, row: Row):
        self._word = row.word  # Checked for None in writer module
        self.form = str(self._word)
        self.lemma = self._word.lemma

        self.presentation_before = (
            row.head_punctuation.source if row.head_punctuation is not None else None
        )
        self.presentation_after = (
            f"{row.tail_punctuation.source} "
            if row.tail_punctuation is not None
            else " "
        )

    def xml(self) -> etree.Element:
        token = etree.Element("token")
        token.set("form", self.form)

        if self._word.pos is not None:
            token.set("part-of-speech", self.part_of_speech)
            token.set("morphology", self.morphology)
        if self.lemma is not None:
            token.set("lemma", self.lemma)

        if self.presentation_before is not None:
            token.set("presentation-before", self.presentation_before)
        token.set("presentation-after", self.presentation_after)

        return token

    @property
    def part_of_speech(self) -> str:
        if self._word.pos == "сущ":
            # Unfortunately, the PROIEL spec does not support
            # animacy for other parts of speech e.g. adjectives
            return "Ne" if "*" in self._word.source else "Nb"

        if self._word.pos == "мест":
            # SCAT does not support a more fine-grained distinction
            # other than personal, reflexive, and everything else
            if isinstance(self._word.tagset, PronounTagset):
                return "Pk" if self._word.tagset.person == "возвр" else "Pp"
            return "Px"

        if self._word.pos.startswith("прил"):
            return "A-"

        if self._word.pos.startswith("числ"):
            return "Mo" if self._word.pos == "числ/п" else "Ma"

        # Verbal distinctions are encoded in the mood property
        if self._word.pos.startswith(("гл", "прич", "инф", "суп")):
            return "V-"

        if self._word.pos == "нар":
            return "Df"

        # PROIEL does not discern between pre- and postpositions
        if self._word.pos in ("пред", "посл"):
            return "R-"

        if self._word.pos == "союз":
            return "C-"

        if self._word.pos == "част":
            return "G-"

        if self._word.pos == "межд":
            return "I-"

        if self._word.pos.isnumeric():
            return "Ma"

        return "X-"

    @property
    def morphology(self) -> str:
        return "".join(
            [
                self._person(),
                self._number(),
                self._tense(),
                self._mood(),
                self._voice(),
                self._gender(),
                self._case(),
                self._degree(),
                self._strength(),
                self._inflection(),
            ]
        )

    def _person(self) -> str:
        if self._word.tagset.person is None or self._word.tagset.person == "возвр":
            return "-"
        if self._word.tagset.person in ("1", "2", "3"):
            return self._word.tagset.person
        return "x"

    def _number(self) -> str:
        if self._word.tagset.number is None or self._word.tagset.person == "возвр":
            return "-"
        if self._word.tagset.number == "ед":
            return "s"
        if self._word.tagset.number == "мн":
            return "p"
        if self._word.tagset.number == "дв":
            return "d"
        return "x"

    def _tense(self) -> str:
        if self._word.tagset.tense is None:
            return "-"
        if self._word.tagset.tense in ("н/б", "наст"):
            return "p"
        if self._word.tagset.tense.startswith(("аор", "а/имп")):
            return "a"
        if self._word.tagset.tense == "имп":
            return "i"
        if self._word.tagset.tense == "плюскв":
            return "l"
        if self._word.tagset.tense == "перф":
            return "r"
        if self._word.tagset.tense in ("буд", "буд 1"):
            return "f"
        if self._word.tagset.tense == "буд 2":
            return "t"
        if self._word.tagset.tense == "прош":
            return "u"
        return "x"

    def _mood(self) -> str:
        if self._word.pos.startswith("прич"):
            return "p"
        if self._word.pos.startswith("инф"):
            return "n"
        if self._word.pos == "суп":
            return "u"

        if self._word.tagset.mood is None:
            return "-"
        if self._word.tagset.mood == "изъяв":
            return "i"
        if self._word.tagset.mood == "повел":
            return "m"
        if self._word.tagset.mood == "сосл":
            return "s"
        return "x"

    def _voice(self) -> str:
        if not self._word.pos.startswith(("гл", "прич", "инф")):
            return "-"
        if self._word.pos.endswith("/в"):
            return "p"
        if (
            self._word.pos == "прич"
            and self._word.tagset.declension is not None
            and self._word.tagset.declension[0] in ("a", "o", "тв")
        ):
            return "p"
        return "a"  # Note active voice by default

    def _gender(self) -> str:
        if self._word.tagset.gender is None or (
            self._word.pos.startswith("гл") and self._word.tagset.mood != "сосл"
        ):
            return "-"
        if self._word.tagset.gender == "м":
            return "m"
        if self._word.tagset.gender == "ж":
            return "f"
        if self._word.tagset.gender == "ср":
            return "n"
        return "x"

    def _case(self) -> str:
        if self._word.tagset.case is None:
            return "-"
        if self._word.tagset.case == "им":
            return "n"
        if self._word.tagset.case == "род":
            return "g"
        if self._word.tagset.case == "дат":
            return "d"
        if self._word.tagset.case == "вин":
            return "a"
        if self._word.tagset.case == "тв":
            return "i"
        if self._word.tagset.case == "мест":
            return "l"
        if self._word.tagset.case == "зв":
            return "v"
        return "x"

    def _degree(self) -> str:
        if not self._word.pos.startswith("прил") or self._word.pos == "прил/н":
            return "-"
        return "c" if self._word.pos == "прил/ср" else "p"

    def _strength(self) -> str:
        if (
            not self._word.pos.startswith(("прил", "прич"))
            or self._word.pos == "прил/н"
        ):
            return "-"
        if self._word.tagset.declension is not None:
            return "s" if self._word.tagset.declension[1] in ("тв", "м") else "w"
        return "t"

    def _inflection(self) -> str:
        return (
            "i"
            if self._word.pos.startswith(
                ("сущ", "мест", "прил", "числ", "гл", "прич", "инф", "суп")
            )
            and self._word.pos != "прил/н"
            else "n"
        )


# -*- coding: utf-8 -*-
import pyaudio
import viVoicecloud as vv
from sjtu.audio import findDevice

device_in = findDevice("ac108", "input")
Sample_channels = 1
Sample_rate = 16000
Sample_width = 2
time_seconds = 0.5  # 录音片段的时长，建议设为0.2-0.5秒

p = pyaudio.PyAudio()  # 实例化
stream = p.open(
    rate=Sample_rate,
    format=p.get_format_from_width(Sample_width),
    channels=Sample_channels,
    input=True,
    input_device_index=device_in,
    start=False)

vv.Login()  # 登录
ASR = vv.asr()  # 实例化

def asr():
    ASR.SessionBegin(language='Chinese')  # 开始语音识别
    stream.start_stream()
    print('***Listening...')

    # 录音并上传到讯飞，当判定一句话已经结束时，status返回3
    status = 0
    while status != 3:
        frames = stream.read(int(Sample_rate * time_seconds), exception_on_overflow=False)
        ret, status, recStatus = ASR.AudioWrite(frames)

    stream.stop_stream()
    print('---GetResult...')

    words = ASR.GetResult()  # 获取结果
    ASR.SessionEnd()  # 结束语音识别
    print(words)
    return words

while True:
    try:
        words = asr()
        if words == "退出。":
            break
        elif words == "点歌。":
            print("请说歌名")
            words = asr()

            from music import play_qq_music

            while True:
                try:
                    play_qq_music.play_music(words)
                except:
                    break
        elif words == "对话。":
            print("请说话")

            import viVoicecloud as vv
            from sjtu import analyze

            vv.Login()
            t = vv.tts()
            while 1:
                try:
                    question = input("I:")
                    json_data = vv.aiui(question)
                    print(json_data)
                    print(type(json_data))

                    answer = analyze.aiui_answer(json_data)
                    print("R:" + answer)

                    t.say(answer, voice="nannan")

                except Exception as e:
                    print(e)
                    vv.Logout()
                    break

            vv.Logout()

            import conversation
            while True:
                try:
                    words = asr()
                    conversation.conversation(words)
                except:
                    break

    except KeyboardInterrupt:
        break

vv.Logout()  # 注销
stream.close()
p.terminate()


"""Define mention aggregator class."""
import numpy as np
from tqdm import tqdm

from constants import *

class Aggregator(object):
    """Aggregate mentions of observations from radiology reports."""
    def __init__(self, categories, verbose=False):
        self.categories = categories

        self.verbose = verbose

    def dict_to_vec(self, d):
        vec = []
        for category in self.categories:
            # There was a mention of the category.
            if category in d:
                label_list = d[category]
                # Only one label, no conflicts.
                if len(label_list) == 1:
                    vec.append(label_list[0])
                # Multiple labels.
                else:
                    # Case 1. There is negated and uncertain.
                    if NEGATIVE in label_list and UNCERTAIN in label_list:
                        vec.append(UNCERTAIN)
                    # Case 2. There is negated and positive.
                    elif NEGATIVE in label_list and POSITIVE in label_list:
                        vec.append(POSITIVE)
                    # Case 3. There is uncertain and positive.
                    elif UNCERTAIN in label_list and POSITIVE in label_list:
                        vec.append(POSITIVE)
                    # Case 4. All labels are the same.
                    else:
                        vec.append(label_list[0])

            # No mention of the category
            else:
                vec.append(NEGATIVE)

        return vec

    def aggregate(self, collection):
        documents = collection.documents
        if self.verbose:
            print("Aggregating mentions...")
            documents = tqdm(documents)

        label_dict = {"uid": [], "Keyword": [], "Label": []}
        for document in documents:
            label_dict["uid"].append(document.id)
            passage = document.passages[0]

            temp_label = []

            phrase = ""
            uncertain_phrase = ""
            for annotation in passage.annotations:
                category = annotation.infons[OBSERVATION]

                if POSITIVE in annotation.infons:
                    phrase += annotation.text + " "
                    temp_label.append(POSITIVE)
                else:
                    temp_label.append(NEGATIVE)

            #conclusion
            if POSITIVE in temp_label:
                label_dict["Keyword"].append(phrase)
                label_dict["Label"].append(POSITIVE)
            else:
                label_dict["Keyword"].append("")
                label_dict["Label"].append(NEGATIVE)

        return label_dict


# -*- coding: utf-8 -*-
import glob
import os
import sys
import time

from PyQt5 import QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QMainWindow, QMessageBox

from swaggerjmx.convert import conversion
from swaggerjmx.settings import Settings as ST

from json2jmx.json_jmx import Ui_MainWindow

class MyThread(QThread):
    # 设置线程变量
    trigger = pyqtSignal(str)

    def __init__(self, parent=None):
        super(MyThread, self).__init__(parent)

    def run_(self, message):
        '''
        向信号trigger发送消息
        '''
        logger_time = time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime(time.time()))
        self.trigger.emit("[{0}] {1}".format(logger_time, message))

class MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        self.pushButton_json_dir.clicked.connect(self.selectJsonPath)
        self.pushButton_trans.clicked.connect(self.selectSaveJmx)

        self.threads = MyThread(self)  # 自定义线程类
        self.threads.trigger.connect(self.update_text)  # 当信号接收到消息时，更新数据

    def selectJsonPath(self):
        # 选择Json文件夹
        json_dir = QtWidgets.QFileDialog.getExistingDirectory(None, "选取Json文件夹", "")
        if ('' != json_dir):
            self.lineEdit_json_dir.setText(json_dir)

    def selectSaveJmx(self):
        # 保存Jmx文件

        json_dir = self.lineEdit_json_dir.text()
        if ('' == json_dir):
            self.threads.run_("Json目录不合法！")
            return

        message = "Json目录:{0}".format(json_dir)
        self.threads.run_(message)
        Files = glob.glob(json_dir + os.sep + "*.json")
        filename_list = [file.split('\\')[-1] for file in Files]
        if (len(filename_list) == 0):
            # self.threads.run_("目录下不存在json文件！")
            QMessageBox.information(self, "提示", "未找到json文件，请检查Json目录！", QMessageBox.Ok)
            return
        self.threads.run_("读取到Json文件：{0}".format(filename_list))

        jmx_dir = QtWidgets.QFileDialog.getExistingDirectory(None, "保存Jmx路径", "")
        if ('' == jmx_dir): return

        ST.swagger_url_json_path = ''
        ST.report_path = jmx_dir
        trans_result = True

        for jsonFile in Files:
            file_name = jsonFile.split('\\')[-1]
            try:
                ST.swagger_url_json_path = (str(jsonFile))
                conversion()
                message = "【{}】 文件格式转换 成功！".format(file_name)
                self.threads.run_(message)
            except Exception as e:
                message = "【{}】 文件格式转换 失败！请检查文件内容。".format(file_name)
                self.threads.run_(message)
                trans_result = False

        message = "文件保存至：【{0}】".format(jmx_dir)
        self.threads.run_(message)

        if (trans_result):
            message = "转换成功！"
        else:
            message = "存在转换失败的文件，请检查文件内容！"
        QMessageBox.information(self, "提示", message, QMessageBox.Ok)

    def update_text(self, message):
        '''
        添加信息到日志栏中(即控件QTextBrowser中)
        '''
        self.textBrowser_logger.append(message)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    sys.exit(app.exec_())


from simple_playgrounds.common.definitions import ElementTypes
from simple_playgrounds.element.elements.activable import ActivableByGem
from simple_playgrounds.element.elements.gem import GemElement

class RescueCenter(ActivableByGem):
    """
    When in contact with a wounded_person, provide a reward of 1 to the drone closest to the wounded_person.
    """

    def __init__(self, **kwargs):

        texture = {'texture_type': 'random_tiles',
                   'color_min': [226, 10, 10],
                   'color_max': [255, 32, 41],
                   'size_tiles': 6}

        super().__init__(config_key=ElementTypes.VENDING_MACHINE,
                         reward=1,
                         texture=texture,
                         **kwargs)

        self._quantity_rewards = None
        self._count_rewards = 0

    def activate(self, activating: GemElement, ):
        list_remove = None

        if activating.elem_activated:
            list_remove = [activating]

        return list_remove, None

    @property
    def reward(self):
        rew = super().reward

        if self._quantity_rewards and self._count_rewards >= self._quantity_rewards:
            return 0

        self._count_rewards += 1
        return rew

    @reward.setter
    def reward(self, rew: float):
        self._reward = rew

    def reset(self):
        super().reset()
        self._count_rewards = 0


import astropy.units as u
import numpy as np
from astropy.io import fits

import matplotlib as mpl
from matplotlib import rc
from astropy.constants import c, h, k_B

#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('font',**{'family':'serif'})#,'sans-serif':['Helvetica']})
rc('text', usetex=True)
# set tickmarks inwards
mpl.rcParams['xtick.direction'] = 'in'
mpl.rcParams['ytick.direction'] = 'in'

# file_HC3N_10_9_TdV_mJy
# N2Hp_TdV = 'data/Per-emb-2-N2Hp-1-0_TdV.fits'
HC3N_10_9_Vlsr = 'data/Per-emb-2-HC3N_10-9_fit_Vc.fits'
HC3N_10_9_TdV = 'data/Per-emb-2-HC3N_10-9_TdV.fits'
N2Dp_TdV = 'data/Per-emb-2-N2Dp-1-0_TdV.fits'
N2Dp_Vlsr = 'data/Per-emb-2-N2Dp_1-0_fit_Vc.fits'
N2Dp_eVlsr = 'data/Per-emb-2-N2Dp_1-0_fit_eVc.fits'
N2Hp_TdV = 'data/Per-emb-2-N2Hp-1-0_TdV.fits'
#
ra_Per2 = 15 * (3 + (32 + 17.92/60.) / 60.) * u.deg
dec_Per2 = (30 + (49 + 48.03 / 60.) / 60.) * u.deg
distance = 300.
N2Dp_TdV_levels = 19e-3 * np.arange(5, 20, 3)
N2Hp_TdV_levels = 30e-3 * np.arange(5, 20, 3)
HC3N_10_9_TdV_levels = 8e-3 * np.arange(5, 20, 3)

Per2_inc = -43*u.deg
Per2_pa = 130*u.deg
Per2_v_lsr = 7.05*u.km/u.s

region_file = 'Streamer_North_v2.reg'

# CO contour levels to show outflow
file_12CO_blue = 'data/Per-emb-2-CO_2-1-TdV-blue.fits'
file_12CO_red = 'data/Per-emb-2-CO_2-1-TdV-red.fits'
CO_red_levs = 0.2 * np.arange(5, 55, 10)
CO_blue_levs = 0.2 * np.arange(5, 55, 10)
#
# Polygon coordinates added by hand from the region file
# The next line is to close the polygon
poly = np.array([53.079519, 30.83452, 53.078404, 30.836177, 53.076689, 30.83787, 53.075746, 30.837944,
                 53.075017, 30.837208, 53.075067, 30.835867, 53.076296, 30.833681, 53.07735, 30.831875,
                 53.077525, 30.829164, 53.078662, 30.827808, 53.079905, 30.82885, 53.080033, 30.832016])
ra_poly = np.append(np.reshape(poly, [-1, 2])[:, 0], poly[0])*u.deg
dec_poly = np.append(np.reshape(poly, [-1, 2])[:, 1], poly[1])*u.deg

def per_emb_2_get_vc_proj_r(file_in=N2Dp_Vlsr, pa_angle=0*u.deg, inclination=0*u.deg):
    """
    Returns the centroid velocity and projected separation in the sky of the
    centroid velocity from Per-emb-2.
    r_proj is in u.au and V_los is in u.km/u.s
    :return: r_proj, V_los
    """
    from astropy.wcs import WCS
    from astropy.io import fits
    import velocity_tools.coordinate_offsets as c_offset
    # load region file and WCS structures
    wcs_Vc = WCS(file_in)
    #
    hd_Vc = fits.getheader(file_in)
    results = c_offset.generate_offsets(hd_Vc, ra_Per2, dec_Per2,
        pa_angle=pa_angle, inclination=inclination)
    rad_au = (results.lon * distance*u.pc).to(u.au, equivalencies=u.dimensionless_angles())
    #
    Vc = fits.getdata(file_in)
    gd = np.isfinite(Vc) == 1
    v_los = Vc[gd]*u.km/u.s
    r_proj = rad_au[gd]
    return r_proj, v_los

def pb_interferometer(freq_obs, telescope='NOEMA'):
    """
    Primary beam diameter for SMA at the observed frequency.
        PB = 48.0 * (231.0*u.GHz) / freq_obs

    :param freq_obs: is the observed frequency in GHz.
    :return: The primary beam FWHM in arcsec
    """
    if telescope == 'NOEMA':
        return (64.1 * u.arcsec * 72.78382 * u.GHz / freq_obs).decompose()
    elif telescope == 'SMA':
        return (48.0 * u.arcsec * 231 * u.GHz / freq_obs).decompose()
    elif telescope == 'ALMA':
        return (21.0 * u.arcsec * 300 * u.GHz / freq_obs).decompose()
    elif telescope == 'ACA':
        return (35.0 * u.arcsec * 300 * u.GHz / freq_obs).decompose()
    elif telescope == 'VLA' or telescope == 'EVLA' or telescope == 'JVLA':
        return (45 * 60.0 * u.arcsec * u.GHz / freq_obs).decompose()
    else:
        print("Telescope still not included")
        return np.nan * u.arcsec

def setup_plot_noema(fig_i, label_col='black', star_col='red'):
    """
    Setup of NOEMA plots, since they will show all the same format.
    """
    fig_i.set_system_latex(True)
    fig_i.ticks.set_color(label_col)
    fig_i.recenter(53.075, 30.8299, radius=45 * (u.arcsec).to(u.deg))
    fig_i.set_nan_color('0.9')
    fig_i.add_beam(color=label_col)
    #
    ang_size = (5e3 / distance) * u.arcsec
    fig_i.add_scalebar(ang_size, label='5,000 au', color=label_col)
    fig_i.show_markers(ra_Per2.value, dec_Per2.value, marker='*', s=60, layer='star',
                       edgecolor=star_col, facecolor=label_col, zorder=31)
    fig_i.tick_labels.set_xformat('hh:mm:ss')
    fig_i.tick_labels.set_yformat('dd:mm:ss')
    fig_i.ticks.set_length(7)
    fig_i.axis_labels.set_xtext(r'Right Ascension (J2000)')
    fig_i.axis_labels.set_ytext(r'Declination (J2000)')
    return

def setup_plot_30m(fig_i, label_col='black', star_col='red'):
    """
    Setup of IRAM 30m plots, since they will show all the same format.
    """
    fig_i.set_system_latex(True)
    fig_i.ticks.set_color(label_col)
    # fig_i.recenter(53.075, 30.8299, radius=45 * (u.arcsec).to(u.deg))
    fig_i.set_nan_color('0.9')
    fig_i.add_beam(color=label_col)
    #
    ang_size = (5e3 / distance) * u.arcsec
    fig_i.add_scalebar(ang_size, label='5,000 au', color=label_col)
    fig_i.show_markers(ra_Per2.value, dec_Per2.value, marker='*', s=60, layer='star',
                       edgecolor=star_col, facecolor=label_col, zorder=31)
    fig_i.tick_labels.set_xformat('hh:mm:ss')
    fig_i.tick_labels.set_yformat('dd:mm')
    fig_i.ticks.set_length(7)
    fig_i.axis_labels.set_xtext(r'Right Ascension (J2000)')
    fig_i.axis_labels.set_ytext(r'Declination (J2000)')
    return

def convert_into_mili(file_name):
    """
    It converts a file into one rescaled by 1e3.
    This is useful to convert between Jy -> mJy or m/s into km/s
    for plotting purposes (e.g. to use with aplpy).

    Usage:
    fig = aplpy.FITSFigure(convert_into_mili(file_in_Jy), figsize=(4,4))
    fig.show_colorscale(vmin=0, vmax=160, cmap='inferno')
    fig.add_colorbar()
    fig.colorbar.set_axis_label_text(r'Integrated Intensity (mJy beam$^{-1}$ km s$^{-1}$)')

    :param file_name: string with filename to process
    :return: hdu
    """
    data, hd = fits.getdata(file_name, header=True)
    return fits.PrimaryHDU(data=data*1e3, header=hd)


import argparse

def remove_prefix(kwargs, prefix):
    assert len(prefix) > 0
    ret = {}
    for key, val in kwargs.items():
        if key.startswith(prefix):
            ret[key[len(prefix):]] = val
    return ret

def parse_known_args_with_prefix(argv, add_args_func, prefix=''):
    arg_parser = argparse.ArgumentParser(allow_abbrev=False)
    add_args_func(arg_parser, prefix)
    args, _ = arg_parser.parse_known_args(argv)
    args = vars(args)
    if prefix != '':
        prefix = prefix.replace('-', '_')
        args = remove_prefix(args, prefix)
    return args


import nltk
from nltk.stem.porter import *
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
import xml.etree.cElementTree as ET
from collections import Counter
import string
from sklearn.feature_extraction.text import TfidfVectorizer
import zipfile
import os

PARTIALS = False

def gettext(xmltext) -> str:
    """
    Parse xmltext and return the text from <title> and <text> tags
    """
    elements = []
    xmltext = xmltext.encode('ascii', 'ignore') # ensure there are no weird char
    tree = ET.ElementTree(ET.fromstring(xmltext))
    for elem in tree.iterfind('.//title'):
        elements.append(elem.text)
    for elem in tree.iterfind('.//text/*'):
        elements.append(elem.text)
    return ' '.join(elements)

def tokenize(text) -> list:
    """
    Tokenize text and return a non-unique list of tokenized words
    found in the text. Normalize to lowercase, strip punctuation,
    remove stop words, drop words of length < 3, strip digits.
    """
    tokenized_words = list()
    text = text.lower()
    text = re.sub('[' + string.punctuation + '0-9\\r\\t\\n]', ' ', text)
    tokens = nltk.word_tokenize(text)
    tokens = [w for w in tokens if len(w) > 2]  # ignore a, an, to, at, be, ...
    for word in tokens:
        if word not in ENGLISH_STOP_WORDS:
            tokenized_words.append(word)
    return tokenized_words

def stemwords(words) -> list:
    """
    Given a list of tokens/words, return a new list with each word
    stemmed using a PorterStemmer.
    """
    new_words = []
    ps = PorterStemmer()
    for word in words:
        new_words.append(ps.stem(word))
    return new_words

def tokenizer(text) -> list:
    return stemwords(tokenize(text))

def compute_tfidf(corpus:dict) -> TfidfVectorizer:
    """
    Create and return a TfidfVectorizer object after training it on
    the list of articles pulled from the corpus dictionary. Meaning,
    call fit() on the list of document strings, which figures out
    all the inverse document frequencies (IDF) for use later by
    the transform() function. The corpus argument is a dictionary
    mapping file name to xml text.
    """
    tfidf = TfidfVectorizer(input='content',
                            analyzer='word',
                            preprocessor=gettext,
                            tokenizer=tokenizer,
                            stop_words='english', # even more stop words
                            decode_error = 'ignore')
    return tfidf.fit(list(corpus.values()))

def summarize(tfidf:TfidfVectorizer, text:str, n:int):
    """
    Given a trained TfidfVectorizer object and some XML text, return
    up to n (word,score) pairs in a list. Discard any terms with
    scores < 0.09. Sort the (word,score) pairs by TFIDF score in reverse order.
    """
    results = list()
    matrix = tfidf.transform([text])
    feature_names = tfidf.get_feature_names()
    scores = matrix.toarray()[0]
    word_index = matrix.nonzero()[1]
    for index in word_index:
        if scores[index] >= 0.09:
            results.append((feature_names[index], round(scores[index],3)))
    return sorted(results, key=lambda item: (item[1], item[0]), reverse=True)[:n]

def load_corpus(zipfilename:str) -> dict:
    """
    Given a zip file containing root directory reuters-vol1-disk1-subset
    and a bunch of *.xml files, read them from the zip file into
    a dictionary of (filename,xmltext) associations. Use namelist() from
    ZipFile object to get list of xml files in that zip file.
    Convert filename reuters-vol1-disk1-subset/foo.xml to foo.xml
    as the keys in the dictionary. The values in the dictionary are the
    raw XML text from the various files.
    """
    xml_dict = dict()
    absfilepath = os.path.expanduser(zipfilename)
    with zipfile.ZipFile(absfilepath, 'r') as zipObj:
        # Get list of files names in zip
        listOfiles = zipObj.namelist()
        # Iterate over the list of file names and extract content
        for filename in listOfiles:
            if filename.endswith('.xml'):
                xml_dict[os.path.basename(filename)] = zipObj.read(filename).strip()
    return xml_dict


#!/Users/kmn182/anaconda3/envs/ENV1/bin/python
# ------------------------------------------------------------
#
#	Program Name: calculate_diagnostics_kepert_ens_avg.py
#
# -------------------------------------------------------------

# Step 1 (import necessary modules)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from netCDF4 import Dataset
import os
import sys
import csv
from output_functions import calc_p_sfc_ens_avg

# define environmental path variable
GOOGLE_ROOT = os.environ['GOOGLE_ROOT'] # this will vary based on the user's system

# define the font family
mpl.rc('font',family='Arial')

# define the configurations
configs = [sys.argv[1]] # this value is read in from the "run_kepert_analysis.sh" script

# define the time step labels
time_steps = range(1, 17) # in days
time_steps = np.asarray(time_steps, dtype='str')
for t_i, time in enumerate(time_steps):
	time_steps[t_i] = time.zfill(2) # the final result is daily time steps as strings with 2 characters and right justification (e.g. '01', '02', etc.)

# how many ensemble members?
num_ensembles = int(sys.argv[2])

# Step 2 (read in the input files)

for c_i, config in enumerate(configs): # loop through each configuration

	# the following input/output paths will vary by user

	# define the input path
	input_path = '/Users/kmn182/ICS_scratch/output/ens_avg/' + config + '/'

	# define the output path
	output_path = GOOGLE_ROOT + '/CPT_Project/ANALYSIS/diagnostics/' + config + '/'
	if not os.path.exists(output_path):
		os.mkdir(output_path) # if the path does not exist, make it

	# calculate surface pressure minimum and surface wind maximum for the configuration (all times included)
	min_sfc_p, max_sfc_wind = calc_p_sfc_ens_avg(config, num_ensembles, time_steps) # this function requires importing output_functions.py

	# Step 2 (create a CSV file to store the model diagnostics)

	f = open(output_path + 'diagnostics_kepert_' + config + '_ens_avg.csv', mode='w')
	csv_writer = csv.writer(f, delimiter=',')
	csv_writer.writerow(['Time Step (days)', '', 'Radius Max Wind (m)', '', 'Surface Inflow Angle (deg)', '', 'Inflow Depth (m)', '', 'Surface Max Wind Speed (m/s)', '', 'Min Surface Pressure (hPa)', '', 'Level of Max Wind (m)'])

	for t_i, time_step in enumerate(time_steps): # loop through each time step

		# Step 3 (read in the input file...assuming one at this point)

		print('Now examining ' + config + '/time step ' + time_step + '...')

		# define file name
		file_name = config + '_ens_avg_' + time_step + '.nc'

		# open up the file of radial averages and read in the data
		dataset = Dataset(input_path + file_name)

		rad_T = dataset.variables['rad_T'][:] # average temperature along the radial (in degrees K)
		rad_q = dataset.variables['rad_Q'][:] # average specific humidity along the radial (in kg/kg)
		rad_v_theta = dataset.variables['rad_v_theta'][:] # average tangential wind along the radial (in m/s)
		rad_v_rad = dataset.variables['rad_v_rad'][:] # average radial wind along the radial (in m/s)
		rad_w = dataset.variables['rad_W'][:] # average vertical velocity along the radial (in m/s)
		rad_kvm = dataset.variables['rad_KVM'][:] # average vertical diffusivity of heat/moisture (in m**2/s)
		rad_tke = dataset.variables['rad_TKE'][:] # average turbulent kinetic energy (in m**2/s)
		rad_lscale = dataset.variables['rad_LSCALE'][:] # average turbulent length scale (in m)
		rad_theta = dataset.variables['rad_THETA'][:] # average potential temperature (in K)
		levels = dataset.variables['lev'][:] # vertical z levels (in m)
		radius = dataset.variables['radius'][:] # horizontal distance from the storm center (in m)

		# define the bounds of the data domain
		min_level = int(np.nanmin(levels))
		min_radius = int(np.nanmin(radius))
		max_level = int(np.nanmax(levels))
		max_radius = int(np.nanmax(radius))

		# Step 4 (calculate the model diagnostics)

		# find the radius of maximum wind (tangential)
		max_wind = np.nanmax(rad_v_theta) # maximum tangential wind
		[max_levels, max_radius] = np.where(rad_v_theta == max_wind)
		max_radius_index = max_radius[0]
		radius_of_max_wind = radius[max_radius_index]

		# find 2x radius of maximum wind
		if 2*radius_of_max_wind > np.nanmax(radius):
			max_radius_index_2x = np.where(radius == np.nanmax(radius))[0][0]
		else:
			max_radius_index_2x = np.where(radius == 2*radius_of_max_wind)[0][0]

		# find the surface inflow angle at the radius of maximum wind
		# first, find the lowest model level with non-NaN data
		for l_i, level in enumerate(levels):
			level_v_theta = rad_v_theta[l_i, max_radius_index]
			if np.ma.is_masked(level_v_theta):
				continue
			else:
				lowest_level_index = l_i
				lowest_level = level
				break
		sfc_v_thetas = rad_v_theta[lowest_level_index, :] # at all radii
		sfc_v_rads = rad_v_rad[lowest_level_index, :] # at all radii
		sfc_v_theta = rad_v_theta[lowest_level_index, max_radius_index] # at the lowest level and at the radius of maximum wind
		sfc_v_rad = rad_v_rad[lowest_level_index, max_radius_index] # these assume that the surface is the lowest model layer with data
		sfc_inflow_angle = np.arctan(sfc_v_rad / sfc_v_theta) # in radians
		sfc_inflow_angle = np.absolute(sfc_inflow_angle * (180. / np.pi))

		# calculate the level at which the maximum tangential wind speed occurs (at the radius of maximum wind)
		max_v_theta = np.nanmax(rad_v_theta[:, max_radius_index])
		max_v_theta_index = np.where(rad_v_theta[:, max_radius_index] == max_v_theta)[0][0]
		max_v_theta_level = levels[max_v_theta_index] # level in meters

		# find the inflow depth based on the surface radial flow at the 2x radius of maximum wind
		sfc_radial_flow = np.absolute(rad_v_rad[lowest_level_index, max_radius_index_2x])
		# loop through each level at the 2x radius of maximum wind to find the level at which inflow gets below 10% of surface radial flow
		for l_i, level in enumerate(levels):
			level_radial_flow = np.absolute(rad_v_rad[l_i, max_radius_index_2x])
			if not np.ma.is_masked(level_radial_flow):
				if level_radial_flow > (0.1 * sfc_radial_flow):
					inflow_depth = level
					continue
				else:
					break

		dataset.close()

		# Step 5 (output the results to a netCDF file)

		time = time_step
		csv_writer.writerow([time, '', str(radius_of_max_wind), '', str(sfc_inflow_angle), '', str(inflow_depth), '', str(max_sfc_wind[t_i]), '', str(min_sfc_p[t_i]), '', max_v_theta_level])

	f.close() # close and save the file
	print('The file has been written for ' + config + '!')


#! /usr/bin/python

if __name__ == '__main__':
    from textProcessor.core.service import Service

    #a = Service().populateGraph("The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators +, -, * and / work just like in most other languages (for example, Pascal or C); parentheses can be used for grouping. For example:")
    #a = Service().populateGraph("Blest with victory and peace, may the heav'n-rescued land Praise the Power that hath made and preserved us a nation! Then conquer we must, when our cause it is just,")

    a = Service().populateGraph("""ney mello sampaio sadksak sdsaljda
aksjdksa
askdjsakljd
ksadjksajd ksdjklsajd sakdjsakjda skasjdkasj
ney mello sampaio""")

    #print(a.getGraph())
    #print(a.getEdges())
    #print(a.getNGrams())

    ngrams = a.getNGrams()

    #for i in ngrams:
        #print(i)

    #print(ngrams.keys())
    #print(ngrams.values())
    items = ngrams.values()
    sorted(items)
    #print(sorted(items))

    for i in sorted(ngrams.items(), key=lambda x:x[1],reverse=True)[0:3]:
        print(i[0][0])
    #print([value for key, value in items])


from functools import reduce
def formatdata():
    current_elf_inventory = []
    foodinventories = []
    with open("./input.txt", "r") as file:
        for line in file.readlines():
            if line == "\n":
                foodinventories.append(current_elf_inventory)
                current_elf_inventory = []
            else: current_elf_inventory.append(int(line.removesuffix('\n')))
    return foodinventories

if __name__ == "__main__":
    calorielist = formatdata()
    elvestotalcalories = list(map(lambda z: reduce(lambda x,y : x+y, z), calorielist))
    firstans = max(elvestotalcalories)
    secondans = sum(sorted(elvestotalcalories)[-3:])
    print(f"Answer to first question: {firstans}\nAnswer to second question: {secondans}")