import os
import json
import numpy as np
import pandas as pd
from operator import itemgetter
import random
import copy
import math
import configparser
import glob

def load_config(config_path):
    # Load the configuration file
    configfile_list = glob.glob(os.path.join(config_path, "*.ini"))
    if len(configfile_list) > 1:
        raise ValueError("More than one config file found: {}".format(configfile_list))

    with open(configfile_list[0]) as f:
        sample_config = f.read()
    config_file = configparser.RawConfigParser(allow_no_value=True)
    config_file.read_string(sample_config)

    return config_file

def get_files(path, ending):
    list_csv_files = []

    for file in os.listdir(path):
        if file.endswith(ending):
            list_csv_files.append(os.path.join(path, file))

    return list_csv_files

def get_list(dictionary):
    """
    From dictionary get keys as list

    :param dictionary: dict
    :return: list
    """

    key_list = []
    for key in dictionary.keys():
        key_list.append(key)

    return key_list

def get_indexes(dfobj, value):
    """
    Get index positions of value in dataframe i.e. dfObj.

    :param dfobj:
    :param value:
    :return:
    """

    listofpos = list()
    # Get bool dataframe with True at positions where the given value exists
    result = dfobj.isin([value])
    # Get list of columns that contains the value
    seriesobj = result.any()
    columnnames = list(seriesobj[seriesobj is True].index)
    # Iterate over list of columns and fetch the rows indexes where value exists
    for col in columnnames:
        rows = list(result[col][result[col] is True].index)
        for row in rows:
            listofpos.append((row, col))

    # Return a list of tuples indicating the positions of value in the dataframe
    return listofpos

def load_sample_config_file(filename, file_type):
    """
    read in configs like paths, files names

    :param filename:
    :param file_type:
    :return: read configs
    """

    if file_type is "csv":
        configs = pd.read_csv(filename, sep=";")

        # No need to save configs in different variables; it is just for visualization and easier to read out later
        file_path = configs['file_path'].values  # 0
        library_path = configs['output_type_spaceranger'].values  # 1
        sample_strings = configs['sample_strings'].values  # 2
        sample_id_strings = configs['sample_id_strings'].astype(str).values  # 3

        # output matrix
        output_type_matrix = configs['output_type_matrix'].values  # 4
        raw_feature_bc_matrix_folder = configs['raw_feature_bc_matrix_folder'].values  # 5
        filtered_feature_bc_matrix_folder = configs['filtered_feature_bc_matrix_folder'].values  # 6

        barcode_file_end = configs['barcode_file_end'].values  # 7
        features_file_end = configs['features_file_end'].values  # 8
        matrix_file_end = configs['matrix_file_end'].values  # 9
        raw_hdf5_file_end = configs['raw_hdf5_file_end'].values  # 10
        filtered_hdf5_file_end = configs['filtered_hdf5_file_end'].values  # 11

        # spatial information
        output_type_spatial = configs['output_type_spatial'].values  # 12

        tissue_pos_list_file_end = configs['tissue_pos_list_file_end'].values  # 13
        scale_factors_file_end = configs['scale_factors_file_end'].values  # 14
        aligned_fiducials_file_end = configs['aligned_fiducials_file_end'].values  # 15
        detected_tissue_file_end = configs['detected_tissue_file_end'].values  # 16
        tissue_hires_file_end = configs['tissue_hires_file_end'].values  # 17
        tissue_low_res_file_end = configs['tissue_low_res_file_end'].values  # 18

        # annotation files
        annotation_path = configs["annotation_path"].values  # 19
        excel_sheet = configs['excel_sheet'].values  # 20

        # lesional_folder = configs['lesional_folder'].values  # 21
        # non_lesional_folder = configs['non-lesional_folder'].values  # 22

        # velocyto (loom files)
        velocyto_path = configs['velocity_path'].values  # 23 -> 21
        loom_file = configs['loom_file_end'].values  # 24 -> 22

        # Capture area
        capture_area = configs['capture_area'].values  # 25 -> 23
        patient = configs['patient'].values  # 26 -> 24

    else:
        with open(filename) as json_file:
            configs = json.load(json_file)

            # No need to save configs in different variables; it is just for visualization and easier to read out later
            file_path = configs['file_path']  # 0
            library_path = configs['output_type_spaceranger']  # 1
            sample_strings = configs['sample_strings']  # 2
            sample_id_strings = configs['sample_id_strings']  # 3

            # output matrix
            output_type_matrix = configs['output_type_matrix']  # 4
            raw_feature_bc_matrix_folder = configs['raw_feature_bc_matrix_folder']  # 5
            filtered_feature_bc_matrix_folder = configs['filtered_feature_bc_matrix_folder']  # 6

            barcode_file_end = configs['barcode_file_end']  # 7
            features_file_end = configs['features_file_end']  # 8
            matrix_file_end = configs['matrix_file_end']  # 9
            raw_hdf5_file_end = configs['raw_hdf5_file_end']  # 10
            filtered_hdf5_file_end = configs['filtered_hdf5_file_end']  # 11

            # spatial information
            output_type_spatial = configs['output_type_spatial']  # 12

            tissue_pos_list_file_end = configs['tissue_pos_list_file_end']  # 13
            scale_factors_file_end = configs['scale_factors_file_end']  # 14
            aligned_fiducials_file_end = configs['aligned_fiducials_file_end']  # 15
            detected_tissue_file_end = configs['detected_tissue_file_end']  # 16
            tissue_hires_file_end = configs['tissue_hires_file_end']  # 17
            tissue_low_res_file_end = configs['tissue_low_res_file_end']  # 18

            # annotation files
            annotation_path = configs["annotation_path"]  # 19
            excel_sheet = configs['excel_sheet']  # 20

            # lesional_folder = configs['lesional_folder']  # 21
            # non_lesional_folder = configs['non-lesional_folder']  # 22

            # velocyto (loom files)
            velocyto_path = configs['velocity_path']  # 23
            loom_file = configs['loom_file_end']  # 24

            # Capture area
            capture_area = configs['capture_area'].values  # 25
            patient = configs['patient'].values  # 26

    return \
        file_path, library_path, sample_strings, sample_id_strings, output_type_matrix, \
        raw_feature_bc_matrix_folder, filtered_feature_bc_matrix_folder, barcode_file_end, features_file_end, \
        matrix_file_end, raw_hdf5_file_end, filtered_hdf5_file_end, output_type_spatial, tissue_pos_list_file_end, \
        scale_factors_file_end, aligned_fiducials_file_end, detected_tissue_file_end, tissue_hires_file_end, \
        tissue_low_res_file_end, annotation_path, excel_sheet, velocyto_path, loom_file, capture_area, patient

def save_obsm_with_library_id(adatas):
    # save .obsm (image coordiantes) as list containing [['X' x 'Y' x 'sample_id'], ...]
    keys_obsm = []
    if len(adatas) > 2:
        list_adata_obsm = adatas[0].obsm['spatial']
        for obj in adatas[1:]:
            unique_samples = np.unique(obj.obs['sample'])
            for sample_name in unique_samples:
                # key_list = obj.obsm_keys()[0]
                size_obj = obj.obsm['spatial'].shape[0]
                keys_obsm.append(sample_name)
                lib_id = np.array(size_obj * [sample_name])
                # convert coordinates to string and save coordinates with library_id
                str_coords = [[str(var[0]), str(var[1]), lib_id[ind]] for ind, var in enumerate(obj.obsm['spatial'])]
                list_adata_obsm.extend(str_coords)
    else:
        list_adata_obsm = []
        for obj in adatas:
            unique_sample = np.unique(obj.obs['sample'])[0]
            # key_list = obj.obsm_keys()[0]
            size_obj = obj.obsm['spatial'].shape[0]
            keys_obsm.append(unique_sample)
            lib_id = np.array(size_obj * [unique_sample])
            # convert coordinates to string and save coordinates with library_id
            str_coords = [[str(var[0]), str(var[1]), lib_id[ind]] for ind, var in enumerate(obj.obsm['spatial'])]
            list_adata_obsm.extend(str_coords)

def concatenate_adatas(adatas, batch_key='library_id'):
    """
    Concatenate multiple adatas by library_id
    CARE: adata.uns['spatial'][library_id] must be unique for each adata! otherwise same properties will be overwritten
    ==> save .uns and .obsm and before and then load it into concatenated annData object

    :param adatas: [list] of adata objects
    :param batch_key: observable name to add to distinguish between batches
    :return: return single adata object containing all information including images
    """
    adata_spatial = adatas[0].copy()

    # save .obsm (image coordiantes) as list containing [[X x Y], ...]
    # to concatenate loom files also save .layers
    list_adata_obsm = []
    for obj in adatas:
        list_adata_obsm.extend(obj.obsm['spatial'])

    # save .uns (images, image properties)
    list_adata_uns = [ann_data.uns['spatial'] for ann_data in adatas]
    adata_spatial = adata_spatial.concatenate(adatas[1:], batch_key=batch_key,
                                              batch_categories=[k + '_' + str(counter + 1)
                                                                for counter, d in enumerate(list_adata_uns)
                                                                for k, v in d.items()],
                                              uns_merge='unique')

    # obsm: now get coordinates by checking third entry of adata_spatial.obsm['spatial'] and then convert strings to int
    # adata_spatial.obsm['spatial'] = np.asarray(list_adata_obsm)

    return adata_spatial

def map_sample_batch_list(adata, num_samples_patient):
    """

    :param adata:
    :param num_samples_patient: [list] [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 2, 2]
    :return:
    """

    def order_of_magnitude(number):
        return math.floor(math.log(number, 10))

    metadata_batch = pd.DataFrame(columns=["sample", "batch"])
    metadata = dict()
    list_project_samples = dict()
    counter_batch = 1
    for ind, project in enumerate(np.unique(adata.obs['project'])):
        list_project_samples[project] = np.unique(adata.obs['sample'][adata.obs['project'] == project])
        sample_names = [int(i.split('_')[1]) for i in list_project_samples[project]]

        temp_num_oom = 10 ** order_of_magnitude(np.amax(sample_names))
        max_samplenumber = np.amax(sample_names) - temp_num_oom

        rest = max_samplenumber % num_samples_patient[ind]
        if rest != 0:
            max_samplenumber = max_samplenumber + rest

        # determine no batches
        num_batches = 0
        list_batches = num_samples_patient.copy()
        number_samples = copy.copy(max_samplenumber)
        while True:
            list_batches.remove(num_samples_patient[num_batches])
            if ((number_samples - num_samples_patient[num_batches]) == 0) | \
                    (num_batches == (len(num_samples_patient) - 1)):
                num_batches += 1
                break
            number_samples = number_samples - num_samples_patient[num_batches]
            num_batches += 1

        batches = []
        for i_c in range(num_batches):
            batches.extend([i_c + 1 + ind] * num_samples_patient[i_c])

        array_sampleids = np.arange(1 + temp_num_oom, temp_num_oom + max_samplenumber + 1)

        for i_c in range(len(array_sampleids)):
            metadata_batch.loc[i_c] = ["_".join([project, str(array_sampleids[i_c])]), batches[i_c]]

        metadata[project] = pd.DataFrame(columns=["sample", "batch"])
        for i_c in range(len(sample_names)):
            sample_batch = metadata_batch[(metadata_batch ==
                                           list_project_samples[project][i_c]).any(1)].stack().unique()
            metadata[project].loc[i_c] = [sample_batch[0], sample_batch[1]]
        num_samples_patient = list_batches

    return metadata

def get_tissue_annot(adata):
    # Use annotations from pathologist instead of clusters
    obs_keys = list(adata.obs_keys())
    # get all manual annotations by extracting all keys with upper case characters
    annotations = [char for char in obs_keys if any(c.isupper() for c in char)]

    if "ANNOTATOR" in annotations:
        annotations.remove("ANNOTATOR")

    # split annotations by disease and tissue / cell types
    elements = ["LESONAL", "NON LESIONAL", "LESIONAL"]
    intersection_ele = np.intersect1d(adata.obs.columns, elements)
    try:
        index = []
        for el in intersection_ele:
            index.append(annotations.index(el))
        target_index = np.amax(index) + 1
        disease_index = np.amin(index)
    except ValueError:
        target_index = None
        print("REMINDER: Insert 'LESONAL' and 'NON LESIONAL' in your excel file")

    tissue_cell_labels = annotations[target_index:]
    disease_labels = np.array(annotations[:disease_index])
    lesion_labels = np.array(itemgetter(*index)(annotations))

    return disease_labels, lesion_labels

