# coding: utf-8

import pytest
import numpy as np
from imageio import imread
from AxonDeepSeg.data_management.data_augmentation import *

class TestCore(object):
    def setup(self):
        # Remember that the stop value in "arrange" is not included
        x = np.arange(0, 16, dtype='uint8')
        y = np.arange(0, 16, dtype='uint8')
        xv, yv = np.meshgrid(x, y)
        self.testImage = xv+yv

        self.mask = np.ones((16, 16, 3), dtype=int)

    def teardown(self):
        pass

    # --------------data_augmentation.py tests-------------- #
    # **NOTE** Because most data augmentation functions chose the parameters
    # randomly within bounds set by the arguments, it's impossible to target
    # test cases for known shifts, rotations, etc. Thus, only broad tests are
    # defined (output dim = input dim, output patch different or same as input
    # patch)

    @pytest.mark.unit
    def test_shifting_returns_different_image(self):
        patch = [self.testImage, self.mask]
        augmentedPatch = shifting(patch, verbose=1)

        assert augmentedPatch[0].shape == patch[0].shape
        assert augmentedPatch[1].shape == patch[1].shape
        assert np.not_equal(augmentedPatch[0], patch[0]).any()

    @pytest.mark.unit
    def test_rescaling_factor_1_returns_same_image(self):
        patch = [self.testImage, self.mask]
        augmentedPatch = rescaling(patch, factor_max=1, verbose=1)

        assert augmentedPatch[0].shape == patch[0].shape
        assert augmentedPatch[1].shape == patch[1].shape
        assert np.equal(augmentedPatch[0], patch[0]).all()

    @pytest.mark.unit
    def test_large_max_rescaling_factor_returns_different_image(self):
        # Note: Since there
        patch = [self.testImage, self.mask]
        augmentedPatch = rescaling(patch, factor_max=100, verbose=1)

        assert augmentedPatch[0].shape == patch[0].shape
        assert augmentedPatch[1].shape == patch[1].shape

        assert np.not_equal(augmentedPatch[0], patch[0]).any()
        # Note: due to  therandomized rescaling factor choice,
        # there is an unavoidable possibility that this test fails
        # simply due to bad luck, so try running the test suite again.

    @pytest.mark.unit
    def test_random_rotation_returns_different_image(self):
        patch = [self.testImage, self.mask]
        augmentedPatch = random_rotation(patch, verbose=1)

        assert augmentedPatch[0].shape == patch[0].shape
        assert augmentedPatch[1].shape == patch[1].shape
        assert np.not_equal(augmentedPatch[0], patch[0]).any()

    @pytest.mark.unit
    def test_elastic_returns_different_image(self):
        patch = [self.testImage, self.mask]
        augmentedPatch = elastic(patch, verbose=1)

        assert augmentedPatch[0].shape == patch[0].shape
        assert augmentedPatch[1].shape == patch[1].shape
        assert np.not_equal(augmentedPatch[0], patch[0]).any()

    @pytest.mark.unit
    def test_flipping_returns_different_image(self):
        # Since the flipping only occurs randomly thus has a probability of
        # not getting flipped, this low-level test only covers the same image
        # size assertions.

        patch = [self.testImage, self.mask]
        augmentedPatch = flipping(patch, verbose=1)

        assert augmentedPatch[0].shape == patch[0].shape
        assert augmentedPatch[1].shape == patch[1].shape

    @pytest.mark.unit
    def test_gaussian_blur_returns_image_of_same_size(self):
        # Because the sigma blur size is also random, it's very difficult to
        # test for a known case (different/same image), so this low-level test
        # only covers the same image size assertions.

        patch = [self.testImage, self.mask]
        augmentedPatch = gaussian_blur(patch, verbose=1)

        assert augmentedPatch[0].shape == patch[0].shape
        assert augmentedPatch[1].shape == patch[1].shape


from django.urls import path

from . import views

app_name = "api"
urlpatterns = [
    path("create/", views.create, name="create"),
    path("read/", views.read, name="read"),
    path("update/", views.update, name="update"),
    path("delete/", views.delete, name="delete"),
    path("read/<int:transaction_id>/", views.read_by_id, name="read_by_id"),
]


import os
import sublime
import unittest

from ..consts import INFO, WARNING, ERROR
from ..utils import (
    find,
    get_default_python_command,
    get_severity_status_string,
    get_error_count,
)

def merge_two_lists(fst, snd):
    return fst + list(set(snd) - set(fst))

class TestUtils(unittest.TestCase):
    def setUp(self):
        self.real_path_environ = os.environ["PATH"]
        self.subl_error_message = sublime.error_message
        self.message_info = {}
        self.message_info[INFO] = 11
        self.message_info[WARNING] = 7
        self.message_info[ERROR] = 4

    def test_find_success(self):
        errors = [
            {"id": 1, "region": range(123, 222)},
            {"id": 2, "region": range(389, 562)},
        ]
        point = 437
        elem = find(point, errors)
        self.assertEqual(elem.get("id"), 2)

    def test_find_failure(self):
        errors = [
            {"id": 1, "region": range(123, 222)},
            {"id": 2, "region": range(389, 562)},
        ]
        point = 837
        elem = find(point, errors)
        self.assertRaises(Exception)

    def test_get_default_python_command_success(self):
        return_val = get_default_python_command()
        self.assertEqual(return_val, 'python3')

    def test_get_default_python_command_fail(self):
        os.environ["PATH"] = os.path.sep
        sublime.error_message = print
        return_val = get_default_python_command()
        self.assertIsNone(return_val)
        os.environ["PATH"] = self.real_path_environ
        sublime.error_message = self.subl_error_message

    def test_merge_two_lists_both_empty(self):
        result = merge_two_lists([], [])
        self.assertEqual(len(result), 0)

    def test_merge_two_lists_one_empty(self):
        result = merge_two_lists(["one", "two", 3], [])
        self.assertEqual(len(result), 3)
        self.assertIn("one", result)

    def test_merge_two_lists_both_with_elements(self):
        result = merge_two_lists(["one", "two", 3], ["blue", True, "something"])
        self.assertEqual(len(result), 6)
        self.assertIn("one", result)
        self.assertIn("something", result)
        self.assertIn(True, result)

    def test_merge_two_lists_with_overlapping_elements(self):
        result = merge_two_lists(["one", "two", 3, True], ["blue", True, "one"])
        self.assertEqual(len(result), 5)
        self.assertIn("one", result)
        self.assertIn("blue", result)
        self.assertIn(True, result)

    def test_get_severity_status_string_info(self):
        result = get_severity_status_string(INFO)
        self.assertEqual(result, "   ⓘ")

    def test_get_severity_status_string_warning(self):
        result = get_severity_status_string(WARNING)
        self.assertEqual(result, "   ⚠")

    def test_get_severity_status_string_error(self):
        result = get_severity_status_string(ERROR)
        self.assertEqual(result, "   ⛔")

    def test_get_error_count(self):
        result = get_error_count(self.message_info, "something something ")
        self.assertEqual(result, "something something ⛔ 4 ⚠ 7 ⓘ 11 ")

if __name__ == "__main__":
    unittest.main()


from openeis.applications import DriverApplicationBaseClass, InputDescriptor, \
    OutputDescriptor, ConfigDescriptor, Descriptor
from openeis.applications import reports
import logging
import datetime as dt
from django.db.models import Avg
from openeis.applications.utils.baseline_models import day_time_temperature_model as ttow
from openeis.applications.utils import conversion_utils as cu

