operacion = ""
reset_Pantalla = False
resultado = 0

# ----funciones para pulsar los numero
def numPulsado(num):
    global operacion
    global reset_Pantalla
    if reset_Pantalla != False:
        numPantalla.set(num)
        reset_Pantalla = False
    else:
        numPantalla.set(numPantalla.get() + num)

# -------funciones----------------------

def suma(num):
    global operacion
    global resultado
    global reset_Pantalla
    resultado += int(num)
    operacion = "suma"
    reset_Pantalla = True
    numPantalla.set(resultado)

# def pulsarIgual():
#     global resultado
#     numPantalla.set(resultado+int(numPantalla.get()))
#     resultado = 0

num1 = 0

contador_resta = 0

def resta(num):
    global operacion
    global resultado
    global num1
    global contador_resta
    global reset_pantalla

    if contador_resta == 0:
        num1 = int(num)
        resultado = num1
    else:
        if contador_resta == 1:
            resultado = num1-int(num)
        else:
            resultado = int(resultado)-int(num)
        numPantalla.set(resultado)
        resultado = numPantalla.get()
    contador_resta = contador_resta+1
    operacion = "resta"
    reset_pantalla = True

contador_divi = 0

def divide(num):
    global operacion
    global resultado
    global num1
    global contador_divi
    global reset_pantalla
    if contador_divi == 0:
        num1 = float(num)
        resultado = num1
    else:
        if contador_divi == 1:
            resultado = num1/float(num)
        else:
            resultado = float(resultado)/float(num)
        numPantalla.set(resultado)
        resultado = numPantalla.get()
    contador_divi = contador_divi+1
    operacion = "division"
    reset_pantalla = True

contador_multi = 0

def multiplica(num):
    global operacion
    global resultado
    global num1
    global contador_multi
    global reset_pantalla
    if contador_multi == 0:
        num1 = int(num)
        resultado = num1
    else:
        if contador_multi == 1:
            resultado = num1*int(num)
        else:
            resultado = int(resultado)*int(num)
        numPantalla.set(resultado)
        resultado = numPantalla.get()
    contador_multi = contador_multi+1
    operacion = "multiplicacion"
    reset_pantalla = True

def pulsar_igual():
    global resultado
    global operacion
    global contador_resta
    global contador_multi
    global contador_divi
    if operacion == "suma":
        numPantalla.set(resultado+int(numPantalla.get()))
        resultado = 0
    elif operacion == "resta":
        numPantalla.set(int(resultado)-int(numPantalla.get()))
        resultado = 0
        contador_resta = 0
    elif operacion == "multiplicacion":
        numPantalla.set(int(resultado)*int(numPantalla.get()))
        resultado = 0
        contador_multi = 0
    elif operacion == "division":
        numPantalla.set(int(resultado)/int(numPantalla.get()))
        resultado = 0
        contador_divi = 0


#!/usr/bin/python3

from threading import Thread,Lock
import time
import xlsxwriter

num = 0
lock=Lock()
def nu1():
    global num
    for i in range(100000):
        lock.acquire()
        num+=1
        lock.release()
    print('nu1的值是：',num)
def nu2():
    global num
    for i in range(100000):
        lock.acquire()
        num+=1
        lock.release()
    print('nu2的值是：',num)

if __name__ == "__main__":
    print('开始运行')
    t1 = Thread(target=nu1)
    t2 = Thread(target=nu2)
    t1.start()
    t2.start()
    t1.join()
    t2.join()

# exitFlag = 0

# class myThread (threading.Thread):
#     def __init__(self, threadID, name, counter):
#         threading.Thread.__init__(self)
#         self.threadID = threadID
#         self.name = name
#         self.counter = counter
#     def run(self):
#         print ("开始线程：" + self.name)
#         print_time(self.name, self.counter, 5)
#         print ("退出线程：" + self.name)

# def print_time(threadName, delay, counter):
#     while counter:
#         if exitFlag:
#             threadName.exit()
#         time.sleep(delay)
#         print ("%s: %s" % (threadName, time.ctime(time.time())))
#         counter -= 1

# # 创建新线程
# thread1 = myThread(1, "Thread-1", 1)
# thread2 = myThread(2, "Thread-2", 2)

# # 开启新线程
# thread1.start()
# thread2.start()
# thread1.join()
# thread2.join()
# print ("退出主线程")


import os
import pickle
import time
import networkx as nx
import sys
sys.path.append("..")
from multiprocessing import Pool
from typing import Any, List, Union
from lib.run_innovation_process import *
from lib.utils import *
from lib.graph2metrics import Graph2Metrics
import matplotlib.pyplot as plt
from dataclasses import dataclass
from typing import List
import os
import csv

import numpy as np
import pandas as pd
import ribs.emitters as emitters
import ribs.schedulers as schedulers
from history2bd.main import History2BD
from ribs.archives import CVTArchive
from tqdm import tqdm

@dataclass
class Params:
    rho: float
    nu: float
    s: str
    gamma: float
    eta: float
    steps: int
    nodes: int = 100
    threads: int = 1

class QualityDiversitySearch:
    k: int
    l: int
    dv: int
    history2bd: History2BD
    thread_num: int = 8
    jl_main: Any =  None
    result_dir_path: str
    archives_dir_path: str
    iteration_num: int
    target: str

    def __init__(
        self,
        k: int,
        l: int,
        dv: int,
        history2bd: History2BD,
        iteration_num: int,
        thread_num: int,
        jl_main: Any,
        target: str,
        dim: int,
        cells: int,
        result_dir_path: str,
    ) -> None:
        self.k = k
        self.l = l
        self.dv = dv
        self.history2bd = history2bd
        self.iteration_num = iteration_num
        self.thread_num = thread_num
        self.jl_main = jl_main
        self.target = target
        self.dim = dim
        self.cells = cells
        self.result_dir_path = result_dir_path
        self.archives_dir_path = f"{self.result_dir_path}/archives"

        os.makedirs(self.archives_dir_path, exist_ok=True)

    def prepare_archive(self) -> CVTArchive:
        archive: Union[CVTArchive, None] = None
        if os.path.exists(f"{self.result_dir_path}/archive.pkl"):
            with open(f"{self.result_dir_path}/archive.pkl", "rb") as f:
                archive = pickle.load(f)
        else:
            archive = CVTArchive(
                solution_dim=2,
                cells=self.cells,
                ranges=[(-5, 5) for _ in range(self.dim)],
            )
        assert archive is not None, "archive should not be None!"
        return archive

    def save_archive(self, archive: CVTArchive, iter: int) -> pd.DataFrame:
        # save latest archive
        with open(f"{self.result_dir_path}/archive.pkl", "wb") as file:
            pickle.dump(archive, file)

        # save archive as csv
        df = archive.as_pandas()
        df.rename(
            columns={
                "solution_0": "rho",
                "solution_1": "nu"
            },
            inplace=True,
        )
        df["objective"] = -df["objective"]
        df.rename(columns={"objective": "NCTF"}, inplace=True)
        df = df[["rho", "nu", "NCTF"]].sort_values(by="NCTF", ascending=True)
        df.to_csv(f"{self.archives_dir_path}/{iter:0>8}.csv", index=False)
        return df

    def set_params_list(self, sols: List[np.ndarray]) -> List[Params]:
        rhos: List[int] = list(map(lambda sol: sol[0].item(), sols))
        nus: List[int] = list(map(lambda sol: sol[1].item(), sols))
        s: List[str] = ["asw" for _ in range(len(rhos))]
        gammas: List[float] = [0.5 for _ in range(len(rhos))]
        etas: List[float] = [0.5 for _ in range(len(rhos))]
        steps: List[int] = [9999999 for _ in range(len(rhos))]
        nodes: List[int] = [100 for _ in range(len(rhos))]
        threads: List[int] = [self.thread_num for _ in range(len(rhos))]

        params_list = list(map(
            lambda t: Params(*t),
            zip(rhos, nus, s, gammas, etas, steps, nodes, threads),
        ))
        return params_list

    def print_status(self, archive: CVTArchive, iter: int, start_time: time) -> None:
        elapsed_time = time.time() - start_time
        print(f"> {iter} iters completed after {elapsed_time:.2f} s")
        print(f"  - Archive Size: {len(archive)}")
        assert archive.stats is not None, "archive.stats is None!"
        print(f"  - Max Score: {archive.stats.obj_max}")

    def run(self):
        archive: Union[CVTArchive, None] = self.prepare_archive()

        already = 0
        if os.path.exists(self.archives_dir_path):
            already = len(os.listdir(self.archives_dir_path))

        initial_model = np.zeros(2)
        bounds = [
            (1, 5),
            (1, 30),
        ]
        emitters_ = [
            emitters.EvolutionStrategyEmitter(
                archive=archive,
                x0=initial_model,
                sigma0=1.0,
                bounds=bounds,
                ranker="2imp",
            )
            for _ in range(5)
        ]
        optimizer = schedulers.Scheduler(archive, emitters_)

        start_time = time.time()

        for iter in tqdm(range(already, self.iteration_num), desc=f"Innovation Search: {self.target}"):
            # Request models from the scheduler
            sols = optimizer.ask()

            params_list = self.set_params_list(sols)

            histories = self.jl_main.parallel_run_waves_model(params_list)

            bcs = self.history2bd.run(histories)
            objs = []

            for history in histories:
                renumbered_history = convert_tuples(history)
                G = nx.Graph()
                G.add_edges_from(renumbered_history)
                NCTF_list = []
                TTF_list = []
                for _ in range(100):
                    NCTF, TTF, failed = run_innovation_process(G, self.l, self.k, self.dv, 200)
                    NCTF_list.append(NCTF)
                    TTF_list.append(TTF)

                average_NCTF = sum(NCTF_list)/len(NCTF_list)
                average_TTF = sum(TTF_list)/len(TTF_list)

                if self.target == "min_NCTF":
                    obj: np.float64 = average_NCTF
                    objs.append(-obj)
                elif self.target == "max_NCTF":
                    obj: np.float64 = average_NCTF
                    objs.append(obj)
                elif self.target == "min_TTF":
                    obj: np.float64 = average_TTF
                    objs.append(-obj)
                elif self.target == "max_TTF":
                    obj: np.float64 = average_TTF
                    objs.append(obj)

            # Send the results back to the scheduler
            optimizer.tell(objs, bcs)

            # save archive
            df = self.save_archive(archive, iter)

            if iter % 25 == 0:
                self.print_status(archive, iter, start_time)

            # Filter the DataFrame where innovation failed
            # filtered_df = df[df['NCTF'] > -9999]
            # filtered_df.head(30).to_csv(f"{self.result_dir_path}/best.csv", index=False)
            df.head(30).to_csv(f"{self.result_dir_path}/optimal_parameters.csv", index=False)

    def analyse(self):
        optimal_parameter_set = pd.read_csv(f"{self.result_dir_path}/optimal_parameters.csv")

        for index, row in optimal_parameter_set.iterrows():
            history = self.jl_main.parallel_run_waves_model([Params(rho=row['rho'], nu=row['nu'], s="asw", gamma=0.5, eta=0.5, steps=1000000, nodes=100, threads=1)])[0]

            history_to_csv(history=history, location=f"{self.result_dir_path}/history/{index}.csv")
            graph = history_to_graph(csv_location=f"{self.result_dir_path}/history/{index}.csv")
            graph_to_json(graph, f"../webapp/src/data/{self.target}{index}.json")

            metrics = Graph2Metrics().graph2metrics(graph=graph)
            metrics_to_csv(metrics, f"{self.result_dir_path}/metrics/{index}.csv")

    def analyse_statistics(self):
        number_networks = 100
        number_simulations = 1000

        best_parameter_set = pd.read_csv(f"{self.result_dir_path}/best.csv").iloc[0]

        # Open a new csv file to write the NCTF scores, total_knowledge_history, and std_deviation_history
        with open(f"{self.result_dir_path}/best_nctf_scores.csv", 'w', newline='') as csvfile:
            csv_writer = csv.writer(csvfile)

            # Write header
            csv_writer.writerow(["nctf", "ttf","total_knowledge_history", "standard_deviation_history", "rho", "nu"])

            for _ in range(number_networks):
                for _ in range(number_simulations):
                    rho_value = int(best_parameter_set['rho'])
                    nu_value = int(best_parameter_set['nu'])
                    s_value = "asw"
                    gamma_value = 0.5
                    eta_value = 0.5
                    steps_value = 1000000
                    nodes_value = 100

                    raw_history = self.jl_main.run_waves_model(rho_value, nu_value, s_value, gamma_value, eta_value, steps=steps_value, nodes=nodes_value)[0].history
                    best_history = convert_tuples(raw_history)
                    G = history_object_to_graph(history=best_history)
                    nctf, ttf, failed, total_knowledge_history, std_deviation_history = run_innovation_process(G, self.l, self.k, self.dv, 200)

                    # Convert the histories to string format
                    total_knowledge_str = '|'.join(map(str, total_knowledge_history))
                    std_deviation_str = '|'.join(map(str, std_deviation_history))

                    # Write the NCTF, total_knowledge_str, and std_deviation_str to csv file
                    csv_writer.writerow([nctf, ttf, total_knowledge_str, std_deviation_str, rho_value, nu_value])

        print(f"NCTF scores saved to {self.result_dir_path}/best_nctf_scores.csv")