def assign_donor_spot(adata, no_samples_per_patient=4):
    """
    Only usable if Number of samples per patient is equal across whole dataset

    :param adata:
    :param no_samples_per_patient:
    :return:
    """
    # get number of samples in data set and divide it by 4 (because each patient donored 4 samples)
    samples = np.unique(adata.obs['library_id'])
    no_donors = int(len(samples) / no_samples_per_patient)
    list_donors = np.arange(1, no_donors + 1).astype(str).tolist()
    adata.obs['donor'] = adata.obs['library_id'].cat.add_categories(list_donors)
    counter = 0
    for c_donors in range(0, len(samples), no_samples_per_patient):
        counter += 1
        donor_samples = samples[c_donors: no_samples_per_patient + c_donors]
        adata.obs['donor'][np.in1d(adata.obs['library_id'], donor_samples)] = str(counter)
    adata.obs['donor'] = adata.obs['donor'].cat.remove_unused_categories()

def junction_to_epidermis_derdepth1(adata, tissue_layers, layers):
    # Rename tissue region 'INTERFACE' to upper, middle or basal EPIDERMIS because some spots got both labels
    m_interface = adata.obs['JUNCTION'] == 1
    if isinstance(layers, list):
        df_temp = adata.obs[layers][m_interface]
    else:
        df_temp = adata.obs[[layers]][m_interface]
    df_temp = df_temp.loc[:, df_temp.columns].replace(1, pd.Series(df_temp.columns, df_temp.columns))
    df_temp['JUNCTION'] = '0'
    for col in df_temp.columns[:-1]:
        df_temp['JUNCTION'] += df_temp[col].astype(str)
    df_temp["JUNCTION"] = df_temp.JUNCTION.str.replace('0', '')
    adata.obs[tissue_layers] = adata.obs[tissue_layers].astype(str)
    adata.obs[tissue_layers][m_interface] = df_temp["JUNCTION"]
    adata.obs[tissue_layers] = adata.obs[tissue_layers].astype('category')

    return adata


data = {}

def topscorer(sub):
	top = data[0][sub]
	for key,value in data.items():
		for subject,marks in value.items():
			if subject==sub:
				if marks>top:
					top = marks

	return "Highest marks in "+str(sub)+ " is "+str(top)

def main():
	n = int(input("Enter no of students:"))
	for i in range(n):
		print("Enter marks of student "+ str(i))
		english = int(input("English Marks: "))
		maths = int(input("Maths Marks: "))
		history = int(input("History Marks: "))
		science = int(input("Science Marks: "))
		percent = (english+maths+history+science)/4;
		data[i]={"english":english,"maths":maths,"history":history,"science":science,"percent":percent}

	for key,value in data.items():
		for subject,percentage in value.items():
			if subject=="percent":
				print("Student "+str(key)+" "+str(percentage))

	print(topscorer('english'))
	print(topscorer('maths'))
	print(topscorer('history'))
	print(topscorer('science'))

if __name__== "__main__":
	main()


"""Continue outer loop.

Print each item _v of list _a which in not contained in list _b.
For this, write an outer loop to iterate on _a and an inner loop to iterate on _b.

Source: programming-idioms.org
"""

# Implementation author: cym13
# Created on 2016-02-18T16:57:59.339267Z
# Last modified on 2016-02-18T16:57:59.339267Z
# Version 1

# Note that using two loops like this in python is by itself _very un-idiomatic. Also one would be wise to define a custom exception to avoid hiding "real" exceptions.

for v in a:
    try:
        for u in b:
            if v == u:
                raise Exception()
        print(v)
    except Exception:
        continue


from typing import Any, Text, Dict, List, Optional
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.events import SlotSet
import json
import sys

sys.path.append("utils")
from rocketchat_api_calls import get_user_info

class ActionUserIdentifier(Action):
    """
    Check and store in a slot the user of the conversation.
    """

    def name(self) -> Text:
        return "action_user_identifier"

    async def run(
        self,
        dispatcher: CollectingDispatcher,
        tracker: Tracker,
        domain: Dict[Text, Any],
    ) -> List[Dict[Text, Any]]:
        if not tracker.slots.get("user"):
            self.tracker = tracker
            user_id = self._digest_sender_id()

            if user_id:
                user_data = get_user_info(user_id).get("user")
                user_name = user_data.get("name")
            else:
                user_data = None
                user_name = "usuario"

            return [SlotSet("user", user_data), SlotSet("user_name", user_name)]

        return []

    def _digest_sender_id(self) -> Optional[Text]:
        try:
            sender_id = self.tracker.sender_id
            if len(sender_id) != 34:
                return None
            sender_id_1 = sender_id[:17]
            sender_id_2 = sender_id[17:]

            try:
                rol = get_user_info(sender_id_1).get("user").get("roles")
                if rol == None:
                    rol = []
            except Exception as e:
                rol = ["other"]

            if "bot" in rol:
                user_id = sender_id_2
            else:
                user_id = sender_id_1
            return user_id
        except Exception as e:
            print(e)
            return None


# https://www.geeksforgeeks.org/maximize-sum-of-given-array-by-rearranging-array-such-that-the-difference-between-adjacent-elements-is-atmost-1/
# Question : Given an array arr[] consisting of N positive integers, the task is to maximize the sum of
# the array element such that the first element of the array is 1 and the difference between the adjacent
# elements of the array is at most 1 after performing the following operations:
# Rearrange the array elements in any way.
# Reduce any element to any number that is at least 1.
#
# Examples: Input: arr[] = {3, 5, 1}
# Output: 6
# Explanation: One possible arrangement is {1, 2, 3} having maximum possible sum 6.
#
# Question Type : ShouldSee
# Used : Make a freq count array of size n+1. It will store freq of each element of inpArr. If any
#        element is more than n, then its freq will be stored at n index of count array. Initialize
#        nextUniqNum as 0. Now loop over the count array, while its value is more than 0 and nextUniqNum
#        is less than current index i, keep incrementing the nextUniqNum and adding the same in ans, while
#        reducing its freq count. It might happen that nextUniqNum becomes equal or more than current index
#        i and count[i] > 1. Meaning more elements need to be added for given i, but we cannont increase
#        nextUniqNum as doing so might increase the last element value in the resultant array but we
#        are just allowed to reduce the values not increase it. So we just repeat with value with i.
#        Add i * count[i] in ans.
#        maxSum(a, n):
#        count = [0] * (n + 1)
#        for i in range(0, n):
#           count[min(a[i], n)] += 1
#        nextUniqNum = 0, ans = 0
#        for i in range(1, n + 1):
#           while count[i] > 0 and nextUniqNum < i:
#               nextUniqNum += 1
#               ans += nextUniqNum
#               count[i] -= 1
#           ans += i * count[i]
#        return ans
# Complexity : O(n)

def maxSum(a, n):
    count = [0] * (n + 1)
    for i in range(0, n):
        count[min(a[i], n)] += 1
    nextUniqNum = 0
    ans = 0

    for i in range(1, n + 1):
        while count[i] > 0 and nextUniqNum < i:
            # nextUniqNum will be incremented only when it is less then current index i.
            nextUniqNum += 1
            ans += nextUniqNum
            count[i] -= 1
        # This line will run when, nextUniqNum will be equal or more than i.
        ans += i * count[i]
    return ans

if __name__ == '__main__':
    arr = [3, 5, 1]
    print(maxSum(arr, len(arr)))

    arr = [1, 2, 2, 2, 3, 4, 5]
    print(maxSum(arr, len(arr)))

    arr = [1, 2, 2, 2, 3, 4, 5, 5, 5]
    print(maxSum(arr, len(arr)))


import PIL
from torchvision import transforms
import time
import torch
import torch.nn as nn
import math
import numpy as np
import torch

steps =5

class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.cnn = nn.Sequential(nn.Conv2d(3,5,kernel_size=3),
                                             nn.Conv2d(5, 5, kernel_size=2,stride=2),
                                             nn.MaxPool2d(kernel_size=2),
                                             nn.Dropout(0.3),
                                             nn.Conv2d(5,12,kernel_size=2),
                                             nn.Conv2d(12, 12, kernel_size=2, stride=2),
                                             nn.MaxPool2d(kernel_size=2),
                                             nn.Dropout(0.2),
                                             nn.Conv2d(12,24,kernel_size=2),
                                             nn.Conv2d(24, 24, kernel_size=2, stride=2),
                                             nn.MaxPool2d(kernel_size=2),
                                             nn.Dropout(0.2),
                                             nn.Conv2d(24, 30, kernel_size=2),
                                             nn.Flatten(),
                                             nn.GELU(),
                                        nn.Linear(120,32),
                                        nn.GELU(),
                                        nn.Linear(32, 2),
                                             nn.Softmax(dim=1))

    def forward(self, input):
        return self.cnn(input)

def Train( device='cuda'):
    trans = transforms.Compose([transforms.ToTensor(),
                                transforms.RandomHorizontalFlip(0.5),
                                transforms.Normalize(mean=(0.5,0.5,0.5),std=(0.5,0.5,0.5))])
    criterion = nn.CrossEntropyLoss()
    model = CNN().to(device)
    optimizer = torch.optim.RAdam(model.parameters(),lr=5e-4)
    for _ in range(steps):
        loss_average = 0
        count =0
        FaceAdder, HelmetAdder = 1, 1
        correctness=0
        for i in range(638):
            try:
                count+=1
                if i % 2 == 0:
                    url = './helmet/Helmet_' + str(HelmetAdder) + '.jpg'
                    HelmetAdder += 1
                    Answer = torch.tensor([0]).to(device)
                else:
                    url = './Face/Face_' + str(FaceAdder) + '.jpg'
                    FaceAdder += 1
                    Answer = torch.tensor([1]).to(device)
                Img = PIL.Image.open(url)
                Img = Img.resize((256, 256))
                Img = Img.convert("RGB")
                Img = trans(Img).float().to(device)
                predict = model(Img.reshape(-1, 3, 256, 256))
                loss = criterion(predict, Answer)
                optimizer.zero_grad()
                loss.backward()
                loss_average += loss.item()
                optimizer.step()
                if torch.argmax(predict, dim=1).item() == Answer:
                    correctness += 1
            except:
                pass
        torch.save(model.state_dict(),'./saved.pt')
        print(loss_average / count,correctness/count*100)

def Value( device='cuda'):
    trans = transforms.Compose([transforms.ToTensor(),
                                transforms.RandomHorizontalFlip(0.5),
                                transforms.Normalize(mean=(0.5,0.5,0.5),std=(0.5,0.5,0.5))])
    model = CNN().to(device)
    saved = torch.load('./saved.pt')
    model.load_state_dict(saved)
    model.eval()
    count=0
    FaceAdder, HelmetAdder = 1, 1
    correctness = 0
    for i in range(638):
        try:
            if i % 2 == 0:
                url = './helmet/Helmet_' + str(HelmetAdder) + '.jpg'
                HelmetAdder += 1
                Answer = torch.zeros(1, 2).to(device)
                Answer[0][0] += 1
            else:
                url = './Face/Face_' + str(FaceAdder) + '.jpg'
                FaceAdder += 1
                Answer = torch.zeros(1, 2).to(device)
                Answer[0][1] += 1

            Img = PIL.Image.open(url)

            Img = Img.resize((256, 256))
            Img = Img.convert("RGB")
            Img = trans(Img).float().to(device)
            predict = model(Img.reshape(-1, 3, 256, 256))
            count +=1
            if torch.argmax(predict,dim=1).item() == torch.argmax(Answer,dim=1).item():
                correctness+=1
        except:
            pass
    print(correctness/count*100,"%")

if __name__ == '__main__':
    Train()
    Value()


import numpy as np
import random
from collections import namedtuple, deque

from model import QNetwork

import torch
import torch.nn.functional as F
import torch.optim as optim

