class Pipeline:

    def __init__(self,queue=[]):
        self.queue=queue

    def add_function(self,fn):
        self.queue.append(fn)

    def apply(self,signal):
        extra_output=[]
        signal_out=[]
        for f in self.queue:
            output=f(signal)
            if type(output)==list:
                signal=output[0]
                extra_output.append([output[i] for i in range(1,len(output))])
            else:
                signal=output
                extra_output.append([])
            signal_out.append(signal)
        return (signal_out,extra_output)

    def __str__(self):
        return [i.__name__ for i in self.queue]


import os
import stat
import unittest
import autoload.vim_shell_executor as sut

INPUT_FILE = "/tmp/input"
ERROR_LOG = "/tmp/error.log"
RESULTS_FILE = "/tmp/results"

class VimShellExecutorTests(unittest.TestCase):

    def tearDown(self):
        self.delete_if_present(ERROR_LOG)
        self.delete_if_present(INPUT_FILE)
        self.delete_if_present(RESULTS_FILE)

    def test_get_program_output_from_buffer_contents_returns_properly_formatted_results_when_given_valid_python_input(self):
        buffer_contents = ["python", "name = 'Jarrod'", "", "def hello():", "    print('Hello {0}'.format(name))", "", "hello()"]
        return_result = sut.get_program_output_from_buffer_contents(buffer_contents)
        expected_result = ["Hello Jarrod"]
        self.assertEqual(expected_result, return_result)

    def test_get_program_output_from_buffer_contents_returns_expected_error_when_given_invalid_input(self):
        buffer_contents = ["not_a_program", "fail = 27"]
        expected_error = ['/bin/sh: 1: not_a_program: not found']
        returned_buffer = sut.get_program_output_from_buffer_contents(buffer_contents)
        self.assertEqual(expected_error, returned_buffer)

    def test_get_program_output_from_buffer_contents_returns_expected_content_when_error_and_std_out_are_produced(self):
        buffer_contents = ["python", "print('This is good')", "raise Exception('This is bad')"]
        expected_error = ['Traceback (most recent call last):', '  File "<stdin>", line 2, in <module>', 'Exception: This is bad', 'This is good']
        returned_buffer = sut.get_program_output_from_buffer_contents(buffer_contents)
        self.assertEqual(expected_error, returned_buffer)

    def test_write_buffer_contents_to_file_writes_correct_contents_to_desired_file(self):
        buffer_contents = ["var example = function() {", "    console.log('this is an example');", "}"]
        sut.write_buffer_contents_to_file(RESULTS_FILE, buffer_contents)
        with open(RESULTS_FILE, "r") as f:
            self.assertEqual(f.readlines(), [line + "\n" for line in buffer_contents])

    def test_execute_file_with_specific_shell_program_populates_an_error_file_when_given_invalid_input_for_specified_shell_command(self):
        sut.write_buffer_contents_to_file(INPUT_FILE, ["(def name 'Jarrod')", "(println name)"])
        sut.execute_file_with_specified_shell_program('python')
        self.assertTrue(os.stat(ERROR_LOG)[stat.ST_SIZE] > 0)

    def read_file_to_string(self, file_to_read):
        with open(file_to_read, "r") as f:
            return f.readlines()

    def delete_if_present(self, file_name):
        if os.path.exists(file_name):
            os.remove(file_name)


"""The Lorenz attractor is a set of chaotic solutions of
a particular system of ordinary differential equations"""
from vedo import *

p = (25, -10, -7)  # starting point (initial condition)
dt = 0.01          # time step

# Define the ODE system to integrate (Lorenz equations)
pts, vel = [], []
for t in np.arange(0, 20, dt):
    x, y, z = p
    v = np.array([-8/3*x+y*z, -10*(y-z), -y*x+28*y-z])
    p = p + v * dt
    pts.append(p)
    vel.append(mag(v))

# Plot the trajectory in 3D space
line = Line(pts).lw(2).cmap("winter", vel).add_scalarbar("speed")
line.add_shadow("x",   3, alpha=0.2)
line.add_shadow("z", -25, alpha=0.2)
pt = Point(pts[0], c="red4", r=12).add_trail(lw=4)

def loop_func(event):
    global i
    if i < len(pts):
        pt.pos(pts[i]).update_trail() # move the point
        plt.render()
        i += 1
    else:
        plt.timer_callback("stop", tid) # stop the timer

i = 0
plt = Plotter(axes=dict(xygrid=False))
plt.show(line, pt, __doc__, viewup="z", interactive=False)
plt.add_callback("timer", loop_func)
tid = plt.timer_callback("start")
plt.interactive().close()