# Make Predictions with k-nearest neighbors on the dataset
from csv import reader

import numpy as np

import word_centroid

# Load a CSV file
def load_csv(filename):
    dataset = list()
    with open(filename, 'r') as file:
        csv_reader = reader(file)
        for row in csv_reader:
            if not row:
                continue
            dataset.append(row)
    return dataset

# Convert string column to float
def str_column_to_float(dataset, column):
    for row in dataset:
        wc = word_centroid.words_15
        row[column] = wc['word'].get(row[column])

def str_to_float(str):
    wc = word_centroid.words_15
    return wc['word'].get(str)

# Convert string column to integer
def str_column_to_int(dataset, column):
    class_values = [row[column] for row in dataset]
    unique = set(class_values)
    lookup = dict()
    for i, value in enumerate(unique):
        lookup[value] = i
        print('[%s] => %d' % (value, i))
    for row in dataset:
        row[column] = lookup[row[column]]
    return lookup

# Find the min and max values for each column
def dataset_minmax(dataset):
    minmax = list()
    for i in range(len(dataset[0])):
        col_values = [row[i] for row in dataset]
        value_min = min(col_values)
        value_max = max(col_values)
        minmax.append([value_min, value_max])
    return minmax

# Rescale dataset columns to the range 0-1
def normalize_dataset(dataset, minmax):
    for row in dataset:
        for i in range(len(row)):
            row[i] = (row[i] - minmax[i][0]) / (minmax[i][1] - minmax[i][0])

# Calculate the Minkowski distance between two vectors
def minkowski_distance(row1, row2, p):
    distance = 0.0
    for i in range(len(row1) - 1):
        distance += np.abs(row1[i] - row2[i]) ** p
    return distance ** (1 / p)

# Locate the most similar neighbors
def get_neighbors(train, test_row, num_neighbors):
    distances = list()
    for train_row in train:
        dist = minkowski_distance(test_row, train_row, 2)
        distances.append((train_row, dist))
    distances.sort(key=lambda tup: tup[1])
    neighbors = list()
    for i in range(num_neighbors):
        neighbors.append(distances[i][0])
    return neighbors

# Make a prediction with neighbors
def predict_classification(train, test_row, num_neighbors):
    neighbors = get_neighbors(train, test_row, num_neighbors)
    output_values = [row[-1] for row in neighbors]
    prediction = max(set(output_values), key=output_values.count)
    return prediction


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from collections import defaultdict
import argparse
import cv2
import glob
import logging
import requests
import os
import sys
import time
import json
import base64
import common
import io
import numpy as np
import gevent.monkey
gevent.monkey.patch_all()

from PIL import Image
from flask import Flask, jsonify, request
from flask_cors import CORS
from flask_socketio import SocketIO, emit
from scipy.misc import imresize

from caffe2.python import workspace

from detectron.core.config import assert_and_infer_cfg
from detectron.core.config import cfg
from detectron.core.config import merge_cfg_from_file
from detectron.utils.io import cache_url
from detectron.utils.logging import setup_logging
from detectron.utils.timer import Timer
import detectron.core.test_engine as infer_engine
import detectron.datasets.dummy_datasets as dummy_datasets
import detectron.utils.c2 as c2_utils

from itertools import permutations

c2_utils.import_detectron_ops()

logging.getLogger('socketio').setLevel(logging.ERROR)
logging.getLogger('engineio').setLevel(logging.ERROR)

# OpenCL may be enabled by default in OpenCV3; disable it because it's not
# thread safe and causes unwanted GPU memory allocations.
cv2.ocl.setUseOpenCL(False)

# Densepose args
cfg_file = 'configs/DensePose_ResNet50_FPN_s1x-e2e.yaml'
weights_file = 'weights/DensePose_ResNet50_FPN_s1x-e2e.pkl'
output_dir = 'DensePoseData/infer_out/'
image_ext = 'jpg'
im_or_folder = ''
workspace.GlobalInit(['caffe2', '--caffe2_log_level=0'])
setup_logging(__name__)
logger = logging.getLogger(__name__)
merge_cfg_from_file(cfg_file)
cfg.NUM_GPUS = 1
cfg.TEST.BBOX_AUG.ENABLED = False
cfg.MODEL.MASK_ON = False
cfg.MODEL.KEYPOINTS_ON = False

# weights = cache_url(args.weights, cfg.DOWNLOAD_CACHE)
assert_and_infer_cfg(cache_urls=False)
model = infer_engine.initialize_model_from_cfg(weights_file)
dummy_coco_dataset = dummy_datasets.get_coco_dataset()

# Server configs
PORT = 22100
app = Flask(__name__)
CORS(app)
#socketio = SocketIO(app)
# Pix2Pix server Configs
PUBLIC_IP = 'pix2pix'
PIX2PIX_PORT = '23100'
PIX2PIX_ROUTE = '/infer'
pix2pixURL = 'http://' + PUBLIC_IP + ':' + PIX2PIX_PORT + PIX2PIX_ROUTE

# Take in base64 string and return PIL image
def stringToImage(base64_string):
  imgdata = base64.b64decode(base64_string)
  return Image.open(io.BytesIO(imgdata))

# Convert PIL Image to an RGB image(technically a numpy array) that's compatible with opencv
def toRGB(image):
  return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

def process_image(input_image, num_of_people, num_of_permutations):
  timers = defaultdict(Timer)
  t = time.time()
  image = stringToImage(input_image[input_image.find(",")+1:])
  img = toRGB(image)
  size = img.shape[:2]
  with c2_utils.NamedCudaScope(0):
    cls_boxes, cls_segms, cls_keyps, cls_bodys = infer_engine.im_detect_all(
      model, img, None, timers=timers
    )

  t2 = time.time()

  #logger.info('Inference time: {:.3f}s'.format(t2 - t))
  jpgs = []

  if cls_bodys is not None:
    (finals,num_people) = process_bodies(img, cls_boxes, cls_bodys, num_of_people, num_of_permutations)
    logger.info('Num of people {}'.format(num_people))
    if len(finals) > 0:
        for final in finals:
            retval, buffer = cv2.imencode('.jpg', final)
            jpg_as_text = base64.b64encode(buffer)
            jpgs.append(jpg_as_text)
    else:
      print('Skipping')
  else:
    print('Skipping')

  return jpgs

def process_bodies(im, boxes, body_uv, num_of_people, num_of_permutations):
    if isinstance(boxes, list):
        box_list = [b for b in boxes if len(b) > 0]
        if len(box_list) > 0:
            boxes = np.concatenate(box_list)
        else:
            boxes = None

    IUV_fields = body_uv[1]
    #print("Shape of image {}".format(im.shape))
    K = 26

    inds = np.argsort(boxes[:,0])
    good_inds = inds[boxes[inds[:],4] >= 0.95]
    #print("Indexes {}".format(good_inds))

    good_size = np.full(good_inds.shape, True, dtype=bool)
    for i, ind in enumerate(good_inds):
        shape = IUV_fields[ind].shape
        #print("Shape {}".format(shape))
        good_size[i] = shape[2] >= 115

    #print("Shapes filter {}".format(good_size))
    real_good_inds = good_inds[good_size]
    num_people = len(real_good_inds)
    #print("Indexes {}".format(good_inds))

    print('Found {} people'.format(len(good_inds)))
    finals = []
    if len(real_good_inds) >= num_of_people:
        perms = list(set(permutations(real_good_inds, num_of_people)))
        np.random.shuffle(perms)
        if num_of_permutations > len(perms):
           num_of_permutations = len(perms)

        for i in range(num_of_permutations):
            good_inds = perms[i]
            print("Indexes {}".format(good_inds))

    #print("Chose random 4 {}".format(good_inds))

            Final = np.zeros([512,512, 3])
            current_offset = 0

            #np.random.shuffle(good_inds)
            #print("Good index {}".format(good_inds))

            one_body_width = int(512 / num_of_people)

            for i, ind in enumerate(good_inds):
                entry = boxes[ind,:]
                #print("Box position: {}, score: {}".format(entry[0],entry[4]))
                entry=entry[0:4].astype(int)
                ####
                output = IUV_fields[ind]
                ####
                ###
                CurrentMask = (output[0,:,:]>0).astype(np.float32)
                BlackMask = (output[0,:,:]==0)
                All_Coords = np.array(im[entry[1]:output.shape[1]+entry[1],entry[0]:output.shape[2]+entry[0],:])
                All_Coords[BlackMask] = 0
                All_Coords = All_Coords.astype(np.uint8)
                resize_ratio = one_body_width / output.shape[2]
                #print("Resize ratio {} ({})".format(resize_ratio, output.shape[2]))
                img = cv2.resize(All_Coords, (one_body_width,int(output.shape[1] * resize_ratio)))

                #cv2.imwrite(os.path.join(output_dir, 'person{}.png'.format(ind)), img)

                Final[128:img.shape[0]+128,current_offset:img.shape[1] + current_offset,:] = img[:(512-128),:,:]

                current_offset = current_offset + one_body_width

            finals.append(Final)

    return (finals, num_people)

# Main
def main(input_img, with_pix2pix = False):
  image = stringToImage(input_img[input_img.find(",")+1:])
  img = toRGB(image)
  logger.info('Processing {} -> {}'.format('New Image', 'Output...'))
  timers = defaultdict(Timer)
  t = time.time()
  size = img.shape[:2]
  with c2_utils.NamedCudaScope(0):
    cls_boxes, cls_segms, cls_keyps, cls_bodys = infer_engine.im_detect_all(
      model, img, None, timers=timers
    )
  for key, timer in timers.items():
    print(key, timer.total_time)
  t2 = time.time()
  r = vis_one_image(img, 'testImage', output_dir, cls_boxes, cls_segms, cls_keyps, cls_bodys, dataset=dummy_coco_dataset, box_alpha=0.3, show_class=True, thresh=0.7, kp_thresh=2)
  t3 = time.time()
  if with_pix2pix:
    r = requests.post(pix2pixURL, data = {'data': r})
  logger.info('Inference time: {:.3f}s'.format(t2 - t))
  logger.info('Visualization time: {:.3f}s'.format(t3 - t2))
  logger.info('Pix2pix time: {:.3f}s'.format(time.time() - t3))
  return r

# ---
# Server Routes
# ---

# Base route, functions a simple testing
@app.route('/')
def index():
  return jsonify(status="200", message='Densepose is running', infer_route='/infer')

@app.route('/infer', methods=['POST'])
def infer():
  print("Running infer")
  content = request.get_json(silent=True)
  results = main(content['data'], True)
  return jsonify(results=results.text)

@app.route('/pose', methods=['POST'])
def pose():
  print("Running pose!!")
  content = request.get_json(silent=True)
  num_of_people = content["numOfPeople"]
  num_of_permutations = content["numOfPermutations"]

  results = process_image(content["data"], num_of_people, num_of_permutations)
  return jsonify(results=results)

"""
# When a client socket connects
@socketio.on('connect', namespace='/query')
def new_connection():
  print('Client Connect')
  emit('successful_connection', {"data": "connection established"})

# When a client socket disconnects
@socketio.on('disconnect', namespace='/query')
def disconnect():
  print('Client Disconnect')

# When a client sends data. This should call the main() function
@socketio.on('get_pose', namespace='/query')
def new_request(request):
  results = main(request["data"], False)
  emit('pose_update', {"results": results})

# When a client sends data. This should call the main() function
@socketio.on('update_request', namespace='/query')
def new_request(request):
  results = main(request["data"], True)
  emit('update_response', {"results": results.text})
"""

#if __name__ == '__main__':
#  socketio.run(app, host='0.0.0.0', port=PORT, debug=False)


#!/usr/bin/env python3
import sys
import os
import re

fileName = sys.argv[1]
f = open(fileName, "r", encoding = 'utf8', errors='ignore')
chars = re.compile('[1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]')

line = f.readline()
line = line.strip()
while line :
    line = line.strip()
    if (chars.search(line) != None) :
        print(line)
    line = f.readline()


import torch
import torch.nn as nn