BUFFER_SIZE = int(1e5)  # replay buffer size
BATCH_SIZE = 64         # minibatch size
GAMMA = 0.99            # discount factor
TAU = 1e-3              # for soft update of target parameters
LR = 5e-4               # learning rate
UPDATE_EVERY = 4        # how often to update the network
ALPHA = 0.6
BETA = 0.4

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

class Agent():
    def __init__(self, state_size, action_size, seed):
        self.state_size = state_size
        self.action_size = action_size
        self.seed = random.seed(seed)

        self.qnetwork_local = QNetwork(state_size, action_size, seed).to(device)
        self.qnetwork_target = QNetwork(state_size, action_size, seed).to(device)
        self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR)

        self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed)
        self.t_step = 0
        self.is_ER_prioritized = False
        print("loaded")

    def step(self, state, action, reward, next_state, done):
        self.memory.add(state, action, reward, next_state, done)

        ## convert to tensors
        t_state = torch.from_numpy(np.vstack([state])).float().to(device)
        t_action = torch.from_numpy(np.vstack([action])).long().to(device)
        t_reward = torch.from_numpy(np.vstack([reward])).float().to(device)
        t_next_state = torch.from_numpy(np.vstack([next_state])).float().to(device)
        t_done = torch.from_numpy(np.vstack([done]).astype(np.uint8)).float().to(device)
        ##
        Q_target, Q_expected = self.get_target_local_Qs(
            (t_state, t_action, t_reward, t_next_state, t_done), GAMMA)
        self.memory.add_TD_error((Q_target-Q_expected).cpu().detach().numpy()[0][0])

        self.t_step = (self.t_step + 1) % UPDATE_EVERY
        if self.t_step == 0:
            if len(self.memory) > BATCH_SIZE:
                experiences = self.memory.sample()
                self.learn(experiences, GAMMA)

    def act(self, state, eps=0):
        state = torch.from_numpy(state).float().unsqueeze(0).to(device)
        self.qnetwork_local.eval()

        with torch.no_grad():
            action_values = self.qnetwork_local(state)

        self.qnetwork_local.train() #sets training mode, that is all - opposite to eval

        if random.random() > eps:
            return np.argmax(action_values.cpu().data.numpy())
        else:
            return random.choice(np.arange(self.action_size))

    def get_target_local_Qs(self, experiences, gamma):
        states, actions, rewards, next_states, dones = experiences

        Q_targets_next = self.qnetwork_target(next_states).detach().max(1)[0].unsqueeze(1)
        Q_targets = rewards + (gamma * Q_targets_next * (1 - dones))

        # Get expected Q values from local model
        Q_expected = self.qnetwork_local(states).gather(1, actions)

        return (Q_targets, Q_expected)

    def learn(self, experiences, gamma):

        Q_targets, Q_expected = self.get_target_local_Qs(experiences, gamma)

        if self.is_ER_prioritized:
            self.memory.update_TD_errors([q[0] for q in (Q_targets-Q_expected).cpu().detach().numpy()])

        #choose between prioritized experienced replay and unifrom one
        #modify update rule
        if self.is_ER_prioritized:
            P = torch.from_numpy(np.vstack(self.memory.chosen_probs)).float().to(device)
            loss = torch.mean( ALPHA*(torch.pow(Q_targets-Q_expected, 2)/torch.pow(P, BETA)) * torch.pow(torch.max(P), BETA) )
        else:
            loss = F.mse_loss(Q_expected, Q_targets)

        #print("loss", loss)
        #print("loss_uni", F.mse_loss(Q_expected, Q_targets))
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step() #|dive into pytorch documentation| it updates params

        # ------------------- update target network ------------------- #
        self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU)

    def soft_update(self, local_model, target_model, tau):
        for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):
            target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)

    def use_prioritized_ER(self, flag=True):
        #when flag==True we use prioritized experience replay instead of uniform one
        self.is_ER_prioritized = flag
        self.memory.is_ER_prioritized = flag

class ReplayBuffer:
    def __init__(self, action_size, buffer_size, batch_size, seed):
        self.action_size = action_size
        self.memory = deque(maxlen=buffer_size)
        self.TD_errors = deque(maxlen=buffer_size)
        self.batch_size = batch_size
        self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"])
        self.seed = random.seed(seed)
        self.is_ER_prioritized = False

    def add(self, state, action, reward, next_state, done):
        """Add a new experience to memory."""
        e = self.experience(state, action, reward, next_state, done)
        self.memory.append(e)

    def add_TD_error(self, TD_error):
        self.TD_errors.append(TD_error)
        assert len(self.TD_errors) == len(self.memory)

    def update_TD_errors(self, vals):
        if len(vals) == len(self.mem_ind_to_recalc_TDE):
            for i, ind in enumerate(self.mem_ind_to_recalc_TDE):
                self.TD_errors[ind] = vals[i]
        else:
            print("memory.update_TD_error: len(vals) not equal to len(self.mem_ind_to_recalc_TDE)")

    def sample(self):
        if self.is_ER_prioritized:
            abs_TD_errors = list(map(abs, self.TD_errors))
            eps_prob = 0.1*max(abs_TD_errors)

            Ps = np.power((abs_TD_errors + eps_prob), ALPHA)
            self.prob = Ps/sum(Ps)
            indices = np.arange(len(self.memory))

            chosen_indices = np.random.choice(indices, self.batch_size, replace=False, p=self.prob)
            self.mem_ind_to_recalc_TDE = chosen_indices.copy()
            #chosen_indices = list(map(int, chosen_indices))
            experiences = []
            [experiences.append(self.memory[ind]) for ind in chosen_indices]
            self.chosen_probs = []
            [self.chosen_probs.append(self.prob[ind]) for ind in chosen_indices]

            #experiences = np.asarray(self.memory)[chosen_indices]
        else:
            experiences = random.sample(self.memory, k=self.batch_size)

        states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device)
        actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().to(device)
        rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device)
        next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(device)
        dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device)

        return (states, actions, rewards, next_states, dones)

    def __len__(self):
        """Return the current size of internal memory."""
        return len(self.memory)


from typing import List

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

class Solution:
     def generateTrees(self, n: int) -> List[TreeNode]:

        # 核心思想
        # 递归求解
        # 与96题不同，96题无需关注数字，只关心序列长度
        # 本体需要关注序列的起始于终止范围
        # 设定一个helper函数，传入初始start和end值，即[1, n]
        # 依次取[start, end]中的值i作为根节点
        # 则左节点的范围是leftTrees = helper(start, i - 1)
        # 则右节点的范围是rightTrees = helper(i + 1, end)
        # 递归调用这两部分，获得所有可行的左子树和可行的右子树，
        # 那么最后一步我们只要从可行左子树集合中选一棵，再从可行右子树集合中选一棵拼接到根节点上，
        # 并将生成的二叉搜索树放入答案数组即可。

        # 当start > end时，无法满足二插树条件：右子树要比左子树小，则说明无法再进行划分，
        # 注意要返回一个可迭代对象[None]

        def helper(start, end):
            allTrees = []

            if start > end:
                return [None]

            for i in range(start, end + 1):  # 枚举可行根节点
                # 获得所有可行的左子树集合
                leftTrees = helper(start, i - 1)

                # 获得所有可行的右子树集合
                rightTrees = helper(i + 1, end)

                # 从左子树集合中选出一棵左子树，从右子树集合中选出一棵右子树，拼接到根节点上
                for l in leftTrees:
                    for r in rightTrees:
                        currTree = TreeNode(i)
                        currTree.left = l
                        currTree.right = r
                        allTrees.append(currTree)

            return allTrees  # 返回allTrees，就是返回该节点下的所有子树集合

        return helper(1, n) if n else []

95.不同的二叉搜索树II.py

95.不同的二叉搜索树II.py


import unittest
# From: https://eli.thegreenplace.net/2011/08/02/python-unit-testing-parametrized-test-cases
class ParametrizedTestCase(unittest.TestCase):
    """ TestCase classes that want to be parametrized should
        inherit from this class.
    """
    def __init__(self, methodName='runTest', param=None):
        super(ParametrizedTestCase, self).__init__(methodName)
        self.param = param

    @staticmethod
    def parametrize(testcase_klass, param=None):
        """ Create a suite containing all tests taken from the given
            subclass, passing them the parameter 'param'.
        """
        testloader = unittest.TestLoader()
        testnames = testloader.getTestCaseNames(testcase_klass)
        suite = unittest.TestSuite()
        for name in testnames:
            suite.addTest(testcase_klass(name, param=param))
        return suite

# Test Data
import jgrapht

g1 = jgrapht.create_graph(directed=False, weighted=False)
g1.add_vertices_from([x for x in range(0,4)])
g1.add_edge(0,1,edge=0)
g1.add_edge(0,2,edge=1)
g1.add_edge(0,3,edge=2)
g1.add_edge(1,3,edge=3)
g1.add_edge(2,3,edge=4)

# Grafo não direcionado conectado
g2 = jgrapht.create_graph(directed=False, weighted=False)
g2.add_vertices_from([x for x in range(9)])
g2.add_edge(0,1,edge=0)
g2.add_edge(0,2,edge=1)
g2.add_edge(1,3,edge=2)
g2.add_edge(1,8,edge=3)
g2.add_edge(7,2,edge=4)
g2.add_edge(2,6,edge=5)
g2.add_edge(2,4,edge=6)
g2.add_edge(3,5,edge=7)
g2.add_edge(6,7,edge=8)
g2.add_edge(7,8,edge=9)

g3 = jgrapht.create_graph(directed=False, weighted=False)

g5 = jgrapht.create_graph(directed=False, weighted=False)
g5.add_vertices_from([0,1,2,3,4])
g5.add_edge(0,1)
g5.add_edge(1,2)
g5.add_edge(2,3)
g5.add_edge(2,4)
g5.add_edge(2,0)
g5.add_edge(3,1)
g5.add_edge(4,1)

class Test_friendship_score(ParametrizedTestCase):
  def test_valid01 (self):
    f,g,p,expected = self.param
    try:
      result = f(g,p)
      self.assertEqual(result,expected)
    except:
      self.assertTrue(f(g,p) is None and g is None)

params = [[g1,0,5],
          [g1,2,3],
          [g1,3,5],
          [g1,1,3],
          [g2,0,2],
          [g2,1,3],
          [g2,2,5],
          [g2,3,2],
          [g2,4,1],
          [g2,5,1],
          [g2,6,3],
          [g2,7,4],
          [g2,8,2],
          [g5,0,3],
          [g5,1,7],
          [g5,2,7],
          [g5,3,3],
          [g5,4,3],
          [g1,4,None],
          [g3,0,None],
          [None,None,None]]


#User function Template for python3
class Solution:
    def countSubArrayProductLessThanK(self, a, n, k):
        count = 0
        product = 1
        start = 0

        for end in range(n):
            product *= a[end]

            while product >= k and start <= end:
                product /= a[start]
                start += 1

            count += end - start + 1

        return count

#{
 # Driver Code Starts

#Initial Template for Python 3

def main():

    T = int(input())

    while(T > 0):
        n, k = [int(x) for x in input().strip().split()]
        arr = [int(x) for x in input().strip().split()]

        print(Solution().countSubArrayProductLessThanK(arr, n, k))

        T -= 1

if __name__ == "__main__":
    main()

# } Driver Code Ends

Count the subarrays having product less than k - GFG/count-the-subarrays-having-product-less-than-k.py


from __future__ import division

def findsubstrnum(s,ss):
    out = []
    ad=ss.find(s,0)
    if s=='radiant_win':
        if ss[ad+len(s)]=='t':
            return -1
        else:
            return 1
    else:
        tmp=''
        while ad!=-1:
            ad=ad+len(s)
            tmp=''
            while ss[ad].isdigit():
                tmp = tmp + ss[ad]
                ad = ad + 1
            if tmp=='4294967295':
                tmp='0'
            tmp=int(tmp)
            if (tmp<50 or tmp>1200) and s!='hero_id' and s!='account_id' and s!='radiant_score' and s!='dire_score' and s!='duration':
                return 0
            out.append(tmp)
            ad=ss.find(s,ad)
        if s=='duration':
            while len(out)!=1:
                del out[len(out)-1]
            out[0]=int(out[0])
        if len(out)==10 or len(out)==1:
            return out
        else:
            return False