class Application(DriverApplicationBaseClass):

    def __init__(self, *args, building_name=None,
                              baseline_startdate=None,
                              baseline_stopdate=None,
                              savings_startdate=None,
                              savings_stopdate=None,
                              **kwargs):
        # Called after app has been staged
        """
        When applications extend this base class, they need to make
        use of any kwargs that were setup in config_param
        """
        super().__init__(*args, **kwargs)

        self.default_building_name_used = False

        if building_name is None:
            building_name = "None supplied"
            self.default_building_name_used = True

        self.building_name = building_name
        self.baseline_start = dt.datetime.strptime(baseline_startdate, '%Y-%m-%d')
        self.baseline_stop = dt.datetime.strptime(baseline_stopdate, '%Y-%m-%d')
        self.savings_start = dt.datetime.strptime(savings_startdate, '%Y-%m-%d')
        self.savings_stop = dt.datetime.strptime(savings_stopdate, '%Y-%m-%d')

    @classmethod
    def get_self_descriptor(cls):
        name = 'Whole-Building Energy Savings'
        desc = 'Whole-building Energy savings is used to quantify\
                the energy savings associated with an improvement\
                in building operations or equipment. Energy savings\
                is calculated as the difference between the metered\
                energy use after improvements were made, and the baseline\
                projection of energy use.'
        return Descriptor(name=name, description=desc)

    @classmethod
    def get_config_parameters(cls):
        # Called by UI
        # load_query = self.inp.get_query_sets('load', group_by='day')
        return {
            "building_name": ConfigDescriptor(str, "Building Name", optional=True),
            "baseline_startdate": ConfigDescriptor(str, "Baseline Start Date (YYYY-MM-DD)", optional=False),
            "baseline_stopdate": ConfigDescriptor(str, "Baseline End Date (YYYY-MM-DD)", optional=False),
            "savings_startdate": ConfigDescriptor(str, "Savings Start Date (YYYY-MM-DD)", optional=False),
            "savings_stopdate": ConfigDescriptor(str, "Savings End Date (YYYY-MM-DD)", optional=False)
            }

    @classmethod
    def required_input(cls):
        # Called by UI
        # Sort out units.
        return {
            'oat':InputDescriptor('OutdoorAirTemperature', 'Outdoor Temperature'),
            'load':InputDescriptor('WholeBuildingPower', 'Building Load')
            }

    @classmethod
    def output_format(cls, input_object):
        # Called when app is staged
        """
        Output:
            datetimeValues: datetime objectes for each energy value.
            predictedValues: values returned after applying the day_time model
            measuredValues: values directly measured from the building
        """
        topics = input_object.get_topics()
        load_topic = topics['load'][0]
        load_topic_parts = load_topic.split('/')
        output_topic_base = load_topic_parts[:-1]

        # TODO: Should names derived from "day time temperature model" be replaced, to
        # reflect the new branding of this application as "whole building energy savings"?
        time_values = '/'.join(output_topic_base + ['daytimetemperature', 'datetime'])
        predicted_values = '/'.join(output_topic_base + ['daytimetemperature', 'predicted'])
        measured_values  = '/'.join(output_topic_base + ['daytimetemperature', 'measured'])
        cusum_values  = '/'.join(output_topic_base + ['daytimetemperature', 'cusum'])

        output_needs = {
            'DayTimeTemperatureModel': {
                'datetimeValues': OutputDescriptor('datetime', time_values),
                'measured': OutputDescriptor('float', measured_values),
                'predicted': OutputDescriptor('float', predicted_values),
                'cumulativeSum' : OutputDescriptor('float', cusum_values)
                }
            }
        return output_needs

    @classmethod
    def reports(cls, output_object):
        # Called by UI to create Viz
        """Describe how to present output to user
        Display this viz with these columns from this table

        display_elements is a list of display objects specifying viz and columns
        for that viz
        """

        report = reports.Report('Whole-Building Energy Savings')

        text_blurb = reports.TextBlurb(text="Analysis shows the cumulative sum of the savings between the \
                                            baseline model and the measured values for a single building.")
        report.add_element(text_blurb)

        xy_dataset_list = []
        xy_dataset_list.append(reports.XYDataSet('DayTimeTemperatureModel', 'datetimeValues', 'cumulativeSum'))
        cumsum_plot = reports.DatetimeScatterPlot(xy_dataset_list,
                                   title='Cumulative Whole Building Energy Savings',
                                   x_label='Timestamp',
                                   y_label='Energy [kWh]'
                                   )
        report.add_element(cumsum_plot)

        text_guide1= reports.TextBlurb(text="A flat slope of the cumulative sum time series indicates that use has\
                                             remained the same. A positive slope indicates energy savings, while a \
                                             negative slope indicates that more energy is being used after the \
                                             supposed \"improvement\" date")
        report.add_element(text_guide1)

        report_list = [report]

        return report_list

    def execute(self):
        # Called after User hits GO
        """
        Calculates weather sensitivity using Spearman rank.
        Also, outputs data points for energy signature scatter plot.
        """
        self.out.log("Starting application: whole building energy savings.", logging.INFO)

        # Gather loads and outside air temperatures. Reduced to an hourly average
        self.out.log("Querying database.", logging.INFO)
        load_query = self.inp.get_query_sets('load', group_by='hour',
                                             group_by_aggregation=Avg,
                                             exclude={'value':None},
                                             wrap_for_merge=True)
        oat_query = self.inp.get_query_sets('oat', group_by='hour',
                                             group_by_aggregation=Avg,
                                             exclude={'value':None},
                                             wrap_for_merge=True)

        self.out.log("Getting unit conversions.", logging.INFO)
        base_topic = self.inp.get_topics()
        meta_topics = self.inp.get_topics_meta()

        load_unit = meta_topics['load'][base_topic['load'][0]]['unit']
        self.out.log(
            "Convert loads from [{}] to [kW].".format(load_unit),
            logging.INFO
            )
        load_convertfactor = cu.getFactor_powertoKW(load_unit)

        temperature_unit = meta_topics['oat'][base_topic['oat'][0]]['unit']
        self.out.log(
            "Convert temperatures from [{}] to [F].".format(temperature_unit),
            logging.INFO
            )

        # Match the values by timestamp
        merged_load_oat = self.inp.merge(load_query, oat_query)

        load_values = []
        oat_values = []
        datetime_values = []

        for x in merged_load_oat:
            if temperature_unit == 'celcius':
                convertedTemp = cu.convertCelciusToFahrenheit(x['oat'][0])
            elif temperature_unit == 'kelvin':
                convertedTemp = cu.convertKelvinToCelcius(
                                cu.convertCelciusToFahrenheit(x['oat'][0]))
            else:
                convertedTemp = x['oat'][0]

            load_values.append(x['load'][0] * load_convertfactor) #Converted to kWh
            oat_values.append(convertedTemp)
            datetime_values.append(x['time'])

        indexList = {}
        indexList['trainingStart'] = ttow.findDateIndex(datetime_values, self.baseline_start)
        self.out.log('@trainingStart '+str(indexList['trainingStart']), logging.INFO)
        indexList['trainingStop'] = ttow.findDateIndex(datetime_values, self.baseline_stop)
        self.out.log('@trainingStop '+str(indexList['trainingStop']), logging.INFO)
        indexList['predictStart'] = ttow.findDateIndex(datetime_values, self.savings_start)
        self.out.log('@predictStart '+str(indexList['predictStart']), logging.INFO)
        indexList['predictStop'] = ttow.findDateIndex(datetime_values, self.savings_stop)
        self.out.log('@predictStop '+str(indexList['predictStop']), logging.INFO)

        for indx in indexList.keys():
            if indexList[indx] == None:
                self.out.log("Date not found in the datelist", logging.WARNING)

        # Break up data into training and prediction periods.
        timesTrain = datetime_values[indexList['trainingStart']:indexList['trainingStop']]
        timesPredict = datetime_values[indexList['predictStart']:indexList['predictStop']]

        valsTrain = load_values[indexList['trainingStart']:indexList['trainingStop']]
        valsActual = load_values[indexList['predictStart']:indexList['predictStop']]

        oatsTrain = oat_values[indexList['trainingStart']:indexList['trainingStop']]
        oatsPredict = oat_values[indexList['predictStart']:indexList['predictStop']]

        # Generate other information needed for model.
        timeStepMinutes = (timesTrain[1] - timesTrain[0]).total_seconds()/60
        # TODO: Should this be calculated in the utility function
        binCt = 6  # TODO: Allow caller to pass this in as an argument.

        # Form the temperature-time-of-week model.
        self.out.log("Finding baseline model", logging.INFO)
        ttowModel = ttow.formModel(timesTrain,
                                   oatsTrain,
                                   valsTrain,
                                   timeStepMinutes,
                                   binCt)

        # Apply the model.
        self.out.log("Applying baseline model", logging.INFO)
        valsPredict = ttow.applyModel(ttowModel, timesPredict, oatsPredict)

        # Output for scatter plot
        prevSum = 0
        for ctr in range(len(timesPredict)):
            # Calculate cumulative savings.
            prevSum += (valsPredict[ctr] - valsActual[ctr])
            local_time = str(self.inp.localize_sensor_time(base_topic['load'][0], timesPredict[ctr]))
            self.out.insert_row("DayTimeTemperatureModel", {
                                "datetimeValues": local_time,
                                "measured": valsActual[ctr],
                                "predicted": valsPredict[ctr],
                                "cumulativeSum": prevSum
                                })


from collections import Counter
mn = input()
m_n = mn.split(' ')
m = int(m_n[0])
n = int(m_n[1])
input_array = input()
input_array_list = input_array.split(' ')
input_array_set = set(input_array_list)

like_set = input()
input_like_set = set(like_set.split(' '))

dislike_set = input()
input_dislike_set = set(dislike_set.split(' '))

result = 0
like_inter = input_array_set.intersection(input_like_set)
dislike_inter = input_array_set.intersection(input_dislike_set)

c=Counter(input_array_list)
for item in like_inter:
    result += c[str(item)]

for item in dislike_inter:
    result -= c[str(item)]

print(result)


import requests
from bs4 import BeautifulSoup
import time, uuid
from datetime import datetime, timedelta
from database import connectToDatabase

def time24hrsback():             #gives the timestamp before 24 hrs
    before24Hours = datetime.today() - timedelta(days=1)
    return before24Hours

def alreadycrawled(link):        #to check if the link is already cralwed between last 24 hrs
    db = connectToDatabase()
    condition = { '$and' : [{"link":link},{"time": {"$gte": time24hrsback()}}] }
    if (db.Links.count_documents(condition) > 0) :
        db.Links.update_many({"link":link}, {"$set" : { 'isCrawled': True,
                'lastCrawlDt': datetime.today().replace(microsecond=0)}})

        return True
    else :
        return False

def getResponse(link):
    response = requests.get(link)
    return(response)

def saveFile(link):
    response = getResponse(link)
    soup = BeautifulSoup(response.content, 'html5lib')
    random_file = str(uuid.uuid4())           #gives random name to the file
    with open ("html/{}.html".format(random_file), 'w') as file:
       file.write(soup.prettify())
    filePath= ("html/{}.html".format(random_file))
    return filePath

def validLinks(link):
    response = requests.get(link)
    soup = BeautifulSoup(response.content, 'html5lib')
    atags = soup.find_all("a", href=True)             #to find all anchor tags with 'href' attribute

    links =[]
    no_of_links = 0

    for i in atags:
        href = i['href']

        if(i.get('href') == '#' ):
            #invalid Link
            continue

        if(i.get('href') =='javascript:'):
           #invalid Link
           continue

        if(i.get('href') ==''):
           #Invalid Link
           continue

        if(i.get('href') =='#xyz'):
           #Invalid Link
           continue

        if(i.get('href') =='http://'):
           #valid Link
           #absolute Link
           links.append(href)
           no_of_links += 1
           continue

        if(i.get('href') =='//'):
           #valid link
           #append
           links.append('https:' + href)
           no_of_links += 1
           continue

    if(no_of_links == 0):
        print('All links crawled')
    return links

time.sleep(10)


import PySimpleGUI as sg
from signup import sign_up_gui
def driver_gui(db):
    sg.theme('LightGrey1')   # Add a touch of color
    # All the stuff inside your window.
    # get the list of cars that belong to the driver
    username = db.get_username()
    print(username)

    user_data = db.get_driver_info(username)
    print(user_data)
    cars = db.get_cars(username)
    cars = [car[0] for car in cars]
    trip = db.get_driver_trip(username)
    print(trip)
    state_list = ['Waiting for approval',  'On the way', 'Passenger in the car', 'Delivered', 'Cancelled']
    if cars == []:
        layout = [  [sg.Image(r'logo50.png')],
                    [sg.Text('Hey! You have no cars registered yet!')],
                    [sg.Button('Register a car'), sg.Button('Cancel')] ]
    elif len(cars)>0:
        layout = [[sg.Image(r'logo50.png')],
                [sg.Text('Hey! Here is your trip information.',visible=len(trip)>0), sg.Checkbox("Availability", user_data[-3], checkbox_color="blue", key="availability", visible=len(cars)>0)],
                [sg.Text('Hey! You have no trips registered yet! Wait for a passenger to request a trip. Your trips will appear here.', visible=len(trip)==0)],
                [sg.Listbox(values=trip, size=(60, 6), key='trip', visible=len(trip)>0)],
                [sg.Button('Select Trip',visible=len(trip)>0), sg.Button('Set Availability', visible = len(cars)>0), sg.Button('Exit')]]

    # Create the Window
    window = sg.Window('RideLink - Driver', layout)

    # Event Loop to process "events" and get the "values" of the inputs
    while True:
        event, values = window.read()

        if event == 'Register a car':
            register_car_gui(db)
            break
        elif event == 'Start':
            driver_gui(db)
            break
        elif event == 'Select Trip':
            if values['trip'] == []:
                sg.popup('Please select a trip!')
                continue
                #['21, 1, 34 ALP 64, 2023-05-21 21:13:11, Waiting for approval', '7, 2, 35 FT 454, 2023-04-27 07:06:39, Passenger in the car']
            selected_trip = values['trip'][0].split(', ') # Get the first selected item
            layout = [[sg.Image(r'logo50.png')],
                    [sg.Text('Hey! Here is your trip information.')],
                    [sg.Text('Trip ID: ' + selected_trip[0])],
                    [sg.Text('Car Plate: ' + selected_trip[2])],
                    [sg.Text('Start Time: ' + selected_trip[3])],
                    [sg.Combo(state_list[state_list.index(selected_trip[4]):int(state_list.index(selected_trip[4]))+1 if state_list.index(selected_trip[4])>2   else int(len(state_list))], default_value=selected_trip[4], key='status')],
                    [sg.Button('Change Status'), sg.Button('Cancel')]]
            window.close()
            window = sg.Window('RideLink - Driver', layout)

        elif event == 'Change Status':
            if values['status'] == selected_trip[4]:
                sg.popup('Status not changed!')
                continue
            db.update_trip_status(selected_trip[0], values['status'])
            sg.popup('Status changed!')
            driver_gui(db)
            break
        elif event == 'Set Availability':
            if values['availability'] == user_data[-3]:
                sg.popup('Availability not changed!')
                continue
            db.update_driver_availability(username, values['availability'])
            sg.popup('Availability changed!')
            driver_gui(db)
            break
        elif event == 'Cancel':
            driver_gui(db)
            break
        elif event == 'Exit':
            break

    window.close()

def register_car_gui(db):
    print('s')


import torch
import torch.nn as nn
from mmcv.runner import BaseModule
from ..builder import NECKS

def gen_dx_bx(xbound, ybound, zbound):
    # xbound: [low_bound, upper_bound, size]
    # 'xbound': [-51.2, 51.2, 0.8]
    # 'ybound': [-51.2, 51.2, 0.8]
    # 'zbound': [-10.0, 10.0, 20.0]
    dx = torch.Tensor([row[2] for row in [xbound, ybound, zbound]]) # [0.8, 0.8, 20]
    bx = torch.Tensor([row[0] + row[2]/2.0 for row in [xbound, ybound, zbound]]) # [-50.8, -50.8, 0]
    nx = torch.Tensor([(row[1] - row[0]) / row[2] for row in [xbound, ybound, zbound]]) # [128, 128, 1]
    return dx, bx, nx

