from typing import Dict
import json as _json
import datetime as _dt

def get_all_events() -> Dict:
    with open("events.json", encoding='utf-8') as events_file:
        data = _json.load(events_file)

    return data

def get_all_month_events(month: str) -> Dict:
    events = get_all_events()
    month = month.lower()
    try:
        month_events = events[month]
        return month_events
    except KeyError:
        return "This is not a month name"

def get_all_day_events(month: str, day: int) -> Dict:
    events = get_all_events()
    month = month.lower()
    try:
        day_events = events[month][str(day)] # Here, I passed day as a string becasue in our json, days are written in string format
        return day_events
    except KeyError:
        return "This is not a valid input"

def get_all_today_events():
    today = _dt.date.today()
    month = today.strftime("%B")
    return get_all_day_events(month, today.day)


from matplotlib import pyplot as plt
import numpy as np
import random
import utils

features = np.array([1,2,3,5,6,7])
labels = np.array([155, 197, 244, 356,407,448])

print(features)
print(labels)

utils.plot_points(features, labels)

# Feature cross / synthetic feature
def feature_cross(num_rooms, population):
    room_per_person_feature = num_rooms / population
    return room_per_person_feature

def simple_trick(base_price, price_per_room, num_rooms, price):
    # select random learning rate
    small_random_1 = random.random()*0.1
    small_random_2 = random.random()*0.1
    # calculate the prediction.
    predicted_price = base_price + price_per_room*num_rooms
    # check where the point is with respect to the line.
    if price > predicted_price and num_rooms > 0:
        # translate the line
        price_per_room += small_random_1
        # rotate the line
        base_price += small_random_2
    if price > predicted_price and num_rooms < 0:
        price_per_room -= small_random_1
        base_price += small_random_2
    if price < predicted_price and num_rooms > 0:
        price_per_room -= small_random_1
        base_price -= small_random_2
    if price < predicted_price and num_rooms < 0:
        price_per_room -= small_random_1
        base_price += small_random_2
    return price_per_room, base_price

def absolute_trick(base_price, price_per_room, num_rooms, price, learning_rate):
    predicted_price = base_price + price_per_room*num_rooms
    if price > predicted_price:
        price_per_room += learning_rate*num_rooms
        base_price += learning_rate
    else:
        price_per_room -= learning_rate*num_rooms
        base_price -= learning_rate
    return price_per_room, base_price

def square_trick(base_price, price_per_room, num_rooms, price, learning_rate):
    predicted_price = base_price + price_per_room*num_rooms
    price_per_room += learning_rate*num_rooms*(price-predicted_price)
    base_price += learning_rate*(price-predicted_price)
    return price_per_room, base_price

# We set the random seed in order to always get the same results.
random.seed(0)

def linear_regression(features, labels, learning_rate=0.01, epochs = 1000):
    price_per_room = random.random()
    base_price = random.random()
    for epoch in range(epochs):
        # Uncomment any of the following lines to plot different epochs
        if epoch == 1:
            utils.draw_line(price_per_room, base_price, starting=0, ending=8)
        elif epoch <= 10:
            utils.draw_line(price_per_room, base_price, starting=0, ending=8)
        elif epoch <= 50:
            utils.draw_line(price_per_room, base_price, starting=0, ending=8)
        elif epoch > 50:
            utils.draw_line(price_per_room, base_price, starting=0, ending=8)
        i = random.randint(0, len(features)-1)
        num_rooms = features[i]
        price = labels[i]
        # Uncomment any of the 2 following lines to use a different trick
        #price_per_room, base_price = absolute_trick(base_price,
        price_per_room, base_price = square_trick(base_price,
                                                  price_per_room,
                                                  num_rooms,
                                                  price,
                                                  learning_rate=learning_rate)
    utils.draw_line(price_per_room, base_price, 'black', starting=0, ending=8)
    utils.plot_points(features, labels)
    print('Price per room:', price_per_room)
    print('Base price:', base_price)
    return price_per_room, base_price

# This line is for the x-axis to appear in the figure
plt.ylim(0,500)

linear_regression(features, labels, learning_rate = 0.01, epochs = 1000)

# The root mean square error function
def rmse(labels, predictions):
    n = len(labels)
    differences = np.subtract(labels, predictions)
    return np.sqrt(1.0/n * (np.dot(differences, differences)))


from cgitb import reset
from flask import Flask, jsonify, request, render_template
import Crypto
import Crypto.Random
from Crypto.PublicKey import RSA
import binascii
from collections import OrderedDict
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
import webbrowser

class Transaction:

    def __init__(self, sender_public_key, sender_private_key, recipient_public_key, amount):
        self.sender_public_key = sender_public_key
        self.sender_private_key = sender_private_key
        self.recipient_public_key = recipient_public_key
        self.amount = amount

    #Function to convert transaction details to dictionary format
    def to_dict(self):
        return OrderedDict({
            'sender_public_key' : self.sender_public_key,
            'recipient_public_key' : self.recipient_public_key,
            'amount' : self.amount
        })

    #Function to sign the transaction
    def sign_transaction(self):
        private_key = RSA.importKey(binascii.unhexlify(self.sender_private_key))
        signer = PKCS1_v1_5.new(private_key)
        hash = SHA.new(str(self.to_dict()).encode('utf8'))
        return binascii.hexlify(signer.sign (hash)).decode('ascii')

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/make/transactions')
def make_transactions():
    return render_template('make_transactions.html')

@app.route('/view/transactions')
def view_transactions():
    return render_template('view_transactions.html')

#Public and private key pair generation for wallet
@app.route('/wallet/new')
def new_wallet():
    random_gen = Crypto.Random.new().read
    private_key = RSA.generate(1024, random_gen)
    public_key = private_key.publickey()

    response={
        'private_key' : binascii.hexlify(private_key.export_key(format('DER'))).decode('ascii'),
        'public_key' :binascii.hexlify(public_key.export_key(format('DER'))).decode('ascii')
    }

    return response