def findsubstrnums(s,ss):
    ad = ss.find(s, 0)
    ad = ad + len(s)
    tmp = ''
    while ss[ad].isdigit():
        tmp = tmp + ss[ad]
        ad = ad + 1
    return tmp

def filtration(ss):
    if len(ss) > 80 and (findsubstrnums('game_mode',ss)=='3' or findsubstrnums('game_mode',ss)=='2' or findsubstrnums('game_mode',ss)=='22') and findsubstrnums('leaver_status',ss)=='0' and findsubstrnums('human_players',ss)=='10':
        return True
    else:
        return False

def mysort(A):
    gpm=A[2]
    xpm=A[3]
    avg=[]
    for i in range(0,4):
        avg.append((gpm[i]+xpm[i])/2)
    for i in range(0,4):
        for j in range(i,4):
            if avg[i]<avg[j]:
                tmp=A[0][i]
                A[0][i]=A[0][j]
                A[0][j]=tmp
                tmp = A[1][i]
                A[1][i] = A[1][j]
                A[1][j] = tmp
    avg = []
    for i in range(5,9):
        avg.append((gpm[i]+xpm[i])/2)
    for i in range(5,9):
        for j in range(i,9):
            if avg[i-5]<avg[j-5]:
                tmp=A[0][i]
                A[0][i]=A[0][j]
                A[0][j]=tmp
                tmp = A[1][i]
                A[1][i] = A[1][j]
                A[1][j] = tmp
    return A

def mysort1(A,dy):
    for i in range(0, 5):
        for j in range(i, 5):
            if dy[1].index(str(A[1][i])) > dy[1].index(str(A[1][j])):
                tmp = A[0][i]
                A[0][i] = A[0][j]
                A[0][j] = tmp
                tmp = A[1][i]
                A[1][i] = A[1][j]
                A[1][j] = tmp
    for i in range(5, 10):
        for j in range(i, 10):
            if dy[1].index(str(A[1][i])) > dy[1].index(str(A[1][j])):
                tmp = A[0][i]
                A[0][i] = A[0][j]
                A[0][j] = tmp
                tmp = A[1][i]
                A[1][i] = A[1][j]
                A[1][j] = tmp
    return A

import numpy as np
fo3=open('dota2heroduiying.txt')
dy=[]
for line in fo3:
    line=line.split()
    dy.append(line)
try:
    pre=np.load('pre30.npy')
    pre=pre.tolist()
except:
    pre = [[] for i in range(114)]

fo = open('highnewdata2.txt')
delet = list('{"[,:')
accountid=[]
for line in fo:
    for i in delet:
        line = line.replace(i, '')
    if filtration(line):
        substr=[]
        substr.append('account_id')
        substr.append('hero_id')
        substr.append('gold_per_min')
        substr.append('xp_per_min')
        substr.append('radiant_win')
        tmp_mex=[]
        for substrs in substr:
            out = findsubstrnum(substrs,line)
            if out!=0:
                tmp_mex.append(out)
            else:
                tmp_mex=[]
                break
        if len(tmp_mex)>1:
            dur=findsubstrnum('duration', line)
            tmp_mex=mysort1(tmp_mex,dy)
            if tmp_mex[4]==-1:
                for ind in range(5):
                    try:
                        pre[int(tmp_mex[1][ind])-1][int(dur[0]/60)]+=1
                    except:
                        n=int(dur[0]/60)
                        while len(pre[int(tmp_mex[1][ind]) - 1])<n+1:
                            pre[int(tmp_mex[1][ind]) - 1].append(0)
                        pre[int(tmp_mex[1][ind]) - 1][int(dur[0] / 60)] += 1
            if tmp_mex[4]==1:
                for ind in range(5,10):
                    try:
                        pre[int(tmp_mex[1][ind])-1][int(dur[0]/60)]+=1
                    except:
                        n = int(dur[0] / 60)
                        while len(pre[int(tmp_mex[1][ind]) - 1]) < n+1:
                            pre[int(tmp_mex[1][ind]) - 1].append(0)
                        pre[int(tmp_mex[1][ind]) - 1][int(dur[0] / 60)] += 1
print(pre)
np.save('pre30.npy',pre)


import pexpect
import os
from glob import glob
from os import stat as os_stat
from pp_utils import Monitor
from stat import S_ISFIFO

"""
    based on pyomxplayer from https://github.com/jbaiter/pyomxplayer
    extensively modified by KenT

    uzblDriver hides the detail of using the luakit command  from browserplayer
    This is meant to be used with pp_browserplayer.py
    Its easy to end up with many copies of uzbl running if this class is not used with care.
    use pp_browserplayer.py for a safer interface.

    External commands
    ----------------------------
    __init__ just creates the instance and initialises variables (e.g. bplayer=uzblDriver())
    play -  opens the browser and plays the first track
    control  - sends commands to uzbl while it is open
    stop - closes the browser.
    terminate - Stops the browser. Used when aborting an application.

    Signals
    ----------
    The following signals are produced while the browser is open
         self.start_play_signal = True when the browser is ready to be used

    is_running() tests whether the sub-process running uzbl is alive.

"""

class UZBLDriver(object):

    def __init__(self,widget):

        self.widget=widget

        self.mon=Monitor()

        self._process=None
        self.fifo=''

    def pause(self):
        pass

    def stop(self):
        self.control('exit')

    # kill the subprocess (uzbl). Used for tidy up on exit.
    def terminate(self,reason):
        self.terminate_reason=reason
        if self.exists_fifo():
            self.control('exit')
            # self._process.close(force=True)

    def play(self, track, geometry):
        self.start_play_signal = False
        # track= "'"+ track.replace("'","'\\''") + "'"

        cmd='uzbl-browser '  + geometry + '--uri='+track
        self.mon.log(self, "Send command to uzbl: "+ cmd)
        self._process = pexpect.spawn(cmd)
        # uncomment to monitor output to and input from uzbl (read pexpect manual)
        # fout= file('/home/pi/pipresents/uzbllogfile.txt','w')  #uncomment and change sys.stdout to fout to log to a file
        # self._process.logfile_send = sys.stdout  # send just commands to stdout
        # self._process.logfile=fout  # send all communications to log

        # and poll for fifo to be available
        self.get_fifo()

    # poll for fifo to be available
    # when it is set start_play_signal
    # browser player calls is_running at intervals to test if uzbl is ended after an exit command
    def get_fifo(self):
        """
        Look for UZBL's FIFO-file in /tmp.
        Don't give up until it has been found.
        """
        candidates = glob('/tmp/uzbl_fifo_*')
        for fifo_file in candidates:
            if S_ISFIFO(os_stat(fifo_file).st_mode):
                self.mon.log(self, 'Found UZBL fifo  in %s.' % fifo_file)
                self.fifo=fifo_file
                self.start_play_signal=True
                return
        # print 'fifo not found trying again'
        self.widget.after(500,self.get_fifo)

    def exists_fifo(self):
        if os.path.exists(self.fifo):
            return True
        else:
            return False

    # send commands to uzbl via the fifo
    def control(self,data):
        if self.exists_fifo():
            self.mon.log(self,'send command to uzbl:'+ data)
            f = open(self.fifo, 'a')
            f.write('%s\n' % data)
            f.close()
            # self.mon.log(self,'sent command to uzbl:'+ data)

   # test of whether _process is running
    def is_running(self):
        return self._process.isalive()


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

from opendrive2lanelet.opendriveparser.elements.road_record import RoadRecord
import numpy as np

__author__ = "Benjamin Orthen, Stefan Urban"
__copyright__ = "TUM Cyber-Physical Systems Group"
__credits__ = ["Priority Program SPP 1835 Cooperative Interacting Automobiles"]
__version__ = "1.2.0"
__maintainer__ = "Sebastian Maierhofer"
__email__ = "commonroad-i06@in.tum.de"
__status__ = "Released"

class ElevationProfile:
    """The elevation profile record contains a series of elevation records
    which define the characteristics of
    the road's elevation along the reference line.

    (Section 5.3.5 of OpenDRIVE 1.4)
    """

    def __init__(self):
        self.elevations = []
        self.start_pos_list = None

    def initialize(self):
        self.start_pos_list = [record[0].start_pos for record in self.elevations]

    def calc_z(self, sPos):
        if self.start_pos_list is None:
            self.initialize()
        if sPos.size>1:
            reverse = sPos[0]>sPos[1]
        else:
            reverse = False
        if reverse:
            sPos_left = np.flip(sPos)
        else:
            sPos_left = sPos

        ds_list = []
        for start_pos in reversed(self.start_pos_list):
            idx = np.searchsorted(sPos_left, start_pos)
            ds_list.append(sPos_left[idx:] - start_pos)
            sPos_left = sPos_left[:idx]

        z = np.array([])
        for i, ds in enumerate(reversed(ds_list)):

            coeff = self.elevations[i][0].polynomial_coefficients
            #z = a+b*ds+c*ds^2+d*ds^3
            z_local = coeff[0]+coeff[1]*ds+coeff[2]*ds**2+coeff[3]*ds**3
            z = np.hstack((z,z_local))

        if reverse:
            z = np.flip(z)

        return z

class ElevationRecord(RoadRecord):
    """The elevation record defines an elevation entry at a given reference line position.

    (Section 5.3.5.1 of OpenDRIVE 1.4)
    """


import sys
sys.stdin = open('input.txt', 'r')
'''
0점은 항상 받을 수 있는 점수
새로운 점수 받을 때마다 더해주고, 이전에 가능한 점수들 + 새로받은 점수 더해
가능한 점수 체크
'''
def res(scores):
    res = {0}
    for i in scores:
        for j in list(res):
            res.add(i+j)
    return len(res)

TC = int(input())
for t in range(1, TC+1):
    N = int(input())
    scores = list(map(int, input().split()))
    print('#{} {}'.format(t, res(scores)))


from http import client
from shutil import ExecError
from sqlite3 import IntegrityError
from unicodedata import name
from flask import request, jsonify
from models import *
from main import app

#User types
#TODO (Temporary way of adding user types)
@app.route('/usertypes', methods=['GET'])
def usertypes():

    users = ['coach', 'client']

    user_exists = Usertype.query.all()

    for user in users:
        if not user_exists:
            user_type_add = Usertype(name=user)
            db.session.add(user_type_add)
            db.session.commit()
        else:
            for db_user in user_exists:
                if db_user.name not in users:
                    user_type_add = Usertype(name=user)
                    db.session.add(user_type_add)
                    db.session.commit()

    all_usertypes = Usertype.query.all()

    output = []

    for usertype in all_usertypes:
        usertype_data = {}
        usertype_data['id'] = usertype.id
        usertype_data['name'] = usertype.name
        output.append(usertype_data)

    return jsonify({'usertypes': output}), 200

#List all coaches
@app.route('/coaches', methods=['GET'])
def coaches():
    #TODO: Fix hardcoded value
    all_coaches = User.query.filter_by(usertype_id=1).all()

    output = []

    for coach in all_coaches:
        coach_data = {}
        coach_data['id'] = coach.id
        coach_data['name'] = coach.name
        coach_data['email'] = coach.email
        coach_data['session_duration'] = coach.session_duration
        output.append(coach_data)

    return jsonify({'coaches': output}), 200

#Users Crud operations --> get, add, update, delete
@app.route('/user', methods=['GET', 'POST', 'PUT', 'DELETE'])
def user_cruds():
    if request.method == 'GET':
        data = request.get_json()

        user = User.query.filter_by(id=data['id'])#.first()

        output = []

        for item in user:
            user_data = {}
            user_data['id'] = item.id
            user_data['name'] = item.name
            user_data['email'] = item.email
            user_data['session_duration'] = item.session_duration
            user_data['usertype_id'] = item.usertype_id
            user_data['usertype'] = item.usertype.name
            output.append(user_data)

        return jsonify({'users': output}), 200

    elif request.method == 'PUT':
        data = request.get_json()

        session_duration = data['session_duration'] if 'session_duration' in data else None

        add_user = User(name=data['name'], email=data['email'], session_duration=session_duration, usertype_id=data['usertype_id'])
        db.session.add(add_user)
        db.session.commit()

        return jsonify({'msg': 'User added successfully'}), 201

    elif request.method == 'POST':
        data = request.get_json()

        user = User.query.filter_by(id=data['id'])#.first()

        if data['email']:
            user.update({'email':data['email']})
            db.session.commit()
            return jsonify({'msg':'Email updated successfully'}), 200

        elif data['name']:
            user.update({'name':data['name']})
            db.session.commit()
            return jsonify({'msg':'Name updated successfully'}), 200

        else:
            return jsonify({'msg':'Wrong parameter'}), 401

    elif request.method == 'DELETE':
        data = request.get_json()

        User.query.filter_by(id=data['id']).delete()
        db.session.commit()

        return jsonify({'msg':'User deleted successfully'}), 200

    else:
        return jsonify({'msg':'Wrong method'}), 401