def cumsum_trick(x, geom_feats, ranks):
    x = x.cumsum(0) # (135577, 64) 沿着行累加
    kept = torch.ones(x.shape[0], device=x.device, dtype=torch.bool) # 135577
    kept[:-1] = (ranks[1:] != ranks[:-1]) # trick:坐标在同一个pillar内的点只保留一个
    x, geom_feats = x[kept], geom_feats[kept] # 提取被保留的voxel特征和geo特征 (35769, 64)和(35769, 4)
    x = torch.cat((x[:1], x[1:] - x[:-1])) # (35769, 64) 计算每个pillar内的特征，并与第一行拼接
    return x, geom_feats

class QuickCumsum(torch.autograd.Function):
    @staticmethod
    def forward(ctx, x, geom_feats, ranks):
        x = x.cumsum(0) # (1761017, 64) 沿着行累加
        kept = torch.ones(x.shape[0], device=x.device, dtype=torch.bool) # 1761017
        kept[:-1] = (ranks[1:] != ranks[:-1]) # trick:坐标在同一个pillar内的点只保留一个

        x, geom_feats = x[kept], geom_feats[kept] # 提取被保留的voxel特征和geo特征 (120991, 64)和(120991, 4)
        x = torch.cat((x[:1], x[1:] - x[:-1])) # (120991, 64) 计算每个pillar内的特征，并与第一行拼接(与cumsum结合的巧妙操作)

        # save kept for backward
        ctx.save_for_backward(kept) # 几何特征不求梯度

        # no gradient for geom_feats
        ctx.mark_non_differentiable(geom_feats)

        return x, geom_feats

    @staticmethod
    def backward(ctx, gradx, gradgeom):
        kept, = ctx.saved_tensors
        back = torch.cumsum(kept, 0) # 对于一维特征，沿着列累加
        back[kept] -= 1 # 减一变为索引

        val = gradx[back] # 提取上下文特征对应位置的梯度，几何特征不求梯度

        return val, None, None # 对应输入