class InverseMultiStageVectorQuantization(nn.Module):
    """See `this page <https://sp-nitech.github.io/sptk/latest/main/imsvq.html>`_
    for details.

    """

    def __init__(self):
        super(InverseMultiStageVectorQuantization, self).__init__()

    def forward(self, indices, codebooks):
        """Perform inverse residual vector quantization.

        Parameters
        ----------
        indices : Tensor [shape=(..., Q)]
            Codebook indices.

        codebooks : Tensor [shape=(Q, K, M+1)]
            Codebooks.

        Returns
        -------
        xq : Tensor [shape=(..., M+1)]
            Quantized vectors.

        Examples
        --------
        >>> msvq = diffsptk.MultiStageVectorQuantization(4, 3, 2)
        >>> imsvq = diffsptk.InverseMultiStageVectorQuantization()
        >>> indices = torch.tensor([[0, 1], [1, 0]])
        >>> xq = imsvq(indices, msvq.codebooks)
        >>> xq
        tensor([[-0.8029, -0.1674,  0.5697,  0.9734,  0.1920],
                [ 0.0720, -1.0491, -0.4491, -0.2043, -0.3582]])

        """
        target_shape = list(indices.shape[:-1])
        target_shape.append(codebooks.size(-1))
        xq = 0
        for i in range(indices.size(-1)):
            code_vector = torch.index_select(
                codebooks[i], 0, indices[..., i].view(-1).long()
            )
            xq = xq + code_vector
        xq = xq.view(target_shape)
        return xq


# -*- coding: utf-8 -*-
"""Submitting render job to RoyalRender."""
import os

from maya.OpenMaya import MGlobal

from openpype.modules.royalrender import lib
from openpype.pipeline.farm.tools import iter_expected_files

class CreateMayaRoyalRenderJob(lib.BaseCreateRoyalRenderJob):
    label = "Create Maya Render job in RR"
    hosts = ["maya"]
    families = ["renderlayer"]

    def update_job_with_host_specific(self, instance, job):
        job.Software = "Maya"
        job.Version = "{0:.2f}".format(MGlobal.apiVersion() / 10000)
        if instance.data.get("cameras"):
            job.Camera = instance.data["cameras"][0].replace("'", '"')
        workspace = instance.context.data["workspaceDir"]
        job.SceneDatabaseDir = workspace

        return job

    def process(self, instance):
        """Plugin entry point."""
        super(CreateMayaRoyalRenderJob, self).process(instance)

        expected_files = instance.data["expectedFiles"]
        first_file_path = next(iter_expected_files(expected_files))
        output_dir = os.path.dirname(first_file_path)
        instance.data["outputDir"] = output_dir

        layer = instance.data["setMembers"]  # type: str
        layer_name = layer.removeprefix("rs_")

        job = self.get_job(instance, self.scene_path, first_file_path,
                           layer_name)
        job = self.update_job_with_host_specific(instance, job)

        instance.data["rrJobs"].append(job)


#! /usr/bin/env python

from __future__ import print_function

import argparse
import sys
import math
import rospy

from swarmie_msgs.msg import Obstacle
from geometry_msgs.msg import Pose2D, Point

from mobility.swarmie import swarmie

def dumb_square(distance):
    swarmie.drive(distance, ignore=Obstacle.IS_VISION)
    swarmie.turn(math.pi/2, ignore=Obstacle.IS_VISION)

    swarmie.drive(distance, ignore=Obstacle.IS_VISION)
    swarmie.turn(math.pi/2, ignore=Obstacle.IS_VISION)

    swarmie.drive(distance, ignore=Obstacle.IS_VISION)
    swarmie.turn(math.pi/2, ignore=Obstacle.IS_VISION)

    swarmie.drive(distance, ignore=Obstacle.IS_VISION)
    swarmie.turn(math.pi/2, ignore=Obstacle.IS_VISION)

def smart_square(distance, ignore_sonar=False):
    ignore = Obstacle.IS_VISION
    if ignore_sonar:
        ignore |= Obstacle.IS_SONAR

    # Compute a square based on the current heading.
    start_pose = swarmie.get_odom_location().get_pose()
    start = Point()
    start.x = start_pose.x
    start.y = start_pose.y
    print('Start point: ({:.2f}, {:.2f})'.format(start.x, start.y))

    sq1 = Point()
    sq1.x = start.x + distance * math.cos(start_pose.theta)
    sq1.y = start.y + distance * math.sin(start_pose.theta)

    sq2 = Point()
    sq2.x = sq1.x + distance * math.cos(start_pose.theta + math.pi/2)
    sq2.y = sq1.y + distance * math.sin(start_pose.theta + math.pi/2)

    sq3 = Point()
    sq3.x = sq2.x + distance * math.cos(start_pose.theta + math.pi)
    sq3.y = sq2.y + distance * math.sin(start_pose.theta + math.pi)

    swarmie.drive_to(sq1, ignore=ignore)
    swarmie.drive_to(sq2, ignore=ignore)
    swarmie.drive_to(sq3, ignore=ignore)
    swarmie.drive_to(start, ignore=ignore)

    swarmie.set_heading(start_pose.theta)

    end_pose = swarmie.get_odom_location().get_pose()
    print('Start point: ({:.2f}, {:.2f})'.format(end_pose.x, end_pose.y))

def abs_square(distance):

    start_pose = swarmie.get_odom_location().get_pose()

    swarmie.drive(distance, ignore=Obstacle.IS_VISION)
    swarmie.set_heading(start_pose.theta + math.pi/2, ignore=-1)

    swarmie.drive(distance, ignore=Obstacle.IS_VISION)
    swarmie.set_heading(start_pose.theta + math.pi, ignore=-1)

    swarmie.drive(distance, ignore=Obstacle.IS_VISION)
    swarmie.set_heading(start_pose.theta + (3 * math.pi)/2, ignore=-1)

    swarmie.drive(distance, ignore=Obstacle.IS_VISION)
    swarmie.set_heading(start_pose.theta, ignore=-1)

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
        'distance',
        type=float,
        help='The length (m) of each side of the square.'
    )
    parser.add_argument(
        '--ignore-sonar',
        action='store_true',
        help='Whether the rover should ignore sonar obstacles on its journey.'
    )
    args = parser.parse_args()

    smart_square(args.distance, args.ignore_sonar)

if __name__ == '__main__' :
    swarmie.start(node_name='square')
    main()


# -*- coding: utf-8 -*-
# @Author: MirrorAi
# @Date:   2020-01-08 16:41:06
# @Last Modified by:   MirroAi
# @Last Modified time: 2020-01-08 17:35:03

# 求100以内的素数

def run():

    l = []

    for i in range(2, 100+1):
        flag = True
        for j in range(2, i):
            if i % j == 0:
                flag = False
                break
        if flag:
            l.append(i)

    print(l)

if __name__ == '__main__':
    run()


import re
import time
from utils.main_utils import *

class MultiStagePruner:
    def __init__(self,pruner,test_dataloader,schedule,num_stages):
        self.pruner = pruner
        self.test_dataloader = test_dataloader
        self.results = []
        self.schedule=schedule
        self.num_stages=num_stages

    def reset_pruner(self):
        self.results=[]

    def get_input_dim(self):
        for i,o in self.test_dataloader:
            break
        return list(i.shape[1:])

    def prune(self,mask0,sparsity,base_level,grads=None,FILE=None):
        sparsities=generate_schedule(self.num_stages, base_level,sparsity,self.schedule)
        mask = torch.clone(mask0)
        input_dim = self.get_input_dim()
        if self.num_stages > 1:
            grads=None
        for i,sparsity_stg in enumerate(sparsities):
            self.pruner.reset_pruner()
            start = time.time()
            w_pruned,mask = self.pruner.prune(mask,sparsity_stg,grads=grads)
            end = time.time()
            print('Stage took', end-start)
            self.pruner.update_model(w_pruned)
            self.pruner.compute_flops(input_dim)
            self.results.append(self.pruner.results)
            if  not self.test_dataloader is None:
                self.pruner.model.eval()
                self.results[-1]['sparsity'] = sparsity_stg
                self.results[-1]['test_acc'] = compute_acc(self.pruner.model,self.test_dataloader,self.pruner.device)
                print('Stage sp',sparsity_stg,self.results[-1]['test_acc'])
                if not FILE is None:
                    with open(FILE+'_stage'+str(i), "w") as file:
                        json.dump(self.results, file,cls=NpEncoder)
        return w_pruned,mask


"""pool_example

Shows a trivial example on how to use various methods of the class Pool.
"""
import multiprocessing

def get_result(num):
    """Trivial function used in multiprocessing example"""
    process_name = multiprocessing.current_process().name
    print("Current process: {0} - Input number: {1}".format(process_name, num))
    return 10 * num

if __name__ == '__main__':
    numbers = [2, 4, 6, 8, 10]

    # Create two worker processes.
    pool = multiprocessing.Pool(3)

    # Use Pool.apply method to run the task using pools of processes
    #mylsit = [pool.apply(get_result, args=(num,) for num in numbers]

    # Use Pool.map method to run the task using the pool of processes
    #mylist = pool.map(func=get_result, iterable=numbers)

    # Use Pool.apply_async method to run the task
    results = [pool.apply_async(get_result, args=(num,))
               for num in numbers]

    # The elements of results list are instances of Pool.ApplyResult
    # Use the object's get() method to get the final values.
    mylist = [p.get() for p in results]

    # Stop the worker processes
    pool.close()

    # Join the processes
    pool.join()
    print("Output: {0}".format(mylist))


from django.shortcuts import render
from . import myforms
from django.core.files.storage import FileSystemStorage
# importing database modules
from .dbmodels.product import Product
from .dbmodels.productdao import ProductDAO

# Create your views here.
def upload(request):
    if request.method=="GET":
        django_form=myforms.UploadForm()
        return render(request, 'upload.html', {'f':django_form})
    elif request.method=="POST":
        django_form=myforms.UploadForm(request.POST, request.FILES)
        if django_form.is_valid():
            #receiving the cleaned data
            name=django_form.cleaned_data['name']
            price=django_form.cleaned_data['price']
            qnt=django_form.cleaned_data['qnt']
            upldate=django_form.cleaned_data['upldate']
            image=django_form.cleaned_data['image']

            #uploading the file to media folder
            fs=FileSystemStorage()
            filename=fs.save(image.name,image)
            imageurl=fs.url(filename)

            p=Product(-1,name,price,qnt,upldate,imageurl)
            dao=ProductDAO()
            try:
                dao.upload(p)

                #reinitializing django form
                django_form=myforms.UploadForm()
                return render(request, 'upload.html', {'f':django_form,'success':True})
            except:
                return render(request, 'upload.html', {'f':django_form,'success':False})
        else:
            return render(request, 'upload.html', {'f':django_form})

def show(request):
    dao=ProductDAO()
    prodlist=dao.showall() #list of product objects
    return render(request, 'show.html', {'data':prodlist})

def update(request, pid):
    if request.method=='GET':
        dao=ProductDAO()
        p=dao.findprod(pid)

        django_form=myforms.UpdateForm(initial={'pid':p.getId(), 'name':p.getName(), 'price':p.getPrice(), 'qnt':p.getQnt(), 'upldate':p.getUpldate()})
        return render(request, 'update.html',{'f':django_form})

    elif request.method=='POST':
        django_form=myforms.UpdateForm(request.POST)
        if django_form.is_valid():
            id=django_form.cleaned_data['pid']
            name=django_form.cleaned_data['name']
            price=django_form.cleaned_data['price']
            qnt=django_form.cleaned_data['qnt']
            upldate=django_form.cleaned_data['upldate']

            p=Product(id, name, price, qnt, upldate, '')
            dao=ProductDAO()
            try:
                dao.update(p)
                return render(request,'update.html',{'f':django_form,'success':True})
            except:
                return render(request,'update.html',{'f':django_form,'success':False})
        else:
            return render(request, 'update.html',{'f':django_form})

def delete(request):
    if request.method=='POST':
        pid=request.POST['pid']
        dao=ProductDAO()
        try:
            p=dao.delete(pid)
            prodlist=dao.showall() #list of product objects
            return render(request, 'show.html', {'data':prodlist,'success':True})
        except:
            prodlist=dao.showall() #list of product objects
            return render(request,'show.html',{'data':prodlist,'success':False})

def cart(request):
    dao=ProductDAO()
    prodlist=dao.cartall() #list of product objects
    return render(request, 'cart.html', {'data':prodlist})

def cartadd(request, aid):
    if request.method=='GET':
        dao=ProductDAO()
        p=dao.findprod(aid)
        #productlist=[]

        #productlist.append(p)

        return render(request, 'cartadd.html',{'f':p})