#List a specific coach’s working hours
@app.route('/coach_hours', methods=['POST'])
def coach_hours():
    data = request.get_json()
    hours = Appointment.query.filter_by(coach_id=data['coach_id']).all()

    output = []

    for hour in hours:
        hour_data = {}
        hour_data['id'] = hour.id
        hour_data['coach'] = hour.coach.name
        hour_data['client'] = hour.client.name
        hour_data['title'] = hour.title
        hour_data['start_time'] = hour.start_time
        hour_data['end_time'] = hour.end_time
        # hour_data['total_hours'] = pass

        output.append(hour_data)

    return jsonify({'coach_hours': output}), 200

#List all appointments
@app.route('/appointments', methods=['GET'])
def appointments():
    all_appointments = Appointment.query.all()

    output = []

    for appointment in all_appointments:
        appointment_data = {}
        appointment_data['id'] = appointment.id
        appointment_data['title'] = appointment.title
        appointment_data['coach_id'] = appointment.coach_id
        appointment_data['coach'] = appointment.coach.name
        appointment_data['client_id'] = appointment.client_id
        appointment_data['client'] = appointment.client.name
        appointment_data['start_time'] = appointment.start_time
        appointment_data['end_time'] = appointment.end_time
        appointment_data['is_active'] = appointment.is_active
        output.append(appointment_data)

    return jsonify({'appointments': output}), 200

#Make, cancel, edit, view appointment
@app.route('/appointment', methods=['GET', 'POST', 'PUT', 'DELETE'])
def appointment_cruds():
    if request.method == 'GET':
        all_appointments = Appointment.query.all()

        output = []

        for appointment in all_appointments:
            appointment_data = {}
            appointment_data['id'] = appointment.id
            appointment_data['title'] = appointment.title
            appointment_data['coach_id'] = appointment.coach_id
            appointment_data['coach'] = appointment.coach.name
            appointment_data['client_id'] = appointment.client_id
            appointment_data['client'] = appointment.client.name
            appointment_data['start_time'] = appointment.start_time
            appointment_data['end_time'] = appointment.end_time
            appointment_data['is_active'] = appointment.is_active
            output.append(appointment_data)

        return jsonify({'appointments': output}), 200

    elif request.method == 'PUT':
        data = request.get_json()

        #Convert string time to python datetime
        start_time = datetime.strptime(data['start_time'], '%d/%m/%y %H:%M')
        end_time = datetime.strptime(data['end_time'], '%d/%m/%y %H:%M')

        #Check if slot is available
        times = Appointment.query.filter_by(is_active=True).all()

        # Get session duration
        initial_duration = User.query.filter_by(id=data['coach_id']).first().session_duration

        for time in times:
            diff = end_time - start_time

            #difference in minutes
            diff = diff.total_seconds() / 60

            #duration in minutes
            duration = int(initial_duration) * 60

            #Cast to integer
            diff = int(diff)
            duration = int(duration)

            if diff != duration:
                return jsonify({'msg': f'Session duration should be {initial_duration} hours'}), 401

            if start_time >= time.start_time and end_time <= time.end_time:
                return jsonify({'msg': 'Appointment not successfully, that session is already booked'}), 401

        add_appointment = Appointment(title=data['title'], coach_id=data['coach_id'], client_id=data['client_id'], start_time=start_time, end_time=end_time, is_active=True)
        db.session.add(add_appointment)
        db.session.commit()

        return jsonify({'msg': 'Appointment added successfully'}), 201

    elif request.method == 'POST':
        data = request.get_json()

        appointment = Appointment.query.filter_by(id=data['id'])#.first()

        if data['title']:
            appointment.update({'title':data['title']})
            db.session.commit()
            return jsonify({'msg':'Title updated successfully'}), 200

        elif data['coach_id']:
            appointment.update({'coach_id':data['coach_id']})
            db.session.commit()
            return jsonify({'msg':'Coach updated successfully'}), 200

        elif data['client_id']:
            appointment.update({'client_id':data['client_id']})
            db.session.commit()
            return jsonify({'msg':'Client updated successfully'}), 200

        elif data['start_time']:
            appointment.update({'start_time':datetime.strptime(data['start_time'], '%d/%m/%y %H:%M')})
            db.session.commit()
            return jsonify({'msg':'Start time updated successfully'}), 200

        elif data['end_time']:
            appointment.update({'end_time':datetime.strptime(data['end_time'], '%d/%m/%y %H:%M')})
            db.session.commit()
            return jsonify({'msg':'End time updated successfully'}), 200

        else:
            return jsonify({'msg':'Wrong parameter'}), 401

    elif request.method == 'DELETE':
        #Soft Delete
        data = request.get_json()

        appointment = Appointment.query.filter_by(id=data['id']).update(dict(is_active=False))
        db.session.commit()

        return jsonify({'msg':'Appointment cancelled successfully'}), 200

    else:
        return jsonify({'msg':'Wrong method'}), 401


# solved: [1926] 그림
# https://www.acmicpc.net/problem/1926
# graph-traversal, bfs
#
# Silver 1
# bfs 기본 문제
# 주어진 그래프에서 1의 영역의 개수, 최대 영역의 크기

from collections import deque

def bfs(x, y):

    queue = deque()
    queue.append((x, y))
    area = 1

    while queue:

        x, y = queue.popleft()

        for i in range(4):

            nx = x + dx[i]
            ny = y + dy[i]

            if nx < 0 or ny < 0 or nx >= n or ny >= m:
                continue

            if visited[nx][ny]:
                continue

            if graph[nx][ny]:
                visited[nx][ny] = True
                area += 1
                queue.append((nx, ny))

    return area

n, m = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(n)]

visited = [[False] * m for _ in range(n)]
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
cnt = 0
ans = 0

for i in range(n):
    for j in range(m):
        if graph[i][j] and not visited[i][j]:
            visited[i][j] = True
            cnt += 1
            ans = max(ans, bfs(i, j))

print(cnt)
print(ans)


"""Phrase search by dumb numpy position differences subtraction, bigram by bigram."""
import numpy as np
from typing import List

def vstack_with_mask(posns: List[np.ndarray], phrase_freqs: np.ndarray, width: int = 0, pad: int = -100):
    """Vertically stack arrays, only accepting those that fit within width.

    Parameters
    ----------
    posns: list of np.ndarray term positions for a given term across multiple docs
    width: int, max number of positions we accept
    pad: int, value to pad with when no position present
    phrase_freqs: np.ndarray, phrase freqs for each doc.
                 -1 indicates "not yet processed" 0 means "defiiitely not a match"

    Returns
    -------
    vstacked: np.ndarray, vertically stacked arrays of those <= width
    mask: np.ndarray, boolean mask of which arrays were accepted (so you can recompute them a different way)
    """
    vstacked = np.zeros((len(posns), width), dtype=posns[0].dtype) + pad
    if not isinstance(posns[0], np.ndarray):
        raise TypeError("posns must be a list of np.ndarrays")
    for idx, array in enumerate(posns):
        if len(array) >= width:
            phrase_freqs[idx] = -2  # Mark as skip this round
        else:
            vstacked[idx, :len(array)] = array
    return vstacked

def stack_term_posns(term_posns: List[np.ndarray], phrase_freqs: np.ndarray, width: int = 10):
    # Pad for easy difference computation
    keep_term_posns = []
    # keep_mask = np.ones(len(self), dtype=bool)
    for term_posn in term_posns:
        this_term_posns = vstack_with_mask(term_posn, phrase_freqs, width=width)
        keep_term_posns.append(this_term_posns)
    return keep_term_posns

def _compute_phrase_freqs(term_posns, phrase_freqs: np.ndarray, slop=1):

    to_compute = phrase_freqs == -1

    if not np.any(to_compute):
        return phrase_freqs

    # Only examine masked
    term_posns = [term_posn[to_compute] for term_posn in term_posns]

    prior_term = term_posns[0]
    for term in term_posns[1:]:
        is_same_term = (term.shape == prior_term.shape) and np.all(term == prior_term)

        # Compute positional differences
        #
        # Each row of posn_diffs is a term posn diff matrix
        # Where columns are prior_term posns, rows are term posns
        # This shows every possible term diff
        #
        # Example:
        #   prior_term = array([[0, 4],[0, 4])
        #         term = array([[1, 2, 3],[1, 2, 3]])
        #
        #
        #   posn_diffs =
        #
        #     array([[ term[0] - prior_term[0], term[0] - prior_term[1] ],
        #            [ term[1] - prior_term[0], ...
        #            [ term[2] - prior_term[0], ...
        #
        #    or in our example
        #
        #     array([[ 1, -3],
        #            [ 2, -2],
        #            [ 3, -1]])
        #
        #  We care about all locations where posn == slop (or perhaps <= slop)
        #  that is term is slop away from prior_term. Usually slop == 1 (ie 1 posn away)
        #  for normal phrase matching
        #
        posn_diffs = term[:, :, np.newaxis] - prior_term[:, np.newaxis, :]

        # For > 2 terms, we need to connect a third term by making prior_term = term
        # and repeating
        #
        # BUT
        # we only want those parts of term that are adjacent to prior_term
        # before continuing, so we don't accidentally get a partial phrase
        # so we need to make sure to
        # Pad out any rows in 'term' where posn diff != slop
        # so they're not considered on subsequent iterations
        term_mask = np.any(posn_diffs == 1, axis=2)
        term[~term_mask] = -100

        # Count how many times the row term is 1 away from the col term
        per_doc_diffs = np.sum(posn_diffs == slop, axis=1, dtype=np.int8)

        # Doc-wise sum to get a 'term freq' for the prior_term - term bigram
        bigram_freqs = np.sum(per_doc_diffs == slop, axis=1)
        if is_same_term:
            satisfies_slop = per_doc_diffs == slop
            consecutive_ones = satisfies_slop[:, 1:] & satisfies_slop[:, :-1]
            consecutive_ones = np.sum(consecutive_ones, axis=1)
            # ceiling divide?
            # Really these show up as
            # 1 1 1 0 1
            # we need to treat the 2nd consecutive 1 as 'not a match'
            # and also update 'term' to not include it
            bigram_freqs -= -np.floor_divide(consecutive_ones, -2)

        # Last loop, bigram_freqs is the full phrase term freq

        # Update mask to eliminate any non-matches
        phrase_freqs[to_compute] = bigram_freqs

        # Should only keep positions of 'prior term' that are adjacent to the
        # one prior to it...
        prior_term = term

    return phrase_freqs

def compute_phrase_freqs(term_posns, phrase_freqs, slop=1, width=10):
    """Compute phrase freq using matrix-diff method for docs up to width posns. Skip others.

    Parameters
    ----------
    term_posns: list of np.ndarray term positions for a given term across multiple docs
    phrase_freqs: np.ndarray, phrase freqs for each doc present in term_posns

    Returns
    -------
    phrase_freqs: np.ndarray, phrase freqs for each doc present in mask

    See Also
    --------
    Colab notebook: https://colab.research.google.com/drive/1NRxeO8Ya8jSlFP5YwZaGh1-43kDH4OXG?authuser=1#scrollTo=5JZV8svpauYB
    """
    if len(term_posns[0]) != len(phrase_freqs):
        raise ValueError("term_posns and phrase_freqs must be same length")
    stacked = stack_term_posns(term_posns, phrase_freqs, width=width)
    phrase_freqs = _compute_phrase_freqs(stacked, phrase_freqs, slop=slop)
    phrase_freqs[phrase_freqs == -2] = -1
    return phrase_freqs


from zvt.recorders_us.simfin.common import BaseSimFinFinanceRecorder
from zvt.domain_us.finance_us import FinanceFactor