from gui.Scaleform.framework import VIEW_TYPE, AppRef
from gui.Scaleform.framework.managers.containers import ExternalCriteria
from tutorial import LOG_WARNING

class AttributeCriteria(ExternalCriteria):

    def __init__(self, dottedPath, value):
        super(AttributeCriteria, self).__init__((dottedPath.split('.'), value))

    def find(self, name, obj):
        path, value = self._criteria
        return self.__getValue(obj, path) == value

    def __getValue(self, popUp, path):
        nextAttr = popUp
        for attr in path:
            nextAttr = getattr(nextAttr, attr, None)

        return nextAttr

class ItemsManager(AppRef):

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

    def findTargetByCriteria(self, targetPath, valuePath, value):
        result = None
        if targetPath == VIEW_TYPE.DIALOG:
            result = self.__findDialog(valuePath, value)
        else:
            LOG_WARNING('Dialogs supported only')
        return result

    def __findDialog(self, path, value):
        result = None
        view = self.app.containerManager.getView(VIEW_TYPE.DIALOG, criteria=AttributeCriteria(path, value))
        if view is not None:
            result = (VIEW_TYPE.DIALOG, view.uniqueName)
        return result


import math
from calculate_v3 import calculate_v3

def find_optimal_theta(ro_meas, v_3, m_3, B, q, initial_theta_lab, tolerance=1e-6, max_iterations=100):
    theta_lab = initial_theta_lab
    z_mes = 2 * math.pi /B /q * m_3 * v_3 * math.cos(theta_lab)

    for i in range(max_iterations):
        R = (m_3 * v_3 * math.sin(theta_lab)) / (q * B)  # Calculate R based on the current theta_lab
        psi = 2 * math.asin(ro_meas / (2 * R))  # Calculate psi using the current theta_lab and ro_meas

        numerator = (1 - (psi / (2 * math.pi))) * z_mes - z_mes
        denominator = 1 - (psi / (2 * math.pi))
        z_next = z_mes - numerator / denominator

        if abs(z_next - z_mes) < tolerance:
            break  # Stop iterating if z converges within the tolerance

        z_mes = z_next

    theta_lab = math.acos((q * B * z_next) / (2 * math.pi * m_3 * v_3))
    return theta_lab

ro_meas = 0.5
m_3 = 2.0
B = 1.0
q = 1.6e-19
initial_theta_lab = 0.1

# Call the calculate_v3 function from the v3_calculation.py file
v_3 = 1.0

optimal_theta_lab = find_optimal_theta(ro_meas, v_3, m_3, B, q, initial_theta_lab)
print(f"Optimal theta_lab: {optimal_theta_lab}")


cc = 0
dc = 0
po = raw_input("look at your current station. what is it's name? ")
if po == 'srrvyce':
    cc = 1
elif po == 'tuomo':
    cc = 2
elif po == 'leeo':
    cc = 3
elif po == 'polutica':
    cc = 4
elif po == 'orvochino':
    cc = 5
elif po == 'loino':
    cc = 6
elif po == 'ilumitcio':
    cc = 7
else :
    print("sorry, that is not a station")
    quit()
pp = raw_input("look at your destination station. what is it's name? ")
if pp == 'srrvyce':
    dc = 1
elif pp == 'tuomo':
    dc = 2
elif pp == 'leeo':
    dc = 3
elif pp == 'polutica':
    dc = 4
elif pp == 'orvochino':
    dc = 5
elif pp == 'loino':
    dc = 6
elif pp == 'ilumitcio':
    dc = 7
else :
    print("sorry, that is not a station")
    quit()
dist = abs(cc - dc)
fare = dist * 1.05
print ("your fare is $"),
print("{:.2f}".format(fare))


from torch.utils.data import Dataset, DataLoader
import numpy as np
import os
import torch
from PIL import Image
from torchvision import transforms