#Code to generate the transactions
@app.route('/generate/transactions', methods=['POST'])
def generate_transactions():
    #Extract transaction details from form
    sender_public_key = request.form['sender_public_key']
    sender_private_key =  request.form['sender_private_key']
    recipient_public_key = request.form['recipient_public_key']
    amount = request.form['amount']

    #Make a Transaction object
    transaction = Transaction(sender_public_key, sender_private_key, recipient_public_key, amount)

    #Convert Transaction object into dictionary and sign it
    response ={'transaction' : transaction.to_dict(),
                'signature' : transaction.sign_transaction()}

    return jsonify(response), 200

if __name__ == '__main__':
    from argparse import ArgumentParser

    parser = ArgumentParser()
    parser.add_argument('-p', '--port', default = 8081, type = int, help ="Port to listen")
    args = parser.parse_args()
    port = args.port

    #Open url in browser
    webbrowser.open('http://127.0.0.1:'+str(port))
    #Run flask app
    app.run(host="0.0.0.0",port=port, debug=True)


file = open('./3/3.txt', 'r')
input = file.readlines()

def get_letter_value(letter):
    letter_value = ord(letter)
    if letter_value < 97:
        return letter_value - 38

    return letter_value - 96

def get_matching_letter():
    found_items = []
    for rucksack in input:
        item_count = len(rucksack)

        for i in range((item_count // 2)):
            if rucksack[i] in rucksack[item_count // 2:]:
                found_items.append(get_letter_value(rucksack[i]))
                break

    return found_items

print(sum(get_matching_letter()))


"""This module allows to interact with the user via the command line and processes
the input information.
"""

import os
import re
from inspect import getsourcefile
import numpy as np
import yaml

class CommandLineParser():
    """See documentation of the init method.
    """

    def __init__(self) -> None:
        """This class allows to parse user input from the command line and validate
        its syntax. Furthermore it allows to create the axes for the goniometer
        from a specific user input format.
        """

        self.parsed = {}
        self._resources_path = os.path.abspath(getsourcefile(lambda: 0)).replace(
            'command_line_interfaces/parser.py', 'resources/')

        with open(f"{self._resources_path}user_input.yaml", 'r') as stream:
            try:
                self.input_options = yaml.safe_load(stream)
            except yaml.YAMLError as error:
                print(error)

        # TODO sometimes e.g. for chi a trailing space is enough to fail the regex
        self.validation_regex = {
            'doi': None,
            'layout': self._create_options_regex('layout'),
            'facility': self._create_options_regex('facility'),
            'beamline': None,
            'rad_type': None,
            "model" : None,
            "location" : None,
            "manufacturer" : self._create_options_regex('manufacturer'),
            'principal_angle': r'\d{1,3}\Z',
            'goniometer_axes' : r'((?:[^,]*,\s*(a|c),\s*)*[^,]*,\s*(a|c))\Z',
            'change_goniometer_axes' : r'((?:[^,]*,\s*(a|c),\s*)*[^,]*,\s*(a|c))\Z',
            'change_det_rot_axes' : r'((?:[^,]*,\s*(a|c),\s*)*[^,]*,\s*(a|c))\Z',
            "two_theta_sense" : self._create_options_regex('two_theta_sense'),
            'detector_axes' : r'((?:[^, ]*,\s*)*[^, ]+)\Z',
            "chi_axis" : r'.*(?:\s+\d{1,3})\Z',
            'kappa_axis': r'.*(((\s|,)(\s)*\d{1,3}){1,2})\Z', # capture something like kappa, 50, 50
            'image_orientation': self._create_options_regex('image_orientation'),
            'fast_direction': self._create_options_regex('fast_direction'),
            'pixel_size': r'(\d+\.?\d*\Z)|(\d+\.?\d*,\s*\d+\.?\d*\Z)',
            'array_dimension': r'(\d+(,\s*)\d+\Z)',
            'filename': r'.*((\.h5)\Z|(\.cbf)\Z|(\.smv)\Z)',
            'goniometer_rot_direction' : \
                self._create_options_regex('goniometer_rot_direction'),
            'frame_numbers': r'^\d+(,\s*\d+)*$',
            'external_url': None,
            'temperature': r'\d+\Z',
            'keep_axes': self._create_options_regex('keep_axes'),
            'url_not_reachable': self._create_options_regex('url_not_reachable'),
        }

    def request_input(self, label):
        """Request input from the user for the given label and the associated
        information in the resources file.

        Args:
            label (str): the label that identifies the request

        Returns:
            str: the input from the user, validated
        """

        while self.parsed.get(label) is None:
            required = 'required' if self.input_options[label].get('required') \
                else 'not required'
            print(f"\n{self.input_options[label]['label']} ({required}):")
            choices = ''
            if self.input_options[label].get('options') is not None:
                options = self.input_options[label]['options']
                if self.input_options[label].get('abbreviate'):
                    options = [option + f' ({option[0]})' for option in options]
                choices = '\n Choices: ' + ', '.join(options)
            print(f"{self.input_options[label]['description']}".strip('\n') + choices)
            self.parsed[label] = self._validated_user_input(label)

        return self.parsed[label]

    def parse_axis_string(self, axis_string):
        """Parse a string of form axis, sense, axis, sense...

        Args:
            axis_string (str): the axis string from the user input

        Raises:
            Exception: axis string is incorrect

        Returns:
            axes (list): a list containing the axis names
            senses (list): a list containing the axis senses
        """

        ax_str = [sub.strip() for sub in axis_string.split(',')]
        if len(ax_str) % 2 != 0:
            raise Exception("Axis string is incorrect: %axis_string")

        axes = []
        senses = []
        for i in range(0, len(ax_str), 2):
            axes.append(ax_str[i])
            sense = ax_str[i+1].lower()
            senses.append(sense)

        return axes, senses

    def make_goniometer_axes(self, goniometer_axes, kappa_info, chi_info):
        """Create the goniometer axes from the user input. The list of gonio axes
        goes in order from top to bottom, meaning that the first "depends on"
        the second and so forth. We assume a two theta axis.
        The items we have to fill in are:
        1. type -> rotation
        2. depends_on -> next in list
        3. equipment -> goniometer
        4. vector -> almost always 1 0 0 (rotation about principal axis)
        5. offset -> always [0 0 0] but needed for loop integrity

        Note that our questions assume looking from above whereas imgCIF is
        looking from below, so the sense of rotation is reversed.

        Args:
            goniometer_axes (tuple): a tuple of lists consisting of the axis names
                and the senses of rotation
            kappa_info (str): the parsed user input string for the kappa axis
            chi_info (str): the parsed user input string for the chi axis

        Returns:
            dict: a dictionary containing the information about the goniometer axes
        """

        axes, senses = goniometer_axes
        axis_type = ["rotation" for _ in axes]
        equip = ["goniometer" for _ in axes]

        if kappa_info != '':
            kappa_info = re.split(r',| ', kappa_info)
            kappa_info = [info for info in kappa_info if info != '']
        else:
            kappa_info = ['']

        if chi_info != '':
            chi_info = re.split(r',| ', chi_info)
            chi_info = [info for info in chi_info if info != '']
        else:
            chi_info = ['']

        # Construct axis dependency chain
        depends_on = []
        depends_on += axes[1:]
        depends_on.append('.')

        # Remember the principal axis direction
        principal = senses[-1]

        # Create direction vectors
        vector = []
        offset = []
        for (axis, sense) in zip(axes, senses):
            rotfac = 1 if sense == principal else -1
            if axis.lower() == kappa_info[0].lower():
                kappa_vec = self._make_kappa_vector(kappa_info)
                kappa_vec[0] *= rotfac
                vector.append(kappa_vec)
            elif axis.lower() == chi_info[0].lower():
                vector.append(self._make_chi_vector(goniometer_axes, chi_info))
            else:
                vector.append([i * rotfac for i in [1, 0, 0]])
            # TODO offset is always 0?
            offset.append([0, 0, 0])

        axes_dict = {
            'axes' : goniometer_axes[0],
            'axis_type' : axis_type,
            'equip' : equip,
            'depends_on' : depends_on,
            'vector' : vector,
            'offset' : offset,
        }
        return axes_dict

    def make_detector_axes(self, det_trans_axes, det_rot_axes, principal_sense,
                           principal_angle, image_orientation, array_info,
                           scan_settings_info):
        """Add information concerning the detector axes. We define our own axis names,
        with the detector distance being inserted when the data file is read. We
        choose det_x to be in the horizontal direction, and det_y to be vertical.
        We need to add:
        1. type -> translation
        2. depends_on -> x,y depend on translation
        3. equipment -> detector
        4. vector -> worked out from user-provided info
        (5. offset -> beam centre, not added here)

        Args:
            principal_sense (str): the sense of the principal axis (a or c)
            principal_angle (int): the orientation of the principal axis in
                degree
            image_orientation (str): the image orientation string, e.g. 'top left',...
            two_theta_sense (str): the sense of the two theta axis (e.g. clockwise)
            array_info (dict): information about the array
            scan_setting_info (dict): information about the scan settings

        Returns:
            dict: a dictionary containing the information about the detector axes
        """

        axis_id = ['dety', 'detx']
        axis_type = ['translation', 'translation']
        equip = ['detector', 'detector']

        # Work out det_x and det_y
        beam_x, beam_y = self._calculate_beam_centre(
            array_info['array_dimension'], array_info['pixel_size'])

        x_d, y_d, x_c, y_c = self._determine_detx_dety(
            principal_angle, principal_sense, image_orientation, beam_x, beam_y)
        vector = [y_d, x_d]
        offset = [[0, 0, 0], [x_c, y_c, 0]]

        # translational axes
        axis_id += det_trans_axes
        axis_type += ['translation' for _ in det_trans_axes]
        equip += ['detector' for _ in det_trans_axes]
        # TODO also for multiple axes correct?
        # Detector translation always opposite to beam direction
        vector += [[0, 0, -1] for _ in det_trans_axes]

        # first_scan = sorted(scan_settings_info.keys())[0]
        # first_scan_info = scan_settings_info[first_scan][0]
        # z_offsets = [first_scan_info.get(axis) for axis in det_trans_axes]

        # for z in z_offsets:
            #TODO this sets unknown offsets to zero...
            # z = z if z is not None else 0
        # offset is zero and non zero in scans
        offset.append([0, 0, 0])

        # rotational axes
        rot_axes, rot_senses = det_rot_axes
        axis_id += rot_axes
        axis_type += ['rotation' for _ in rot_axes]
        equip += ['detector' for _ in rot_axes]
        for idx, axis in enumerate(rot_axes):
            rotsense = 1 if rot_senses[idx] == principal_sense else -1
            vector.append([rotsense, 0, 0])
            offset.append([0, 0, 0])

        axis_id += ['gravity', 'source']
        axis_type += ['.', '.']
        equip += ['gravity', 'source']
        gravity = self._determine_gravity(principal_angle, principal_sense)
        vector += [gravity, [0, 0, 1]]
        offset += [[0, 0, 0], [0, 0, 0]]

        # the above ordering must reflect the stacking!
        depends_on = axis_id[1:-(len(rot_axes)+1)] + ['.' for _ in range(len(rot_axes)+2)]

        axes_dict = {
            'axes' : axis_id,
            'axis_type' : axis_type,
            'equip' : equip,
            'depends_on' : depends_on,
            'vector' : vector,
            'offset' : offset,
        }
        return axes_dict

    def _validated_user_input(self, label):
        """Request an user input and validate the input according to an apppropriate
        regular expression.

        Args:
            label (str): the label that identifies the request
        """

        user_input = input(' >> ')
        if self.validation_regex.get(label) is not None:
            pattern = re.compile(
                self.validation_regex[label])
            parsed_input = pattern.match(user_input)
            if parsed_input:
                parsed_input = parsed_input.group(0)
        else:
            parsed_input = user_input

        # required parameter, but either regex failed or no input was made if no regex
        # is defined
        if self.input_options[label].get('required') and parsed_input in [None, '']:
            print(' ==> Could not interpret your input correctly! This input is required, \
please try again.')
            parsed_input = None
        # not required with defined regex, but no user input
        elif not self.input_options[label].get('required') and user_input == '':
            parsed_input = ''
        # not required with defined regex, but user input
        elif not self.input_options[label].get('required') and parsed_input is None:
            print(' ==> Could not interpret your input correctly! Please try again.')

        if parsed_input is not None:
            print(f" ==> Your input was: {parsed_input}")

        return parsed_input

    def _make_kappa_vector(self, kappa_info):
        """Costruct the kappa vector out of the parsed information on kappa.

        Args:
            kappa_info (list): a list with name and rotation angle

        Returns:
            list: the components of the kappa vector
        """

        if len(kappa_info) == 2:
            kappa_info.append("0")

        kapang = float(kappa_info[1])
        kappoise = float(kappa_info[2])

        # Now calculate direction of axis in X-Z plane assuming
        # rotation of kappa is same as principal axis. There is no
        # Y component as home position is always under beam path.
        up_comp = np.cos(kapang)
        across_comp = np.sin(kapang)
        if kappoise == 0:
            # is under incident beam collimator in X-Z plane
            z_comp = -1 * across_comp
        elif kappoise == 180:
            z_comp = across_comp

        return [up_comp, 0.0, z_comp]

    def _make_chi_vector(self, goniometer_axes, chi_info):
        """Construct the chi vector out of the parsed information on chi.

        Args:
            goniometer_axes (tuple): a tuple of lists consisting of the axis names
                and the senses of rotation
            chi_info (list): a list with name and rotation angle

        Returns:
            list: the components of the chi vector
        """

        axes, senses = goniometer_axes
        axname = chi_info[0].lower()
        rot = np.radians(-1 * float(chi_info[1]))

        # Now turn this into an axis direction
        # At the provided rotation, the chi axis is parallel to z. It is rotated
        # by -chi_rot about omega to bring it to the start position. The sense
        # of omega rotation is always about 1 0 0 by definition
        axes_lowered = [axis.lower() for axis in axes]
        ax_index = axes_lowered.index(axname)
        chi_sense = senses[ax_index]

        chi_beam_dir = np.array([0, 0, 1]) if chi_sense == "a" \
            else np.array([0, 0, -1])
        chi_rot = np.array([
            [1.0, 0.0, 0.0],
            [0.0, np.cos(rot), -np.sin(rot)],
            [0.0, np.sin(rot), np.cos(rot)]
        ])

        return list(np.dot(chi_rot, chi_beam_dir))

    def _determine_gravity(self, principal_angle, principal_sense):
        """Determine the gravity vector.

        Args:
            principal_angle (str): the angle of the principal axis in degree
            principal_sense (str): the sense of rotation of the principal axis

        Returns:
            list: the gavity vector
        """

        angle = int(principal_angle) if principal_sense == "a" \
            else int(principal_angle) + 180

        if angle >= 360:
            angle = angle - 360

        if angle == 0:
            gravity = [0, 1, 0]  # spindle at 3 o'clock, rotating anticlockwise
        elif angle == 90:
            gravity = [1, 0, 0]
        elif angle == 180:
            gravity = [0, -1, 0]
        else:
            gravity = [-1, 0, 0]

        return gravity

    def _determine_detx_dety(self, principal_angle, principal_sense, corner,
                             beam_x, beam_y):
        """Determine direction of detx (horizontal) and dety (vertical) in
        imgCIF coordinates.

        Args:
            principal_angle (str): the principal angle
            principal_sense (str): the principal sense of the goniometer axes
            corner (str): the orientation of the first pixel (e.g. 'top right')
            beam_x (str): the beam center in x direction in mm
            beam_y (str): the beam center in y direction in mm

        Returns:
            x_direction (list): the vector for the detector x direction
            y_direction (list): the vector for the detector y direction
            x_centre (float): the beamcentre in x direction
            y_centre (float): the beamcentre in y direction

        """

        # Start with basic value and then flip as necessary
        x_direction = [-1, 0, 0] # spindle rotates anticlockwise at 0, top_left origin
        y_direction = [0, 1, 0]
        x_centre = beam_x
        y_centre = -1 * beam_y

        if corner == "top right":
            x_direction = [i * -1 for i in x_direction]
            x_centre = -1 * beam_x

        elif corner == "bottom right":
            x_direction = [i * -1 for i in x_direction]
            y_direction = [i * -1 for i in y_direction]
            x_centre *= -1
            y_centre *= -1

        elif corner == "bottom left":
            y_direction = [i * -1 for i in y_direction]
            y_centre *= -1

        # The direction of the principal axis flips by 180 if the sense changes
        angle = int(principal_angle) if principal_sense == "a" \
            else int(principal_angle) + 180

        if angle >= 360:
            angle = angle - 360

        if angle == 90:
            temp = x_direction
            temp_centre = x_centre
            x_direction = y_direction
            x_centre = y_centre
            y_direction = [i * -1 for i in temp]
            y_centre = temp_centre
        elif angle == 180:
            x_direction = [i * -1 for i in x_direction]
            y_direction = [i * -1 for i in y_direction]
            x_centre *= -1
            y_centre *= -1
        elif angle == 270:
            temp = x_direction
            temp_centre = x_centre
            x_direction = [i * -1 for i in y_direction]
            x_centre = -1 * y_centre
            y_direction = temp
            y_centre = temp_centre

        return x_direction, y_direction, x_centre, y_centre

    def _create_options_regex(self, label, case_insensitive=True):
        """Create a regular expression that matches only the options for the given
        label.

        Args:
            label (str): the label that identifies the request
            case_insensitive (bool, optional): Whether the regex should be case
                insensitive. Defaults to True.

        Returns:
            regexp: regular expression formed by the options for the input label
        """
        options = self.input_options[label].get('options')
        if options is not None:
            options_regex = r'|'.join(options)
            if self.input_options[label].get('abbreviate'):
                first_letters = [option[0] for option in options]
                letters_regex = r'|'.join(first_letters)
                options_regex += r'|' + letters_regex
            options_regex = r'(' + options_regex + r')\Z'

            if case_insensitive:
                options_regex = r'(?i)' + options_regex
        else:
            options_regex = None

        return options_regex

    def _calculate_beam_centre(self, array_dimension, pixel_size):
        """The default beam centre is at the centre of the detector. We must
        indicate this position in mm with the correct signs.

        Args:
            array_dimension (tuple): a tuple with the x and y dimension of the pixels
            pixel_size (tuple): a tuple with the pixel sizes in x an y direction

        Returns:
            tuple: the x and y beam centre in mm
        """

        dim_x, dim_y = array_dimension
        pix_x, pix_y = pixel_size

        return float(pix_x) * float(dim_x)/2, float(pix_y) * float(dim_y)/2


import re
from pyspark import SparkConf, SparkContext

def normalizeWords(text):
    return re.compile(r'\W+', re.UNICODE).split(text.lower())

conf = SparkConf().setMaster("local").setAppName("WordCount")
sc = SparkContext(conf = conf)

input = sc.textFile("file:///sparkcourse/book.txt")
words = input.flatMap(normalizeWords)

# Note: Count by value creates a python object instead of a RDD hence .collect() not required to fetch the data
wordCounts = words.countByValue()

for word, count in wordCounts.items():
    cleanWord = word.encode('ascii', 'ignore')
    if (cleanWord):
        print(cleanWord.decode() + " " + str(count))


# M0_C9 - Sudoku Validator
import sys
import os
from typing import List

def validate(grid: List[List[int]]) -> bool:
    """Validates a given 2D list representing a completed Sudoku puzzle"""
    # Write your code here
    pass

##########################################
### DO NOT MODIFY CODE BELOW THIS LINE ###
##########################################
def load_puzzle(filename: str) -> List[List[int]]:
    """Reads a file containing a Sudoku puzzle into a 2D list"""
    invalid_msg = 'error: invalid Sudoku puzzle supplied'

    grid = []
    try:
        with open(filename) as fp:
            for line in fp:
                row = [int(num) for num in line.split()]
                if len(row) != 9:
                    sys.exit(invalid_msg)
                grid.append(row)
    except IOError as e:
        sys.exit(e)

    if len(grid) != 9:
        sys.exit(invalid_msg)

    return grid

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print('Usage: python3 sudoku_validator.py path/to/testfile.txt')
        sys.exit()

    grid = load_puzzle(sys.argv[1])
    print(validate(grid))


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the countingSort function below.
def countingSort(arr):
    m=max(arr)
    res=[0]*(m+1)
    for i in range(len(arr)):
        res[arr[i]]+=1
    ans=[]
    for i in range(len(res)):
        if res[i]>0:
            temp=[i]*res[i]
            ans.extend(temp)
    return ans

if __name__ == '__main__':

    n = int(input())

    arr = list(map(int, input().rstrip().split()))

    result = countingSort(arr)

    print(' '.join(map(str, result)))


import importlib.util
import shutil
from pathlib import Path
from typing import List

import pandas as pd
import plotly.express as px

from bot_game import Bot

EXAMPLES_FOLDER = Path("examples")
DOWNLOAD_FOLDER = Path("downloads")
DOWNLOAD_FOLDER.mkdir(exist_ok=True)

def save_code_to_file(code: str, filename: str):
    fpath = DOWNLOAD_FOLDER / f"{filename}.py"
    with open(fpath, "w") as fh:
        fh.write(code)

    return fpath

def save_file(filename: str, filebytes: bytes):
    fpath = DOWNLOAD_FOLDER / filename
    with open(fpath, "wb") as fh:
        fh.write(filebytes)

    return fpath

def import_file(fpath: Path):
    spec = importlib.util.spec_from_file_location(fpath.parts[-1], str(fpath))
    m = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(m)
    return m

def validate_file(fpath: Path):
    m = import_file(fpath)
    assert hasattr(m, "strategy"), "The file does not have a function called `strategy`"
    assert callable(
        m.strategy
    ), "The variable `strategy` is not callable! Is it a function?"

def build_all_bots() -> List[Bot]:
    bots = []
    for fp in DOWNLOAD_FOLDER.glob("*.py"):
        bot = Bot(name=fp.stem)
        m = import_file(fp)
        bot.strategy_func = m.strategy
        bots.append(bot)

    return bots

def add_example_bots():
    for fp in EXAMPLES_FOLDER.glob("*.py"):
        shutil.copy(fp, DOWNLOAD_FOLDER / fp.parts[-1])

def plot_grand_prix_results(winnings, x_col="Bot", y_col="Races Won"):
    podium_df = (
        pd.Series(winnings, name=y_col)
        .sort_values(ascending=False)
        .rename_axis(x_col)
        .reset_index()
    )

    fig = px.bar(podium_df, x=x_col, y=y_col, color=y_col)
    return fig

def create_animation(df):
    fig = px.scatter(
        df.assign(
            size=10,
        ),
        x="position",
        y="name",
        animation_frame="round",
        animation_group="name",
        size="size",
        color="name",
        hover_data=["direction", "last_action", "action_order"],
        hover_name="name",
        range_x=[0, 10],
    )
    return fig

def delete_all_bots():
    for fp in DOWNLOAD_FOLDER.glob("*.py"):
        fp.unlink()


#
# @lc app=leetcode id=682 lang=python3
#
# [682] Baseball Game
#

# @lc code=start
class Solution:
    def calPoints(self, ops: List[str]) -> int:
        res = []
        for i in ops:
            if i == '+':
                res.append(res[-1] + res[-2])
            elif i == 'D':
                res.append(res[-1]*2)
            elif i == 'C':
                res.pop()
            else:
                res.append(int(i))

        return sum(res)
# @lc code=end


from eth.exceptions import (
    ReservedBytesInCode,
)
from eth.vm.forks.berlin.computation import (
    BerlinComputation,
)

from ..london.constants import (
    EIP3541_RESERVED_STARTING_BYTE,
)
from .opcodes import (
    LONDON_OPCODES,
)

class LondonComputation(BerlinComputation):
    """
    A class for all execution *message* computations in the ``London`` fork.
    Inherits from :class:`~eth.vm.forks.berlin.BerlinComputation`
    """

    opcodes = LONDON_OPCODES

    @classmethod
    def validate_contract_code(cls, contract_code: bytes) -> None:
        super().validate_contract_code(contract_code)

        if contract_code[:1] == EIP3541_RESERVED_STARTING_BYTE:
            raise ReservedBytesInCode(
                "Contract code begins with EIP3541 reserved byte '0xEF'."
            )


from read_the_maxfilename_for_sort import max_number
import requests

i = 1
temp_number = max_number()

def download(url):
    global i
    global temp_number
    print('Processing {0} url:{1}'.format(i,url))
    img = open('{}.jpg'.format(temp_number),'wb')
    respone = requests.get(url, stream=True).content
    img.write(respone)
    i += 1
    temp_number += 1
    img.close()


import os
import numpy as np
import matplotlib
matplotlib.use('agg')
import xrt.runner as xrtrun
import xrt.plotter as xrtplot
import xrt.backends.raycing as raycing

from SKIF_NSTU_SCW import SKIFNSTU
from utilits.xrt_tools import crystal_focus

resol='mat'
E0 = 30000
subdir=rf"C:\Users\synchrotron\PycharmProjects\SKIF\SKIF_NSTU_SCW\results\{resol}\{E0}\R-R"

def define_plots(bl):
    plots = []
    scan_name = 'change-screen-%s'  % (bl.bentLaueCylinder02.Rx)
    if not os.path.exists(os.path.join(subdir, scan_name)):
        os.mkdir(os.path.join(subdir, scan_name))

    plots.append(xrtplot.XYCPlot(beam='screen03beamLocal01', title='Sample-XZ',
                                 xaxis=xrtplot.XYCAxis(label='x', unit='mm', data=raycing.get_x),
                                 yaxis=xrtplot.XYCAxis(label='z', unit='mm', data=raycing.get_z),
                                 aspect='auto', saveName='Sample-XZ.png'
                                  ))
    for plot in plots:
        plot.saveName = os.path.join(subdir, scan_name,
                                     plot.title + '-%sm' % bl.bentLaueCylinder02.Rx + '.png'
                                     )
        plot.persistentName = plot.saveName.replace('.png', f'.{resol}')
    return plots

def define_plots_diver(bl):
    plots = []
    scan_name = 'diver-screen-'
    if not os.path.exists(os.path.join(subdir, scan_name)):
        os.mkdir(os.path.join(subdir, scan_name))
    plots.append(xrtplot.XYCPlot(beam='screen02beamLocal01', title=f'{scan_name}',
                                 xaxis=xrtplot.XYCAxis(label='x', unit='mm', data=raycing.get_x),
                                 yaxis=xrtplot.XYCAxis(label=r'$x^{\prime}$', unit='', data=raycing.get_xprime),
                                 aspect='auto', saveName=f'{scan_name}_Sample-XX.png'
                                 ))
    for plot in plots:
        plot.saveName = os.path.join(subdir,scan_name,
                                     plot.title + '-%sm' % bl.bentLaueCylinder01.Rx + '.png'
                                     )
        plot.persistentName = plot.saveName.replace('.png', f'.pickle')
    return plots

def change_screen(plts, bl):
    scan_name = 'change-screen-%s' % (bl.bentLaueCylinder02.Rx)
    d0=bl.screen03.center[1]
    for dist in np.linspace(-500., 500., 50):

        bl.screen03.center[1]=d0+dist
        for plot in plts:
            plot.xaxis.limits=None
            plot.yaxis.limits = None
            plot.caxis.limits = None
            plot.saveName = os.path.join(subdir, scan_name,
                                     plot.title + '_%s' % bl.screen03.center[1] + '.png'
                                     )
            plot.persistentName = plot.saveName.replace('png', f'{resol}')
        yield

def main():
    beamLine = SKIFNSTU()
    diver=False

    dist0=beamLine.bentLaueCylinder02 .center[1]
    beamLine.align_energy(E0, 1000)
    beamLine.alignE = E0

    # for R in np.linspace(-2000., -500., 5):
    #     beamLine.bentLaueCylinder01.Rx = R
    #     beamLine.bentLaueCylinder02.Rx = R
    #     beamLine.bentLaueCylinder01.Ry = R/1.e6
    #     beamLine.bentLaueCylinder02.Ry = R/1.e6
    #     plots = define_plots(beamLine)
    #     scan = change_screen
    #     if (diver==False):
    #         beamLine.screen03.center[1] = dist0+crystal_focus(subdir +
    #                                                 '\diver-screen-\diver-screen-' + '-%sm' % beamLine.bentLaueCylinder01.Rx + '.pickle')
    #     if diver:
    #         scan = None
    #         plots = define_plots_diver(beamLine)
    #
    #
    #     xrtrun.run_ray_tracing(
    #         plots=plots,
    #         backend=r"raycing",
    #         repeats=5,
    #         beamLine=beamLine,
    #         generator=scan,
    #         generatorArgs=[plots, beamLine]
    #         )
    #     beamLine.screen03.center[1]=dist0+10000
    beamLine.glow()

if __name__ == '__main__':
    main()


# First we'll import the os module
# This will allow us to create file paths across operating systems
import os

# Module for reading CSV files
import csv

# Specify the path where the file is residing
csvpath = os.path.join('Resources', 'election_data.csv')

# Declare variables and intialize
total_votes = 0
charles_votes = 0
diana_votes = 0
raymon_votes = 0

# Method 2: Improved Reading using CSV module

with open(csvpath) as csvfile:

    # CSV reader specifies delimiter and variable that holds contents
    csvreader = csv.reader(csvfile, delimiter=',')

    print(csvreader)

    # Read the header row first (skip this step if there is now header)
    csv_header = next(csvreader)
    print(f"CSV Header: {csv_header}")

    # Read each row of data after the header
    for row in csvreader:
        print(row)

        # Count the total votes in the dataset
        total_votes = total_votes + 1

        # candidates name is listed in row 2 of the dataset
        candidate_name = row[2]

        # count votes for each candidate

        if "Charles Casper Stockham" == candidate_name:
            charles_votes = charles_votes + 1

        if "Diana DeGette" == candidate_name:
                diana_votes = diana_votes + 1

        if "Raymon Anthony Doane" == candidate_name:
                    raymon_votes = raymon_votes + 1

        # Find percentage votes for each candidate
        charles_percent = (charles_votes / total_votes) * 100

        diana_percent = (diana_votes / total_votes) * 100

        raymon_percent = (raymon_votes / total_votes) * 100

        # To find the winner of the election, zip list together to form dictionary
    if charles_votes > diana_votes and charles_votes > raymon_votes:
        winner = "Charles Casper Stockham"
    elif diana_votes > charles_votes and diana_votes > raymon_votes:
        winner = "Diana DeGette"
    else:
        winner ="Raymon Anthony Doane"

# print to terminal
print("Election Results")
print("--------------------------------------")
print(f"Total Votes: {str(total_votes)}")
print("--------------------------------------")
print(f"Charles Casper Stockham: {charles_percent:.3f}% ({charles_votes})")
print(f"Diana DeGette: {diana_percent:.3f}% ({diana_votes})")
print(f"Raymon Anthony Doane: {raymon_percent:.3f}% ({raymon_votes})")
print("--------------------------------------")
print(f"Winner: {winner}")
print("--------------------------------------")

# write to file
# Specify the file to write to
output_path = os.path.join("Analysis", "election_result.txt")

# Open the file using "write" mode. Specify the variable to hold the contents
with open(output_path, 'w+') as file:

    # Initialize writer
    file.write(f"Election Results\n")
    file.write("\n")
    file.write(f"-----------------------------------\n")
    file.write("\n")
    file.write(f"Total Votes: {total_votes}\n")
    file.write("\n")
    file.write(f"-------------------------------------\n")
    file.write("\n")
    file.write(f"Charles Casper Stockham: {charles_percent:.3f}% ({charles_votes})\n")
    file.write(f"Diana DeGette: {diana_percent:.3f}% ({diana_votes})\n")
    file.write(f"Raymon Antony Doane: {raymon_percent:.3f}% ({raymon_votes})\n")
    file.write(f"-------------------------------------\n")
    file.write(f"Winner: {winner}\n")
    file.write(f"-------------------------------------\n")


import random

from discord.ext import commands

class Hive(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

    @commands.command(name='roll_dice',
                      help='<min> <max>')
    async def roll_dice(self, ctx, min: int, max: int):
        await ctx.send(random.randint(min, max))

def setup(bot):
    bot.add_cog(Hive(bot))


"""
All together

Demonstrate how you can build a quick and dirty framework with a bottle like
API.

Chick is the main application frame.
CapitalizeResponse is a middleware which you can use to wrap your application.
It stores session information, and it capitalizes all responses.
"""

def request_factory(env):
    """
    Dynamically create a Request class with slots and read
    only attributes

    """
    class Request:

        __slots__ = [k.replace(".", "_").lower() for k in env.keys()]

        def __setattr__(self, name, value):
            try:
                getattr(self, name)
                raise ValueError("Can't modify {}".format(name))
            except AttributeError:
                super().__setattr__(name, value)

    request = Request()

    for k, v in env.items():
        setattr(request, k.replace(".", "_").lower(), v)

    return request

class Chick:

    """
    A WSGI Application framework with API inspired by Bottle and Flask.

    There is No HTTPRequest Object and No HTTPResponse object.

    Just barebone routing ...
    """

    routes = {}

    def __call__(self, environ, start_response):
        try:
            callback, method = self.routes.get(environ.get('PATH_INFO'))
        except TypeError:
            start_response('404 Not Found', [('Content-Type', 'text/plain')])
            return [b'404 Not Found']

        if method != environ.get('REQUEST_METHOD'):
            start_response('405 Method Not Allowed',
                           [('Content-Type', 'text/plain')])
            return [b'404 Method Not Allowed']

        request = request_factory(environ)
        response = callback(request)

        start_response(response.status, response.content_type)
        return (response.body.encode(),)

    def add_route(self, path, wrapped, method):
        self.routes[path] = (wrapped, method)

    def get(self, path):
        def decorator(wrapped):
            self.add_route(path, wrapped, 'GET')
            return wrapped

        return decorator

    def post(self, path):
        def decorator(wrapped):
            self.add_route(path, wrapped, 'POST')
            return wrapped

        return decorator

class Response:

    __slots__ = ('body', 'status', 'content_type')

    def __init__(self, body, status='200 OK',
                 content_type="text/plain"):
        self.body = body
        self.status = status
        self.content_type = [('Content-Type', content_type)]

    def __iter__(self):
        return [self.body]

class CapitalizeResponseMiddleware:

    """
    A middlerware that manipulates the response
    """
    def __init__(self, app):
        self.app = app
        self.visits = 0  # state keeping made easier

    def __call__(self, environ, start_response, *args, **kw):
        self.visits += 1

        response = self.app(environ, start_response)
        response = [line.upper() for line in response]
        response.append("\nYou visited {} times".format(self.visits).encode())

        return response

chick = Chick()

@chick.get("/")
def index(request):
    return Response("hello world!")

@chick.post("/input/")
def test_post(request):

    return Response("")

@chick.get("/response/")
def response(request):

    res = "".join("{}: {}\n".format(s, getattr(request, s))
                  for s in request.__slots__)

    return Response("hello world!\n" + res)

capital_chick = CapitalizeResponseMiddleware(chick)

if __name__ == "__main__":
    from wsgiref.simple_server import make_server
    httpd = make_server('', 8000, capital_chick)
    print("Serving on port 8000...")

    # Serve until process is killed
    httpd.serve_forever()


import argparse
import sys
from pathlib import Path
from typing import List

import numpy as np
import torch

from thre3d_atom.modules.volumetric_model.volumetric_model import (
    VolumetricModel,
    VolumetricModelRenderingParameters,
)
from thre3d_atom.rendering.volumetric.voxels import (
    GridLocation,
    FeatureGrid,
    VoxelSize,
)
from thre3d_atom.utils.constants import (
    NUM_RGBA_CHANNELS,
)
from thre3d_atom.utils.imaging_utils import SceneBounds, CameraIntrinsics

def parse_arguments(args: List[str]) -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        "Converts Feature-Grid (+ mlp model) into an RGBA grid",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    # fmt: off
    # Required arguments
    parser.add_argument("-i", "-m", "--model_path",
                        action="store", type=Path, required=True, help="path to the trained 3dSGDS model")
    parser.add_argument("-o", "--output_dir",
                        action="store", type=Path, required=True, help="path to the output directory")
    # fmt: on

    parsed_args = parser.parse_args(args)
    return parsed_args

## noinspection PyUnresolvedReferences
def main() -> None:
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    args = parse_arguments(sys.argv[1:])

    # load the numpy model:
    np_model = np.load(args.model_path, allow_pickle=True)
    features = torch.from_numpy(np_model["grid"]).to(device=device)
    grid_size = np_model["grid_size"]
    grid_location = GridLocation(*np_model["grid_center"])

    grid_dim = features.shape[:-1]
    x_voxel_size = grid_size[0] / (grid_dim[0] - 1)
    y_voxel_size = grid_size[1] / (grid_dim[1] - 1)
    z_voxel_size = grid_size[2] / (grid_dim[2] - 1)

    feature_grid = FeatureGrid(
        features=features.permute(3, 0, 1, 2),
        voxel_size=VoxelSize(x_voxel_size, y_voxel_size, z_voxel_size),
        grid_location=grid_location,
        tunable=True,
    )

    render_params = VolumetricModelRenderingParameters(
        num_rays_chunk=1024,
        num_points_chunk=65536,
        num_samples_per_ray=256,
        num_fine_samples_per_ray=0,
        perturb_sampled_points=True,
        density_noise_std=0.0,
    )
    vol_mod = VolumetricModel(
        render_params=render_params,
        grid_dims=grid_dim,
        feature_dims=NUM_RGBA_CHANNELS,
        grid_size=grid_size,
        grid_center=grid_location,
        device=device,
    )
    vol_mod.feature_grid = feature_grid
    torch.save(
        vol_mod.get_save_info(
            extra_info={
                "scene_bounds": SceneBounds(0.1, 2.5),
                "camera_intrinsics": CameraIntrinsics(256, 256, 256),
                "hemispherical_radius": 1.0,
            }
        ),
        f"{args.output_dir}/model_rgba.pth",
    )

if __name__ == "__main__":
    main()


from rb_api.dto.two_mode_graph.article_keyword_dto import ArticleKeywordDTO
from rb_api.json_serialize import JsonSerialize

import json

class TopicEvolutionDTO(JsonSerialize):

    def __init__(self):
        self.wordList = []
        self.yearList = []

    def add_year(self, year: int) -> None:
        self.yearList.append(year)

    def add_keyword(self, value: str, score: float) -> None:
        word_values = [word for word in self.wordList if word.value == value]
        if word_values:
            word_values[0].score_list.append(score) # there is only 1 word for value
            return

        keyword = ArticleKeywordDTO(value, "Keyword")
        keyword.scoreList.append(score)
        self.wordList.append(keyword)

    def normalize(self):
        for year_index, _ in enumerate(self.yearList):
            maxim = max([word.score_list[year_index] for word in self.wordList])

            if maxim > 0:
                for word in self.wordList:
                    word.score_list[year_index] = word.score_list[year_index] / maxim

    def serialize(self):
        return json.dumps(self.__dict__)


from fastapi import FastAPI, Depends
from sqlalchemy import create_engine
from sqlalchemy.dialects.sqlite import *
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from typing import List
from pydantic import BaseModel, constr

app = FastAPI()

SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args = {"check_same_thread": False})
session = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

def get_db():
   db = session()
   try:
      yield db
   finally:
      db.close()

class Books(Base):
   __tablename__ = 'book'
   id = Column(Integer, primary_key=True, nullable=False)
   title = Column(String(50))
   author = Column(String(50))
   publisher = Column(String(50))
   Base.metadata.create_all(bind=engine)

class Book(BaseModel):
   id: int
   title: str
   author:str
   publisher: str
   class Config:
      orm_mode = True

@app.post('/add_new', response_model=Book)
def add_book(b1: Book, db: Session = Depends(get_db)):

   bk=Books(id=b1.id, title=b1.title, author=b1.author,
            publisher=b1.publisher)
   db.add(bk)
   db.commit()
   db.refresh(bk)
   return Books(**b1.model_dump())

@app.get('/list', response_model=List[Book])
def get_books(db: Session = Depends(get_db)):
   recs = db.query(Books).all()
   return recs

@app.get("/book/{id}")
async def get_book(id: int, db: Session = Depends(get_db)):
   return db.query(Books).filter(Books.id == id).first()

@app.put('/update/{id}', response_model=Book)
def update_book(id:int, book:Book, db: Session = Depends(get_db)):
   b1 = db.query(Books).filter(Books.id == id).first()
   b1.id=book.id
   b1.title=book.title
   b1.author=book.author
   b1.publisher=book.publisher
   db.commit()
   return db.query(Books).filter(Books.id == id).first()

@app.delete("/delete{id}")
async def delete_book(id: int, db: Session = Depends(get_db)):
   try:
      db.query(Books).filter(Books.id == id).delete()
      db.commit()
   except Exception as e:
      raise Exception(e)
   return {"delete status": "success"}


import numpy as np
import pandas as pd
from scipy.io import loadmat

def glf(
    mz: np.ndarray,
    intens: np.ndarray,
    delta_cts: float = 0.1,
    delta_mz: float = 2000.0,
    k: float = 7.0
) -> np.ndarray:
    y1 = np.max(intens) * 0.02
    y2 = (np.max(intens) - y1) * delta_cts
    res = y1 + y2 / (1 + np.e ** (y2 * k / (mz - delta_mz)))
    return res

def parse_database(database: np.ndarray, strain_precision = "full") -> pd.DataFrame:

    prec = {"genus": 1, "species": 2, "full": 3}

    num_entities = len(database)
    mz, peaks, strain = [], [], []
    for i in range(num_entities):
        curr_entity = database[i][0]
        for obs_id in range(len(curr_entity["tax"])):
            observation = curr_entity[obs_id]
            mz.append(observation["pik"][0])
            peaks.append(observation["pik"][1])
            st = observation["tax"][0]
            st = st.split(" ")
            st = " ".join(st[:prec[strain_precision]])
            strain.append(st)

    df = pd.DataFrame(columns=["Intens.", "m/z", "strain"], dtype="object")
    df["Intens."] = peaks
    df["m/z"] = mz
    df["strain"] = strain
    return df

def read_pkf(pkf_path: str, strain_precision: str = "full"):
    data = loadmat(pkf_path)
    database = data["C"]["dbs"][0]
    df = parse_database(database, strain_precision)
    return df