finance_factor_map = {
    "Ticker": "code",
    "Report Date": "report_date",
    'Restated Date': "restated_date",
    "Shares (Basic)": "basic_shares",
    "Shares (Diluted)": "deluted_shares",

    "EBITDA": "ebitda",
    "Total Debt": "total_debt",
    "Free Cash Flow": "fcf",
    "Gross Profit Margin": "gross_profit_margin",
    "Operating Margin": "operating_margin",
    "Net Profit Margin": "net_profit_margin",
    "Return on Equity": "roe",
    "Return on Assets": "roa",
    "Free Cash Flow to Net Income": "fcf_net_income",
    "Current Ratio": "current_ratio",
    "Liabilities to Equity Ratio": "liabilities_to_equity_ratio",
    "Debt Ratio": "debt_ratio",
    "Earnings Per Share, Basic": "basic_eps",
    "Earnings Per Share, Diluted": "diluted_esp",
    "Sales Per Share": "sps",
    "Equity Per Share": "equity_ps",
    "Free Cash Flow Per Share": "fcf_ps",
    "Dividends Per Share":"dps",
    "Pietroski F-Score": "pietroski"
}

class USStockFinanceFactorRecorder(BaseSimFinFinanceRecorder):
    provider = "simfin"
    data_schema = FinanceFactor

    datasets = ["derived", "derived-banks", "derived-insurancec"]
    market = "us"
    variant = "annual"

    def get_data_map(self):
        return finance_factor_map

    def drop_columns(self, df):
        df.drop(columns=['SimFinId', 'Currency', 'Fiscal Year', 'Fiscal Period', 'Restated Date', 'Publish Date'], inplace=True)
        return df

__all__ = ['USStockFinanceFactorRecorder']

if __name__ == '__main__':
    # init_log('blance_sheet.log')
    recorder = USStockFinanceFactorRecorder()
    recorder.run()


from model import *

sess = tf.Session()

def restore(session, shape):

    # create IAF and load previously trained weights
    flow = IAF(inputs=tf.placeholder(dtype=tf.float32, shape=shape),
               cond=tf.placeholder(dtype=tf.float32, shape=shape),
               teacher=None,
               flows=1,
               filter_width=3,
               hidden_units=64,
               output_classes=2,
               nb_mixtures=2,
               training=False)

    load = tf.train.Saver()

    load.restore(session, "/tmp/IAF.ckpt")

    print("Model restored")

    return flow

def generate(session, flow, cond):

    # generate random noise input
    gen = np.random.logistic(0., 1., [32, 1, 10, 1])

    gen_audio = session.run(flow.outputs,
                            feed_dict={flow.inputs: gen, flow.cond: cond})

    gen_audio = inv_mu_law(gen_audio, 65535.)

    return gen_audio

def main():

    iaf = restore(sess, [32, 1, 10, 1])

    gen_block = generate(sess, iaf, np.zeros([32, 1, 10, 1], np.float32))

    print(gen_block)

    outputs = gen_block

    for i in range(1):

        gen_block = generate(sess, iaf, gen_block)

        outputs = np.concatenate([outputs, gen_block], axis=2)

    print("Generated audio files")

    file = outputs.reshape([outputs.shape[0], outputs.shape[2]])

    for i in range(2):

        save_audio("/tmp/gen_file_{0}.wav".format(i), file[i], 44100)

if __name__ == "__main__":
    main()


import pytest
import contextlib
import time
import datetime

measurements = []

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    terminalreporter.write('\nDuration report:\n')
    for i in measurements:
        identifier = i['module'].__name__
        if i['cls']:
            identifier += f"::{i['cls'].__name__}"
        if i['function']:
            identifier += f"::{i['function'].__name__}"
        duration = datetime.timedelta(seconds=i['duration'])
        description = i['description']
        terminalreporter.write(f"> {duration} [{identifier}] {description}\n")

@pytest.fixture
def duration(request):

    @contextlib.contextmanager
    def wrapper(description):
        start = time.monotonic()
        yield
        duration = time.monotonic() - start
        measurements.append({'module': request.module,
                             'cls': request.cls,
                             'function': request.function,
                             'description': description,
                             'duration': duration})

    return wrapper


import phys
import pygame
import pygame.draw as PD
import pygame.image
import pygame.transform

import lasercannon
import enemy

import obstacle
import waterlock

import color

import sheethelper

import math

class PlayerShot(phys.PhysEntity):

    def __init__(self, i_x, i_y, w, h, v, d, camera, c, player, state):
        phys.PhysEntity.__init__(self, i_x, i_y, w, h, camera, state)
        self.player = player
        self.g = 0
        self.yvel = 0
        self.xvel = 0
        self.yacc = 0
        self.xacc = 0
        #v=1
        self.dir = d
        if d == 'N':
            self.yvel = -1 * v
        elif d == 'E':
            self.xvel = v
        elif d == 'S':
            self.yvel = v
        elif d == 'W':
            self.xvel = -1 * v

        if c == color.RED:
            self.frames = [pygame.image.load("../Images/bullet_red.png")
                           .convert_alpha()]
        elif c == color.BLUE:
            self.frames = [pygame.image.load("../Images/bullet_blue.png")
                           .convert_alpha()]
        elif c == color.GREEN:
            self.frames = [pygame.image.load("../Images/bullet_green.png")
                           .convert_alpha()]
        elif c == color.YELLOW:
            self.frames = [pygame.image.load("../Images/bullet_yellow.png")
                           .convert_alpha()]
        else:
            self.frames = [pygame.Surface((w, h)).convert_alpha()]
            self.frames[0].fill((0, 0, 0, 1))

        self.c = c

        if d == 'N' or d == 'S':
            self.frames[0] = pygame.transform.scale(self.frames[0], (h, w))
            self.frames[0] = pygame.transform.rotate(self.frames[0], 90)
        else:
            self.frames[0] = pygame.transform.scale(self.frames[0], (w, h))

        self.numframes = 1
        self.dying = False
        self.dietimer = 40

    def update(self, dt):
        phys.PhysEntity.update(self, dt)
        if not self.in_update_area():
            self.player._delete_shot(self)
        elif self.dying:
            self.dietimer -= 1
            if (self.dietimer <= 0):
                self._stateObject.GAME.remove_entity(self)

    def draw(self, canvas):
        phys.PhysEntity.draw(self, canvas)

    def get_frame(self):
        return self.frames[int(self.time % self.numframes)]

    def _halt(self, name, reporter, target):
        if reporter == self and not self.dying:
            remove = False
            if isinstance(target, lasercannon.Lasercannon):
                target.take_dmg(10)
                self.dying = True
                remove = True
            if isinstance(target, enemy.Enemy):
                target.take_dmg(10)
                self.dying = True
                remove = True
            if isinstance(target, waterlock.WaterLock):
                target.take_dmg(10)
                self.dying = True
                remove = True
            if isinstance(target, obstacle.Obstacle):
                self.dying = True
                remove = True
            if remove:
                self.xvel = 0
                self.yvel = 0
                if self.c == color.GREEN:
                    self.frames = sheethelper.load_frames(
                        "../Images/sparks_green.png", 4, 0, 0,
                        64, 64)
                else:
                    self.frames = sheethelper.load_frames(
                        "../Images/sparks.png", 4, 0, 0,
                        64, 64)
                self.numframes = 4
                self.xpos -= 32
                self.ypos -= 32


# driver.py

from signal import *
import time
from multiprocessing import Process,Value
import os

driver_pid = Value('i', 0)
seller_pid = Value('i', 0)

def driver_handler(sig,frame):

    if sig == SIGUSR1:
        print("Bus start")
    elif sig == SIGUSR2:
        print("speed over limit")
    elif sig == SIGTSTP:
        os.kill(seller_pid.value,SIGUSR1)

def seller_handler(sig,frame):

    if sig == SIGINT:
        os.kill(driver_pid.value,SIGUSR1)
    elif sig == SIGQUIT:
        os.kill(driver_pid.value,SIGUSR2)
    elif sig == SIGUSR1:
        print("arrived the station")

def driver():
    driver_pid.value = os.getpid()
    print(os.getpid())
    print(driver_pid.value)
    time.sleep(0.5)
    signal(SIGTSTP,driver_handler)
    signal(SIGUSR1,driver_handler)
    signal(SIGUSR2,driver_handler)
    signal(SIGINT,SIG_IGN)
    signal(SIGQUIT,SIG_IGN)
    while True:
        pass

def ticket_seller():
    seller_pid.value = os.getpid()
    print(os.getpid())
    print(seller_pid.value)
    time.sleep(0.5)
    signal(SIGINT,seller_handler)
    signal(SIGQUIT,seller_handler)
    signal(SIGUSR1,seller_handler)
    signal(SIGTSTP,SIG_IGN)
    while True:
        pass

signal(SIGTSTP,SIG_IGN)
signal(SIGINT,SIG_IGN)
signal(SIGQUIT,SIG_IGN)

p1 = Process(target = driver)
p2 = Process(target = ticket_seller)
p1.start()
p2.start()
p1.join()
p2.join()


# -*- coding: utf-8 -*-
"""
Created on Sun Mar 29 09:47:39 2020

@author: zhenyu
"""
import numpy as np
import matplotlib.pyplot as plt
from enum import Enum
import math
import copy

class Integer():#用来计算积分的类
    def __init__(self,a1,a2,b2,b1,b0,step =math.pow(10,-4)):#math.pow(10,-3)

        self.a2 = a2#上界
        self.a1 = a1#下界
        self.step = step#步长

        #函数系数
        self.b0 = b0
        self.b1 = b1
        self.b2 = b2

        self.n = math.floor((self.a2 - self.a1)/self.step)#n个完整的直角梯形
        self.s = 0#积分结果

    def func(self,x):#函数
        return self.b2*math.pow(x,2) + self.b1*x + self.b0

    def discreNum(self,k):#第k个离散数
        return self.a1 + self.step * k

    def calculate(self):
        i = 0
        for i in range(self.n):#遍历所有完整的小直角梯形
            self.s += 0.5 * self.step * (self.func(self.discreNum(i)) + self.func(self.discreNum(i + 1)))
            #self.s += self.step * self.func(self.discreNum(i ))
        #self.s +=  0.5*(self.a2 - self.a1 - self.step * self.n) * (self.func(self.discreNum(i + 1)) + self.func(self.a2))#加上不完整的直角梯形

        #print("被积函数为：{0}x^2 + {1}x + {2}".format(self.b2,self.b1,self.b0))
        #print("积分下限为：{0}，积分上限为：{1}".format(self.a1,self.a2))
        #print("步长为：{0}，积分结果为：{1}".format(self.step,self.s))
        #print()
        return self.s

class Lv(Enum):
    NB = 0
    NM = 1
    NS = 2
    ZO = 3
    PS = 4
    PM = 5
    PB = 6