class ProjectDataset(Dataset):

    def __init__(self, base_dir):
        self.root_dir = base_dir
        self.episodes = [p for p in os.listdir(
            base_dir) if p.startswith('episode')]
        self.num_episodes = len(self.episodes)
        episode_len = []
        for episode in self.episodes:
            episode_dir = os.path.join(base_dir, episode)
            episode_len.append(len(os.listdir(episode_dir)) // 4)

        self.episode_len = episode_len

        self.transform = transforms.Compose([transforms.CenterCrop(512),
                                             transforms.ToTensor()])

    def __len__(self):
        return sum(self.episode_len)

    def __getitem__(self, idx):
        episode_num = idx % self.num_episodes
        episode = self.episodes[episode_num]
        point_ID = idx % self.episode_len[episode_num]
        img = self.transform(self.get_raw_img(episode, point_ID))
        seg_GT = self.transform(
            self.get_segmentation_img(episode, point_ID))[0, :, :]*255
        depth_img = self.transform(self.get_depth_img(episode, point_ID))
        depth_GT = torch.Tensor(self.depth_to_array(depth_img))

        return img, seg_GT, depth_GT

    def depth_to_array(self, image):
        img = np.array(image.permute((1, 2, 0)))
        # Apply (R + G * 256 + B * 256 * 256) / (256 * 256 * 256 - 1).
        normalized_depth = np.dot(img, [1.0, 256.0, 65536.0])
        normalized_depth /= 16777215.0  # (256.0 * 256.0 * 256.0 - 1.0)
        normalized_depth *= 1000 * 255
        return normalized_depth

    def get_raw_img(self, episode, point_ID):
        file_name = 'CentralRGB_' + str(point_ID).zfill(5) + '.png'
        file_path = os.path.join(
            self.root_dir, os.path.join(episode, file_name))
        return Image.open(file_path)

    def get_segmentation_img(self, episode, point_ID):
        file_name = 'CentralSemanticSeg_' + str(point_ID).zfill(5) + '.png'
        file_path = os.path.join(
            self.root_dir, os.path.join(episode, file_name))
        return Image.open(file_path)

    def get_depth_img(self, episode, point_ID):
        file_name = 'CentralDepth_' + str(point_ID).zfill(5) + '.png'
        file_path = os.path.join(
            self.root_dir, os.path.join(episode, file_name))
        return Image.open(file_path)

if __name__ == "__main__":
    dataset = ProjectDataset(base_dir='episodes/')

    dataloader = DataLoader(
        dataset, batch_size=1, shuffle=True, num_workers=1)
    # dataloader = DataLoader(vqa_dataset, batch_size=100)
    print(dataloader)
    # sample = vqa_dataset[1]
    # print(sample)

    for i_batch, sample_batched in enumerate(dataloader):
        print(i_batch, torch.max(
            sample_batched[1]), torch.min(sample_batched[1]))

        img, seg_GT, depth_GT = sample_batched
        print(img.shape)
        print(depth_GT.min())
        print(depth_GT.max())
        print(seg_GT.shape)
        print(seg_GT.max())
        print(seg_GT.min())
        print(depth_GT.shape)
        if(i_batch == 10):
            break
    # print(i, sample['image'].shape, sample['landmarks'].shape)


# sourcery skip: avoid-builtin-shadow
import boto3
import time

client = boto3.client('athena')

response_query = client.start_query_execution(
    QueryString='SELECT * FROM "dev_raw"."vw_openactive_api_individual_facility_use_slots_offers" limit 10;',
    QueryExecutionContext={
        'Database': 'dev_raw'
    },
    ResultConfiguration={
        'OutputLocation': 's3://athena-results-usta/athena-results/unsaved'
    },
    WorkGroup='primary'

)
time.sleep(60)
id = response_query['QueryExecutionId']
response = client.get_query_results(
    QueryExecutionId=id,
    MaxResults=10
)
print(response)


# class vector2d:
#     def __init__(self,i,j):
#         self.i=i
#         self.j=j
#     def __str__(self):
#         return f'{self.i} + {self.j}'
# class vector3d(vector2d):
#     def __init__(self,i,j,k):
#         super().__init__(i,j)
#         self.k=k
#     def __str__(self):
#         return f'{self.i} + {self.j} + {self.k}'
# v2d=vector2d(2,3)
# v3d=vector3d(3,5,7)
# # print(v2d)
# print(v3d)

# class Animal:
#     def __init__(self):
#
#         print('im an Animal')
# class pet(Animal):
#     def __init__(self):
#         super().__init__()
#
#         print('In a Pet')
# class Dog(pet):
#     def __init__(self):
#
#         super().__init__()
#         print('im a dog')
#     def bark(self):
#         print('bhao bhaio bahao')
# animal=Animal()
# pet=pet()
# dog=Dog()
# dog.bark()

class Employee:
    def __init__(self,salary,increment):
        self.salary=salary
        self.increment=increment
    @property
    def AfterIncrement(self):
        return self.salary * self.increment
    @AfterIncrement.setter
    def AfterIncrement(self,inc):
        self.increment=inc/ self.salary

e=Employee(1000,1.5)
print(e.AfterIncrement)
print(e.increment)
e.AfterIncrement=2000
print(e.increment)
print(e.AfterIncrement)
# print(e.AfterIncrement)