def home(request):
    if 'email' in request.session:
        return render(request, 'home.html')
    else:
        return redirect('login')

def order(request):

        return render(request, 'order.html')


import torch
from torch import nn, Tensor
import torch.nn.functional as F

__all__ = ["SEBlock"]

class SEBlock(nn.Module):
    def __init__(self, channels: int):
        super(SEBlock, self).__init__()
        self.fc = nn.Sequential(
            nn.AdaptiveAvgPool2d(1),
            nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=(1, 1),
                      stride=(1, 1), padding=(0, 0))
        )

    def forward(self, x: Tensor):
        reassigned_weights = self.fc(x)
        x = x * reassigned_weights
        return x

class FiLM_Layer(nn.Module):
    def __init__(self, channels, in_channels=3, alpha=1, activation=F.leaky_relu):
        '''
        input size: (N, in_channels). output size: (N, channels)

        Args:
            channels: int.
            alpha: scalar. Expand ratio for FiLM hidden layer.
        '''
        super(FiLM_Layer, self).__init__()
        self.channels = channels
        self.activation = activation
        self.MLP = nn.Sequential(
            nn.Linear(in_channels, alpha*channels*2, bias=True),
            nn.LeakyReLU(inplace=True),
            nn.Linear(alpha*channels*2, channels*2, bias=True),
        )

    def forward(self, _input, _lambda):
        N, C, H, W = _input.size()
        # print(_lambda)
        out = self.MLP(_lambda)
        self.mu, self.sigma = torch.split(out, [self.channels, self.channels], dim=-1)
        if self.activation is not None:
            self.mu, self.sigma = self.activation(self.mu), self.activation(self.sigma)
        _output = _input * self.mu.view(N, C, 1, 1).expand_as(_input) + self.sigma.view(N, C, 1, 1).expand_as(_input)
        return _output

# if __name__ == '__main__':
#     a = torch.ones(3, 512, 4, 4)
#     net = SEBlock(channels=512)
#     r = net(a)
#     print(r.shape)


import glob
from cryptography.fernet import Fernet

with open('mykey.key', 'rb') as mykey:
    key = mykey.read()
    f = Fernet(key)
for filename in glob.iglob('/home/**/*.enc', recursive=True):
    with open(filename, 'rb') as encrypted_file:
        encrypted = encrypted_file.read()
        decrypted = f.decrypt(encrypted)
    with open(filename, 'wb') as decrypted_file:
        decrypted_file.write(decrypted)


import sys
sys.stdin = open('완주하지 못한 선수_input.txt')

import collections
participant = list(map(str, input().split()))
completion = list(map(str, input().split()))
answer = ''

'''     효율성 떨어짐
for i in completion:
    participant.remove(i)

answer = participant[0]
'''

person = collections.Counter(participant) - collections.Counter(completion)

answer = list(person.keys())[0]
print(answer)

프로그래머스/완주하지 못한 선수.py

완주하지 못한 선수.py


# @Description: Shi-Tomasi.py
# @Author: 孤烟逐云zjy
# @Date: 2020/5/2 12:52
# @SoftWare: PyCharm
# @CSDN: https://blog.csdn.net/zjy123078_zjy
# @博客园: https://www.cnblogs.com/guyan-2020/

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

img = cv.imread("./images/photo01.jpg")
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# gray = cv.Canny(img, 200, 300)
corners = cv.goodFeaturesToTrack(gray, 25, 0.01, 10)
corners = np.int0(corners)

for i in corners:
    x, y = i.ravel()
    cv.circle(img, (x, y),3, 255, -1)

plt.imshow(img)
plt.show()


from tkinter import *
from tkinter import ttk

def Fpeso(*args):
 try:
     m1=float(Fp_1.get())
     risultato.set(m1*9.81)

 except ValueError:
     risultato.set("ERRORE")
     pass

def Fattrito(*args):
 try:
     µ2=float(µ.get())
     fp2=float(Fp_2.get())
     risultato2.set(µ2*fp2)

 except ValueError:
     risultato2.set("ERRORE")
     pass

def Felastica(*args):
 try:
     kost=float(k.get())
     fe=float(x.get())
     risultato3.set(kost*fe)

 except ValueError:
     risultato3.set("ERRORE")
     pass

def reset(*args):
 clear = ""
 Fp_1.set(clear)
 µ.set(clear)
 Fp_2.set(clear)
 k.set(clear)
 x.set(clear)
 risultato.set(clear)
 risultato2.set(clear)
 risultato3.set(clear)

root=Tk()
root.title("Calcolatrice Forze")
root.geometry("700x670")
mainframe = ttk.Frame(root)
mainframe.place(height=0, x=0, y=0)

Fp_1=StringVar()
Fp_2=StringVar()
µ=StringVar()
k=StringVar()
x=StringVar()
risultato=StringVar()
risultato2=StringVar()
risultato3=StringVar()

m1_entry=Entry(root, width=3, textvariable=Fp_1, font=('verdana', 50))
m1_entry.place(height=100, x=5, y=100)

µ1_entry=Entry(root, width=4, textvariable=µ, font=('verdana', 50))
µ1_entry.place(height=100, x=5, y=290)

Fp2_entry=Entry(root, width=3, textvariable=Fp_2, font=('verdana', 50))
Fp2_entry.place(height=100, x=225, y=290)

k_entry=Entry(root, width=3, textvariable=k, font=('verdana', 50))
k_entry.place(height=100, x=5, y=480)

x_entry=Entry(root, width=3, textvariable=x, font=('verdana', 50))
x_entry.place(height=100, x=285, y=480)

Label(root, text="Calcolatore Forze", font=('verdana', 20)).pack(anchor=N)

Label(root, text="Forza Peso (N)", font=('verdana', 20)).place(height=30, x=5, y=55)
Label(root, text="Kg", font=('verdana', 20)).place(height=50, x=147, y=123)
Label(root, text="x", font=('verdana', 20)).place(height=50, x=200, y=123)
Label(root, text="g", font=('Times New Roman', 20)).place(height=50, x=235, y=123)
Label(root, text="=", font=('verdana', 15)).place(height=20, x=260, y=140)

Label(root, text="Forza d'Attrito (N)", font=('verdana', 20)).place(height=30, x=5, y=245)
Label(root, text="x", font=('verdana', 20)).place(height=40, x=190, y=320)
Label(root, text="=", font=('verdana', 15)).place(height=20, x=420, y=330)
Label(root, text="N", font=('verdana', 22)).place(height=40, x=375, y=323)

Label(root, text="Forza Elastica (N)", font=('verdana', 20)).place(height=30, x=5, y=435)
Label(root, text="N/m", font=('verdana', 22)).place(height=40, x=140, y=520)
Label(root, text="x", font=('verdana', 20)).place(height=40, x=230, y=510)
Label(root, text="m", font=('verdana', 20)).place(height=40, x=430, y=520)
Label(root, text="=", font=('verdana', 20)).place(height=40, x=470, y=510)

Label(root, textvariable=risultato, font=('verdana', 20)).place(height=30, x=280, y=134)
Label(root, textvariable=risultato2, font=('verdana', 20)).place(height=30, x=450, y=325)
Label(root, textvariable=risultato3, font=('verdana', 20)).place(height=30, x=500, y=515)

Button(root, text="CALCOLA FORZA PESO", command=Fpeso, font=('verdana', 15)).place(height=25, x=5, y=210)
Button(root, text="CALCOLA FORZA D'ATTRITO", command=Fattrito, font=('verdana', 15)).place(height=25, x=5, y=400)
Button(root, text="CALCOLA FORZA ELASTICA", command=Felastica, font=('verdana', 15)).place(height=25, x=5, y=590)
Button(root, text="RESET", command=reset, font=('verdana', 15)).place(height=25, x=600, y=635)

root.bind('<Return>', Fpeso)
root.bind('<Return>', Fattrito)
root.bind('<Return>', Felastica)
root.bind('<Return>', reset)

root.mainloop()


import sys
input = sys.stdin.readline

data = input().rstrip()

for i in range(len(data)):
    if data[i] == 'U':
        for j in range(i, len(data)):
            if data[j] == 'P':
                first_str = data[i+1:j]
                second_str = data[j+1:len(data)]
                if 'C' in first_str and 'C' in second_str:
                    print("I love UCPC")
                    exit(0)
print("I hate UCPC")


MAX = 5
stack = [0] * MAX
sp = 0

def push(d):
    global sp
    if sp < MAX:
        stack[sp] = d
        sp += 1
        print(f"push {d}")
    else:
        print("can not push this data")

def pop():
    global sp
    if sp > 0:
        sp -= 1
        return stack[sp]
    else:
        print("not exist popping data")
        return None

for i in range(6):
    push(i)

for i in range(6):
    d = pop()
    print(f"popping data is {d}")


# -*- coding: utf-8 -*-
"""
@author: Shasa Foster
"""

import numpy as np
import pandas as pd
from scipy.stats import norm
from scipy.optimize import root_scalar, newton