class Rule():#规则类
    def __init__(self,Lv_E,Lv_EC,Lv_dKp,Lv_dKi,Lv_dKd):#对规则的描述
        self.Lv_E = Lv_E
        self.Lv_EC = Lv_EC
        self.Lv_dKp = Lv_dKp
        self.Lv_dKi = Lv_dKi
        self.Lv_dKd = Lv_dKd

    def calcMsv(self,e,ec,E,EC):#calculate Membership Value计算隶属度值，并取最小值

         E_ms = E.msSet[self.Lv_E.name]#E的某个模糊子集
         EC_ms = EC.msSet[self.Lv_EC.name]#EC的某个模糊子集

         #输入对E和EC的适配度
         a1 = E_ms.calc(e)
         a2 = EC_ms.calc(ec)

         #返回最小值
         if (a1 >= a2):
             return a2
         else:
             return a1

    def compare(self,x,c1,c2,maxflag):#比较一个区间内两个一次函数的大小

        a1 = c1[0]*x + c1[1]
        a2 = c2[0]*x + c2[1]
        if(a1>a2):
            if (maxflag == True):
                return c1
            else:
                return c2
        elif(a1 == a2):
            return -1

        else:
            if (maxflag == True):
                return c2
            else:
                return c1

    def whichregion(self,x,points):#给定输入，返回输入所在的区间
        if (x < points[0] or x > points[-1]):
            return -1
        elif (x == points[0]):
            return 0
        else:
            for p in points:
                if(x <= p):
                    return points.index(p)-1

    def cutTop(self,ms,a):#削顶运算,参数为一个模糊子集和一个适配度

        cutTopPoints = []#削顶后的分段点
        cutTopCoefficient = []#削顶后的函数系数

        for p  in  ms.points:#加入隶属函数的分段点
            cutTopPoints.append(p)
        for i in range (len(ms.coefficient)):#加入切割线与隶属函数的交点
            k = ms.coefficient[i][0]
            b = ms.coefficient[i][1]
            cross = (a-b)/k
            cutTopPoints.append(cross)
        cutTopPoints = list(set(cutTopPoints))
        cutTopPoints.sort()

        for i in range(len(cutTopPoints)-1):
            region = [cutTopPoints[i],cutTopPoints[i+1]]
            c1 = [0,a]
            x = (region[0] + region[1])/2
            num = self.whichregion(x,ms.points)
            c2 = ms.coefficient[num]

            coeff = self.compare(x,c1,c2,False)

            cutTopCoefficient.append(copy.deepcopy(coeff))

        return cutTopPoints,cutTopCoefficient

    def get_outms(self,dKp,dKi,dKd):#得到输出的模糊子集
        dKp_ms = dKp.msSet[self.Lv_dKp.name]#dKp的某个模糊子集
        dKi_ms = dKi.msSet[self.Lv_dKi.name]#dKi的某个模糊子集
        dKd_ms = dKd.msSet[self.Lv_dKd.name]#dKd的某个模糊子集
        return dKp_ms,dKi_ms,dKd_ms

    def  integrate(self,p1,p2,c1,c2):#将削顶后的图形合成

        integratePoints = []   #所有规则合成后的分段点
        integrateCoefficient = [] #所有规则合成后的函数参数
        tempPoints = [] #临时的分段点

        for p in p1:
            tempPoints.append(p)
        for p in p2:
            tempPoints.append(p)

        tempPoints = list(set(tempPoints))
        tempPoints.sort()

        for p in tempPoints:#将临时分段点加入
            integratePoints.append(p)

        for i in range(len(tempPoints) - 1):

            x1 = tempPoints[i]#第一个输入
            x2 = tempPoints[i+1]#第二个输入

            num2_1 = self.whichregion(x2,p1)#第二个输入在第一个图形的哪个区间
            if num2_1 == -1:
                c2_1 = [0,0]
            else:
                c2_1 = c1[num2_1]#对应区间的函数参数

            num2_2 = self.whichregion(x2,p2)#第二个输入在第二个图形的哪个区间
            if num2_2 == -1:
                c2_2 = [0,0]
            else:
                c2_2 = c2[num2_2]#对应区间的函数参数

            result1 = self.compare(x1,c2_1,c2_2,True)
            result2 = self.compare(x2,c2_1,c2_2,True)

            if(result1 == result2):#在两点之间无交叉
                if result1 == -1:#两线重合
                    integrateCoefficient.append(copy.deepcopy(c2_1))
                else:#两线平行
                    integrateCoefficient.append(copy.deepcopy(result1))
            elif result1 == -1:#端点相等
                integrateCoefficient.append(copy.deepcopy(result2))
            elif result2 == -1:#端点相等
                integrateCoefficient.append(copy.deepcopy(result1))

            else:#两点之间有交叉
                cross = (c2_2[1] - c2_1[1])/(c2_1[0] - c2_2[0])
                integratePoints.append(cross)
                new_result1 =  self.compare((cross+tempPoints[i])/2,c2_1,c2_2,True)
                new_result2 =  self.compare((cross+tempPoints[i+1])/2,c2_1,c2_2,True)
                integrateCoefficient.append(copy.deepcopy(new_result1))
                integrateCoefficient.append(copy.deepcopy(new_result2))

        integratePoints = list(set(integratePoints))
        integratePoints.sort()
        return integratePoints,integrateCoefficient

    def draw(self,points,coefficient,color = 'b'):
        drawpoints = []
        for i in range(len(points)-1):
            drawpoints.append([points[i],points[i+1]])

        for i in range (len(drawpoints)):
            x = np.linspace(drawpoints[i][0],drawpoints[i][1],100)
            y = coefficient[i][0]*x + coefficient[i][1]
            plt.plot(x,y,color,linewidth=2, markersize=2)

        #plt.legend(loc = "best")
        plt.show()

class Var():#变量类
    def __init__(self,universe):
        self.universe = universe#变量的论域
        self.name = ["NB","NM","NS","ZO","PS","PM","PB"]#模糊子集的名称
        self.msSet ={}#模糊子集的集合
        for i in range (7):#创建七个模糊子集,并存入字典msSet中
            self.msSet[self.name[i]] = Ms(-universe + (i - 1) * universe/3,-universe
                      + i * universe/3,-universe + (i + 1) * universe/3,universe)

class Ms():#模糊子集类
    def __init__(self,a,b,c,universe):

        #三角形三个参数
        self.a = a
        self.b = b
        self.c = c

        #论域范围
        self.universe = universe

        #函数分段点,及其函数解析式
        if(self.a < -self.universe):#NB
            self.points = [self.b,self.c]#分段点
            self.drawpoints =[[self.b,self.c]]#画图用的分段点
            self.coefficient =[[1/(b-c),-c/(b-c)]]#函数系数
        elif(self.c > self.universe):#PB
            self.points = [self.a,self.b]
            self.drawpoints =[[self.a,self.b]]
            self.coefficient =[[1/(b-a),-a/(b-a)]]
        else:#除去两端的一般情况
            self.points = [self.a,self.b,self.c]
            self.drawpoints =[[self.a,self.b],[self.b,self.c]]
            self.coefficient =[[1/(b-a),-a/(b-a)],[1/(b-c),-c/(b-c)]]

    def calc(self,x):#计算隶属度
        isflag = -1#标志输入变量属于哪个区间
        for i in range(len(self.drawpoints)):
            if (x>=self.drawpoints[i][0] and x<=self.drawpoints[i][1]):#如果在第i个区间
                isflag = i
                break

        if (isflag == -1):#不属于任何区间，即隶属度为零
            return 0
        else :
            return self.coefficient[isflag][0]*x + self.coefficient[isflag][1]

    def draw(self):#绘出隶属度图像
        for i in range (len(self.drawpoints)):
            x = np.linspace(self.drawpoints[i][0],self.drawpoints[i][1],100)
            y = self.coefficient[i][0]*x + self.coefficient[i][1]
            plt.plot(x,y,'bo',linewidth=2, markersize=2)

        plt.legend(loc = "best")

def fis(e,ec,E,EC,rule,dKp,dKi,dKd):#推理得到一条规则的三个输出

    a = rule.calcMsv(e,ec,E,EC)#最小适配度

    dKp_ms,dKi_ms,dKd_ms = rule.get_outms(dKp,dKi,dKd)#输出的模糊子集

    p1,c1 = rule.cutTop(dKp_ms,a)#dKp的削顶后的隶属函数
    #rule1.draw(p1,c1)

    p2,c2 = rule.cutTop(dKi_ms,a)#dKi的削顶后的隶属函数
    #rule1.draw(p2,c2)

    p3,c3 = rule.cutTop(dKd_ms,a)#dKd的削顶后的隶属函数
    #rule1.draw(p3,c3)

    return p1,c1,p2,c2,p3,c3

def defuzzy(points,coefficient):#解模糊
    myregions = []
    myup = copy.deepcopy(coefficient)
    mydown = copy.deepcopy(coefficient)
    length = len(points)-1
    for m in range(length):
        myregions.append([points[m],points[m+1]])#积分上下界
    for m in range(length):
        myup[m].append(0)#分子
        mydown[m].insert(0,0)#分母
    #print("myup is:{}".format(myup))
    #print("mydown is:{}".format(mydown))
    #print("myregions is:{}".format(myregions))

    upvalue = 0#分子值
    downvalue = 0#分母值

    for i in range(len(points)-1):
        try:

            integer1 = Integer(myregions[i][0], myregions[i][1], myup[i][0],myup[i][1], myup[i][2])
            upvalue += integer1.calculate()

            integer2= Integer(myregions[i][0], myregions[i][1], mydown[i][0],mydown[i][1], mydown[i][2])
            downvalue += integer2.calculate()
        except:
            print("积分异常")

    return upvalue/downvalue#合成后图形重心的横坐标

def  fuzzyControl(e,ec,Kx,all_virs,rulesNum = 49):
    #得到单个规则的输出
    for i in range(1,rulesNum + 1):
        all_virs["output"+str(i)] = fis(e,ec,E,EC,all_virs["rule"+str(i)],dKp,dKi,dKd)

    stylelist = ["dKp","dKi","dKd"]
    Kx = Kx#0,1,2分别代表PID
    #所有规则的输出合成
    temp_p = output1[2*Kx]
    temp_c = output1[2*Kx + 1]

    for i in range(2,rulesNum + 1):
        temp_p,temp_c = rule1.integrate(temp_p,all_virs["output"+str(i)][2*Kx],temp_c,all_virs["output"+str(i)][2*Kx + 1])

    rule1.draw(temp_p,temp_c)

    #print("temp_p is:{}".format(temp_p))
    #print("temp_c is:{}".format(temp_c))
    u = defuzzy(temp_p,temp_c)  #解模糊
    print("{0}={1}".format(stylelist[Kx],u))