@NECKS.register_module()
class ViewTransformerLiftSplatShoot(BaseModule):
    def __init__(self, grid_config=None, data_config=None,
                 numC_input=512, numC_Trans=64, downsample=16,
                 image_view_supervision=False, voxel=False, **kwargs):
        super(ViewTransformerLiftSplatShoot, self).__init__()
        if grid_config is None:
            grid_config = {
                'xbound': [-51.2, 51.2, 0.8],
                'ybound': [-51.2, 51.2, 0.8],
                'zbound': [-10.0, 10.0, 20.0],
                'dbound': [1.0, 60.0, 1.0],}
        self.grid_config = grid_config
        dx, bx, nx = gen_dx_bx(self.grid_config['xbound'],
                               self.grid_config['ybound'],
                               self.grid_config['zbound'],
                               )
        self.dx = nn.Parameter(dx, requires_grad=False) # [0.8, 0.8, 20]
        self.bx = nn.Parameter(bx, requires_grad=False) # [-50.8, -50.8, 0]
        self.nx = nn.Parameter(nx, requires_grad=False) # [128, 128, 1]

        if data_config is None:
            data_config = {'input_size': (256, 704)}
        self.data_config = data_config
        self.downsample = downsample # 下采样16倍

        self.frustum = self.create_frustum()
        self.D, _, _, _ = self.frustum.shape
        self.numC_input = numC_input
        self.numC_Trans = numC_Trans
        self.depthnet = nn.Conv2d(self.numC_input, self.D + self.numC_Trans, kernel_size=1, padding=0)
        self.geom_feats = None
        self.image_view_supervision = image_view_supervision
        self.voxel=voxel

    def get_depth_dist(self, x):
        return x.softmax(dim=1)

    def create_frustum(self):
        # make grid in image plane
        ogfH, ogfW = self.data_config['input_size'] # 256, 704
        fH, fW = ogfH // self.downsample, ogfW // self.downsample # 16, 44
        ds = torch.arange(*self.grid_config['dbound'], dtype=torch.float).view(-1, 1, 1).expand(-1, fH, fW)
        D, _, _ = ds.shape # 59
        xs = torch.linspace(0, ogfW - 1, fW, dtype=torch.float).view(1, 1, fW).expand(D, fH, fW)
        ys = torch.linspace(0, ogfH - 1, fH, dtype=torch.float).view(1, fH, 1).expand(D, fH, fW)

        # D x H x W x 3
        frustum = torch.stack((xs, ys, ds), -1) # (59, 16, 44, 3) 在原图上间隔采样16个像素采样，并且深度从1-60米，间隔1米采样
        return nn.Parameter(frustum, requires_grad=False)

    def get_geometry(self, rots, trans, intrins, post_rots, post_trans, offset=None):
        """Determine the (x,y,z) locations (in the ego frame)
        of the points in the point cloud.
        Returns B x N x D x H/downsample x W/downsample x 3
        """
        B, N, _ = trans.shape

        # undo post-transformation 恢复到图像变换前的点 P' = R*P + t --> P = R^(-1) * (P' - t)
        # B x N x D x H x W x 3
        # self.frustum:(59, 16, 44, 3) 这里是图片变换后特征图产生的点是P'
        # post_trans:(8, 5, 3) --> (8, 6, 1, 1, 1, 3)
        points = self.frustum - post_trans.view(B, N, 1, 1, 1, 3) # (8, 6, 59, 16, 44, 3)
        if offset is not None:
            _,D,H,W = offset.shape
            points[:,:,:,:,:,2] = points[:,:,:,:,:,2]+offset.view(B,N,D,H,W)
        # post_rots:(8, 6, 3, 3) --> (8, 6, 1, 1, 1, 3, 3)
        # points:(8, 6, 59, 16, 44, 3)--> (8, 6, 59, 16, 44, 3, 1)
        # 这里的变换包含resize，此时已经恢复到900x1600的原始图片对应点
        # frustum生成是在特征图上均匀撒点，但是经过数据增强逆变换后会对应到原图的上的不同点，对齐特征
        points = torch.inverse(post_rots).view(B, N, 1, 1, 1, 3, 3).matmul(points.unsqueeze(-1))

        # cam_to_lidar
        points = torch.cat((points[:, :, :, :, :, :2] * points[:, :, :, :, :, 2:3],
                            points[:, :, :, :, :, 2:3]
                            ), 5) # 逆归一化 --> (8, 6, 59, 16, 44, 3, 1)
        if intrins.shape[3]==4: # for KITTI
            shift = intrins[:,:,:3,3]
            points  = points - shift.view(B,N,1,1,1,3,1)
            intrins = intrins[:,:,:3,:3]
        # 这里的rot和trans都是经过点云增强后的矩阵
        # 相当于对伪点云做增强，gt随着增强，因为伪点云特征和gt是可以对应上的
        combine = rots.matmul(torch.inverse(intrins)) # 乘相机内参恢复到相机坐标系下，然后乘相机到lidar的旋转矩阵，变换到lidar系下
        points = combine.view(B, N, 1, 1, 1, 3, 3).matmul(points).squeeze(-1) # (8, 6, 59, 16, 44, 3)
        points += trans.view(B, N, 1, 1, 1, 3) # (8, 6, 59, 16, 44, 3)

        # points_numpy = points.detach().cpu().numpy()
        return points # (8, 6, 59, 16, 44, 3)

    def voxel_pooling(self, geom_feats, x):
        B, N, D, H, W, C = x.shape # 8, 6, 59, 16, 44, 64
        Nprime = B * N * D * H * W # 1993728
        nx = self.nx.to(torch.long) # [128, 128, 1]
        # flatten x
        x = x.reshape(Nprime, C) # (1993728, 64)

        # flatten indices
        # 这里转换为voxle(pillar)坐标
        geom_feats = ((geom_feats - (self.bx - self.dx / 2.)) / self.dx).long() # (8, 6, 59, 16, 44, 3)
        geom_feats = geom_feats.view(Nprime, 3) # # (1993728, 3)
        batch_ix = torch.cat([torch.full([Nprime // B, 1], ix,
                                         device=x.device, dtype=torch.long) for ix in range(B)])
        geom_feats = torch.cat((geom_feats, batch_ix), 1) # (1993728, 4)

        # filter out points that are outside box
        kept = (geom_feats[:, 0] >= 0) & (geom_feats[:, 0] < self.nx[0]) \
               & (geom_feats[:, 1] >= 0) & (geom_feats[:, 1] < self.nx[1]) \
               & (geom_feats[:, 2] >= 0) & (geom_feats[:, 2] < self.nx[2]) # # (1993728, )
        x = x[kept] # (1761017, 64)
        geom_feats = geom_feats[kept] # (1761017, 4) 过滤在锥体范围外的点

        # get tensors from the same voxel next to each other
        ranks = geom_feats[:, 0] * (self.nx[1] * self.nx[2] * B) \
                + geom_feats[:, 1] * (self.nx[2] * B) \
                + geom_feats[:, 2] * B \
                + geom_feats[:, 3] # (1761017,) 将4维索引拉成一维(tips:每一维乘后面的所有维度)
        sorts = ranks.argsort()
        x, geom_feats, ranks = x[sorts], geom_feats[sorts], ranks[sorts]

        # BEVFusion中将下面部分使用CUDA实现
        # cumsum trick
        x, geom_feats = QuickCumsum.apply(x, geom_feats, ranks) # 将空间中相邻的排在一起（120991, 64)和（120991, 4)

        # griddify (B x C x Z x X x Y)
        final = torch.zeros((B, C, nx[2], nx[1], nx[0]), device=x.device) # (8, 64, 1, 128, 128)
        # 将预测的伪点云特征放入对应位置
        final[geom_feats[:, 3], :, geom_feats[:, 2], geom_feats[:, 1], geom_feats[:, 0]] = x
        if self.voxel:
            return final.sum(2), x, geom_feats # (8, 64, 1, 128, 128)
        # collapse Z
        final = torch.cat(final.unbind(dim=2), 1) # (8, 64, 128, 128)

        return final # (8, 64, 128, 128)

    def forward(self, input):
        """
        imgs: (8, 6, 3, 256, 704)
        rots: (8, 6, 3, 3)
        trans: (8, 6, 3)
        intrins: (8, 6, 3, 3)
        post_rots: (8, 6, 3, 3)
        post_trans: (8, 6, 3)
        """
        x, rots, trans, intrins, post_rots, post_trans = input
        B, N, C, H, W = x.shape # (8, 6, 512, 16, 64)
        x = x.view(B * N, C, H, W) # (48, 512, 16, 44)
        x = self.depthnet(x) # (48, 123, 16, 44)
        depth = self.get_depth_dist(x[:, :self.D]) # (48, 59, 16, 44)
        geom = self.get_geometry(rots, trans, intrins, post_rots, post_trans) # (8, 6, 59, 16, 44, 3)
        img_feat = x[:, self.D:(self.D + self.numC_Trans)] # (48, 64, 16, 44)

        # Lift
        # (48, 1, 59, 16, 44) *  (48, 64, 1, 16, 44) --> (48, 64, 59, 16, 44)
        volume = depth.unsqueeze(1) * img_feat.unsqueeze(2) # product
        volume = volume.view(B, N, self.numC_Trans, self.D, H, W) # (8, 6, 64, 59, 16, 44)
        volume = volume.permute(0, 1, 3, 4, 5, 2) # (8, 6, 59, 16, 44, 64)

        # Splat
        bev_feat = self.voxel_pooling(geom, volume) # (8, 64, 128, 128)
        if self.image_view_supervision:
            return bev_feat, [x[:, :self.D].view(B,N,self.D,H,W), x[:, self.D:].view(B,N,self.numC_Trans,H,W)]
        return bev_feat # (8, 64, 128, 128)


#!/usr/bin/python3
"""
prints the first State object from the database hbtn_0e_6_us
"""
from model_state import Base, State
from sqlalchemy import (create_engine)
from sys import argv
from sqlalchemy.orm import sessionmaker

if __name__ == "__main__":
    engine = create_engine(
        'mysql+mysqldb://{}:{}@localhost/{}'
        .format(argv[1], argv[2], argv[3]), pool_pre_ping=True)
    Base.metadata.create_all(engine)

    Session = sessionmaker(bind=engine)
    session = Session()

    states = session.query(State).filter(State.name.like('%a%'))
    for state in states:
        print("{}: {}".format(state.id, state.name))


import streamlit as st
import cv2
from PIL import Image
import numpy as np
import copy

st.markdown("
Color Image
", unsafe_allow_html=True)
st.markdown("
Praktikum 1 Pengolahan Citra Digital
", unsafe_allow_html=True)

image = cv2.imread("./Tugas/Meeting 4/Images/gambar.jpeg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
r, g, b = cv2.split(image)
r_dup = copy.deepcopy(r)
g_dup = copy.deepcopy(g)
b_dup = copy.deepcopy(b)
r_dup[:] = 0
g_dup[:] = 0
b_dup[:] = 0

tab1, tab2, tab3, tab4, tab5= st.tabs(["RGB", "BGR", "Red", "Green", "Blue"])

with tab1:
  st.markdown("
RGB
", unsafe_allow_html=True)
  st.image(image)

with tab2:
  st.markdown("
BGR
", unsafe_allow_html=True)
  st.image(cv2.cvtColor(image, cv2.COLOR_RGB2BGR))

with tab3:
  st.markdown("
Red
", unsafe_allow_html=True)
  merged = cv2.merge([r, g_dup, b_dup])
  pil_032 = Image.fromarray(merged)
  st.image(pil_032)

with tab4:
  st.markdown("
Green
", unsafe_allow_html=True)
  merged = cv2.merge([r_dup, g, b_dup])
  pil_032 = Image.fromarray(merged)
  st.image(pil_032)

with tab5:
  st.markdown("
Blue
", unsafe_allow_html=True)
  merged = cv2.merge([r_dup, g_dup, b])
  pil_032 = Image.fromarray(merged)
  st.image(pil_032)


import pprint
import re  # noqa: F401

import six

from asposeslidescloud.models.fill_format import FillFormat

class PictureFill(FillFormat):

    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'type': 'str',
        'crop_bottom': 'float',
        'crop_left': 'float',
        'crop_right': 'float',
        'crop_top': 'float',
        'dpi': 'int',
        'image': 'ResourceUri',
        'base64_data': 'str',
        'svg_data': 'str',
        'picture_fill_mode': 'str',
        'image_transform_list': 'list[ImageTransformEffect]'
    }

    attribute_map = {
        'type': 'type',
        'crop_bottom': 'cropBottom',
        'crop_left': 'cropLeft',
        'crop_right': 'cropRight',
        'crop_top': 'cropTop',
        'dpi': 'dpi',
        'image': 'image',
        'base64_data': 'base64Data',
        'svg_data': 'svgData',
        'picture_fill_mode': 'pictureFillMode',
        'image_transform_list': 'imageTransformList'
    }

    type_determiners = {
        'type': 'Picture',
    }

    def __init__(self, type='Picture', crop_bottom=None, crop_left=None, crop_right=None, crop_top=None, dpi=None, image=None, base64_data=None, svg_data=None, picture_fill_mode=None, image_transform_list=None):  # noqa: E501
        """PictureFill - a model defined in Swagger"""  # noqa: E501
        super(PictureFill, self).__init__(type)

        self._crop_bottom = None
        self._crop_left = None
        self._crop_right = None
        self._crop_top = None
        self._dpi = None
        self._image = None
        self._base64_data = None
        self._svg_data = None
        self._picture_fill_mode = None
        self._image_transform_list = None
        self.type = 'Picture'

        self.crop_bottom = crop_bottom
        self.crop_left = crop_left
        self.crop_right = crop_right
        self.crop_top = crop_top
        self.dpi = dpi
        if image is not None:
            self.image = image
        if base64_data is not None:
            self.base64_data = base64_data
        if svg_data is not None:
            self.svg_data = svg_data
        self.picture_fill_mode = picture_fill_mode
        if image_transform_list is not None:
            self.image_transform_list = image_transform_list

    @property
    def crop_bottom(self):
        """Gets the crop_bottom of this PictureFill.  # noqa: E501

        Percentage of image height that is cropped from the bottom.  # noqa: E501

        :return: The crop_bottom of this PictureFill.  # noqa: E501
        :rtype: float
        """
        return self._crop_bottom

    @crop_bottom.setter
    def crop_bottom(self, crop_bottom):
        """Sets the crop_bottom of this PictureFill.

        Percentage of image height that is cropped from the bottom.  # noqa: E501

        :param crop_bottom: The crop_bottom of this PictureFill.  # noqa: E501
        :type: float
        """
        self._crop_bottom = crop_bottom

    @property
    def crop_left(self):
        """Gets the crop_left of this PictureFill.  # noqa: E501

        Percentage of image height that is cropped from the left.  # noqa: E501

        :return: The crop_left of this PictureFill.  # noqa: E501
        :rtype: float
        """
        return self._crop_left

    @crop_left.setter
    def crop_left(self, crop_left):
        """Sets the crop_left of this PictureFill.

        Percentage of image height that is cropped from the left.  # noqa: E501

        :param crop_left: The crop_left of this PictureFill.  # noqa: E501
        :type: float
        """
        self._crop_left = crop_left

    @property
    def crop_right(self):
        """Gets the crop_right of this PictureFill.  # noqa: E501

        Percentage of image height that is cropped from the right.  # noqa: E501

        :return: The crop_right of this PictureFill.  # noqa: E501
        :rtype: float
        """
        return self._crop_right

    @crop_right.setter
    def crop_right(self, crop_right):
        """Sets the crop_right of this PictureFill.

        Percentage of image height that is cropped from the right.  # noqa: E501

        :param crop_right: The crop_right of this PictureFill.  # noqa: E501
        :type: float
        """
        self._crop_right = crop_right

    @property
    def crop_top(self):
        """Gets the crop_top of this PictureFill.  # noqa: E501

        Percentage of image height that is cropped from the top.  # noqa: E501

        :return: The crop_top of this PictureFill.  # noqa: E501
        :rtype: float
        """
        return self._crop_top

    @crop_top.setter
    def crop_top(self, crop_top):
        """Sets the crop_top of this PictureFill.

        Percentage of image height that is cropped from the top.  # noqa: E501

        :param crop_top: The crop_top of this PictureFill.  # noqa: E501
        :type: float
        """
        self._crop_top = crop_top

    @property
    def dpi(self):
        """Gets the dpi of this PictureFill.  # noqa: E501

        Picture resolution.  # noqa: E501

        :return: The dpi of this PictureFill.  # noqa: E501
        :rtype: int
        """
        return self._dpi

    @dpi.setter
    def dpi(self, dpi):
        """Sets the dpi of this PictureFill.

        Picture resolution.  # noqa: E501

        :param dpi: The dpi of this PictureFill.  # noqa: E501
        :type: int
        """
        self._dpi = dpi

    @property
    def image(self):
        """Gets the image of this PictureFill.  # noqa: E501

        Internal image link.  # noqa: E501

        :return: The image of this PictureFill.  # noqa: E501
        :rtype: ResourceUri
        """
        return self._image

    @image.setter
    def image(self, image):
        """Sets the image of this PictureFill.

        Internal image link.  # noqa: E501

        :param image: The image of this PictureFill.  # noqa: E501
        :type: ResourceUri
        """
        self._image = image

    @property
    def base64_data(self):
        """Gets the base64_data of this PictureFill.  # noqa: E501

        Base 64 image data.  # noqa: E501

        :return: The base64_data of this PictureFill.  # noqa: E501
        :rtype: str
        """
        return self._base64_data

    @base64_data.setter
    def base64_data(self, base64_data):
        """Sets the base64_data of this PictureFill.

        Base 64 image data.  # noqa: E501

        :param base64_data: The base64_data of this PictureFill.  # noqa: E501
        :type: str
        """
        self._base64_data = base64_data

    @property
    def svg_data(self):
        """Gets the svg_data of this PictureFill.  # noqa: E501

        SVG image data.  # noqa: E501

        :return: The svg_data of this PictureFill.  # noqa: E501
        :rtype: str
        """
        return self._svg_data

    @svg_data.setter
    def svg_data(self, svg_data):
        """Sets the svg_data of this PictureFill.

        SVG image data.  # noqa: E501

        :param svg_data: The svg_data of this PictureFill.  # noqa: E501
        :type: str
        """
        self._svg_data = svg_data

    @property
    def picture_fill_mode(self):
        """Gets the picture_fill_mode of this PictureFill.  # noqa: E501

        Fill mode.  # noqa: E501

        :return: The picture_fill_mode of this PictureFill.  # noqa: E501
        :rtype: str
        """
        return self._picture_fill_mode

    @picture_fill_mode.setter
    def picture_fill_mode(self, picture_fill_mode):
        """Sets the picture_fill_mode of this PictureFill.

        Fill mode.  # noqa: E501

        :param picture_fill_mode: The picture_fill_mode of this PictureFill.  # noqa: E501
        :type: str
        """
        if picture_fill_mode is not None:
            allowed_values = ["Tile", "Stretch"]  # noqa: E501
            if picture_fill_mode.isdigit():
                int_picture_fill_mode = int(picture_fill_mode)
                if int_picture_fill_mode < 0 or int_picture_fill_mode >= len(allowed_values):
                    raise ValueError(
                        "Invalid value for `picture_fill_mode` ({0}), must be one of {1}"  # noqa: E501
                        .format(picture_fill_mode, allowed_values)
                    )
                self._picture_fill_mode = allowed_values[int_picture_fill_mode]
                return
            if picture_fill_mode not in allowed_values:
                raise ValueError(
                    "Invalid value for `picture_fill_mode` ({0}), must be one of {1}"  # noqa: E501
                    .format(picture_fill_mode, allowed_values)
                )
        self._picture_fill_mode = picture_fill_mode

    @property
    def image_transform_list(self):
        """Gets the image_transform_list of this PictureFill.  # noqa: E501

        Image transform effects.  # noqa: E501

        :return: The image_transform_list of this PictureFill.  # noqa: E501
        :rtype: list[ImageTransformEffect]
        """
        return self._image_transform_list

    @image_transform_list.setter
    def image_transform_list(self, image_transform_list):
        """Sets the image_transform_list of this PictureFill.

        Image transform effects.  # noqa: E501

        :param image_transform_list: The image_transform_list of this PictureFill.  # noqa: E501
        :type: list[ImageTransformEffect]
        """
        self._image_transform_list = image_transform_list

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, PictureFill):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        return not self == other


import speech_recognition as sr # recognise speech
import playsound # to play an audio file
from gtts import gTTS # google text to speech
import random
from time import ctime # get time details
import webbrowser # open browser
import ssl
import certifi
import time
import os # to remove created audio files
import datetime
import requests, json

BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
r = sr.Recognizer() # initialise a recogniser

def there_exists(terms):
    for term in terms:
        if term in voice_data:
            return True

def there_exists1(terms):
    for term in terms:
        if term in voice_data1:
            return True

# listen for audio and convert it to text:
def record_audio(ask=False):
    with sr.Microphone() as source: # microphone as source
        voice_data = ''
        if ask:
            speak(ask)
        audio = r.listen(source, 10, 10)  # listen for the audio via source
        print("Done Listening")

        try:
            voice_data = r.recognize_google(audio)  # convert audio to text
        except sr.UnknownValueError: # error: recognizer does not understand
            speak('I did not get that')
        except sr.RequestError:
            speak('Sorry, the service is down') # error: recognizer is not connected
        return voice_data.lower()

# get string and make a audio file to be played
def speak(audio_string):
    tts = gTTS(text=audio_string, lang='en') # text to speech(voice)
    r = random.randint(1,20000000)
    audio_file = 'audio' + str(r) + '.mp3'
    tts.save(audio_file) # save as mp3
    playsound.playsound(audio_file) # play the audio file
    #print(audio_string) # print what app said
    os.remove(audio_file) # remove audio file

def respond(voice_data):
    if there_exists(["what is your name","what's your name","tell me your name"]):
        speak("My Name is Test. what's your name?")
    if there_exists(["my name is"]):
        speak("nice to meet you i will remember that ,so do you want to eat or watch something!")

    if there_exists(["eat"]):
        speak("Here are some of the foods I recommend for you today")

    if there_exists(["watch"]):
        speak("What if we remember the old days and watch the Titanic ! ")

    if there_exists(["what's the time","tell me the time","what time is it","what is the time"]):
        speak(ctime())

    if there_exists(['hey','hi','hello','Good morning','Good afternoon','Good evening']):
        speak("What's your mood today?")

    elif there_exists(['happy','nice']):
        speak("What if we go to walk ?")

    elif there_exists(["sick","got cold","got a temperatare"]):
        speak('Do you want me to call a doctor ?')
    elif there_exists(['hungry']):
        speak('Do you want to eat some delicious food')
    elif there_exists(["bad","sad","ugly","angry","i'm not ok","stressed","upset"]):
        speak('what if we read some books !')

    if "yes" in voice_data:
        print('call doctor')
    elif "no" in voice_data:
        speak('so try to eat some healthy food')

    if there_exists(["it's good outside"]):
        search_term = voice_data.split("for")[-1]
        url = "https://www.google.com/search?sxsrf=ACYBGNSQwMLDByBwdVFIUCbQqya-ET7AAA%3A1578847393212&ei=oUwbXtbXDN-C4-EP-5u82AE&q=weather&oq=weather&gs_l=psy-ab.3..35i39i285i70i256j0i67l4j0i131i67j0i131j0i67l2j0.1630.4591..5475...1.2..2.322.1659.9j5j0j1......0....1..gws-wiz.....10..0i71j35i39j35i362i39._5eSPD47bv8&ved=0ahUKEwiWrJvwwP7mAhVfwTgGHfsNDxsQ4dUDCAs&uact=5"
        webbrowser.get().open(url)
        speak("I think it's a good day,but you can do some excercise in you'r room")

    if'search'in voice_data:
        search = record_audio('what do you want to search for ?')
        url = 'https://google.com/search?q=' + search
        webbrowser.get().open(url)
        speak('Here is what I found for ' + search)

    if there_exists(["what is my exact location"]):
        url = "https://www.google.com/maps/search/Where+am+I+?/"
        webbrowser.get().open(url)
        speak("You must be somewhere near here, as per Google maps")
    if there_exists(["exit", "quit", "goodbye"]):
        speak("Have a nice day ,good bye")
        exit()

time.sleep(1)
currentTime = datetime.datetime.now()
currentTime.hour
if currentTime.hour < 12:
    speak("Good morning")
    print('Good morning.')
elif 12 <= currentTime.hour < 18:
    speak("Good afternoon")
    print('Good afternoon.')
else:
    speak("Good evening")
    print('Good evening.')

while 1:
    voice_data = record_audio() # get the voice input
    respond(voice_data) # respond


import cv2
import numpy as np

from classes.camera import Camera
from classes.trackbars import Trackbars
from utils.utils import get_resize_picture

class Inklinometer:
    def __init__(self, camera: Camera, trackbars: Trackbars, options: dict):
        self.gray = None
        self.REL_FROM_CENTER_TO_FIRST_HATCH = options["REL_FROM_CENTER_TO_FIRST_HATCH"]
        self.REL_BETWEEN_HATCH_TO_END = options["REL_BETWEEN_HATCH_TO_END"]
        self.NUMBER_OF_ARC_SECONDS_ONE_STROKE = options["NUMBER_OF_ARC_SECONDS_ONE_STROKE"]
        self.COUNT_ARC_SECOND = options["COUNT_ARC_SECOND"]
        self.camera = camera
        self.trackbars = trackbars
        success, img = camera.get_image()
        self.height, self.width = img.shape[:2]
        self.center_bubble = 0
        self.x1 = 0
        self.y1 = 0
        self.x2 = 0
        self.y2 = 0
        self.is_vert = 0
        self.getgrad = "NONE"
        self.x1_framing, self.y1_framing, self.x2_framing, self.y2_framing = 0, 0, 0, 0

    def get_second_method(self):
        """
        Функция определяет сколько в одном пикселе угловых секунд
        И выводит результат
        :param x1: координата пузырька
        :param y1: координата пузырька
        :param x2: координата пузырька
        :param y2: координата пузырька
        :param is_vert: булевское значение повернутости экрана
        :param count_sec: Количество секунд в одном пикселе
        :param width_win: ширина окна
        :param height_win: высота окна
        :return: Возрвращает угловые секунды
        """
        if self.is_vert == 0:
            center = (self.y1 + self.y2) / 2
            reference_point = self.height / 2
        else:
            center = (self.x1 + self.x2) / 2
            reference_point = self.width / 2
        # result_second = (reference_point - center) * self.COUNT_ARC_SECOND
        result_second = self.center_bubble * -0.009037444160292861
        # print(f"reference_point = {reference_point}")
        # print(f"center = {center}")
        return result_second

    def view_image(self, src, str, scale=100):
        try:
            src = cv2.resize(src, self.get_resize_picture(src, scale))
            cv2.imshow(str, src)
        except:
            pass

    def get_cont(self, img, from_=200, to_=5000):
        contours, hierarchy = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        x, y, w, h = 0, 0, 0, 0
        for id, cnt in enumerate(contours):
            area = cv2.contourArea(cnt)
            if area > from_ and area < to_:
                peri = cv2.arcLength(cnt, True)
                approx = cv2.approxPolyDP(cnt, 0.01 * peri, True)
                x, y, w, h = cv2.boundingRect(approx)

        # Переменные для того чтобы повторно не проводить обрезку
        area_framing = abs(self.x2_framing - self.x1_framing) * abs(self.y2_framing - self.y1_framing) - (w + h)

        # self.x1_framing, self.y1_framing, self.x2_framing, self.y2_framing = 0, 0, 0, 0
        if abs(self.x1_framing - x) + abs(self.x2_framing - (x + w)) + abs(self.y1_framing - y) + abs(
                self.y2_framing - (y + h)) > 10 * 4 or area_framing > 100000:
            return x, y, x + w, y + h
        else:
            return self.x1_framing, self.y1_framing, self.x2_framing, self.y2_framing

    def select_method(self, image, r=215, g=236, b=241, scale=100, hsv=[0, 255, 56, 255, 0, 255], med=0):
        # image = cv2.resize(image, get_resize_picture(image, scale))

        lower = np.array((hsv[0], hsv[2], hsv[4]), np.uint8)
        upper = np.array((hsv[1], hsv[3], hsv[5]), np.uint8)
        self.view_image(image, "original", scale)
        # Применение Медианного фильтра
        MedianNeChet = med
        if med > 1:
            if med % 2 == 0:
                MedianNeChet += 1
            image = cv2.medianBlur(image, MedianNeChet)

        # self.view_image(image, "Original", scale)
        hsv_img = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
        # lower = np.array([188, 199, 219])
        # upper = np.array([208, 219, 241])
        curr_mask = cv2.inRange(hsv_img, lower, upper)
        # hsv_img[curr_mask > 0] = ([208, 255, 200])
        hsv_img[curr_mask > 0] = ([255, 255, 255])
        self.view_image(hsv_img, "hsv_img", scale)  ## 2

        # Фильтрация
        ## Преобразование HSV-изображения к оттенкам серого для дальнейшего
        ## оконтуривания
        RGB_again = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2RGB)
        self.gray = cv2.cvtColor(RGB_again, cv2.COLOR_RGB2GRAY)

        # Обрезка
        w, h = self.gray.shape[:2]
        thresh = cv2.inRange(hsv_img, lower, upper)
        self.x1_framing, self.y1_framing, self.x2_framing, self.y2_framing = self.get_cont(thresh, 1000, (w * h) * 0.9)
        # x1, y1, x2, y2 = 0, 115, 640, 210
        cv2.rectangle(thresh, (self.x1_framing, self.y1_framing), (self.x2_framing, self.y2_framing), (0, 255, 0), 2)
        # self.view_image(thresh, "Test", scale)
        self.gray = self.gray[self.y1_framing:self.y2_framing, self.x1_framing:self.x2_framing]

        ret, imgf = cv2.threshold(self.gray, 0, 255, cv2.THRESH_OTSU)
        self.view_image(imgf, "imgf", scale)

        threshold = imgf

        x1, y1, x2, y2 = self.get_cont(threshold, from_=200, to_=10000)
        cv2.rectangle(self.gray, (x1, y1), (x2, y2), (0, 255, 0), 2)

        return x1, y1, x2, y2

    @staticmethod
    def get_resize_picture(src, scale):
        width = int(src.shape[1] * scale / 100)
        height = int(src.shape[0] * scale / 100)

        dsize = (width, height)
        return dsize

    @property
    def th(self) -> int | float:
        horizontal_count = self.trackbars.horizontal_count
        if horizontal_count == 0:
            th = (self.height // 2) / self.REL_FROM_CENTER_TO_FIRST_HATCH
        else:
            th = (self.width // 2) / self.REL_FROM_CENTER_TO_FIRST_HATCH
        return th

    @property
    def bth(self) -> int | float:
        horizontal_count = self.trackbars.horizontal_count
        if horizontal_count == 0:
            bth = ((self.height // 2) - self.th) / self.REL_BETWEEN_HATCH_TO_END
        else:
            bth = ((self.width // 2) - self.th) / self.REL_BETWEEN_HATCH_TO_END
        return bth

    @property
    def get_gradus(self):
        # Штрихи
        horizontal_count = self.trackbars.horizontal_count
        y_ex = self.extreme_values(self.y1, self.y2, self.height / 2)
        x_ex = self.extreme_values(self.x1, self.x2, self.width / 2)
        if horizontal_count == 0:
            center = self.height // 2
            ex = y_ex
        else:
            center = self.width // 2
            ex = x_ex

        diap1 = [self.th, self.th + self.bth * 8]
        diap2 = [-self.th, -self.th - self.bth * 8]
        centerDiap = self.th + (self.bth * 8) / 2
        ex -= center
        if horizontal_count == 0:
            cv2.rectangle(self.gray, ((self.width), round(self.th + center)),
                          ((self.width), round(centerDiap + center)),
                          (0, 255, 0),
                          1)
            cv2.rectangle(self.gray, ((self.width), round(-self.th + center)),
                          ((self.width), round(-centerDiap + center)),
                          (0, 255, 0),
                          1)
        else:
            cv2.rectangle(self.gray, (round(self.th + center), (self.width)),
                          (round(centerDiap + center), (self.width)),
                          (0, 255, 0),
                          1)
            cv2.rectangle(self.gray, (round(-self.th + center), (self.width)),
                          (round(-centerDiap + center), (self.width)),
                          (0, 255, 0),
                          1)
        if ex >= diap1[0] and ex <= diap1[1]:
            self.getgrad = -(centerDiap - ex)
            self.getgrad = (self.getgrad / self.bth) * self.NUMBER_OF_ARC_SECONDS_ONE_STROKE
            self.getgrad = round(self.getgrad, 2)
            if self.getgrad < 0:
                self.getgrad = "~=0"
        elif ex >= diap2[1] and ex <= diap2[0]:
            self.getgrad = -(-centerDiap - ex)
            self.getgrad = (self.getgrad / self.bth) * self.NUMBER_OF_ARC_SECONDS_ONE_STROKE
            self.getgrad = round(self.getgrad, 2)
            if self.getgrad > 0:
                self.getgrad = "~=0"
        else:
            self.getgrad = "NONE"

        maxgrad = self.COUNT_ARC_SECOND * 4
        if horizontal_count == 0:
            if self.getgrad == "NONE":
                self.getgrad = self.getgrad
            elif self.getgrad == ">" + str(maxgrad):
                self.getgrad = self.getgrad
                if self.getgrad == "NONE":
                    self.getgrad = ">" + str(maxgrad)
            elif self.getgrad == "<-" + str(maxgrad):
                self.getgrad = self.getgrad
                if self.getgrad == "NONE":
                    self.getgrad = "<-" + str(maxgrad)
            elif self.getgrad == "~=0":
                self.getgrad = self.getgrad
            elif self.getgrad > 0:
                self.getgrad = self.getgrad
                if self.getgrad == "NONE":
                    self.getgrad = ">" + str(maxgrad)
            elif self.getgrad <= 0:
                self.getgrad = self.getgrad
                if self.getgrad == "NONE":
                    self.getgrad = "<-" + str(maxgrad)
        else:
            if self.getgrad == "NONE":
                self.getgrad = self.getgrad
            elif self.getgrad == ">" + str(maxgrad):
                self.getgrad = self.getgrad
                if self.getgrad == "NONE":
                    self.getgrad = ">" + str(maxgrad)
            elif self.getgrad == "<-" + str(maxgrad):
                self.getgrad = self.getgrad
                if self.getgrad == "NONE":
                    self.getgrad = "<-" + str(maxgrad)
            elif self.getgrad == "~=0":
                self.getgrad = self.getgrad
            elif self.getgrad > 0:
                self.getgrad = self.getgrad
                if self.getgrad == "NONE":
                    self.getgrad = ">" + str(maxgrad)
            elif self.getgrad <= 0:
                self.getgrad = self.getgrad
                if self.getgrad == "NONE":
                    self.getgrad = "<-" + str(maxgrad)

        return self.getgrad

    @staticmethod
    def extreme_values(y_up, y_down, center):
        if (y_up + y_down) / 2 < center:
            return y_up
        else:
            return y_down

    # def

    def main(self):
        # r = self.trackbars.r
        # g = self.trackbars.g
        # b = self.trackbars.b
        med = self.trackbars.med

        h_min = self.trackbars.h_min
        h_max = self.trackbars.h_max
        s_min = self.trackbars.s_min
        s_max = self.trackbars.s_max
        v_min = self.trackbars.v_min
        v_max = self.trackbars.v_max
        hsv_list = [h_min, h_max, s_min, s_max, v_min, v_max]

        success, img = self.camera.get_image()

        horizontal_count = self.trackbars.horizontal_count

        x_ex = self.extreme_values(self.x1, self.x2, self.width / 2)

        scale_percent = self.trackbars.scale_percent
        if scale_percent == 0:
            scale_percent = 1

        # Подсчёт значений по x, y
        self.x1, self.y2, self.x2, self.y1 = self.select_method(img, scale=scale_percent, hsv=hsv_list,
                                                                med=med)
        self.height, self.width = img.shape[:2]

        th = self.th
        bth = self.bth

        # Центральная линия
        if horizontal_count == 0:
            # Штрихи
            cv2.rectangle(self.gray, (0, round(th + self.height / 2)),
                          (self.width, round(th + bth * 8 + self.height / 2)),
                          (0, 255, 0), 4)
            cv2.rectangle(self.gray, (0, round(self.height / 2 - th)),
                          (self.width, round(self.height / 2 - th - bth * 8)),
                          (0, 255, 0), 4)

            # Центральная линия
            # cv2.rectangle(imgContour, (0,((self.height)//2)), (1920,((self.height)//2)), (0,255,0), 6)
            cv2.rectangle(self.gray, (0, (self.height // 2)), (1920, (self.height // 2)), (0, 255, 0), 6)
        else:
            # Штрихи
            cv2.rectangle(self.gray, (round(th + self.width / 2), 0),
                          (round(th + bth * 8 + self.width / 2), self.height),
                          (0, 255, 0),
                          4)
            cv2.rectangle(self.gray, (round(self.width / 2 - th), 0),
                          (round(self.width / 2 - th - bth * 8), self.height),
                          (0, 255, 0),
                          4)

            # Центральная линия
            cv2.rectangle(self.gray, ((self.width // 2), 0), ((self.width // 2), 1920), (0, 255, 0), 6)
            cv2.rectangle(self.gray, ((self.width // 2), 0), ((self.width // 2), 1920), (0, 255, 0), 6)

            self.center_bubble = (self.x1 + self.x2) / 2
            # Заполнение информационного окна
            winfo = np.zeros((512, 512, 3), np.uint8)
            cv2.putText(winfo, f"Отклонение пузырька = {self.get_gradus}''", (0, 150), cv2.FONT_HERSHEY_COMPLEX, 0.8,
                        (0, 150, 0),
                        2)
            cv2.putText(winfo, f"X_EX = {x_ex}px", (0, 200), cv2.FONT_HERSHEY_COMPLEX, 0.8, (0, 150, 0), 2)
            cv2.putText(winfo, f"Center = {self.width / 2}px", (0, 250), cv2.FONT_HERSHEY_COMPLEX, 0.8, (0, 150, 0), 2)
            cv2.putText(winfo, f"X_left = {self.x1}px", (0, 300), cv2.FONT_HERSHEY_COMPLEX, 0.8, (0, 150, 0), 2)
            cv2.putText(winfo, f"X_right = {self.x2}px", (0, 350), cv2.FONT_HERSHEY_COMPLEX, 0.8, (0, 150, 0), 2)
            cv2.putText(winfo, f"SR_arifm = {self.center_bubble}px", (0, 400), cv2.FONT_HERSHEY_COMPLEX, 0.8,
                        (0, 150, 0),
                        2)
            cv2.putText(winfo, f"bth = {bth}px", (0, 450), cv2.FONT_HERSHEY_COMPLEX, 0.8, (0, 150, 0), 2)
            cv2.putText(winfo,
                        f"count_sec = {self.get_second_method()}''",
                        (0, 500), cv2.FONT_HERSHEY_COMPLEX, 0.8, (0, 150, 0), 2)

            # Отображение изображений
            self.view_image(self.gray, "gray", scale_percent)  ## 3
            cv2.putText(winfo,
                        f"count_sec = {self.get_second_method()}''",
                        (0, 500), cv2.FONT_HERSHEY_COMPLEX, 0.8, (0, 150, 0), 2)
            cv2.imshow("Window", winfo)


#
# Solved Date: 20.04.22.

import sys
import collections
sys.setrecursionlimit(10 ** 4)

read = sys.stdin.readline
DXY = ((1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1))

def dfs(land, y, x):
    land[y][x] = 0
    count = 1
    for dy, dx in DXY:
        new_y = y + dy
        new_x = x + dx
        if 0 <= new_y < len(land) and 0 <= new_x < len(land[0]) and land[new_y][new_x]:
            count += dfs(land, new_y, new_x)
    return count

def bfs(land, y, x):
    queue = collections.deque()
    queue.append((y, x))
    land[y][x] = 0
    count = 1
    while queue:
        y, x = queue.popleft()
        for dy, dx in DXY:
            new_y = y + dy
            new_x = x + dx
            if 0 <= new_y < len(land) and 0 <= new_x < len(land[0]) and land[new_y][new_x]:
                land[new_y][new_x] = 0
                count += 1
                queue.append((new_y, new_x))
    return count

def main(mode=''):
    while True:
        width, height = (int(x) for x in read().split())
        land = []
        if not width and not height:
            break
        for _ in range(height):
            land.append([int(x) for x in read().split()])
        ans = []
        if mode == 'dfs':
            for y in range(len(land)):
                for x in range(len(land[0])):
                    if land[y][x] == 1:
                        ans.append(dfs(land, y, x))
        else:
            for y in range(len(land)):
                for x in range(len(land[0])):
                    if land[y][x] == 1:
                        ans.append(bfs(land, y, x))
        print(len(ans))

if __name__ == '__main__':
    main('dfs')


import whisper
import numpy as np

class WhisperModel():
    def __init__(self, model_type="large"):
        print("loading whisper")
        self.model = whisper.load_model(model_type, download_root="/app/model/whisper/")
        self.language = 'en'
        self.task = 'transcribe'

    async def set_model_settings(self, language, task):
        self.language = language
        self.task = task
        message = {"message": "Settings set correctly"}
        return message

    async def process_audio(self, data):
        audio = np.array([], dtype=np.int16)
        buffer = np.frombuffer(data["bytes"], dtype=np.int16).astype(np.float32) / 2**15
        audio = np.concatenate([audio, buffer])
        result = self.model.transcribe(audio, language=self.language, task=self.task)
        print(result["text"])
        return result["text"].strip()


"""
Contains the abstract class of a probability distrobution and associated marginals.
"""
import numpy as np
from ..utilities import utils
from ..utilities.profiler import profile
from .variable import RandomVariableCollection
from . import variable_sort
from functools import reduce
import math
from ..utilities.constants import *

class ProbDist():

    def __init__(self, rvc, support):
        self._support = np.asarray(support)
        if (self._support.size == 0):
            self.__is_null = True
        else:
            self.__is_null = False
        # print(self._support > 0)
        if not np.all(self._support >= 0):
            if not np.all(self._support >= -mach_tol):
                print(self._support)
                raise Exception("Some of the support is negative.")
            else:
                # print(self._support)
                self._support[np.where(self._support <= mach_tol)] = 0.0
        sum_support = np.sum(self._support)
        if utils.is_close(sum_support,1.0):
            self.__impossible = False
        elif utils.is_close(sum_support,0.0):
            self.__impossible = True
        else:
            raise ValueError("Probability distribution does not sum to 1.0 or 0.0. Sums to {0}".format(sum_support))
        self._rvc = rvc
        self._num_variables = len(self._rvc)
        # if axis_map is not None:
        #     self._axis_map = axis_map
        # else:
        # Assume order matches canonical order
        self._correlation_settings = {'method': 'same'}
        self._axis_map = self._rvc.names.dict

    def _multi_axis_map(self, names):
        return tuple(self._axis_map[name] for name in names)

    @staticmethod
    def distance(pd_a, pd_b):
        assert(pd_a._rvc == pd_b._rvc), "Random Variables don't match."
        dist = 0.0
        for a, b in zip(pd_a.canonical_ravel(), pd_b.canonical_ravel()):
            dist += (b - a)**2
        return math.sqrt(dist)

    @staticmethod
    def from_callable_support(rvc, callable_support):
        array_dims = tuple(rv.num_outcomes for rv in rvc)
        # print(array_dims)
        support = np.zeros(array_dims)
        for _, outcome_index, outcome in rvc.iter_named_outcomes():
            p = callable_support(*outcome)
            support[outcome_index] = p
        return ProbDist(rvc, support)

    @staticmethod
    def product_marginals(*args, **kwargs):
        pds = [pd for pd in args if not pd.__is_null]
        if len(pds) == 0:
            raise Exception("Distributions are empty.")
        if len(pds) == 1:
            return pds[0]
        rvcs = [pd._rvc for pd in pds]
        supports = [pd._support for pd in pds]
        joint_support = reduce(lambda a,b: np.tensordot(a,b,axes=0), supports)
        assert(joint_support.shape == sum([s.shape for s in supports], ()))
        # print("---------")
        # print(joint_support.ravel())
        if kwargs.get('transpose_sort', True):
            variable_names = sum([rvs.names.list for rvs in rvcs], [])
            variable_names_sort = variable_sort.argsort(variable_names)
            joint_support = np.transpose(joint_support, axes=variable_names_sort)
        # print(variable_names_sort)
        # print(sorted_support.ravel())
        return joint_support

    def __mul__(A,B):
        if A._rvc.intersection(B._rvc):
            raise Exception("Can't multiply distributions that share random variables.")
        AB_rvc = A._rvc.union(B._rvc)
        AB = A.__new_child(AB_rvc, ProbDist.product_marginals(A,B, transpose_sort=True))
        return AB

    def _sub_support(self, outcome_dict):
        outcome_association = []
        slice_obj = [slice(None)] * self._num_variables
        for rv_name, outcome_label in outcome_dict.items():
            rv = self._rvc.get_rv(rv_name)
            outcome_index = rv.outcomes.index(outcome_label)
            slice_obj[self._axis_map[rv_name]] = outcome_index
            outcome_association.append((rv, outcome_index))
        sub_support = self._support[tuple(slice_obj)]
        return sub_support, outcome_association

    def prob(self, outcome_dict):
        sub_support, _ = self._sub_support(outcome_dict)
        prob = np.sum(sub_support)
        return prob

    def _dev_slice(self, slice):
        return self._support[slice]

    def _total_prob(self, selectors):
        total = 0.0
        for i in selectors:
            total += self._support[i]
        return total

    def correlation(self, rvc_names):
        rvc = self._rvc.sub(rvc_names)
        return self._correlation(rvc)

    def update_correlation_settings(self, settings):
        self._correlation_settings.update(settings)

    def _correlation(self, rvc):
        s = self._correlation_settings
        method = s['method']
        mpd = self._marginal(rvc)
        additive = []
        subtractive = []
        for names, outcome_indices, outcome in rvc.iter_named_outcomes():
            slice_indices = tuple(outcome_indices[i] for i in mpd._multi_axis_map(names))
            if method=='same':
                is_additive = False
                if 'mod' in s:
                    is_additive = utils.all_equal(utils.list_mod(outcome, mod=s['mod']))
                else:
                    is_additive = utils.all_equal(outcome)
                if is_additive:
                    additive.append(slice_indices)
                else:
                    subtractive.append(slice_indices)
            if method=='two_expect':
                # assume outcomes mean {-1, +1}
                product_outcome = (-1)**(len(outcome) - sum(outcome))
                if product_outcome == 1:
                    additive.append(slice_indices)
                else:
                    subtractive.append(slice_indices)
        add_prob = mpd._total_prob(additive)
        sub_prob = mpd._total_prob(subtractive)
        return add_prob - sub_prob

    def __new_child(self, rvc, support):
        child = ProbDist(rvc, support)
        child.update_correlation_settings(self._correlation_settings)
        return child

    def condition(self, cond_outcome_dict):
        sub_support, outcome_association = self._sub_support(cond_outcome_dict)
        prob = np.sum(sub_support)
        if prob != 0.0:
            sub_support = sub_support / prob
        rvs = [rv_assoc[0] for rv_assoc in outcome_association]
        d_rvc = self._rvc - RandomVariableCollection(rvs)
        conditioned_pd = self.__new_child(d_rvc, sub_support)
        return conditioned_pd

    def marginal(self, rvc_names):
        rvc = self._rvc.sub(rvc_names)
        return self._marginal(rvc)

    def _marginal(self, rvc):
        rv_to_sum = self._rvc - rvc
        if not rv_to_sum:
            return self
        else:
            axis_to_keep = [self._axis_map[rv.name] for rv in rvc]
            axis_to_sum = tuple(set(range(self._support.ndim)) - set(axis_to_keep))
            marginal_support = np.sum(self._support, axis=axis_to_sum)
            marginal_pd = self.__new_child(rvc, marginal_support)
            return marginal_pd

    def H(self, *args):
        return self.entropy(*args)

    def entropy(self, X_names, Y_names=()):
        X = self._rvc.sub(X_names)
        Y = self._rvc.sub(Y_names)
        return self._entropy(X, Y)

    def _entropy(self, X, Y):
        XY = X.union(Y)
        p_XY = self._marginal(XY)
        p_Y = self._marginal(Y)
        H_XY = utils.entropy(p_XY._support)
        H_Y = utils.entropy(p_Y._support)
        # Chain rule H(X|Y) = H(Y, X) - H(Y)
        return H_XY - H_Y

    def I(self, *args):
        return self.mutual_information(*args)

    def mutual_information(self, Xs_names, Y_names=[]):
        Xs = tuple(self._rvc.sub(X_names) for X_names in Xs_names)
        Y = self._rvc.sub(Y_names)
        return self._mutual_information(Xs, Y)

    def _mutual_information(self, Xs, Y):
        if len(Xs) > 1:
            Xs_reduced = Xs[0:-1]
            Y_expanded = Y.union(Xs[-1])

            return self._mutual_information(Xs_reduced, Y) - \
                   self._mutual_information(Xs_reduced, Y_expanded)
        elif len(Xs) == 1:
            return self._entropy(Xs[0], Y)
        else:
            return 0

    def _unpack_prob_space(self):
        for names, indices, outcome in self._rvc.iter_named_outcomes():
            axis_desc = self._multi_axis_map(names)
            support_slice = [0]*len(names)
            for i, slice_index in enumerate(axis_desc):
                support_slice[slice_index] = indices[i]
            p = self._support[tuple(support_slice)]
            yield outcome, p

    def canonical_ravel(self):
        for outcome, p in self._unpack_prob_space():
            yield p

    def __str__(self):
        fs = "{outcome} -> {probability}"
        print_list = ["=== ProbDist ==="]
        # print_list.append(self.__repr__())
        print_list.append(str(self._rvc))
        print_list.append("{0} Achievable outcomes.".format(np.count_nonzero(self._support)))
        print_list.append(fs)
        for outcome, p in self._unpack_prob_space():
            if p > 1e-5:
                print_list.append(fs.format(outcome=outcome, probability=p))
        print_list.append("================")
        return '\n'.join(print_list)

@profile
def perform_tests():
    rvc = RandomVariableCollection({})
    support = []
    pd = ProbDist(rvc, support)
    print(pd)
    print(pd.prob({}))

if __name__ == '__main__':
    perform_tests()


from opentrons import robot, containers, instruments

robot.head_speed(x=18000, y=18000, z=5000, a=400, b=400)

class Vector(object):
    def tolist(self):
        return list(self.input_list)

    def astype(self, input_type):
        if input_type == int:
            return Vector([int(float(x)) for x in self.input_list])
        return Vector([input_type(x) for x in self.input_list])

    def __init__(self, input_list):
        self.input_list = input_list

class DataFrame(object):
    def __len__(self):
        return self.length

    def __getitem__(self, value):
        return Vector(self.dict_input[value])

    def __init__(self, dict_input, length):
        self.dict_input = dict_input
        self.length = length

# Function that reads a csv file correctly without having to import anything (issues with molport). Uses 2 classes, Vector and DataFrame
def read_csv(input_file):
    lines = open(input_file).readlines()
    header = lines[0].rstrip().split(",")
    out_d = {}
    for head in header:
        out_d[head] = []
    for line in lines[1:]:
        spl_line = line.rstrip().split(",")
        for i, head in enumerate(header):
            out_d[head].append(spl_line[i])
    df = DataFrame(out_d, len(lines[1:]))
    return df

# CSV file data
reaction_conditions_df = read_csv(
    r"C:\Users\opentrons\protocols\GitHub_repos\OT1-coding\coupling_sequence_phip - Try2\csv\forMeIAddition\reaction_conditions.csv")

def reactants_transfer(reactants):
    # Deck setup

    tiprack_1000 = containers.load("tiprack-1000ul-H", "B3")
    tiprack_1000_2 = containers.load("tiprack-1000ul-H", "D3")
    #tiprack_1000_3 = containers.load("tiprack-1000ul-H", "B1")
    storage_rack = containers.load("FluidX_24_2ml", "D1")
    destination_rack1 = containers.load("StarLab_96_tall", "A1")
    trash = containers.load("point", "C3")

    # Pipettes SetUp
    p1000 = instruments.Pipette(
        name='eppendorf1000_no_min',
        axis='b',
        trash_container=trash,
        tip_racks=[tiprack_1000, tiprack_1000_2],
        max_volume=1000,
        min_volume=0,
        channels=1,
    )
    id_header = "reaction"
    reaction_to_start = "Coupling_sequence"
    split_volume_header = "volume amine to add"
    transfer_number_header = "number of transfer per vial"

    for index, value in enumerate(reaction_conditions_df[id_header].tolist()):
        if value == reaction_to_start:
            volume_per_reaction = float(reaction_conditions_df[split_volume_header].tolist()[index])
            transfer_number = int(reaction_conditions_df[transfer_number_header].tolist()[index])
            source_location_1 = [storage_rack.wells(0).bottom()]
            source_location_2 = [storage_rack.wells(1).bottom()]
            source_location_3 = [storage_rack.wells(2).bottom()]

            destination_1 = [x.top(-10) for x in destination_rack1.wells(0, to=transfer_number-1)]
            destination_2 = [x.top(-10) for x in destination_rack1.wells(transfer_number, to=transfer_number*2-1)]
            destination_3 = [x.top(-10) for x in destination_rack1.wells(transfer_number*2, to=transfer_number*3-1)]

            p1000.distribute(volume_per_reaction, source_location_1,destination_1, air_gap=10)
            p1000.distribute(volume_per_reaction, source_location_2,destination_2, air_gap=10)
            p1000.distribute(volume_per_reaction, source_location_3,destination_3, air_gap=10)
reactants_transfer(reaction_conditions_df)


from datetime import datetime, timedelta

from discord import Embed
from discord.ext import commands
import re
import discord
from discord.ext.commands import Cog
from discord.ext.commands import command, has_permissions

from ..db import db

time_regex = re.compile(r"(?:(\d{1,5})(h|s|m|d))+?")
time_dict = {'h': 3600, 's': 1, 'm': 60, 'd': 86400}

class TimeConverter(commands.Converter):
    async def convert(self, ctx, argument):
        args = argument.lower()
        matches = re.findall(time_regex, args)
        time = 0
        for key, value in matches:
            try:
                time += time_dict[value] * float(key)
            except KeyError:
                raise commands.BadArgument(f"{value} is an invalid time key! h|m|s|d are valid arguments")
            except ValueError:
                raise commands.BadArgument(f"{key} is not a number!")
        return time

# Here are all the number emotes.
# 0⃣ 1⃣ 2⃣ 3⃣ 4⃣ 5⃣ 6⃣ 7⃣ 8⃣ 9⃣

# numbers = ("1⃣", "2⃣", "3⃣", "4⃣", "5⃣",
# 		   "6⃣", "7⃣", "8⃣", "9⃣", "🔟")

numbers = ("⬆","⬇")

class Reactions(Cog):

	def __init__(self, bot):
		self.bot = bot
		self.polls = []
	def custom_check():
            def predicate(ctx):
                cog = ctx.bot.get_cog("Fun")
                command  =  db.field("SELECT commandname FROM command WHERE channelid = ?", ctx.channel.id)
                if command is not None:
                    command.split(',')
                    if  len(command)> 1 and ctx.command.name in command :
                        return
                    elif ctx.command.name in command :
                        return
                return True
            return commands.check(predicate)

	@Cog.listener()
	async def on_ready(self):
		if not self.bot.ready:

			self.bot.cogs_ready.ready_up("reactions")

	@command(name="createpoll", aliases=["poll"], description = 'start a poll', usage = '+poll <time> <question>')
	@custom_check()
	# @has_permissions(manage_guild=True) new
	async def create_poll(self, ctx, time: TimeConverter, *, question:str):
		'''+poll 1m kya mai cute hu '''
		try:

                    embed = Embed(title="Poll",
                                            colour=ctx.author.colour,
                                            timestamp=datetime.utcnow())

                    embed.add_field(name = 'Question', value = question,inline = False)
                    embed.add_field(name = 'Time', value = time, inline = False)

                    message = await ctx.send(embed=embed)

                    for emoji in numbers:
                            await message.add_reaction(emoji)

                    self.polls.append((message.channel.id, message.id))

                    self.bot.scheduler.add_job(self.complete_poll, "date", run_date=datetime.now()+timedelta(seconds =time),args=[message.channel.id, message.id])
		except:
                    await ctx.send(f'type {ctx.prefix}help createpoll')

	async def complete_poll(self, channel_id, message_id):
                try:
                    message = await self.bot.get_channel(channel_id).fetch_message(message_id)

                    most_voted = max(message.reactions, key=lambda r: r.count)
                    for reaction in message.reactions :
                            if str(reaction.emoji) =='⬆':
                                    x = reaction.count
                            if str(reaction.emoji) =='⬇':
                                    y = reaction.count
                    if x == y :
                            await message.channel.send(" The results are in and oops it's a tie ")
                    else:
                            await message.channel.send(f"The results are in and option {most_voted.emoji} was the most popular with {most_voted.count-1:,} votes!")
                    self.polls.remove((message.channel.id, message.id))
                    await message.delete()
                except :
                    pass

	# @Cog.listener()
	# async def on_raw_reaction_add(self, payload):
	# 	if self.bot.ready and payload.message_id == self.reaction_message.id:
	# 		current_colours = filter(lambda r: r in self.colours.values(), payload.member.roles)
	# 		await payload.member.remove_roles(*current_colours, reason="Colour role reaction.")
	# 		await payload.member.add_roles(self.colours[payload.emoji.name], reason="Colour role reaction.")
	# 		await self.reaction_message.remove_reaction(payload.emoji, payload.member)

	# 	elif payload.message_id in (poll[1] for poll in self.polls):
	# 		message = await self.bot.get_channel(payload.channel_id).fetch_message(payload.message_id)

	# 		for reaction in message.reactions:
	# 			if (not payload.member.bot
	# 				and payload.member in await reaction.users().flatten()
	# 				and reaction.emoji != payload.emoji.name):
	# 				await message.remove_reaction(reaction.emoji, payload.member)

	# 	elif payload.emoji.name == "⭐":
	# 		message = await self.bot.get_channel(payload.channel_id).fetch_message(payload.message_id)

	# 		if not message.author.bot and payload.member.id != message.author.id:
	# 			msg_id, stars = db.record("SELECT StarMessageID, Stars FROM starboard WHERE RootMessageID = ?",
	# 									  message.id) or (None, 0)

	# 			embed = Embed(title="Starred message",
	# 						  colour=message.author.colour,
	# 						  timestamp=datetime.utcnow())

	# 			fields = [("Author", message.author.mention, False),
	# 					  ("Content", message.content or "See attachment", False),
	# 					  ("Stars", stars+1, False)]

	# 			for name, value, inline in fields:
	# 				embed.add_field(name=name, value=value, inline=inline)

	# 			if len(message.attachments):
	# 				embed.set_image(url=message.attachments[0].url)

	# 			if not stars:
	# 				star_message = await self.starboard_channel.send(embed=embed)
	# 				db.execute("INSERT INTO starboard (RootMessageID, StarMessageID) VALUES (?, ?)",
	# 						   message.id, star_message.id)

	# 			else:
	# 				star_message = await self.starboard_channel.fetch_message(msg_id)
	# 				await star_message.edit(embed=embed)
	# 				db.execute("UPDATE starboard SET Stars = Stars + 1 WHERE RootMessageID = ?", message.id)

	# 		else:
	# 			await message.remove_reaction(payload.emoji, payload.member)

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


from __future__ import annotations

import logging

import click
import numpy as np

import vpype as vp

from .cli import cli
from .decorators import global_processor

try:
    # noinspection PyUnresolvedReferences
    import vpype_viewer

    _vpype_viewer_ok = True
except ImportError:  # pragma: no cover
    _vpype_viewer_ok = False

__all__ = ("show",)

COLORS = [
    (0, 0, 1),
    (0, 0.5, 0),
    (1, 0, 0),
    (0, 0.75, 0.75),
    (0, 1, 0),
    (0.75, 0, 0.75),
    (0.75, 0.75, 0),
    (0, 0, 0),
]

@cli.command(group="Output")
@click.option("--classic", is_flag=True, help="Use the classic viewer.")
@click.option("--force", is_flag=True, hidden=True, help="Force modern viewer")
@click.option("-p", "--show-pen-up", is_flag=True, help="Display pen-up trajectories.")
@click.option("-d", "--show-points", is_flag=True, help="Display paths points with dots.")
@click.option("-o", "--outline", is_flag=True, help="Display in outline mode (modern only).")
@click.option(
    "-c",
    "--colorful",
    is_flag=True,
    help="Display in outline colorful mode (takes precedence over --outline).",
)
@click.option("-a", "--show-axes", is_flag=True, help="Display axes (classic only).")
@click.option(
    "-g", "--show-grid", is_flag=True, help="Display grid (implies -a, classic only)."
)
@click.option(
    "-h", "--hide-legend", is_flag=True, help="Do not display the legend (classic only)."
)
@click.option(
    "-u",
    "--unit",
    type=str,
    default="px",
    help="Units of the plot (when --show-grid is active, classic only).",
)
@global_processor
def show(
    document: vp.Document,
    classic: bool,
    force: bool,
    show_pen_up: bool,
    show_points: bool,
    outline: bool,
    colorful: bool,
    show_axes: bool,
    show_grid: bool,
    hide_legend: bool,
    unit: str,
):
    """Display the geometry in an graphical user interface.

    By default, this command use a modern, hardware-accelerated viewer (currently in beta) with
    a preview mode (adjustable pen width and opacity) and interactive controls to adjust
    display options. This viewer requires OpenGL 3.3 support.

    The original, Matplotlib-based viewer is still available with the `--classic` option. The
    classic viewer does not have interactive controls for display options. Use the command-line
    options to customize the display.
    """

    if not classic:
        # test for vpype_viewer
        if not _vpype_viewer_ok:
            logging.warning(
                "!!! show: vpype viewer not available, reverting to classic mode. Note: use "
                "`pip install vpype[all]` to install the vpype viewer."
            )
            classic = True
        else:
            mgl_ok = _test_mgl()
            if not mgl_ok and not force:
                classic = True
                logging.warning("!!! show: ModernGL not available, reverting to classic mode.")
            elif not mgl_ok and force:
                logging.warning("!!! show: ModernGL not available but forced to vpype viewer.")

    if classic:
        _show_mpl(
            document,
            show_axes,
            show_grid,
            show_pen_up,
            show_points,
            hide_legend,
            colorful,
            unit,
        )
    else:
        view_mode = vpype_viewer.ViewMode.PREVIEW
        if outline or show_points:
            view_mode = vpype_viewer.ViewMode.OUTLINE
        if colorful:
            view_mode = vpype_viewer.ViewMode.OUTLINE_COLORFUL

        vpype_viewer.show(
            document, view_mode=view_mode, show_pen_up=show_pen_up, show_points=show_points
        )

    return document

def _test_mgl() -> bool:
    """Tests availability of ModernGL."""
    # noinspection PyBroadException
    try:
        import glcontext

        backend = glcontext.default_backend()
        ctx = backend(mode="standalone", glversion=330)
        if ctx.load("glProgramUniform1iv") == 0:
            logging.info("ModernGL detection: glProgramUniform1iv not found")
            return False
    except Exception as exc:
        logging.info(f"ModernGL detection failed with error {exc}")
        return False

    return True

def _show_mpl(
    document: vp.Document,
    show_axes: bool,
    show_grid: bool,
    show_pen_up: bool,
    show_points: bool,
    hide_legend: bool,
    colorful: bool,
    unit: str,
):
    """Display the geometry using matplotlib.

    By default, only the geometries are displayed without the axis. All geometries are
    displayed with black. When using the `--colorful` flag, each segment will have a different
    color (default matplotlib behaviour). This can be useful for debugging purposes.
    """

    # deferred import to optimise startup time
    try:
        import matplotlib.collections
        import matplotlib.pyplot as plt
    except ImportError:
        logging.warning(
            "!!! show: classic viewer not available, ignore command. Note: use `pip install "
            "matplotlib` to enable the classic viewer."
        )
        return

    scale = 1 / vp.convert_length(unit)

    fig = plt.figure()
    color_idx = 0
    collections = {}

    # draw page boundaries
    if document.page_size:
        w = document.page_size[0] * scale
        h = document.page_size[1] * scale
        dw = 10 * scale
        plt.plot(
            np.array([0, 1, 1, 0, 0]) * w,
            np.array([0, 0, 1, 1, 0]) * h,
            "-k",
            lw=0.25,
            label=None,
        )
        plt.fill(
            np.array([w, w + dw, w + dw, dw, dw, w]),
            np.array([dw, dw, h + dw, h + dw, h, h]),
            "k",
            alpha=0.3,
            label=None,
        )

    for layer_id, lc in document.layers.items():
        if colorful:
            color = COLORS[color_idx:] + COLORS[:color_idx]
            marker_color = "k"
            color_idx += len(lc)
        else:
            color = COLORS[color_idx]  # type: ignore
            marker_color = [color]  # type: ignore
            color_idx += 1
        if color_idx >= len(COLORS):
            color_idx = color_idx % len(COLORS)

        layer_lines = matplotlib.collections.LineCollection(
            (vp.as_vector(line) * scale for line in lc),
            color=color,
            lw=1,
            alpha=0.5,
            label=str(layer_id),
        )
        collections[layer_id] = [layer_lines]
        plt.gca().add_collection(layer_lines)

        if show_points:
            points = np.hstack([line for line in lc]) * scale
            layer_points = plt.gca().scatter(
                points.real, points.imag, marker=".", c=marker_color, s=16
            )
            collections[layer_id].append(layer_points)

        if show_pen_up:
            pen_up_lines = matplotlib.collections.LineCollection(
                (
                    (vp.as_vector(lc[i])[-1] * scale, vp.as_vector(lc[i + 1])[0] * scale)
                    for i in range(len(lc) - 1)
                ),
                color=(0, 0, 0),
                lw=0.5,
                alpha=0.5,
            )
            collections[layer_id].append(pen_up_lines)
            plt.gca().add_collection(pen_up_lines)

    plt.gca().invert_yaxis()
    plt.axis("equal")
    plt.margins(0, 0)

    if not hide_legend:
        lgd = plt.legend(loc="upper right")
        # we will set up a dict mapping legend line to orig line, and enable
        # picking on the legend line
        line_dict = {}
        for lgd_line, lgd_text in zip(lgd.get_lines(), lgd.get_texts()):
            lgd_line.set_picker(True)  # 5 pts tolerance
            lgd_line.set_pickradius(5)
            layer_id = int(lgd_text.get_text())
            if layer_id in collections:
                line_dict[lgd_line] = collections[layer_id]

        def on_pick(event):
            line = event.artist
            vis = not line_dict[line][0].get_visible()
            for ln in line_dict[line]:
                ln.set_visible(vis)

            if vis:
                line.set_alpha(1.0)
            else:
                line.set_alpha(0.2)
            fig.canvas.draw()

        fig.canvas.mpl_connect("pick_event", on_pick)

    if show_axes or show_grid:
        plt.axis("on")
        plt.xlabel(f"[{unit}]")
        plt.ylabel(f"[{unit}]")
    else:
        plt.axis("off")
    if show_grid:
        plt.grid("on")
    plt.show()


#Machine Vision and Robotics Course Project
#Fire detection using Image Processing
#import modules
import cv2#Computer vision module for video capture and image processing
import numpy as np#Python numbers module for matrix manipulation
import time#time module to measure time for pauses
import winsound# windows sound module for alarm
v=cv2.VideoCapture(0)#Capture live video using camera 0 (default webcam) and store values in v
time.sleep(2)#pause for 2 seconds
fdc=cv2.CascadeClassifier(r'C:\python\python36\fire_detection.xml')#Load generated cascade classifier into fdc
frequency = 2500#Define alarm frequency as 2500 Hz
duration = 500#Define alarm duration as 500 ms
while(1):#Loop code continously
        d,i=v.read()#Get frame from video capture. If frame is obtained, store TRUE in d and store image matrix in i
        print(i.shape)#Print image dimensions in console
        fire=fdc.detectMultiScale(i,1.3,9)#Use detectMultiScale function to detect objects, passing image,scale factor and minNeighbors as parameters
        print(fire)#Print dimensions of detected object (fire) matrix in console

        if(len(fire)>=1):#If 1 or more objects (fires) are detected
         for x,y,w,h in fire:#Store coordinates of upper-left corner in x and y, and widht and height in w and h
              font=cv2.FONT_HERSHEY_SIMPLEX#Define font
              cv2.putText(i,'FIRE DETECTED',(x-w,y-h),font,0.5,(0,255,255),2,cv2.LINE_AA)#Display "FIRE DETECTED" test
              cv2.rectangle(i,(x,y),(x+w,y+h),(0,0,255),2)#Display rectangle around fire
              time.sleep(0.2)#Pause of  for 0.2 seconds
              winsound.Beep(frequency, duration)#Sound alarm
        cv2.imshow('image',i)#Display processed image on screen

        if(len(fire)>=1):#If 1 or more objects (fires) are detected

           print('FIRE DETECTED')#Print "FIRE DETECTED" to console
        k=cv2.waitKey(5)#If keypress is detected, wait 5 seconds
        if(k==ord('q')):#If detected key is q
                cv2.destroyAllWindows()#Stop all processing
                break#Exit loop