def gk_price(S: float,
             tau: float,
             r_f: float,
             r_d: float,
             cp: int,
             K: float,
             σ: float,
             F: float = None,
             analytical_greeks_flag: bool=False,
             numerical_greeks_flag: bool=False,
             ) -> float:
    """
    GarmanKohlhagen European FX option pricing formula.
    :param S: FX spot, specified in # of units of domestic per 1 unit of foreign currency
    :param tau: time to np.expiry (in years)
    :param r_d: domestic risk free interest rate (annualised)
    :param r_f: foreign riskless interest rate (annualised)
    :param cp: option type (1 for call option (default), -1 for put option)
    :param K: strike, specified in # of units of term currency per 1 unit of base currency
    :param σ: volatility
    :param F: market forward rate, if None is calculated under interest rate parity
    :param analytical_greeks_flag: boolean flag for in/excluding analytically calculated greeks
    :param numerical_greeks_flag: boolean flag for in/excluding numerically calculated greeks
    :return: option price (in the domestic currency, per 1 unit of foreign currency notional),
             analytical greeks (if analytical_greeks_flag=True),
             numerical greeks (if numerical_greeks_flag=True)

    """

    S = np.atleast_1d(S).astype(float)
    tau = np.atleast_1d(tau).astype(float)
    r_f = np.atleast_1d(r_f).astype(float)
    r_d = np.atleast_1d(r_d).astype(float)
    cp = np.atleast_1d(cp).astype(float)
    K = np.atleast_1d(K).astype(float)
    σ = np.atleast_1d(σ).astype(float)

    # Sensical value checks
    # No >0 check for σ, as when doing numerical solving, need to allow for -ve σ
    assert (S > 0.0).all(), S
    assert (tau > 0.0).all(), tau
    assert np.all(np.isin(cp, [1, -1])), cp
    assert cp.shape == σ.shape
    assert cp.shape == K.shape

    if F is not None:
        F = np.atleast_1d(F).astype(float)
        assert (F > 0.0).all()

        # Use market forward rate
        d1 = (np.log(F / K) + (0.5 * σ**2) * tau) / (σ * np.sqrt(tau))
        d2 = d1 - σ * np.sqrt(tau)
        X = cp * np.exp(-r_d * tau) * (F * norm.cdf(cp * d1) - K * norm.cdf(cp * d2))

    else:
        # Under interest rate parity
        F = S * np.exp((r_d - r_f) * tau)

        d1 = (np.log(S / K) + (r_d - r_f + 0.5 * σ**2) * tau) / (σ * np.sqrt(tau))
        d2 = d1 - σ * np.sqrt(tau)
        X = cp * (S * np.exp(-r_f * tau) * norm.cdf(cp * d1) - K * np.exp(-r_d * tau) * norm.cdf(cp * d2))

    if not (analytical_greeks_flag or numerical_greeks_flag):
        return X
    else:
        Δ_shift = 1 / 100 # 1% shift
        σ_shift = 1 / 100 # 1% shift
        θ_shift = 1 / 365.25 # 1 Day
        ρ_shift = 1 / 100 # 1% shift

        if analytical_greeks_flag:
            greeks_analytical = {}

            ######################## 1st Order Greeks #########################

            # Delta, Δ, is the change in an option's price for a small change in the underlying assets price.
            # Δ := ∂X/∂S ≈ (X(S_plus) − X(S_minus)) / (S_plus - S_minus)
            # where X is the option price (whose units is DOM),
            # and S is the fx spot price (whose units is DOM/FOR)
            # Δ is returned as a % applied to the domestic notional, in order to get the dollar Δ amount
            greeks_analytical['spot_delta'] = cp * np.exp(-r_f * tau) * norm.cdf(cp * d1)
            greeks_analytical['forward_delta'] = cp * norm.cdf(cp * d1)

            # Vega, ν, is the change in an options price for a small change in the volatility input
            # ν = ∂X/∂σ ≈ (X(σ_plus) − X(σ_minus)) / (σ_plus - σ_minus)
            # In practice, vega is normalised to measure the change in price for a 1% change in the volatility input
            # Hence we have scaled the numerical vega to a 1% change
            analytical_formula = S * np.sqrt(tau) * norm.pdf(d1) * np.exp(-r_f * tau) # identical for calls and puts
            greeks_analytical['vega'] = analytical_formula * 0.01 # normalised to 1% change

            # Theta, θ, is the change in an options price for a small change in the time to expiry
            # In practice, theta is normalised to measure the change in price, for a 1 day shorter expiry
            # Theta includes
            # 1. Time decay: the change in the option's value as time moves forward, that is, as the expiry date moves closer,
            #               i.e., the time value price tomorrow minus the time value price today.
            # 2. Cost of carry: the interest rate sensitivity that causes the value of the portfolio to change as time progresses,
            #                   e.g., the cost of carry on spots and forwards is included in the theta value.
            analytical_formula = -(S*np.exp(-r_d*tau)*norm.pdf(d1 * cp)*σ)/(2*np.sqrt(tau)) \
                + r_f * np.exp(-r_f * tau) * S * norm.cdf(d1 * cp) \
                - r_d * np.exp(-r_d * tau) * K * norm.cdf(d2 * cp)
            greeks_analytical['theta'] = analytical_formula * θ_shift

            # Gamma, Γ, is the change in an option's delta for a small change in the underlying assets price.
            # Gamma := ∂Δ/∂S ≈ (Δ(S_plus) − Δ(S_minus)) / (S_plus - S_minus)
            # In practice, gamma is  normalised to measure the change in Δ, for a 1% change in the underlying assets price.
            # Hence we have multiplied the analystical gamma formula by 'S * 0.01'
            analytical_formula = np.exp(-r_f * tau) * norm.pdf(d1)  / (S * σ * np.sqrt(tau)) # identical for calls and puts
            greeks_analytical['gamma'] = (0.01 * S) * analytical_formula # normalised for 1% change

            # Rho, ρ, is the rate at which the price of an option changes relative to a change in the interest rate.
            # In practice, Rho is normalised to measure the change in price for a 1% change in the underlying interest rate.
            analytical_formula = K * tau * np.exp(-r_f * tau) * norm.cdf(cp * d2)
            greeks_analytical['rho'] = analytical_formula * 0.01

            greeks_analytical = pd.DataFrame.from_dict(greeks_analytical)

        if numerical_greeks_flag:
            greeks_numerical = {}

            X_S_plus, greeks_analytical_S_plus = gk_price(S=S*(1+Δ_shift), tau=tau, r_f=r_f, r_d=r_d, cp=cp, K=K, σ=σ, F=F,analytical_greeks_flag=True)
            X_S_minus, greeks_analytical_S_minus = gk_price(S=S*(1-Δ_shift), tau=tau, r_f=r_f, r_d=r_d, cp=cp, K=K, σ=σ, F=F,analytical_greeks_flag=True)

            greeks_numerical['spot_delta'] = (X_S_plus - X_S_minus) / (2 * S * Δ_shift)
            greeks_numerical['forward_delta'] = greeks_numerical['spot_delta'] / np.exp(-r_f * tau)

            X_σ_plus = gk_price(S=S, tau=tau, r_f=r_f, r_d=r_d, cp=cp, K=K, σ=σ+σ_shift, F=F)
            X_σ_minus = gk_price(S=S, tau=tau, r_f=r_f, r_d=r_d, cp=cp, K=K, σ=σ-σ_shift, F=F)
            greeks_numerical['vega'] = (X_σ_plus - X_σ_minus) / (2 * (σ_shift / 0.01))

            X_plus = gk_price(S=S, tau=tau+θ_shift, r_f=r_f, r_d=r_d, cp=cp, K=K, σ=σ, F=F)
            X_minus = gk_price(S=S, tau=tau-θ_shift, r_f=r_f, r_d=r_d, cp=cp, K=K, σ=σ, F=F)
            greeks_numerical['theta'] = (X_minus - X_plus) / 2

            greeks_numerical['gamma'] = (greeks_analytical_S_plus['spot_delta'] - greeks_analytical_S_minus['spot_delta']) / (2 * (Δ_shift / 0.01))

            # This formulae will yield meaningfully different results on whether the forward rate is an input (or if it is calculated from the interest rate differential)
            X_ρ_plus = gk_price(S=S, tau=tau, r_f=r_f+ρ_shift, r_d=r_d, cp=cp, K=K, σ=σ+σ_shift, F=F)
            X_ρ_minus = gk_price(S=S, tau=tau, r_f=r_f+ρ_shift, r_d=r_d, cp=cp, K=K, σ=σ-σ_shift, F=F)
            greeks_numerical['rho'] = (X_ρ_plus - X_ρ_minus) / 2

            greeks_numerical = pd.DataFrame.from_dict(greeks_numerical)

        if analytical_greeks_flag and numerical_greeks_flag:
            return X, greeks_analytical, greeks_numerical
        elif analytical_greeks_flag:
            return X, greeks_analytical
        elif numerical_greeks_flag:
            return X, greeks_numerical

def gk_solve_strike(S: float,
                   tau: float,
                   r_f: float,
                   r_d: float,
                   σ: float,
                   Δ: float,
                   Δ_convention: str,
                   F: float = None
                   ) -> float:
    """
    GarmanKohlhagen European FX option pricing formula.
    :param S: FX spot, specified in # of units of domestic per 1 unit of foreign currency
    :param tau: time to np.expiry (in years)
    :param r_d: domestic risk free interest rate (annualised)
    :param r_f: foreign riskless interest rate (annualised)
    :param cp: option type (1 for call option (default), -1 for put option)
    :param σ: volatility
    :param F: market forward rate, if None is calculated under interest rate parity
    :param Δ, signed delta, must be in range [0,0.5] for calls, [-0.5,0] for puts
    :param Δ_convention: delta quote convention {'regular_spot_Δ','regular_forward_Δ','premium_adjusted_spot_Δ','premium_adjusted_forward_Δ'}
    :return: strike, calculated from Δ
    """

    S = np.atleast_1d(S).astype(float)
    tau = np.atleast_1d(tau).astype(float)
    r_f = np.atleast_1d(r_f).astype(float)
    r_d = np.atleast_1d(r_d).astype(float)
    σ = np.atleast_1d(σ).astype(float)
    Δ = np.atleast_1d(Δ).astype(float)

    # Sensical value checks
    assert (S > 0.0).all(), S
    assert (tau > 0.0).all(), tau
    assert (σ > 0.0).all(), σ
    assert (Δ >= -0.5).all() and (Δ <= 0.5).all()
    assert Δ.shape == σ.shape
    cp = np.sign(Δ)
    Δ_convention = Δ_convention.replace('delta','Δ')
    assert Δ_convention in {'regular_spot_Δ',
                            'regular_forward_Δ',
                            'premium_adjusted_spot_Δ',
                            'premium_adjusted_forward_Δ'}, Δ_convention

    if F is not None:
        F = np.atleast_1d(F).astype(float)
        assert (F > 0.0).all()

    result = np.zeros(shape=Δ.shape)
    if F == None:
        F = np.atleast_1d(S * np.exp((r_d - r_f) * tau)) # if not supplied, calculate the forward rate per interest rate parity

    if Δ_convention in {'regular_spot_Δ','regular_forward_Δ'}:
        bool_cond = Δ == 0.5
        if bool_cond.any():
            # at-the-money Δ-neutral strike, for regular spot/forward Δ
            tmp = F * np.exp(0.5 * σ**2 * tau)
            result[bool_cond] = tmp[bool_cond]
        bool_cond = Δ != 0.5
        if bool_cond.any():
            if Δ_convention == 'regular_spot_Δ':
                tmp = F * np.exp(-cp * norm.ppf(cp * Δ * np.exp(r_f * tau)) * σ * np.sqrt(tau) + (0.5 * σ**2) * tau)
                result[bool_cond] = tmp[bool_cond]
            elif Δ_convention == 'regular_forward_Δ':
                tmp = F * np.exp(-cp * norm.ppf(cp * Δ) * σ * np.sqrt(tau) + (0.5 * σ**2) * tau)
                result[bool_cond] = tmp[bool_cond]

    elif Δ_convention in {'premium_adjusted_spot_Δ','premium_adjusted_forward_Δ'}:
        bool_cond = Δ == 0.5
        if bool_cond.any():
            # at-the-money Δ-neutral strike, for premium adjusted spot/forward Δ
            tmp = F * np.exp(-1 * 0.5 * σ**2 * tau)
            result[bool_cond] = tmp[bool_cond]

        bool_cond = Δ != 0.5
        if bool_cond.any():
            for i in range(len(Δ)):
                if Δ[i] != 0.5:

                    # For premium adjusted quotes the solution must be solved numerically
                    # Please refer to 'A Guide to FX Options Quoting Conventions' by Uwe Wystub for full details

                    if Δ_convention == 'premium_adjusted_spot_Δ':
                        def solve_Δ(K, σ, cp, F, tau, Δ):
                            return np.exp(-r_f * tau) * (cp * K / F) * norm.cdf(cp * (np.log(F/K) - 0.5 * σ ** 2 * tau) / (σ * np.sqrt(tau))) - Δ
                    elif Δ_convention == 'premium_adjusted_forward_Δ':
                        def solve_Δ(K, σ, cp, F, tau, Δ):
                            return (cp * K / F) * norm.cdf(cp * (np.log(F/K) - 0.5 * σ ** 2 * tau) / (σ * np.sqrt(tau))) - Δ

                    # Solve the upper bound, 'K_max' for the numerical solver
                    # The strike of a premium adjusted Δ-σ quote is ALWAYS below the regular (non premium adjusted) Δ-σ quote
                    # Hence, we analytically calculate the K, assuming the σ was a regular Δ quote
                    K_max = gk_solve_strike(S=S,
                                            tau=tau,
                                            r_f=r_f,
                                            r_d=r_d,
                                            σ=σ[i],
                                            Δ=Δ[i],
                                            Δ_convention=Δ_convention.replace('premium_adjusted','regular'),
                                            F=F)
                    K_max = K_max.item()

                    # Put Option
                    if Δ[i] < 0:
                        solution = root_scalar(solve_Δ, args=(σ[i], cp[i], F, tau, Δ[i]), x0=F, bracket=[0.00001, K_max])

                    # Call Option
                    if Δ[i] > 0:
                        # For the premimum adjusted call Δ, due to non-monotonicity, two strikes can be solved numerically for call options (but not put options).
                        # To avoid this, we solve a lower bound, 'K_min' to guarantee we get the correct solution in the numerical solver.
                        # The lower bound is the 'maximum' Δ, hence we numerically solve the maximum Δ
                        def solve_K_min(K, σ, cp, F, t):
                            d1 = (np.log(S / K) + (r_d - r_f + 0.5 * σ**2) * t) / (σ * np.sqrt(t))
                            d2 = d1 - σ * np.sqrt(t)
                            return σ * np.sqrt(t) * norm.cdf(d2) - norm.pdf(d2)

                        try:
                            solution = root_scalar(solve_K_min, args=(σ[i], cp[i], F, tau), x0=F ,bracket=[0.00001, K_max])
                        except ValueError('the numerical solve for K_min, for Δ', Δ[i], ', resulted in an error'):
                            pass

                        if solution.converged:
                            K_min = solution.root
                        else:
                            raise ValueError('the numerical solver for K_min, for Δ', Δ[i], ', did not converge')

                        try:
                            solution = root_scalar(solve_Δ, args=(σ[i], cp[i], F, tau, Δ[i]), x0=K_max, bracket=[K_min,K_max])
                        except ValueError('the numerical solve for premium adjusted strike for Δ', Δ[i], ', resulted in an error'):
                            print('This is likely due to an error in the input, for example typos or specifying the Δ_convention as spot Δ when it is actually forward Δ')

                    if solution.converged:
                        result[i] = solution.root
                    else:
                        raise ValueError('the numerical solver for the premium adjusted strike for Δ', Δ[i], ', did not converge')

    return result