if __name__ =="__main__":

    #添加输入输出变量
    E = Var(6)
    EC = Var(6)
    dKp = Var(3)
    dKi = Var(3)
    dKd = Var(3)

    #建立模糊规则
    rule1 = Rule(Lv.NB,Lv.NB,Lv.PB,Lv.NB,Lv.PS)
    rule2 = Rule(Lv.NB,Lv.NM,Lv.PB,Lv.NB,Lv.NS)
    rule3 = Rule(Lv.NB,Lv.NS,Lv.PM,Lv.NM,Lv.NB)
    rule4 = Rule(Lv.NB,Lv.ZO,Lv.PM,Lv.NM,Lv.NB)
    rule5 = Rule(Lv.NB,Lv.PS,Lv.PS,Lv.NS,Lv.NB)
    rule6 = Rule(Lv.NB,Lv.PM,Lv.ZO,Lv.ZO,Lv.NM)
    rule7 = Rule(Lv.NB,Lv.PB,Lv.ZO,Lv.ZO,Lv.PS)

    rule8 = Rule(Lv.NM,Lv.NB,Lv.PB,Lv.NB,Lv.PS)
    rule9 = Rule(Lv.NM,Lv.NM,Lv.PB,Lv.NB,Lv.NS)
    rule10 = Rule(Lv.NM,Lv.NS,Lv.PM,Lv.NM,Lv.NB)
    rule11 = Rule(Lv.NM,Lv.ZO,Lv.PS,Lv.NS,Lv.NM)
    rule12 = Rule(Lv.NM,Lv.PS,Lv.PS,Lv.NS,Lv.NM)
    rule13 = Rule(Lv.NM,Lv.PM,Lv.ZO,Lv.ZO,Lv.NS)
    rule14 = Rule(Lv.NM,Lv.PB,Lv.NS,Lv.PS,Lv.ZO)

    rule15 = Rule(Lv.NS,Lv.NB,Lv.PM,Lv.NB,Lv.ZO)
    rule16 = Rule(Lv.NS,Lv.NM,Lv.PM,Lv.NM,Lv.NS)
    rule17 = Rule(Lv.NS,Lv.NS,Lv.PM,Lv.NS,Lv.NM)
    rule18 = Rule(Lv.NS,Lv.ZO,Lv.PS,Lv.NS,Lv.NM)
    rule19 = Rule(Lv.NS,Lv.PS,Lv.ZO,Lv.ZO,Lv.NS)
    rule20 = Rule(Lv.NS,Lv.PM,Lv.NS,Lv.PM,Lv.NS)
    rule21 = Rule(Lv.NS,Lv.PB,Lv.NS,Lv.PM,Lv.ZO)

    rule22 = Rule(Lv.ZO,Lv.NB,Lv.PM,Lv.NM,Lv.ZO)
    rule23 = Rule(Lv.ZO,Lv.NM,Lv.PM,Lv.NM,Lv.NS)
    rule24 = Rule(Lv.ZO,Lv.NS,Lv.PS,Lv.NS,Lv.NS)
    rule25 = Rule(Lv.ZO,Lv.ZO,Lv.ZO,Lv.ZO,Lv.NS)
    rule26 = Rule(Lv.ZO,Lv.PS,Lv.NS,Lv.PS,Lv.NS)
    rule27 = Rule(Lv.ZO,Lv.PM,Lv.NM,Lv.PM,Lv.NS)
    rule28 = Rule(Lv.ZO,Lv.PB,Lv.NM,Lv.PM,Lv.ZO)

    rule29 = Rule(Lv.PS,Lv.NB,Lv.PS,Lv.NM,Lv.ZO)
    rule30 = Rule(Lv.PS,Lv.NM,Lv.PS,Lv.NS,Lv.ZO)
    rule31 = Rule(Lv.PS,Lv.NS,Lv.ZO,Lv.ZO,Lv.ZO)
    rule32 = Rule(Lv.PS,Lv.ZO,Lv.NS,Lv.PS,Lv.ZO)
    rule33 = Rule(Lv.PS,Lv.PS,Lv.NS,Lv.PS,Lv.ZO)
    rule34 = Rule(Lv.PS,Lv.PM,Lv.NM,Lv.PM,Lv.ZO)
    rule35 = Rule(Lv.PS,Lv.PB,Lv.NM,Lv.PB,Lv.ZO)

    rule36 = Rule(Lv.PM,Lv.NB,Lv.PS,Lv.ZO,Lv.PB)
    rule37 = Rule(Lv.PM,Lv.NM,Lv.ZO,Lv.ZO,Lv.PM)
    rule38 = Rule(Lv.PM,Lv.NS,Lv.NS,Lv.PS,Lv.PM)
    rule39 = Rule(Lv.PM,Lv.ZO,Lv.NM,Lv.PS,Lv.PM)
    rule40 = Rule(Lv.PM,Lv.PS,Lv.NM,Lv.PM,Lv.PS)
    rule41 = Rule(Lv.PM,Lv.PM,Lv.NM,Lv.PB,Lv.PS)
    rule42 = Rule(Lv.PM,Lv.PB,Lv.NB,Lv.PB,Lv.PB)

    rule43 = Rule(Lv.PB,Lv.NB,Lv.ZO,Lv.ZO,Lv.PB)
    rule44 = Rule(Lv.PB,Lv.NM,Lv.ZO,Lv.ZO,Lv.PM)
    rule45 = Rule(Lv.PB,Lv.NS,Lv.NM,Lv.PS,Lv.PM)
    rule46 = Rule(Lv.PB,Lv.ZO,Lv.NM,Lv.PM,Lv.PM)
    rule47 = Rule(Lv.PB,Lv.PS,Lv.NM,Lv.PM,Lv.PS)
    rule48 = Rule(Lv.PB,Lv.PM,Lv.NB,Lv.PB,Lv.PS)
    rule49 = Rule(Lv.PB,Lv.PB,Lv.NB,Lv.PB,Lv.PB)

    #给定输入
    input1 = -5#E[-6,6]
    input2 = -3#EC[-6,6]

    all_virs=locals()#所有变量的字典

    #进行模糊推理、解模糊，并打印出结果，参数为e,ec,Kx
    fuzzyControl(input1,input2,0,all_virs)#dKp
    fuzzyControl(input1,input2,1,all_virs)#dKi
    fuzzyControl(input1,input2,2,all_virs)#dKd


# https://plum-poppy-0ea.notion.site/Dice-Roller-faf046ef3f4b4ce2800d210cf13183ab
from random import randint

num_dice = int(input("How many dice are we rolling? " ))
num_sides = int(input("How many sides on each die? " ))

while True:
    result = "|"
    for die in range(num_dice):
        rand = randint(1,num_sides)
        result += f"{rand}|"
    print(result)
    again = input("Roll again? ('q' to quit) ")
    if again == "q":
        break


from osv import osv, fields
from tools.translate import _

class valid_stock_moves(osv.osv):
    """View that filter stock_moves by not state = 'cancel' Use this view to show traceability tree"""
    _name = "valid.stock.moves"
    _auto = False

    def _get_simplified_trace_up(self, cr, uid, ids, field_name, arg, context):
        """get the last childs moves for a specific move"""
        res = {}
        for move in self.browse(cr, uid, ids):
            cr.execute("select id from stock_move_parents(%s)", (move.id,))
            records = []
            for record in cr.fetchall():
                records.append(record[0])
            if records[0] in ids:
                res[move.id] = []
            else:
                res[move.id] = records
        return res

    def _get_simplified_trace_down(self, cr, uid, ids, field_name, arg, context):
        """get the top parents moves for a specific move"""
        res = {}
        for move in self.browse(cr, uid, ids):
            cr.execute("select id from stock_move_childs(%s)", (move.id,))
            records = []
            for record in cr.fetchall():
                records.append(record[0])
            if records[0] in ids:
                res[move.id] = []
            else:
                res[move.id] = records
        return res

    def _get_move_type(self, cr, uid, ids, field_name, arg, context = {}):
        """get the type of move for do more accessibly traceability tree"""
        return self.pool.get('stock.move').get_move_type(cr, uid, ids, context=context)

    _columns = {
            'id': fields.integer('id', readonly=True),
            'name': fields.char('Name', size=64, readonly=True, select=True),
            'product_id': fields.many2one('product.product', 'Product', readonly=True, select=True),
            'product_qty': fields.float('Quantity', readonly=True),
            'product_uom': fields.many2one('product.uom', 'Product UOM', readonly=True, select=True),
            'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot', readonly=True, select=True),
            'expiry_date': fields.datetime('Expiry Date', readonly=True),
            'supplier': fields.char('Supplier', size=64, readonly=True),
            'tracking_id': fields.many2one('stock.tracking', 'Pack', select=True, readonly=True),
            'product_packaging': fields.many2one('product.packaging', 'Packaging', readonly=True, select=True),
            'picking_id': fields.many2one('stock.picking', 'Packing List', readonly=True, select=True),
            'location_id': fields.many2one('stock.location', 'Location', readonly=True, select=True),
            'location_dest_id': fields.many2one('stock.location', 'Dest. Location', readonly=True, select=True),
            'date': fields.datetime('Date Created', readonly=True),
            'date_expected': fields.datetime('Date', readonly=True),
            'state': fields.selection([('draft', 'Draft'), ('waiting', 'Waiting'), ('confirmed', 'Not Available'), ('assigned', 'Available'), ('done', 'Done'), ('cancel', 'Cancelled')],'State', size=12, readonly=True),
            'move_history_simplified_up': fields.function(_get_simplified_trace_up, method=True, relation='stock.move', type="many2many", string='Traceability simplified upstream'),
            'move_history_simplified_down': fields.function(_get_simplified_trace_down, method=True, relation='stock.move', type="many2many", string='Traceability simplified downstream'),
            'move_history_ids': fields.many2many('stock.move', 'stock_move_history_ids', 'parent_id', 'child_id', 'Move History'),
            'move_history_ids2': fields.many2many('stock.move', 'stock_move_history_ids', 'child_id', 'parent_id', 'Move History'),
            'move_type': fields.function(_get_move_type, method=True, string='Type', type="char", size=24, readonly=True),
            'production_id': fields.many2one('mrp.production', 'Production', readonly=True, select=True)
    }

    def init(self, cr):
        """creates view when install"""
        cr.execute("""
            create or replace view valid_stock_moves as (
                select stock_move.id as id,stock_move.name as name,stock_move.product_id as product_id,product_qty,product_uom,prodlot_id,stock_production_lot.life_date as expiry_date,
                    supplier,tracking_id,product_packaging,picking_id,location_id,location_dest_id,stock_move.date as date,
                    date_expected,state,production_id
                from stock_move left join stock_production_lot on stock_move.prodlot_id = stock_production_lot.id
                where state not in ('cancel')
            )""")

    def unlink(self, cr, uid, ids, context={}):
        """not can delete, beacause is database view"""
        raise osv.except_osv(_('Error !'), _('You cannot delete any record!'))

valid_stock_moves()


# (c) 2009, 2012, 2015, 2017 Tim Sawyer, All Rights Reserved

from django.urls import re_path
#from django.contrib.sitemaps.views import sitemap

#from bands.sitemap import BandSitemap

from . import views

#sitemaps = {
#  'bands' : BandSitemap,
#}

urlpatterns = [
    re_path(r'^$', views.bands_list),
  #  re_path(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
    re_path(r'^add/$', views.add_band),
    re_path(r'^options/$', views.band_options),
    re_path(r'^edit/([-\w]+)/$', views.edit_band),
    re_path(r'^winners/$', views.contest_winners),
    re_path(r'^([A-Z0]+)/$', views.bands_list),
    re_path(r'^([\w\-]+)/$', views.single_band),
    re_path(r'^([\w\-]+)/delete/$', views.delete_single_band),
    re_path(r'^([\w\-]+)/aliases/$', views.single_band_aliases),
    re_path(r'^([\w\-]+)/aliases/(\d+)/show/$', views.single_band_alias_show),
    re_path(r'^([\w\-]+)/aliases/(\d+)/hide/$', views.single_band_alias_hide),
    re_path(r'^([\w\-]+)/aliases/(\d+)/delete/$',views.single_band_alias_delete),
    re_path(r'^([\w\-]+)/WhitFridayConductors/$', views.update_whit_friday_conductors),
    re_path(r'^([\w\-]+)/talk/$', views.talk),
    re_path(r'^([\w\-]+)/talk/edit/$', views.talk_edit),
    re_path(r'^([\w\-]+)/embed/$', views.band_results_embed),
    re_path(r'^([\w\-]+)/csv/$', views.band_results_csv),
    re_path(r'^chartdata/([\w\-]+)/$', views.chart_json),
    re_path(r'^chartdata/([\w\-]+)/([a-z0-9\-]+)/$', views.chart_json_filter),
    re_path(r'^chartdata/([\w\-]+)/([A-Z0-9\-]+)/$', views.chart_json_filter_group),
    re_path(r'^([\w\-]+)/tag/([A-Za-z0-9\-]+)/$', views.single_band_filter_tag),
    re_path(r'^([\w\-]+)/([a-z0-9\-]+)/$', views.single_band_filter),
    re_path(r'^([\w\-]+)/([A-Z0-9\-]+)/$', views.single_band_filter_group),
]


#!/usr/bin/env python3
import fileinput
import string
from collections import Counter

## count_three_word_seqs(): Reads text from files specified by command line arguments or from
## stdin and constructs a Counter object of all three word sequences.
# Input: optional parameter for specifying files outside the command line
# Returns: Counter object in the form {('one', 'two', 'three'):53, ('by', 'the', 'way'):33}
def count_three_word_seqs(files_str=None):
    seqs_count = Counter()

    # Read each line of text from files specifed or stdin, ignore case and punctuation
    with fileinput.input(files=files_str) as f:
        words = (word
                    for line in f
                        for word in
                            line.translate(str.maketrans("", "", string.punctuation)).lower().split())

        # Try to get the first three words if there are three
        try:
            word1, word2, word3 = next(words), next(words), next(words)
        except StopIteration:
            return seqs_count

        # Get and count every three word sequence
        for next_word in words:
            seqs_count.update({(word1, word2, word3)})
            word1 = word2
            word2 = word3
            word3 = next_word
        # Capture the last sequence (or only sequence if the text contains only one)
        seqs_count.update({(word1, word2, word3)})

    return seqs_count

if __name__ == '__main__':
    seqs_count = count_three_word_seqs()

    # Print the 100 most common three word sequences in the text in the format "33 - by the way"
    for count_tuple in seqs_count.most_common(100):
        print(f"{count_tuple[1]} - {' '.join(count_tuple[0])}")


#!/usr/bin/env python3

# Created by: Matsuru Hoshi
# Created on: Sept 2019
# This is program area rect

def main():
    # funciton calculates area and pereimetn

    #input
    side = float(input("What is side dimension:"))
    side2 = float(input("What is other dimension:"))

    #process
    area = side * side2
    perimeter = 2 * (side + side2)

    #output
    print("\nThe area is " + str(round(area)) + " units squared")
    print("The perimeter is " + str(round(perimeter)) + " units")

if __name__ == "__main__":
    main()