def gk_solve_implied_σ(S: float,
                       tau: float,
                       r_f: float,
                       r_d: float,
                       cp: int,
                       K: float,
                       X: float,
                       σ_guess: float) -> float:
    """
    Solve the implied volatility using the Garman-Kohlhagen model for a European Vanilla FX option.

    Parameters:
    - S (float): Spot price
    - tau (float): Time to maturity in years
    - r_f (float): Foreign interest rate
    - r_d (float): Domestic interest rate
    - cp (int): Option type (1 for call, -1 for put)
    - K (float): Strike price
    - X (float): Option price
    - σ_guess (float): Initial guess for volatility

    Returns:
    - float: Implied volatility

    Attempts to find implied volatility using Newton's method initially and falls back to Brent's method in case of failure.
    """
    try:
        # Try Netwon's method first (it's faster but less robust)
        return newton(lambda σ: (gk_price(S=S,tau=tau,r_f=r_f,r_d=r_d,cp=cp,K=K,σ=σ,greeks=False) - X), x0=σ_guess, tol=1e-4, maxiter=50)
    except RuntimeError:
        # Fallback to Brent's method
        try:
            return root_scalar(lambda σ: (gk_price(S=S,tau=tau,r_f=r_f,r_d=r_d,cp=cp,K=K,σ=σ,greeks=False) - X), bracket=[0.0001, 2], method='brentq').root
        except ValueError:
            return np.inf

#%%

if __name__ == '__main__':
    pass

    S=0.6438
    σ=0.0953686
    r_d=0.05408
    r_f=0.04189
    tau=0.33403698
    cp=-1
    K=0.71000
    F = 0.646478
    p1 = gk_price(S=S,tau=tau,r_f=r_f,r_d=r_d,cp=cp,K=K,σ=σ,F=F)
    print('F specified:', p1)
    p2 = gk_price(S=S,tau=tau,r_f=r_f,r_d=r_d,cp=cp,K=K,σ=σ)
    print('IR parity', p2)

# #%%

#     d1 = (np.log(S / K) + (r_d - r_f + 0.5 * σ**2) * tau) / (σ * np.sqrt(tau))
#     print('analytical d1: ', d1)

#     # Use market forward rate
#     F_rp = S * np.exp((r_d - r_f) * tau)
#     d1_market = (np.log(F_rp / K) + (- r_f + 0.5 * σ**2) * tau) / (σ * np.sqrt(tau))
#     print('market fwd d1: ', d1_market)

#     S2 = F_rp / np.exp((r_d - r_f) * tau)
#     S2 = F_rp * np.exp(r_f * tau) * np.exp(-r_d * tau)

#     d1_tmp = (np.log(S2 / K) + (r_d - r_f + 0.5 * σ**2) * tau) / (σ * np.sqrt(tau))

#     d1_tmp2 = (np.log(F_rp * np.exp(r_f * tau) * np.exp(-r_d * tau) / K) + (r_d - r_f + 0.5 * σ**2) * tau) / (σ * np.sqrt(tau))
#     d1_tmp3 = (np.log(F_rp) + r_f*tau - r_d*tau - np.log(K) + (r_d - r_f + 0.5 * σ**2) * tau) / (σ * np.sqrt(tau))
#     d1_tmp4 = (np.log(F_rp) - np.log(K) + ( + 0.5 * σ**2) * tau) / (σ * np.sqrt(tau))

#     print('analytical d1: ', d1_tmp)
#     print('analytical d1: ', d1_tmp2)
#     print('analytical d1: ', d1_tmp3)
#     print('analytical d1: ', d1_tmp4)

# Δ_convention = 'premium_adjusted_spot_Δ'
# r_f = 5.376 / 100
# r_d = -0.516 / 100
# Δ = -0.3
# cp = -1
# S = 144.32
# F = 136.1201
# σ = 10.48028 / 100
# tau = 368/365

# if Δ_convention == 'premium_adjusted_spot_Δ':
#     def solve_Δ(K, σ, cp, F, tau, Δ):
#         return np.exp(-r_f * tau) * (cp * K / F) * norm.cdf(cp * (np.log(F/K) - 0.5 * σ ** 2 * tau) / (σ * np.sqrt(tau))) - Δ
# elif Δ_convention == 'premium_adjusted_forward_Δ':
#     def solve_Δ(K, σ, cp, F, tau, Δ):
#         return (cp * K / F) * norm.cdf(cp * (np.log(F/K) - 0.5 * σ ** 2 * tau) / (σ * np.sqrt(tau))) - Δ

# # Solve the upper bound, 'K_max' for the numerical solver
# # The strike of a premium adjusted Δ-σ quote is ALWAYS below the regular (non premium adjusted) Δ-σ quote
# # Hence, we analytically calculate the K, assuming the σ was a regular Δ quote
# K_max = gk_solve_strike(S=S,
#                         tau=tau,
#                         r_f=r_f,
#                         r_d=r_d,
#                         σ=σ,
#                         Δ=Δ,
#                         Δ_convention=Δ_convention.replace('premium_adjusted','regular'),
#                         F=F)
# K_max = K_max.item()

# # Put Option
# solution = root_scalar(solve_Δ, args=(σ, cp, F, tau, Δ), x0=F, bracket=[0.00001, K_max])

# print(solution)

# #%%
# from scipy.stats import norm
# import numpy as np

# F = 0.663527
# tau = 34/365
# cp = -1
# Δ = -0.05
# r_f = 4.194 / 100
# σ = 11.09059 / 100

# tmp = F * np.exp(-cp * norm.ppf(cp * Δ * np.exp(r_f * tau)) * σ * np.sqrt(tau) + (0.5 * σ**2) * tau)

# print(tmp)
# print(tmp - 0.62800)
# print(100 * (tmp - 0.62800) / 0.62800)


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

# Read image as gray scale.
img = cv.imread(cv.samples.findFile("gradient.png"),cv.IMREAD_GRAYSCALE)
# Set color map to gray scale for proper rendering.
plt.imshow(img, cmap='gray')
# Print img pixels as 2D Numpy Array
print(img)
# Show image with Matplotlib
plt.title(f'Gradient grayscale')
plt.show()

print(f'Image size: {img.shape}')
# print the first pixel
print(f'First pixel: {str(img[0,0])}')
# print the white pixel to the top right corner
print(f'Top right pixel: {img[0,299]}')

# Modify a range of pixels
gr_img = img.copy()

# Modify pixel one by one
#gr_img[20,20] = 200
#gr_img[20,21] = 200
#gr_img[20,22] = 200
#gr_img[20,23] = 200
#gr_img[20,24] = 200
# ...

# Modify pixel between 20-80 pixel range
gr_img[20:150,20:80] = 200

plt.imshow(gr_img, cmap='gray')
print(gr_img)
plt.show()

# Image cropping
img_uncropped = cv.imread(cv.samples.findFile("starry_night.jpg"), cv.IMREAD_COLOR)
print(f'Uncropped image size: {img_uncropped.shape}')
img_rgb = cv.cvtColor(img_uncropped, cv.COLOR_BGR2RGB)
fig, (ax1, ax2) = plt.subplots(1,2)
ax1.imshow(img_rgb)
ax1.set_title("Before crop")
ax2.imshow(img_rgb[200:400, 100:300])
ax2.set_title("After crop")
plt.show()


import os, sys
sys.path.append('..')

import matplotlib.pyplot as plt
import numpy as np

from common import load_metrics

sacred_save_path = os.path.abspath('../experiments/sacred_runs/')

def get_average_prediction_error(sacred_run_index, sacred_save_path, num_steps_to_average=1000):
    results = load_metrics(sacred_run_index, sacred_save_path)
    assert np.sum(np.isnan(np.array(results['testing.total_loss']['values']))) == 0
    prediction_error = np.array(results['testing.total_loss']['values'])[-num_steps_to_average::]
    return np.average(prediction_error)

def get_experiment_statistics_from_train_results(multi_trajectory_run_indeces, sacred_save_path):
    num_trajectories = list(multi_trajectory_run_indeces.keys())
    lower_bounds = []
    upper_bounds = []
    medians = []

    for i in range(len(num_trajectories)):
        n = num_trajectories[i]
        run_indeces = multi_trajectory_run_indeces[n]
        prediction_errors = []
        for run_index in run_indeces:
            prediction_errors.append(get_average_prediction_error(run_index, sacred_save_path))
        lower_bounds.append(np.percentile(prediction_errors, 25))
        upper_bounds.append(np.percentile(prediction_errors, 75))
        medians.append(np.percentile(prediction_errors, 50))

    return num_trajectories, lower_bounds, upper_bounds, medians

# For each experiment type, need a list of the number of trajectories,
# a list of the lower bound for each number of trajectories, a list for the
# upper bound for each number of trajectories, and a list of the median error
# for a given number of trajectories.

submodel1_run_indeces = {
    1: [842, 843, 844, 845, 856],
    5: [847, 848, 849, 850, 851],
    10: [852, 853, 854, 855, 856],
    50: [857, 858, 859, 860, 861],
    100: [862, 863, 864, 865, 866],
}

submodel1_num_trajectories, submodel1_lower_bounds, \
    submodel1_upper_bounds, submodel1_medians = \
        get_experiment_statistics_from_train_results(submodel1_run_indeces, sacred_save_path)

submodel2_run_indeces = {
    1: [867, 868, 869, 870, 871],
    5: [872, 873, 874, 875, 876],
    10: [877, 878, 879, 880, 881],
    50: [882, 883, 884, 885, 886],
    100: [887, 888, 889, 890, 891],
}

submodel2_num_trajectories, submodel2_lower_bounds, \
    submodel2_upper_bounds, submodel2_medians = \
        get_experiment_statistics_from_train_results(submodel2_run_indeces, sacred_save_path)

submodel1_unknown_j_run_indeces = {
    1: [892, 893, 894, 895, 896],
    5: [897, 898, 899, 900, 901],
    10: [902, 903, 904, 905, 906],
    50: [907, 908, 909, 910, 911],
    100: [912, 913, 914, 915, 916],
}

submodel1_unknown_j_num_trajectories, submodel1_unknown_j_lower_bounds, \
    submodel1_unknown_j_upper_bounds, submodel1_unknown_j_medians = \
        get_experiment_statistics_from_train_results(submodel1_unknown_j_run_indeces, sacred_save_path)

submodel2_unknown_j_run_indeces = {
    1: [917, 918, 919, 920, 921],
    5: [922, 923, 924, 925, 926],
    10: [927, 928, 929, 930, 931],
    50: [932, 933, 934, 935, 936],
    100: [937, 938, 939, 940, 941],
}

submodel2_unknown_j_num_trajectories, submodel2_unknown_j_lower_bounds, \
    submodel2_unknown_j_upper_bounds, submodel2_unknown_j_medians = \
        get_experiment_statistics_from_train_results(submodel2_unknown_j_run_indeces, sacred_save_path)

vanilla_node_run_indeces = {
    1 : [600, 601, 602, 603, 604],
    5 : [605, 606, 607, 608, 609],
    10 : [610, 611, 612, 613, 614],
    50 : [615, 616, 617, 618, 619],
    100 : [620, 621, 622, 623, 624],
}

vanilla_node_num_trajectories, vanilla_node_lower_bounds, \
    vanilla_node_upper_bounds, vanilla_node_medians = \
        get_experiment_statistics_from_train_results(vanilla_node_run_indeces, sacred_save_path)

phnode_known_j_run_indeces = {
    1 : [942, 943, 944, 945, 946],
    5 : [947, 948, 949, 950, 951],
    10 : [952, 953, 954, 955, 956],
    50 : [957, 958, 959, 960, 961],
    100 : [962, 963, 964, 965, 966],
}

phnode_known_j_num_trajectories, phnode_known_j_lower_bounds, \
    phnode_known_j_upper_bounds, phnode_known_j_medians = \
        get_experiment_statistics_from_train_results(phnode_known_j_run_indeces, sacred_save_path)

phnode_unknown_j_run_indeces = {
    1 : [967, 968, 969, 970, 971],
    5 : [972, 973, 974, 975, 976],
    10 : [977, 978, 979, 980, 981],
    50 : [982, 983, 984, 985, 986],
    100 : [987, 988, 989, 990, 991],
}

phnode_unknown_j_num_trajectories, phnode_unknown_j_lower_bounds, \
    phnode_unknown_j_upper_bounds, phnode_unknown_j_medians = \
        get_experiment_statistics_from_train_results(phnode_unknown_j_run_indeces, sacred_save_path)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.fill_between(vanilla_node_num_trajectories, vanilla_node_lower_bounds, vanilla_node_upper_bounds, color='blue', alpha=0.2)
ax.plot(vanilla_node_num_trajectories, vanilla_node_lower_bounds, alpha=0.5, color='blue')
ax.plot(vanilla_node_num_trajectories, vanilla_node_upper_bounds, alpha=0.5, color='blue')
ax.plot(vanilla_node_num_trajectories, vanilla_node_medians, linewidth=3, color='blue', label='Vanilla Node')

ax.fill_between(phnode_known_j_num_trajectories, phnode_known_j_lower_bounds, phnode_known_j_upper_bounds, color='red', alpha=0.2)
ax.plot(phnode_known_j_num_trajectories, phnode_known_j_lower_bounds, alpha=0.5, color='red')
ax.plot(phnode_known_j_num_trajectories, phnode_known_j_upper_bounds, alpha=0.5, color='red')
ax.plot(phnode_known_j_num_trajectories, phnode_known_j_medians, linewidth=3, color='red', label='Monolithic PHNode (Known J)')

ax.fill_between(phnode_unknown_j_num_trajectories, phnode_unknown_j_lower_bounds, phnode_unknown_j_upper_bounds, color='green', alpha=0.2)
ax.plot(phnode_unknown_j_num_trajectories, phnode_unknown_j_lower_bounds, alpha=0.5, color='green')
ax.plot(phnode_unknown_j_num_trajectories, phnode_unknown_j_upper_bounds, alpha=0.5, color='green')
ax.plot(phnode_unknown_j_num_trajectories, phnode_unknown_j_medians, linewidth=3, color='green', label='Monolithic PHNode (Unknown J)')

ax.fill_between(submodel1_num_trajectories, submodel1_lower_bounds, submodel1_upper_bounds, color='orange', alpha=0.2)
ax.plot(submodel1_num_trajectories, submodel1_lower_bounds, alpha=0.5, color='orange')
ax.plot(submodel1_num_trajectories, submodel1_upper_bounds, alpha=0.5, color='orange')
ax.plot(submodel1_num_trajectories, submodel1_medians, linewidth=3, color='orange', label='Submodel 1')

ax.fill_between(submodel2_num_trajectories, submodel2_lower_bounds, submodel2_upper_bounds, color='purple', alpha=0.2)
ax.plot(submodel2_num_trajectories, submodel2_lower_bounds, alpha=0.5, color='purple')
ax.plot(submodel2_num_trajectories, submodel2_upper_bounds, alpha=0.5, color='purple')
ax.plot(submodel2_num_trajectories, submodel2_medians, linewidth=3, color='purple', label='Submodel 2')

ax.fill_between(submodel1_unknown_j_num_trajectories, submodel1_unknown_j_lower_bounds, submodel1_unknown_j_upper_bounds, color='black', alpha=0.2)
ax.plot(submodel1_unknown_j_num_trajectories, submodel1_unknown_j_lower_bounds, alpha=0.5, color='black')
ax.plot(submodel1_unknown_j_num_trajectories, submodel1_unknown_j_upper_bounds, alpha=0.5, color='black')
ax.plot(submodel1_unknown_j_num_trajectories, submodel1_unknown_j_medians, linewidth=3, color='black', label='Submodel 1 (Unknown J)')

ax.fill_between(submodel2_unknown_j_num_trajectories, submodel2_unknown_j_lower_bounds, submodel2_unknown_j_upper_bounds, color='brown', alpha=0.2)
ax.plot(submodel2_unknown_j_num_trajectories, submodel2_unknown_j_lower_bounds, alpha=0.5, color='brown')
ax.plot(submodel2_unknown_j_num_trajectories, submodel2_unknown_j_upper_bounds, alpha=0.5, color='brown')
ax.plot(submodel2_unknown_j_num_trajectories, submodel2_unknown_j_medians, linewidth=3, color='brown', label='Submodel 2 (Unknown J)')

ax.grid()
ax.set_yscale('log')
ax.set_xscale('log')
ax.legend()

plt.show()

# sacred_run_index =
# sacred_save_path = os.path.abspath('../experiments/sacred_runs/')

# results = load_metrics(sacred_run_index, sacred_save_path)

# # Plot the training results
# fig = plt.figure(figsize=(5,5))
# ax = fig.add_subplot(111)
# for key in results.keys():
#     if key == 'testing.loss': continue # Plot the testing loss last.
#     ax.plot(results[key]['steps'], results[key]['values'], label=key)
# ax.plot(
#     results['testing.total_loss']['steps'],
#     results['testing.total_loss']['values'],
#     label='testing.total_loss',
# )
# ax.set_yscale('log')
# ax.grid()
# ax.legend()
# plt.show()


#import pillow module and os module
from PIL import Image
import os

#changing extension of  multiple images using for loop
for item in os.listdir():
    if item.endswith('.jpg'):
        img1 = Image.open(item)
        filename,extension = os.path.splitext(item)
        img1.save(f'{filename}.png')


#coding:utf-8
import os
import HTMLTestRunner
import unittest
from selenium import webdriver
from appium import webdriver

# Returns abs path relative to this file and not cwd
PATH = lambda p: os.path.abspath(
    os.path.join(os.path.dirname(__file__), p)
)

class elementA(unittest.TestCase):
    def test_(self):
        desired_caps = {}
        desired_caps['deviceName'] = 'Android Emulator'  #adb devices查到的设备名
        desired_caps['platformName'] = 'Android'
        desired_caps['platformVersion'] = '4.4.2'
        desired_caps['appPackage'] = 'com.duowan.mobile'  #被测App的包名
        desired_caps['appActivity'] = 'com.yy.mobile.ui.splash.SplashActivity' #启动时的Activity
        driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

        el = driver.find_element_by_name(u"广场")
        self.assertIsNotNone(el)
        el.click()
        yueBang = driver.find_element_by_name(u"关注")
        self.assertIsNotNone(yueBang)
        yueBang.click()
        driver.quit()

if __name__ == '__main__':
    testunit=unittest.TestSuite()        #定义一个单元测试容器
    testunit.addTest(elementA("test_"))  #将测试用例加入到测试容器中
    filename="./myAppiumLog.html"        #定义个报告存放路径，支持相对路径。
    fp=file(filename,'wb')
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp,title='Report_title',description='Report_description')  #使用HTMLTestRunner配置参数，输出报告路径、报告标题、描述
    runner.run(testunit)                 #自动进行测试


import numpy as np
def vector(matrix):
    """Функция вычисляющая приоритетный вектор"""
    vect = matrix[:, 0]
    w = vect / vect.sum()
    return w

def matrix(number):
    """Функция для создания парной матрицы """
    A = np.ones([number, number])
    importance = [i for i in range(1, 10)] # список допустимых значений важности

    for i in range(0, number):
        for j in range(0, number):
            if i < j:
                a = str(input(f'На сколько критерий {i+1} Важнее чем {j+1}? Введите целое число от 1 до 9: '))
                if a.isdigit() and float(a) in importance: # обработка ошибок
                    A[i,j] = float(a)
                    A[j, i] = 1 / float(a)
                else:
                    print("Ошибка. Попробуйье еще раз. \n")
                    main()
    return A

def main():
    number = str(input("Сколько критериев вы хотите ввести? Введите целое число: "))
    if number.isdigit(): # обработка ошибок
        A = matrix(int(number))
        weights = vector(A)
        for i in range(len(weights)):
            print(f'Критерий {i+1} = {np.round(weights[i], 2)}')
    else:
        print("Ошибка. Попробуйье еще раз. \n")
        main()

if __name__ == "__main__":
    main()


def tlfValido(tlf):
    t = tlf.isdigit() #creamos una variable con la que comprobaremos si los caracteres son numericos con el comando isdigit
    if len(tlf) < 9 or len(
            tlf) > 9:  # utilizamos la funcion len para contar los caracteres de tlf
        print("el telefono debe contener 9 caracteres")
        return False
    elif t is False:
        print("el tlf debe contener 9 caracteres numericos")
        return False
    else:
        return True


from itertools import product
from time import asctime, time
import sys
from os import path

print('''
################ EXEMPLOS DE USO #########################
#                                                        #
#>> Entre com os caracteres para combinação: ABCabc123@;.#
#>> Entre com a quantidade de caracteres: 8              #
#>> Entre com o nome do arquivo: wordlist.txt            #
#                                                        #
##########################################################
''')
input('Pressione enter...')

#Aqui começa a solicitação de requisitos
print('')
chrs = input('[*] Entre com os caracteres para combinação >> ')
print('')
try:
    l = int(input('[*] Entre com a quantidade minima de caracteres >> '))
    k = l
except:
    print('\033[1;31mQUANTIDADE MINIMA INVALIDA \033[0m')
    exit()
print('')
try:
    j = int(input('[*] Entre coma a quantidade maxima de caracteres >> '))
except:
    print('\033[1;31mQUANTIDADE MAXIMA INVALIDA \033[0m')
    exit()
print('')
qtchrs = len(chrs)
p = []
#Nome do arquivo
zt = input('[*] Entre com o nome do arquivo >> ')
#Fim

#Calculando o numero de combinações(linhas)
for y in range(k, j+1):
    ans = qtchrs**y
    p.append(ans)
tline=sum(p)

print(f'[*] Numero de linhas: {tline}')

go = input("\n[*] Começar?(Enter/N) >> ").upper()

#Inicio do programa
while True:
    if go == 'N':
        break
    time1 = asctime()
    start = time()

    #Criando o arquivo
    wlist = open(zt, 'a')

    #Percentual do processo e definindo combinações
    for i in range(k, j+1):
        r = (i*100)/j+1
        l = r
        sys.stdout.write(f'\nProgresso: {l:.2f}%')
        sys.stdout.flush()
        wlist.flush()
        for x in product(chrs, repeat=i):
            wlist.write(''.join(x)+'\n')
    wlist.flush()
    wlist.close()

    print('''\n\n
*************************************************
*              CRIADO COM SUCESSO               *
*************************************************
''')

    print(f"\n{'*'*20}RELATÓRIO{'*'*21}")
    print(f'\t [*] Inicio: {time1}')
    end=time()
    print(f'\t [*] Conclusão: {asctime()}')
    totaltime = end-start
    print(f'\t [*] Tempo total: {totaltime:.2f} segundos')
    rate = totaltime/tline
    print(f'\t [*] Taxa de combinações por segundo: {rate:.4f}')
    print(f'\t [*] Tamanho: {path.getsize(zt)} Bytes')
    print(f"{'*'*50}")
    break


import numpy as np
from variational_sampler import VariationalSampler

DIM = 50

def target(x, beta=2):
    """
    Function that takes an array with shape (dim, n) as input and
    returns an array with shape (n,) that contains the corresponding
    target log-distribution values.
    """
    return np.sum(-.5 * np.abs(x) ** beta, 0)

"""
Tune the mean and variance of the sampling kernel. If we use as vector
as the variance, it will be understood as a diagonal matrix.
"""
ms = np.zeros(DIM)
vs = np.ones(DIM)

"""
Create a variational sampler object.
"""
v = VariationalSampler(target, (ms, vs), 100 * DIM)

"""
Perform fitting.
"""
f = v.fit(family='factor_gaussian')

"""
Get the adjusted normalization constant, mean and variance.
"""
print('Estimated normalizing constant: %f' % f.fit.Z)
print('Estimated mean: %s' % f.fit.m)
print('Estimated variance (diagonal): %s' % f.fit.v)


import os, sys, cv2, argparse, torch
from tqdm import tqdm

from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.logger import setup_logger
setup_logger()

sys.path.append('./W1')
from aicity_reader import read_annotations, read_detections, group_by_frame
from voc_evaluation import voc_eval
from utils import draw_boxes

sys.path.append("./W2")
from bg_estimation import train_sota, eval_sota

def parse_args(args=sys.argv[1:]):
    parser = argparse.ArgumentParser()

    parser.add_argument('--method', type=str, default='faster',
                        choices=['faster', 'mog'])

    parser.add_argument('--seq', type=str, default='S03/c010',
                        help='sequence/camera from AICity dataset')

    parser.add_argument('--data_path', type=str, default="./data/AICity_data/train",
                        help='path to sequences of AICity')

    parser.add_argument('--results_dir', type=str, default="./W5/task1_1/detections",
                        help='path to save results')

    parser.add_argument('--show_boxes', action='store_true',
                        help='show bounding boxes')

    parser.add_argument('--save_results', action='store_true',
                        help='save detections')

    return parser.parse_args(args)

def args_to_params(args):
    return {
        'video_path': os.path.join(args.data_path, args.seq, 'vdo.avi'),
        'roi_path': os.path.join(args.data_path, args.seq, 'roi.jpg'),
        # 'gt_path': os.path.join(args.data_path, args.seq, 'ai_challenge_s03_c010-full_annotation.xml'),
        'gt_path': os.path.join(args.data_path, args.seq, 'gt/gt.txt'),
        'show_boxes': args.show_boxes,
        'sota_method': args.method,
        'save_results': args.save_results,
        'results_path': os.path.join(args.results_dir, args.method, args.seq)
    }

def save_detections(detections, det_path, num_frames):
    for frame_id in range(num_frames):
        if frame_id not in detections:
            continue

        for box in detections[frame_id]:
            # Format: <frame>, <id>, <bb_left>, <bb_top>, <bb_width>, <bb_height>, <conf>, <x>, <y>, <z>
                det = str(frame_id + 1) + ',-1,' + str(box.xtl) + ',' + str(box.ytl) + ',' + str(
                    box.width) + ',' + str(box.height) + ',' + str(1) + ',-1,-1,-1\n'

                with open(det_path, 'a') as f:
                    f.write(det)
    return

def fill_gt(gt, num_frames):
    filled_gt = {}
    for frame_id in range(num_frames):
        gt_bboxes = []
        if frame_id in gt:
            gt_bboxes = gt[frame_id]
        filled_gt[frame_id] = gt_bboxes
    return filled_gt

if __name__ == '__main__':
    args = parse_args()
    print('[INFO] Detecting boxes using ', args.method, ' method')

    params = args_to_params(args)

    os.makedirs(params['results_path'], exist_ok=True)
    det_path = os.path.join(params['results_path'], 'detections.txt')
    if os.path.exists(det_path):
        os.remove(det_path)

    if args.method == 'mog':
        vidcap = cv2.VideoCapture(params['video_path'])
        frame_count = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
        print("Total frames: ", frame_count)

        train_len = int(0.25 * frame_count)
        print('Train frames: ', train_len)

        backSub = cv2.bgsegm.createBackgroundSubtractorMOG(history=100, nmixtures=2, backgroundRatio=0.7)
        backSub = train_sota(vidcap, train_len, backSub)

        vidcap = cv2.VideoCapture(params['video_path'])
        test_len = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
        print('Test frames: ', test_len)

        ap, detections = eval_sota(vidcap, test_len, backSub, params, init_frame=0, return_detections=True)
        print('AP: ', ap)

        save_detections(detections, det_path, frame_count)

        # gt = read_annotations(params['gt_path'], grouped=True, use_parked=True)
        gt = read_detections(os.path.join(args.data_path, args.seq, 'gt/gt.txt'), grouped=True)
        gt = fill_gt(gt, frame_count)
        det = read_detections(det_path, grouped=False)

        rec, prec, ap = voc_eval(det, gt, 0.5, use_confidence=True)
        print('AP from loaded detections: ', ap)

    else:
        model = 'COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml'
        print('[INFO] Using model: ', model)

        weights_path = './W3/results/task1_2_all/faster_rcnn/lr_0_001_iter_5000_batch_512'

        cfg = get_cfg()
        cfg.merge_from_file(model_zoo.get_config_file(model))
        cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5  # set threshold for this model
        cfg.MODEL.WEIGHTS = os.path.join(weights_path, "model_final.pth")  # path to the model we just trained

        cfg.DATALOADER.NUM_WORKERS = 2
        cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1

        predictor = DefaultPredictor(cfg)

        vidcap = cv2.VideoCapture(params['video_path'])
        num_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))

        for frame_id in tqdm(range(num_frames), desc='Detecting cars in video sequence...'):
            _, frame = vidcap.read()

            outputs = predictor(frame)

            pred_boxes = outputs["instances"].pred_boxes.to("cpu")
            scores = outputs["instances"].scores.to("cpu")

            for idx in range(len(pred_boxes)):
                box = pred_boxes[idx].tensor.numpy()[0]

                # Format: <frame>, <id>, <bb_left>, <bb_top>, <bb_width>, <bb_height>, <conf>, <x>, <y>, <z>
                det = str(frame_id + 1) + ',-1,' + str(box[0]) + ',' + str(box[1]) + ',' + str(
                    box[2] - box[0]) + ',' + str(box[3] - box[1]) + ',' + str(scores[idx].item()) + ',-1,-1,-1\n'

                with open(det_path, 'a+') as f:
                    f.write(det)

        # gt = read_annotations(os.path.join(args.data_path, args.seq, 'ai_challenge_s03_c010-full_annotation.xml'), grouped=True, use_parked=True)
        gt = read_detections(params['gt_path'], grouped=True)
        gt = fill_gt(gt, num_frames)
        det = read_detections(det_path, grouped=False)

        rec, prec, ap = voc_eval(det, gt, 0.5, use_confidence=True)
        print('AP: ', ap)

        if args.show_boxes:
            gt = read_annotations(params['gt_path'], grouped=True, use_parked=True)
            det = read_detections(det_path, grouped=True)

            vidcap = cv2.VideoCapture(params['video_path'])
            # vidcap.set(cv2.CAP_PROP_POS_FRAMES, initial_frame)  # to start from frame #frame_id
            num_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))

            for frame_id in range(num_frames):
                _, frame = vidcap.read()

                if frame_id >= 1755 and frame_id <= 1835:
                    frame = draw_boxes(frame, gt[frame_id], color='g')
                    frame = draw_boxes(frame, det[frame_id], color='b', det=True)

                    cv2.imshow('frame', frame)
                    if cv2.waitKey() == 113:  # press q to quit
                        break

            cv2.destroyAllWindows()


import sys

import pygame

import random, time

from pygame.locals import *

pygame.init()

FPS = 30

framepersec = pygame.time.Clock()

#colors

BLUE = (0, 0, 255)

RED = (255, 0, 0)

GREEN = (0, 255, 0)

BLACK = (0, 0, 0)

WHITE = (255, 255, 255)

GREY = (128, 128, 128)

SCREEN_WIDTH = 400

SCREEN_HEIGHT = 600

SPEED = 20

SCORE = 0

#Screating texts and setting fonds

font = pygame.font.SysFont("Verdana", 60)

font2 = pygame.font.SysFont("Verdana", 15)

font_small = pygame.font.SysFont("Verdana", 20)

game_over = font.render("Game Over", True, BLACK)

background = pygame.image.load("AnimatedStreet.png")

screen = pygame.display.set_mode((400, 600))

screen.fill(WHITE)

pygame.display.set_caption("Racer")

background = pygame.image.load('AnimatedStreet.png')

pygame.mixer.Sound('week10_materials_background.wav').play(-1)
class Enemy(pygame.sprite.Sprite):

    def __init__(self):

        super().__init__()

        self.image = pygame.image.load("Enemy.png")

        self.rect = self.image.get_rect()

        self.rect.center=(random.randint(40, SCREEN_WIDTH-40), 0)

    def move(self):

        self.rect.move_ip(0, 10)

        if (self.rect.bottom > 600):

            self.rect.top = 0

            self.rect.center = (random.randint(30, 370), 0)

class Player(pygame.sprite.Sprite):

    def __init__(self):

        super().__init__()

        self.image = pygame.image.load("Player.png")

        self.rect = self.image.get_rect()

        self.rect.center = (160, 520)

    def move(self):

        pressed_keys = pygame.key.get_pressed()

        if self.rect.left > 0:

              if pressed_keys[K_LEFT]:

                  self.rect.move_ip(-5, 0)

        if self.rect.right < SCREEN_WIDTH:

              if pressed_keys[K_RIGHT]:

                  self.rect.move_ip(5, 0)

class Coin(pygame.sprite.Sprite):

    def __init__(self):

        super().__init__()

        self.image = pygame.image.load('coin.png')

        self.rect = self.image.get_rect()

    def move(self):

        self.rect.move_ip(0, 10)

        if (self.rect.bottom > 600):

            self.rect.top = 0

            self.rect.center = (random.randint(30, 370), 0)

    def update(self):

        if self.rect.colliderect(Player.rect):

            Player.score += 1

            self.kill()

p1 = Player()

e1 = Enemy()

c1 = Coin()

enemies = pygame.sprite.Group()

enemies.add(e1)

coins = pygame.sprite.Group()

coins.add(c1)

all_sprites = pygame.sprite.Group()

all_sprites.add(p1)

all_sprites.add(e1)

all_sprites.add(c1)

INC_SPEED = pygame.USEREVENT + 1

pygame.time.set_timer(INC_SPEED, 1000)

while True:

    for event in pygame.event.get():

        if event.type == INC_SPEED:

            SPEED += 4

        if event.type == pygame.QUIT:

            pygame.quit()

            sys.exit()

    screen.blit(background, (0, 0))

    #в этой части кода мы двигаем и перерисовываем наши объекты

    for entity in all_sprites:

        screen.blit(entity.image, entity.rect)

        entity.move()

    #

    #in this part we increase score if player collide with coin and generate new coin after that

    if pygame.sprite.spritecollideany(p1, coins):

        SCORE += 1

        c1.rect.center = (random.randint(30, 370), 0)

        pygame.display.update()

    #this part of code show in the screen the score of the player

    score = font2.render(f"Score:{SCORE}", True, BLACK)

    screen.blit(score, (10, 10))

    if pygame.sprite.spritecollideany(p1, enemies):

        pygame.mixer.Sound('week10_materials_crash.wav').play(1)

        time.sleep(0.5)

        screen.fill(RED)

        screen.blit(game_over, (30, 250))

        pygame.display.update()

        for entity in all_sprites:

            entity.kill()

        time.sleep(2)

        pygame.quit()

        sys.exit()

    pygame.display.update()

    framepersec.tick(FPS)


import numpy.fft as fft
import numpy as np
def NH3FirstGuess(pskobj,vmin=-250.0,vmax=250):

  ckms = 2.99792458e5

  voff_lines = np.array([19.8513,
                  19.3159,
                  7.88669,
                  7.46967,
                  7.35132,
                  0.460409,
                  0.322042,
                  -0.0751680,
                  -0.213003,
                  0.311034,
                  0.192266,
                  -0.132382,
                  -0.250923,
                  -7.23349,
                  -7.37280,
                  -7.81526,
                  -19.4117,
                  -19.5500])

  tau_wts = np.array([0.0740740,
              0.148148,
              0.0925930,
              0.166667,
              0.0185190,
              0.0370370,
              0.0185190,
              0.0185190,
              0.0925930,
              0.0333330,
              0.300000,
              0.466667,
              0.0333330,
              0.0925930,
              0.0185190,
              0.166667,
              0.0740740,
              0.148148])

  deltanu = -1*voff_lines/ckms*23.6944955e9

  #guess at typical line width for NH3 line
  linewidth = 0.5
  chanwidth = (pskobj.xarr[1]-pskobj.xarr[0])/1e3
  ftdata = fft.fft(pskobj.data.filled(0))
  tvals = fft.fftfreq(len(pskobj.data))/chanwidth
  deltafcns = np.zeros(pskobj.data.shape,dtype=np.complex)
  for idx, dv in enumerate(voff_lines):
    deltafcns += tau_wts[idx]*(np.cos(2*np.pi*dv*tvals)+
                               1j*np.sin(2*np.pi*dv*tvals))*\
                               np.exp(-tvals**2*(linewidth/chanwidth)**2/(2))
  ccor = np.real((fft.ifft(np.conj(ftdata)*deltafcns))[::-1])

  vaxis = np.array(pskobj.xarr.as_unit('km/s'))
  subsetidx = (vaxis>vmin)*(vaxis<vmax)*np.isfinite(np.array(pskobj.data))
  peakIndex = np.argmax(ccor[subsetidx])

  #pull out a 6 km/s slice around the peak
  deltachan = np.abs(3.0 / chanwidth)
  t = ((pskobj.data.filled(0))[subsetidx])[(peakIndex-deltachan):(peakIndex+deltachan)]
  v = (vaxis[subsetidx])[(peakIndex-deltachan):(peakIndex+deltachan)]
  # Calculate line width.
  sigv = np.sqrt(abs(np.sum(t*v**2)/np.sum(t)-(np.sum(t*v)/np.sum(t))**2))

  if (np.isnan(sigv)):
    sigv = 0.85840189 # mean of sigv from first set of data from ./nh3_all/

  # Peak of cross correlation is the brightness.

  v0 = np.float((vaxis[subsetidx])[peakIndex])
  # Set the excitation temperature to be between CMB and 20 K
  # and equal to the peak brightness + 2.73 if valid.
  tex = np.min([np.max([pskobj.data[peakIndex],0])+2.73,20])

  guess = [20, # 20 K kinetic temperature
           tex,  #
           15, # Log NH3
           sigv, # velocity dispersion
           v0,
           0.5]
  return(guess)


tabby_cat = "\t I'm tabbed in."
persian_cat = "I'm split\non a line."
backlash_cat = "I'm \\ a \\ cat."

fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishes
\t* Catnip\n\t* Grass
"""

print(tabby_cat)
print(persian_cat)
print(backlash_cat)
print(fat_cat)

# What was that?
print(tabby_cat + "{}".format("that's_great\nnice"))
# SyntaxError: unexpected character after line continuation character