from simpletransformers.language_generation import LanguageGenerationModel

import os

def download_model():
    import dropbox
    dbx = dropbox.Dropbox("gzhGYnEbdx0AAAAAAAAAAW5Ab2pW_0ShlpGFbDOnBkzRTlSLJCBn889-RDubhfLt")

    with open("from_scratch/best_model/pytorch_model.bin", "wb") as f:
        print("getting file")
        metadata, res = dbx.files_download(path="/mcnlp/pytorch_model.bin")
        print("writing file")
        f.write(res.content)
class McNLP:
    def __init__(self,):
        if not os.path.isfile('from_scratch/best_model/pytorch_model.bin'):
            download_model()
        try:
            self.model = LanguageGenerationModel("gpt2", "from_scratch/best_model", args={"max_length": 200, "temperature":1},use_cuda=False)
        except:
            os.remove("from_scratch/best_model/pytorch_model.bin")
            download_model()
            print("retry")
            self.model = LanguageGenerationModel("gpt2", "from_scratch/best_model", args={"max_length": 200, "temperature":1},use_cuda=False)

    def generate(self,string_to_start,temperature=1, max_length=200):
        generated = self.model.generate(string_to_start,args={'temperature':temperature,'max_length':max_length}, verbose=False)
        return generated[0].replace(',','\n')

# mc = McNLP()
# f = open("demofile2.txt", "a", encoding='utf8')
# f.write(mc.generate("שורף את הביט", temperature=1.8,max_length=300))
# f.close()
# print()


import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import functools
import logging
from panodr_module import *
logger = logging.getLogger(__name__)

class GatedGenerator(nn.Module):
    def __init__(self):
        super(GatedGenerator, self).__init__()
        self.latent_channels = 64
        self.in_spade_channels = 3
        self.in_SEAN_channels = 3
        self.pad_type = 'spherical'
        self.activation = 'relu'
        self.norm = 'in'
        self.out_channels = 3
        self.use_Unet = False

        self.structure_model = UNet(n_channels = 3, n_classes = 3)
        self.Zencoder = Zencoder(self.in_SEAN_channels, 512)
        self.spade_block_1 = SPADEResnetBlock(self.latent_channels*4, self.latent_channels*4, self.in_spade_channels,  Block_Name='up_0')
        self.spade_block_2 = SPADEResnetBlock(self.latent_channels*2, self.latent_channels*2, self.in_spade_channels,  Block_Name='up_1')

        self.refinement = nn.Sequential(

            GatedConv2d(4, self.latent_channels, 5, 2, 2, pad_type = self.pad_type, activation = self.activation, norm='none'),
            GatedConv2d(self.latent_channels, self.latent_channels * 2, 3, 1, 1, pad_type = self.pad_type, activation = self.activation, norm = self.norm),
            GatedConv2d(self.latent_channels * 2, self.latent_channels * 4, 3, 2, 1, pad_type = self.pad_type, activation = self.activation, norm = self.norm),
            GatedConv2d(self.latent_channels * 4, self.latent_channels * 4, 3, 1, 1, pad_type = self.pad_type, activation = self.activation, norm = self.norm),
            # Bottleneck
            GatedConv2d(self.latent_channels * 4, self.latent_channels * 4, 3, 1, 1, pad_type = self.pad_type, activation = self.activation, norm = self.norm),
            GatedConv2d(self.latent_channels * 4, self.latent_channels * 4, 3, 1, 1, pad_type = self.pad_type, activation = self.activation, norm = self.norm),
            GatedConv2d(self.latent_channels * 4, self.latent_channels * 4, 3, 1, 2, dilation = 2, pad_type = self.pad_type, activation = self.activation, norm = self.norm),
            GatedConv2d(self.latent_channels * 4, self.latent_channels * 4, 3, 1, 4, dilation = 4, pad_type = self.pad_type, activation = self.activation, norm = self.norm),
            GatedConv2d(self.latent_channels * 4, self.latent_channels * 4, 3, 1, 8, dilation = 8, pad_type = self.pad_type, activation = self.activation, norm = self.norm),
            GatedConv2d(self.latent_channels * 4, self.latent_channels * 4, 3, 1, 16, dilation = 16, pad_type = self.pad_type, activation = self.activation, norm = self.norm),
            GatedConv2d(self.latent_channels * 4, self.latent_channels * 4, 3, 1, 1, pad_type = self.pad_type, activation = self.activation, norm = self.norm),
            GatedConv2d(self.latent_channels * 4, self.latent_channels * 4, 3, 1, 1, pad_type = self.pad_type, activation = self.activation),
        )
        self.refine_dec_1 = nn.Sequential(nn.Upsample(scale_factor=2),
        GatedConv2d(self.latent_channels * 4, self.latent_channels * 2, 3, 1, 1, activation = self.activation, pad_type='zero', norm=self.norm),
        )
        self.refine_dec_2 =  GatedConv2d(self.latent_channels * 2, self.latent_channels * 2, 3, 1, 1, pad_type = self.pad_type, activation = self.activation)
        self.refine_dec_3 = nn.Sequential(nn.Upsample(scale_factor=2),

        GatedConv2d(self.latent_channels * 2, self.latent_channels, 3, 1, 1, pad_type ='zero', activation = self.activation),
        )
        self.refine_dec_4 = GatedConv2d(self.latent_channels, self.out_channels, 3, 1, 1, pad_type = self.pad_type, norm='none', activation = 'tanh')

    def forward(self, data):
        image = data[0,:,:,:].unsqueeze_(0)
        inverse_mask = (data[1,:,:,:].unsqueeze_(0))[:,0,:,:].unsqueeze_(0)
        masked_input = image * (1.0-inverse_mask) + inverse_mask

        #_sem_layout = None
        _sem_layout = torch.zeros_like(image)
        sem_layout = torch.zeros_like(image)

        structure_model_output = self.structure_model(masked_input).clone()
        if self.use_Unet:
            #old
            sem_layout = None
            sem_layout = torch.softmax(structure_model_output, dim = 1)
            _sem_layout = torch.argmax(sem_layout, dim=1, keepdim=True)
            _sem_layout = torch.clamp(_sem_layout, min=0, max=2)
            sem_layout.scatter_(1, _sem_layout, 1)

        else:
            sem_layout = data[2,:,:,:].unsqueeze_(0)
            sem_layout = sem_layout[0,:,:]
            sem_layout = torch.softmax(structure_model_output, dim = 1)
            _sem_layout = torch.argmax(sem_layout, dim=1, keepdim=True)
            _sem_layout = torch.clamp(_sem_layout, min=0, max=2)
            sem_layout.scatter_(1, _sem_layout, 1)

        second_out = self.refinement(torch.cat((masked_input, inverse_mask), 1))  #Enconder + bottleneck
        style_codes = self.Zencoder(input=image, segmap=sem_layout)
        z = self.spade_block_1(second_out, sem_layout, style_codes)
        second_out = self.refine_dec_1(z)
        second_out = self.refine_dec_2(second_out)
        z = self.spade_block_2(second_out, sem_layout, style_codes)
        second_out = self.refine_dec_3(z)
        second_out = self.refine_dec_4(second_out)
        second_out = torch.clamp(second_out, 0, 1)

        #get the diminished img
        output = image * (1.0-inverse_mask) + second_out * inverse_mask

        return output, sem_layout, second_out

def spectral_norm(module, mode=True):
    if mode:
        return nn.utils.spectral_norm(module)

    return module


from generator.data_generator import DataGenerator

# 1: Instantiate two `DataGenerator` objects: One for training, one for validation.

# Optional: If you have enough memory, consider loading the images into memory for the reasons explained above.

train_dataset = DataGenerator()
val_dataset = DataGenerator()

# 2: Parse the image and label lists for the training and validation datasets.

# Images
images_dir = '/Users/mike/Downloads/udacity_driving_datasets'

# Ground truth
train_labels_filename = '/Users/mike/Downloads/udacity_driving_datasets/labels_train.csv'
val_labels_filename = '/Users/mike/Downloads/udacity_driving_datasets/labels_val.csv'

train_dataset.parse_csv(images_dir=images_dir,
                        labels_filename=train_labels_filename,
                        input_format=['image_name', 'xmin', 'xmax', 'ymin', 'ymax', 'class_id'],
                        include_classes='all')

val_dataset.parse_csv(images_dir=images_dir,
                      labels_filename=val_labels_filename,
                      input_format=['image_name', 'xmin', 'xmax', 'ymin', 'ymax', 'class_id'],
                      include_classes='all')

train_dataset.create_hdf5_dataset(file_path='dataset/dataset_udacity_traffic_train.h5',
                                  resize=False,
                                  variable_image_size=True,
                                  verbose=True)

val_dataset.create_hdf5_dataset(file_path='dataset/dataset_udacity_traffic_val.h5',
                                resize=False,
                                variable_image_size=True,
                                verbose=True)


import os
from pricerequester import PriceRequester
from resultdata import ResultData
from ratedictionary import RateDictionary

if os.name == 'posix':
	RATE_DIC_FILE_PATH = '/sdcard/rateDic.txt'
else:
	RATE_DIC_FILE_PATH = 'D:\\Development\\Python\\CryptoPricer\\test\\rateDicSavedData.txt'

MINUTE_PRICE_DAY_NUMBER_LIMIT = 7   # if the request date is older than current time - this value,
									# the price returned is a day close price, not a minute price !

IDX_DATA_ENTRY_TO = 1

class PriceRequesterTestStub(PriceRequester):
	'''
	This class is used for testing purposes only to solve the fact that sometimes requesting
	a fiat/fiat (USD/CHF for example) historical price does not return a correct price.
	'''

	def __init__(self):
		super(PriceRequesterTestStub, self).__init__()
		self.rateDic = RateDictionary()

	# NO INTEREST TO CACHE RATES FOR DATE TIMES WHICH CHANGES AT EACH UNIT TEST
	# EXECUTION !
	#
	# def _getHistoMinutePriceAtUTCTimeStamp(self, crypto, unit, timeStampUTC, exchange, resultData):
	# 	rate = self.rateDic.getRate(crypto, unit, timeStampUTC, exchange)
	#
	# 	if not rate:
	# 		# the rate is not cached and is queried for the first time
	# 		resultData = super()._getHistoMinutePriceAtUTCTimeStamp(crypto, unit, timeStampUTC, exchange, resultData)
	# 		rate = resultData.getValue(resultData.RESULT_KEY_PRICE)
	#
	# 		if rate:
	# 			# no exception indicating that the coin pair is not supported was raised
	# 			self.rateDic.saveRate(crypto, unit, timeStampUTC, exchange, rate)
	# 	else:
	# 		resultData.setValue(ResultData.RESULT_KEY_PRICE_TYPE, resultData.PRICE_TYPE_HISTO_MINUTE)
	# 		resultData.setValue(ResultData.RESULT_KEY_PRICE_TIME_STAMP, timeStampUTC)
	# 		resultData.setValue(ResultData.RESULT_KEY_PRICE, rate)
	#
	# 	return resultData

	def _getHistoDayPriceAtUTCTimeStamp(self, crypto, unit, timeStampUTC, exchange, resultData):
		# fed up with this fucking provider which regurlarly return an invalid value of 1.06
		# for USD/CHF on CCCAGG on 12/9/17 !
		if crypto == 'USD' and unit == 'CHF' and exchange == 'CCCAGG' and timeStampUTC == 1536710400:
			rate = 0.9728
			resultData.setValue(resultData.RESULT_KEY_PRICE, rate)
		elif crypto == 'USD' and unit == 'CHF' and exchange == 'CCCAGG' and timeStampUTC == 1505174400:
			rate = 1.001
			resultData.setValue(resultData.RESULT_KEY_PRICE, rate)
		elif crypto == 'USD' and unit == 'EUR' and exchange == 'CCCAGG' and timeStampUTC == 1505174400:
			rate = 0.8346
			resultData.setValue(resultData.RESULT_KEY_PRICE, rate)
		else:
			rate = self.rateDic.getRate(crypto, unit, timeStampUTC, exchange)

		if not rate:
			# the rate is not cached and is queried for the first time
			resultData = super()._getHistoDayPriceAtUTCTimeStamp(crypto, unit, timeStampUTC, exchange, resultData)
			rate = resultData.getValue(resultData.RESULT_KEY_PRICE)

			if rate != None and rate > 0:
				# no exception indicating that the coin pair is not supported was raised
				self.rateDic.saveRate(crypto, unit, timeStampUTC, exchange, rate)
		else:
			resultData.setValue(ResultData.RESULT_KEY_PRICE_TYPE, resultData.PRICE_TYPE_HISTO_DAY)
			resultData.setValue(ResultData.RESULT_KEY_PRICE_TIME_STAMP, timeStampUTC)
			resultData.setValue(ResultData.RESULT_KEY_PRICE, rate)

		return resultData

	def getCurrentPrice(self,
						crypto,
						unit,
						exchange):
		resultData = super().getCurrentPrice(crypto,
											 unit,
											 exchange)

		return resultData

if __name__ == '__main__':
	pr = PriceRequesterTestStub()


import requests
from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher

class ActionAskCovidRegion(Action):

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

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        response = requests.get(
            "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-json/dpc-covid19-ita-regioni-latest.json").json()
        entity_par=tracker.latest_message["entities"] #recupero delle entities contenute nell'ultimo messaggio
        check_slot = tracker.get_slot("regione") #recupero dello slot
        regione = ""
        parameter = ""
        print("last message x par:", entity_par, "\n")
        print(check_slot)

        if check_slot is not None:
            regione=check_slot
        message = "please enter a correct italian region name"

        for e in entity_par:
            if e['entity'] == "parameter":
                parameter = e['value']
                parameter= parameter.strip().title() #recupero parametro

        for data in response: #costruzione del messaggio output
            if data["denominazione_regione"] == regione.title():
                print(data)
                if parameter == "Actual Positive Cases":
                    message="Actual positive cases: " + str(data['nuovi_positivi'])
                elif parameter == "Hospitalized With Symptoms":
                    message = "Hospitalized with symptoms: " + str(data['ricoverati_con_sintomi'])
                elif parameter == "Intensive Care Unit":
                    message = "Intensive care unit: " + str(data['terapia_intensiva'])
                elif parameter == "Total Deceased":
                    message = "Total deceased: " + str(data['deceduti'])
                elif parameter == "General Situation":
                    message = "Actual positive cases: " + str(data['nuovi_positivi']) + " Hospitalized with symptoms: " + str(
                    data['ricoverati_con_sintomi']) + " Intensive care unit:" + str(
                    data['terapia_intensiva']) + " Total deceased:" + str(data['deceduti'])
                else: print("it wasnt possible to provide datas, sorry")

        print(message)
        dispatcher.utter_message( regione + ": \n" + message) #presentazione del messaggio

        return []

class ActionAskCovidItaly(Action):

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

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        global parameter
        response = requests.get(
            "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-json/dpc-covid19-ita-andamento-nazionale-latest.json").json()
        intent = tracker.latest_message["intent"]
        entity_par = tracker.latest_message["entities"]
        message1=""
        print("last message", intent)
        print("last message x par:", entity_par, "\n")

        for e in entity_par:
            if e['entity'] == "parameter":
                parameter = e['value']
                parameter= parameter.strip().title()

        for data in response:
            if data["stato"] == "ITA":
                print(data)
                if parameter == "Actual Positive Cases":
                    message1 = "Actual positive cases: " + str(data['nuovi_positivi'])
                elif parameter == "Hospitalized With Symptoms":
                    message1 = "Hospitalized with symptoms: " + str(data['ricoverati_con_sintomi'])
                elif parameter == "Intensive Care Unit":
                    message1 = "Intensive care unit: " + str(data['terapia_intensiva'])
                elif parameter == "Total Deceased":
                    message1 = "Total deceased: " + str(data['deceduti'])
                elif parameter == "General Situation":
                    message1 = "Actual positive cases: " + str(
                        data['nuovi_positivi']) + " Hospitalized with symptoms: " + str(
                        data['ricoverati_con_sintomi']) + " Intensive care unit:" + str(
                        data['terapia_intensiva']) + " Total deceased:" + str(data['deceduti'])
                else:
                    print("it wasnt possible to provide datas, sorry")

        print(message1)
        dispatcher.utter_message("Covid situation in Italy: "  + "\n" + message1)

        return []


class Solution:
    def lis(self, nums, i):
        if i == 0:
            return 1
        if self.cache[i] != -1:
            return self.cache[i]
        mlen = 1
        for j in range(i):
            if nums[j] < nums[i]:
                curr = 1 + self.lis(nums, j)
                mlen = max(mlen, curr)
        self.cache[i] = mlen
        return mlen

    def lengthOfLIS(self, nums: List[int]) -> int:
        n = len(nums)
        self.cache = [-1] * n
        mlen = 1
        for i in range(n):
            curr = self.lis(nums, i)
            mlen = max(mlen, curr)
        return mlen


#!/usr/bin/env python
# coding: utf-8

# In[1]:

# Train the model
# After training we will have a dataset
# dataset is sent to CNN classifier we have used (VGG16) here.
# Examples of other CNN classifier: Resnet, InceptionNet, MObile Net V2
# Mobile Net V2 is very light, It uses Rpi, 25 Mb, accuray is 70% wrt 72% of VGG16 whih uses 500 Mb

# In[2]:

# Mask problem is easy as compared to emotion problem.
# Here, Model is exported.
# We are using transfer learning, where last layer is removed and our layer is added.
# Input is taken using webcam that is applied to the model.
# Screen detection is done first.
# We are cropping the face only with the rectangle for improved accuracy.
# Haar cascade is used to get frontal face detection.

# In[3]:

import os
# to get all files

# In[4]:

from keras.preprocessing import image
import cv2

# In[5]:

categories = ['without_mask','with_mask']

# In[6]:

data = []
for category in categories:
    path = os.path.join('train',category)

    label = categories.index(category)
    # without_mask index is 0
    # with_mask index is 1

    for file in os.listdir(path):
        # Now we will read image using opencv

        img_path = os.path.join(path,file)
        img = cv2.imread(img_path)
        img = cv2.resize(img,(224,224))

        data.append([img,label]) # for adding both the with and without mask images
        # (image,0) for image in without_mask folder
                                 #(image,1) for image in with_mask folder

# we will create a dataset 2 columns, 1st one is image and 2d is the label

# In[7]:

len(data)

# In[8]:

import random

# In[9]:

random.shuffle(data) # for mixing the with and without mask images

# In[10]:

# to separate X and y and then convert it into numpy array
X = []
y = []

for features,label in data:
    X.append(features)
    y.append(label)

# In[11]:

len(X)

# In[12]:

len(y)

# In[13]:

import numpy as np

# In[14]:

X = np.array(X)
# X should be 2d array
y = np.array(y)
# y should be 1d array since it is just a label

# In[15]:

X.shape
# 1508 is no of images with its shape (224,224,3) 224x224 and 3 is no of channels

# In[16]:

y.shape
# y are the labels

# In[17]:

y

# In[18]:

X

# In[19]:

X = X/255# in order to standize the X

# In[20]:

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2)

# In[21]:

X_test.shape

# In[22]:

# 302 is no of images in test

# In[23]:

# we will create CNN architecture and do the transfer learning

# In[24]:

from keras.applications.vgg16 import VGG16

# In[25]:

vgg = VGG16()

# In[26]:

vgg.summary()
# This is our vgg model

# In[27]:

# predictions (Dense)         (None, 1000)              4097000
#This last layer will be removed and we will add our layer with 1 node

# In[28]:

from keras import Sequential

# In[29]:

model = Sequential()

# In[30]:

for layer in vgg.layers[:-1]:  # to exclude last layer
    model.add(layer)

# In[31]:

model.summary()
# now last layer is removed and new model is created
# vgg is a functional model, but we needed sequential thats why we used sequential workflow

# In[32]:

#we will freeze all the layers so that their weights wont be updated during training

# In[33]:

for layer in model.layers:
    layer.trainable = False

# In[34]:

model.summary()

# In[35]:

# Now, all trainable parameters are set to 0 i.e. parameters are freezed

# In[36]:

# we are adding our last layer
from keras.layers import Dense

# In[37]:

model.add(Dense(1,activation='sigmoid'))

# In[38]:

model.summary()

# In[39]:

# this last layer has 4097 parameters, its 1 and 4096 coming from previous layer

# In[40]:

# 4097 are trainable parameters

# In[41]:

model.compile(optimizer='Adam',loss='binary_crossentropy',metrics=['accuracy'])
# to increase the accuracy, we can use learning rate of 0.0001

# In[ ]:

model.fit(X_train,y_train,epochs=5,validation_data=(X_test,y_test))

# In[ ]:

cap = cv2.VideoCapture(0) # to detect the face, 0 for webcam

# In[ ]:

while True:

    ret,frame = cap.read()
    #reading the image
    #ret gives us true or flase value
    #frame gives us the image

    # call for detection method
    img = cv2.resize(frame,(224,224))

    y_pred = detect_face_mask(img) # image is sent to the function, the ouput stored in y_pred
    # frame to get a smaller video, img for the normal window size

    coods = detect_face(cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY))

    for x,y,w,h in coods:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2) # 1is thickness

    if y_pred == 0:
        draw_label(frame,"Mask",(30,30),(0,255,0))
    else:
        draw_label(frame,"No Mask",(30,30),(0,0,255))

    draw_label(frame,"Face Mask Detection", (10,10),(255,0,0))
    #(255,0,0) is blue color

    print(y_pred)

    cv2.imshow('windows', frame) # we are displaying the frame

    if cv2.waitKey(1) & 0xFF == ord('x'):
        break

cv2.destroyAllWindows()

# In[ ]:

def detect_face_mask(img):

    #y_pred = model.predict_classes(img.reshape(1,224,224,3))
    y_pred = model.predict(img.reshape(1,224,224,3))
    y_pred = np.round(y_pred).astype(int)
    # our trained model will predict whether it is with or without mask as 1 or 0 as output

    return y_pred

# In[ ]:

sample1 = cv2.imread('sample1.jpg')
sample1 = cv2.resize(sample1,(224,224))

# In[ ]:

detect_face_mask(sample1)

# In[ ]:

# 1 index means with mask, which is right.

# In[ ]:

# now implementing a text in the video telling us whether mask is on or not

def draw_label(img,text,pos,bg_color): #pos is position

    text_size = cv2.getTextSize(text,cv2.FONT_HERSHEY_SIMPLEX,1,cv2.FILLED) # 1 is font scale
    # cv2.filled is thickness

    end_x = pos[0]+text_size[0][0] + 2 # 2 is the margin
    end_y = pos[1]+text_size[0][1] - 2

    cv2.rectangle(img,pos,(end_x,end_y),bg_color,cv2.FILLED)
    cv2.putText(img,text,pos,cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,0),1,cv2.LINE_AA)
    # (0,0,0) is the color, LINE_AA is type of line used

# In[ ]:

#face detection square

#import haar cascading file

haar = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

def detect_face(img):

    coods = haar.detectMultiScale(img)
    return coods


print("")
num1 = int(input("Enter your First Num : "))
num2 = int(input("Enter your Second Num : "))

def hcf(num1, num2):
    minnum = min(num1,num2)

    if minnum == num1:
        while num2%minnum != 0 or num1%minnum != 0 :
            minnum -= 1
    else:
        while num1%minnum != 0 or num2%minnum !=0 :
            minnum -= 1

    return minnum

print("")
print(f"H.C.F of {num1} and {num2} is {hcf(num1,num2)}")
print("")


from typing import Optional

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def swapHelper(self, head: Optional[ListNode],root: Optional[ListNode], prev:Optional[ListNode]):
        if head == None:
            return root
        elif head.next == None:
            return root
        else:
            third = head.next.next
            temp = head
            head = head.next
            head.next = temp
            temp.next = third
            prev.next = head
            return self.swapHelper(third,root,head.next)

    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head == None:
            return None
        elif head.next == None:
            return head
        else:
            third = head.next.next
            temp = head
            head = head.next
            head.next = temp
            temp.next = third
            return self.swapHelper(third,head,head.next)

#Exercise: https://leetcode.com/problems/swap-nodes-in-pairs/
#Given a linked list, swap every two adjacent nodes and return
# its head. You must solve the problem without modifying the
# values in the list's nodes (i.e., only nodes themselves may be changed.)


#  Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
#  a. o produto do dobro do primeiro com metade do segundo .
#  b. a soma do triplo do primeiro com o terceiro.
#  c. o terceiro elevado ao cubo.

class Calculador:
    def __init__(self, inteiro_1, inteiro_2, real):
        self.real = real
        self.inteiro_2 = inteiro_2
        self.inteiro_1 = inteiro_1

    def calculo_a(self):
        dobro_de_i1 = self.inteiro_1 * 2
        metade_do_i2 = (self.inteiro_2 / 2)
        produto = dobro_de_i1 * metade_do_i2
        return f'resultado A: {produto}'

    def calculo_b(self):
        triplo_de_i1 = self.inteiro_1 * 3
        soma = triplo_de_i1 + self.real
        return f'resultado B: {soma}'

    def calculo_c(self):
        valor = self.real ** 3
        return f'resultado C: {valor}'

    def calculos_abc(self):
        dobro_de_i1 = self.inteiro_1 * 2
        metade_do_i2 = (self.inteiro_2 / 2)
        produto = dobro_de_i1 * metade_do_i2
        triplo_de_i1 = self.inteiro_1 * 3
        soma = triplo_de_i1 + self.real
        valor = self.real ** 3
        return f'resultado A: {produto}, resultado B: {soma}, resultado C: {valor}'

if __name__ == '__main__':
    calculador = Calculador(3, 40, 8)
    print(calculador.calculo_a())
    print(calculador.calculo_b())
    print(calculador.calculo_c())
    print(calculador.calculos_abc())

x1 = int(input('Informe o primeiro número inteiro: '))  # resposta certa, corrigido da internet
x2 = int(input('Informe o segundo número inteiro: '))
r = float(input('Informe um número real: '))

a = (2 * x1) * (x2 / 2)
b = 3 * x1 + r
c = r ** 3

print(a)
print(b)
print(c)


import bluetooth
import struct

def connect_bluetooth(mac: str):
	try:
		print(f"Connecting to MAC address {mac}")
		sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
		sock.connect((mac, 1))
		print(f"Connected to {mac}")

		return sock

	except bluetooth.btcommon.BluetoothError as e:
		print(e)
		return None

class BluetoothWriter:
	def __init__(self, sock):
		self.__socket = sock

	# opcode and params must be 0-127
	def write(self, opcode: int, *params: int):
		integers = [opcode, *params]
		print(integers)
		data = "".join(chr(c) for c in integers)
		self.__socket.send(data)


import cvxpy as cp
import numpy as np

import sympy
from sympy import var
from sympy.matrices import Matrix, eye, zeros, ones, diag, GramSchmidt

var('e1 e2 g p1 p2 p3')

M = Matrix([[0, 0, -1], [1, 0, 0], [0, 1, 0]])

P = Matrix([[0, 1 / 2], [1 / 2, 0]])
S = Matrix([[0, 1 / 2], [1 / 2, -e1]])
SP2 = Matrix([[0, 1 / 2], [1 / 2, -e2]])
L = Matrix([[g, 0], [0, -1]])

supp = {
    "P": P,
    "S": S,
    "L": L
}

order = 'LLS'

def xp(order):
    x1 = Matrix.diag([p1 * supp[order[0]][0, 0], p2 * supp[order[1]][0, 0], p3 * supp[order[2]][0, 0]])
    x2 = Matrix.diag([p1 * supp[order[0]][0, 1], p2 * supp[order[1]][0, 1], p3 * supp[order[2]][0, 1]])
    x3 = Matrix.diag([p1 * supp[order[0]][1, 0], p2 * supp[order[1]][1, 0], p3 * supp[order[2]][1, 0]])
    x4 = Matrix.diag([p1 * supp[order[0]][1, 1], p2 * supp[order[1]][1, 1], p3 * supp[order[2]][1, 1]])
    Xp = Matrix([[x1, x2], [x3, x4]])
    mc = Matrix([[M], [Matrix.eye(3)]])
    Xp = mc.transpose() @ Xp @ mc
    return Xp

Xp = xp(order)

p1 = cp.Variable(1)
p2 = cp.Variable(1)
p3 = cp.Variable(1)
v1 = 5
v2 = 6
h = 2

Xp = Xp.subs([(e1, v1), (e2, v2), (g, h), (p1, p1), (p2, p2), (p3, p3)])

#
# Xp2=Xp.subs(p1,3)
#
#
# cp.bmat([[Xp[0, :]], [Xp[1, :]], [Xp[2, :]]])


from django import forms  #import modułu wbudowanych formularzy

from .models import Topic, Entry #import modelu Topic

class TopicForm(forms.ModelForm): #Utworzenie klasy TopicForm z przekazanym modelem formularza
    class Meta:
        model = Topic #Budowanie formularza o model Topic
        fields = ['text'] #Możliwość wprowadzania tylko treść do pola text
        labels = {'text': ''} #informacja, że kolumna text nie ma etykiety

class EntryForm(forms.ModelForm):
    class Meta:
        model = Entry
        fields = ['text']
        labels = {'text': ''}
        widgets = {'text': forms.Textarea(attrs={'cols': 80})} #Nadpisanie ustawień aby dla kolumny 'text' wyświetlic textarea o szerokości 80


# Definition for singly-linked list with a random pointer.
class RandomListNode(object):
    def __init__(self, x):
        self.label = x
        self.next = None
        self.random = None

class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: RandomListNode
        :rtype: RandomListNode
        """
        if head is None:
            return None
        hash = {}
        chead = RandomListNode(head.label)
        hash[head] = chead
        p = head
        q = chead
        # 建立next的映射
        while p:
            q.random = p.random
            if p.next:
                q.next = RandomListNode(p.next.label)
                hash[p.next] = q.next
            else:
                q.next = None
            p = p.next
            q = q.next

        # 建立random的映射
        p = chead
        while p:
            if p.random:
                p.random = hash[p.random]
            p = p.next
        return chead


import copy

import pygame

from sim_utils.config import LANE_LIGHT_LOCATION, LANE_LENGTH, FACTOR_SPEED, SAFETY_DISTANCE, EMERGENCY_RED_MAX_SPEED, \
    METHOD
from sim_utils.utils import load_image, get_screen_center, get_lane_points, stopping_position, get_rotation, \
    acceleration_time

class Vehicle(pygame.sprite.Sprite):
    def __init__(self, name: str, speed: int, max_speed: int,
                 acceleration: int, braking: int, turn_rate: int, scale: tuple,
                 direction: str,  dataStorage, next_lane, id_: int = -1, time_waited: int = 0, debug=False):
        self.dataStorage = dataStorage
        pygame.sprite.Sprite.__init__(self)

        self.load_car_image(direction, name, scale)

        # Font for debugging purposes
        self.font = pygame.font.SysFont("monospace", 14)

        # Initially start the car at the start of the lane
        self.position = 0.0

        self.direction = direction
        self.next_lane = next_lane
        self.id = id_
        self.name = name
        self.scale = scale
        # TODO: better solution to determine length/width
        self.width = min(self.rect.height, self.rect.width)
        self.length = max(self.rect.height, self.rect.width)
        self.rect = pygame.Rect(-100, -100, self.rect.width, self.rect.height)
        self.speed = speed
        self.max_speed = max_speed
        self.acceleration = acceleration
        self.turn_rate = turn_rate
        self.braking = braking
        self.turning = False
        self.turning_start = None
        self.reached_destination = False
        self.ticks = 0
        self.wait_time = time_waited

        self.debug = debug
        # TODO: debug
        self.queue_length = 0

        if self.next_lane and not self.direction_change(self.next_lane, self.direction):
            # No direction change, zero turn rate
            self.turn_rate = 0

    def update_cycle(self, lane, queue_length, previous_car, intersection_blocked):
        self.ticks += 1

        # If car is stopped in queue, increase wait time
        if lane.towards and self.speed == 0:
            self.wait_time += 1

        if self.turning and self.direction_change(self.next_lane, self.direction):
            self.speed = 0

        elif (previous_car is not None and
              (stopping_position(self.position, max(self.length, self.width), self.speed, self.braking) >
               stopping_position(previous_car.position, max(previous_car.length, previous_car.width),
                                 previous_car.speed, previous_car.braking) -
               max(previous_car.length, previous_car.width) / LANE_LENGTH - SAFETY_DISTANCE)):
            # Braking now avoids a collision with the car in front
            self.speed = max(0, self.speed - self.braking)

        elif lane.checklight() == 'green':
            # Light is green; accelerate
            self.speed = min(self.speed + self.acceleration, self.max_speed)

        elif self.passed_light():
            # Already passed the light; accelerate
            self.speed = min(self.speed + self.acceleration, self.max_speed)

        elif (stopping_position(self.position, max(self.length, self.width), self.speed, self.braking) >
              LANE_LIGHT_LOCATION - SAFETY_DISTANCE):
            # Braking now stops before the light
            self.speed = max(0, self.speed - self.braking)

        else:
            # No action required, accelerate
            self.speed = min(self.speed + self.acceleration, self.max_speed)

        if (lane.towards and
            intersection_blocked and
            LANE_LIGHT_LOCATION > self.position > (LANE_LIGHT_LOCATION - 0.05)):
            # Car is about to enter intersection but emergency is crossing; brake
            self.speed = max(0, self.speed - self.braking)

        if (previous_car is not None and
            previous_car.position >LANE_LIGHT_LOCATION and
            self.direction_change(previous_car.next_lane, previous_car.direction)):
            # Car in front is turning, wait at light
            self.speed = max(0, self.speed - self.braking)

        self.position += (self.speed * FACTOR_SPEED) / LANE_LENGTH

        # TODO: debug
        self.queue_length = queue_length

        keep_car = True
        if self.position > 1.0:
            if self.next_lane:
                # Car transitions to next lane
                if self.turning:
                    if self.ticks - self.turning_start > self.turn_rate:
                        # Car is done turning, remove car, add one to next lane
                        self.turning = False
                        keep_car = False
                        self.next_lane[0].addCar(
                            Vehicle(self.name, self.speed, self.max_speed,
                                    self.acceleration, self.braking, self.turn_rate, self.scale,
                                    self.next_lane[1], self.dataStorage, None,
                                    time_waited=self.wait_time, debug=self.debug)
                        )
                else:
                    # Start turning on the intersection
                    self.turning = True
                    self.turning_start = self.ticks
            else:
                # Car has reached destination
                self.dataStorage.add_destination(self.direction, self.ticks, self.wait_time)
                keep_car = False

        if not keep_car:
            # Remove sprite from group
            self.kill()
            return False
        return True

    def update_emergency(self, lane):
        self.ticks += 1

        if self.position < (LANE_LIGHT_LOCATION - 0.15):
            # Accelerate towards max speed
            self.speed = min(self.speed + self.acceleration, self.max_speed)
        elif lane.checklight() != 'green':
            # Slow down to maximum red traversing speed
            self.speed = max(EMERGENCY_RED_MAX_SPEED, self.speed - self.braking)
        else:
            # Accelerate
            self.speed = min(self.speed + self.acceleration, self.max_speed)

        self.position += (self.speed * FACTOR_SPEED) / LANE_LENGTH

        # TODO: Below is copied from update_cycle()
        keep_car = True
        if self.position > 1.0:
            if self.next_lane:
                # Car transitions to next lane
                if self.turning:
                    if self.ticks - self.turning_start > self.turn_rate:
                        # Car is done turning, remove car, add one to next lane
                        self.turning = False
                        keep_car = False
                        self.next_lane[0].add_emerg_vehicle(
                            Vehicle(self.name, self.speed, self.max_speed,
                                    self.acceleration, self.braking, self.turn_rate, self.scale,
                                    self.next_lane[1], self.dataStorage, None, debug=self.debug)
                        )
                else:
                    # Start turning on the intersection
                    self.turning = True
                    self.turning_start = self.ticks
            else:
                # Car has reached destination
                keep_car = False

        if not keep_car:
            # Remove sprite from group
            self.kill()
            return False
        return True

    def render(self, screen, lane, prev_car, side_parked=False):
        if side_parked:
            start, end = get_lane_points(lane, get_screen_center(), order_offset=1)
        else:
            start, end = get_lane_points(lane, get_screen_center(), center_line=True)

        if self.direction == 'E':
            self.rect.center = (start.x + self.position * LANE_LENGTH,
                                start.y)
        if self.direction == 'W':
            self.rect.center = (start.x - self.position * LANE_LENGTH,
                                start.y)
        if self.direction == 'N':
            self.rect.center = (start.x,
                                start.y - self.position * LANE_LENGTH)
        if self.direction == 'S':
            self.rect.center = (start.x,
                                start.y + self.position * LANE_LENGTH)
        if self.debug:
            # debug_output = str(round(self.position, 2))
            previous_id = -1
            if prev_car is not None:
                previous_id = prev_car.id
            debug_output = 'None'
            # debug_output = str(self.id) + ', ' + str(previous_id)
            # debug_output = str(self.direction)
            # debug_output = str(self.queue_length)
            if lane.light is not None:
                debug_output = str(round(lane.light.getGreentime(), 2))
            # debug_output = str(round(acceleration_time(1.0-self.position, self.speed, self.acceleration,
            #                                            self.max_speed), 2))
            # debug_output = str(lane.emergency_active)

            text = self.font.render(debug_output, 1, (255, 255, 255), (0, 0, 0))
            screen.blit(text, self.rect.bottomright)

    def passed_light(self):
        return self.position > LANE_LIGHT_LOCATION

    def rotate_car(self, angle_start, angle_end, portion):
        current_angle = portion * (angle_end - angle_start)
        self.image = pygame.transform.rotate(self.image, current_angle)
        self.rect = self.image.get_rect()

    def load_car_image(self, direction, vehicle_name, scale):
        self.image, self.rect = load_image(vehicle_name + '.png', -1)

        # Scale original image
        new_width = int(self.rect.width * scale[0])
        new_height = int(self.rect.height * scale[1])
        self.image = pygame.transform.scale(self.image, (new_width, new_height))

        # Rotate image according to direction
        rotation_angle = get_rotation(direction)
        self.image = pygame.transform.rotate(self.image, rotation_angle)
        self.rect = self.image.get_rect()

    @staticmethod
    def direction_change(next_lane, direction):
        if next_lane and next_lane[1] != direction:
            return True
        return False


"""© 2022 The Trustees of Columbia University in the City of New York.
This work may be reproduced, distributed, and otherwise exploited for
academic non-commercial purposes only, provided that it cites the original work:

    Stefan J. Hofmeister, Michael Hahn, and Daniel Wolf Savin, "Deriving instrumental point spread functions from partially occulted images,"
    Journal of the Optical Society of America A 39, 2153-2168 (2022), doi: 10.1364/JOSAA.471477.

To obtain a license to use this work for commercial purposes, please contact
Columbia Technology Ventures at techventures@columbia.edu <mailto:techventures@columbia.edu>.
"""

import numpy as np
import glob
import os
from inout import read_image, save_image
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.colors import Normalize, LogNorm

#This is the top level routine for identifying the occulted pixels
def find_occulted_pixels(config):
    folder_run = config['general']['folder_run']
    method     = config['occultation_mask']['method']
    if 'add_distance' in config['occultation_mask']: add_distance = config['occultation_mask']['add_distance']
    else: add_distance = 0

    #if occultation masks have been predefined
    if method == 'predefined': files = glob.glob(folder_run + '/occultation_mask/*.npz')
    else:                      files = glob.glob(folder_run + '/deconvolved_image/*.npz')

    for file in files:
        #here, you can also define your own methods for finding the occulted pixels
        if method == 'predefined':
            #if the occultation mask has been provided by the user
            occultation_mask = convert_toimage(file, dtype = np.int8, save = False)
            img = read_image(folder_run + '/deconvolved_image/' + os.path.splitext(os.path.basename(file))[0] + '.npz')

        if method == 'threshold':
            #derive the occultation masks by an adaptive threshold technique
            img = read_image(file, dtype = np.float16)
            thr        = config['occultation_mask']['threshold']
            use_median = config['occultation_mask']['threshold_usemedian']
            occultation_mask = find_occulted_pixels_bythr(img, thr, use_median)

        if add_distance > 0:
            kernel_size = 2 * np.floor(add_distance).astype(np.int) + 1
            kx, ky = np.meshgrid(np.arange(kernel_size) - kernel_size//2, np.arange(kernel_size) - kernel_size//2)
            kr = kx**2 + ky**2
            kernel = np.zeros((kernel_size, kernel_size))
            kernel[kr <= add_distance**2] = 1
            mask_ignore = (occultation_mask == -1)
            occultation_mask = np.logical_not(occultation_mask)
            occultation_mask = ndimage.convolve(occultation_mask.astype(np.int8), kernel.astype(np.int8), mode = 'nearest')
            occultation_mask = np.logical_not(occultation_mask).astype(np.int8)
            occultation_mask[mask_ignore] = -1

        #plot the occultation mask, one time solely the occultation mask and one time overlayed to the image
        filename_figure = os.path.splitext(file)[0] + '.jpg'
        fig, ax = plt.subplots(1, 2, figsize = (12, 5))
        ax1 = ax[0]
        divider = make_axes_locatable(ax1)
        cax1 = divider.append_axes('right', size='5%', pad=0.05)
        im1 = ax1.imshow(occultation_mask, norm = Normalize(vmin = -1, vmax = 1, clip = True), interpolation = 'nearest', cmap = 'viridis')
        fig.colorbar(im1, cax=cax1, orientation='vertical', ticks=[-1, 0, 1])
        ax2 = ax[1]
        divider = make_axes_locatable(ax2)
        cax2 = divider.append_axes('right', size='5%', pad=0.05)
        img_occ_marked = np.copy(img)
        img_occ_marked[occultation_mask == 1] = 10000
        im2 = ax2.imshow(img_occ_marked,  norm=LogNorm(vmin=1, vmax=10000, clip = True), interpolation = 'nearest', cmap = 'viridis')
        fig.colorbar(im2, cax=cax2, orientation='vertical')
        plt.tight_layout()
        plt.savefig(filename_figure, dpi = 600)
        plt.close(fig)
        #finally, save the occultation mask
        save_image(occultation_mask, folder_run + '/occultation_mask/' + os.path.basename(file), plot = False, dtype = np.int8, keys = 'img')

#In this section, you can put your own algorithms to identify occulted pixels. The function should use the (psf deconvolved) image "img" as input, and return a numpy array with a zero background and the pixels identified as occulted set to one.

def find_occulted_pixels_bythr(img, thr, use_median = True):
    #define if using the median or mean of the illuminated portion of the image as references
    if use_median: avg_function = np.median
    else: avg_function = np.mean

    #define a mask containing the occulted pixels
    occulted_pixels = np.zeros(img.shape)

    #derive the mean/median of the image and set the occulted pixels as all pixels smaller than threshold * mean/median. Rederive the mean/median only from the not-occulted pixels, find the occulted pixels, and iterate until the result converges.
    img_mean_last = 0.
    for i in range(100): #use 100 as the max number of iterations. Usually, <10 iterations are sufficient for convergence
        img_mean = avg_function(img[occulted_pixels == 0])
        occulted_pixels = img < (img_mean * thr)
        if img_mean == img_mean_last:
            break
        else:
            img_mean_last = img_mean
    return np.array(occulted_pixels)


'''
    Patricio Tena Zozaya A01027293
    Francisco Acuña Franco A01027294

    The following program evaluates a given string in and NDFA-lambda automata given by a text file and returns if the string
    is accepted or rejected.
    Input should be as follows: bba, abb, bcb, abzca

    *Notes:
    - The string is not separated by commas
    - At the beginig of the program, all *.txt files will be displayed and you'll have to select the file to use by the index of it
    - more info about the versions of the program at: https://github.com/tenapato/NDFALambda

'''

from os import listdir
from os.path import join, isfile
import glob
# Automata class for saving the information extacted from the text file
class Automata:
    states = []
    symbols = []
    initialState = ""
    finalState = []
    transitionTable = []

# Method for parsing the given text file
def buildAutomata(file):
    """
    Method for parsing the given text file
    """

    with open(file) as f:
            lines = f.readlines();

    A1 = Automata()

    count = 0
    for line in lines:
        count += 1

    #separating each state and adding it to an array
    states = lines[0].split(",")
    states = ','.join(states).strip()
    states = states.split(",")

    A1.states = states

    A1.states = states

    #Separate alphabet symbols
    symbols = lines[1].split(",")
    symbols = ','.join(symbols).strip()
    symbols = symbols.split(",")
    A1.symbols = symbols

    #Assign inital state
    initialState = lines[2].split(",")
    initialState = ''.join(initialState).strip()
    initialState = initialState.split(",")
    A1.initialState =  initialState

    #Assign final state
    finalState = lines[3].split(",")
    finalState = ','.join(finalState).strip()
    finalState = finalState.split(",")

    A1.finalState = finalState;

    #Create the transition
    transitionTable = []

    for j in range(count):
        #print(j)
        if j > 3:
            transitionTable += lines[j].split('\n')

    while("" in transitionTable):
        transitionTable.remove("")

    sizeOfTT = len(transitionTable) #Save the size of the transition table to a variable
    A1.transitionTable = transitionTable

    return A1

# Method for creating the dictionaries of the automatas with any kind of symbols
def buildDictionary(Automata):
    """
    Method for creating the dictionaries of the automatas with any kind of symbols
    """
    p = str(Automata.states)
    # ---------- Create the automate dictionary ----------- #
    transitionMatrix = []
    comparar = []
    count = 0
    for i in Automata.transitionTable:
        var1, var2 = Automata.transitionTable[count].split("=>")
        nextState = var2.split(",")
        state, symbol = var1.split(",")
        transitionMatrix += [[state, symbol, nextState]]
        comparar += [state]
        count+=1

    test = []

    print("Symbols"  + str(Automata.symbols))

    for i in range(len(transitionMatrix)):
        #print("TM: " + str(transitionMatrix[i][1]) + " Symbols: " + str(j))
        if transitionMatrix[i][1]  == "lambda":
            test += [{"lambda": transitionMatrix[i][2]}]
        elif transitionMatrix[i][1] in Automata.symbols:
            test += [{transitionMatrix[i][1]: transitionMatrix[i][2]}]
            #print(transitionMatrix[i][1])

    zip_it = zip(comparar, test)

    dictAutomata = dict(zip_it)

    #print(dictAutomata)
    repetidos = []

    repetidos = [x for n, x in enumerate(comparar) if x in comparar[:n]]  #find any state that has more than one transition and add the to a string
    # Compares if any string that is al ready in th dictionary has more than 1 returning state, if so, it adds the missing states to the dictionary
    for r in repetidos:
        for rep in range(len(transitionMatrix)):
            if r == transitionMatrix[rep][0]:
                dictAutomata[r][transitionMatrix[rep][1]] = transitionMatrix[rep][2]

    return dictAutomata

def lambdaClosure(states):
    """
    Method that recives a set of states, applies lambda closure, and returns a set of states

    args:
        states([String]): Check lambda closure four each recieved state

    return:
        list of lambda closure for each states
    """

    returnStates = []
    if states is not None:
        for state in states:
            if dictAutomata.get(state, {}).get("lambda"):
                returnStates += dictAutomata.get(state, {}).get("lambda")
            if state not in returnStates:
                returnStates.append(state)
        print("(LC) Lambda closure of: " + str(states) + " returns: " + str(returnStates))

    return returnStates

def transitionFunction(state, char):
    """
    Method that recieves a state, and a char, applies the transition function and returns a state

    args:
        state(string): State used as a key value in the automata dictionary
        char(string): Letter of the given string used as key value in the automata dictionary

    return:
        the state of applying the transition fucntion as a string
    """

    temp = dictAutomata.get(state, {}).get(char)
    if temp:
        print("(TF) State: " + str(state) + " with char "+ "'"+ str(char) +"'"+ " returns: " + str(dictAutomata.get(state, {}).get(char)))
        #temp2 = dictAutomata.get(state, {}).get(char)
        return (dictAutomata.get(state, {}).get(char))

def extendedTransitionFunction(state, string): #
    """
    Recursive function that receives a state and retrurns a set of strings

    args:
        state(string): Initial state used as a key value for the transition function
        string(string): String to validate in the given automata

    return:
        A set of states
    """
    if len(string) == 0:  # Base case
        res = lambdaClosure(state)
        return res
    else:
        # Cut string
        print("String: " + str(string))
        temp = string[-1]
        string.pop(len(string)-1)
        print("String after cut: " + str(string))
        var = extendedTransitionFunction(state, string)

        res = []
        if var is not None:
            for v in var:
                var2 = transitionFunction(v, temp)
                res += lambdaClosure(var2)

        return res

def help():

    while True:
        print("Enter the index of the function you want know more about:")
        print("0) Lambda Closure")
        print("1) Transition Function")
        print("2) Extended Transition Function")
        print("3) Exit\n")
        index = int(input("Index: "))

        if(index) == 0:
            print(lambdaClosure.__doc__)
        if(index) == 1:
            print(transitionFunction.__doc__)
        if(index) == 2:
            print(extendedTransitionFunction.__doc__)
        if(index) == 3:
            return False

if __name__ == "__main__":

    op = input("Would you like help? (y/n) ")

    if op == "y":
        help()

    print("Select file to use (*.txt): " )
    files = glob.glob("./automataFiles/*.txt")  # Fetches all .txt files from the local directory
    i = 1

    #print("0) Help")

    for f in files:  # Display each txt file as a menu
        print(str(i) + ") " + str(f[16:]))
        i+=1

    selectedFile = int(input("Index of file: "))

    Automata = buildAutomata(files[selectedFile-1]) #Method that receives the name of the file to use and returns an Automata class

    dictAutomata = buildDictionary(Automata) #Method that receives an Automata class and turns it into a dictionary of dictionaries

    print("Dictionary" + str(dictAutomata))
    string = input("Enter the string to validate: ")
    stringToSend = []
    for s in string:
        stringToSend.append(s)

    string2 = []
    for s in string:
        string2.append(s)

    ans = extendedTransitionFunction(Automata.initialState, stringToSend) # Calling the Recursive Extended Transition Function

    print("Final returning states: " + str(ans))
    if ans is not None:
        if any (x in ans for x in Automata.finalState):
                print("The string "+ str(string2) +" is accepted")

        else:
            print("The string "+ str(string2) +" is rejected")


# Birthday Chocolate

n = int(input())

s = list(map(int, input().split(" ")))

d, m = map(int, input().split(" "))

def birthdayChocolate(m, d):
    ss = []
    count = 0
    for i in range(len(s)):
        if m > len(s):
            break
        else:
            ss.append(s[i: m])
            m += 1
    for i in ss:
        if sum(i) == d:
            count += 1
        else:
            continue
    return count

print(birthdayChocolate(2, 3))


#import psycopg2
from daos.user import UserDAO

class PostDAO:
    def __init__(self):
    #An image_id = -1 means there's no image in the message
        P1 = [1, 'Dudas, inquietudes, temores, sin sabores', '08/17/2018', 0, 4, 0, 4, 0, 2, 3]
        P2 = [2, 'Manuel, por favor, danos la A', '02/25/2019', 1, 3,  4, 3, 1, 2, 0]
        P3 = [3, 'Viva Puerto Rico Libre', '01/22/2019', 2, 2, 2, 2, 2, 0, 1]
        P4 = [4, 'Pero con ciudadania americana', '01/22/2019', 3,  2, 3, 1, 3, 4, 6]
        P5 = [5, 'Ya que son unas bestias de icom 5016', '02/12/2019', 4, 0, 4, 0, 3, 2, 6]

        self.data = []
        self.data.append(P1)
        self.data.append(P2)
        self.data.append(P3)
        self.data.append(P4)
        self.data.append(P5)

    def getAllPosts(self):
        return self.data

    def getPostById(self, post_id):
        for p in self.data:
            if int(post_id) == p[0]:
                return p
        return None

    def getPostContent(self, param1):
        result = []
        for p in self.data:
            if param1 == p[1]:
                result.append(p)
        return result

    def getPostDate(self, param2):
        result = []
        for p in self.data:
            if param2 == p[2]:
                result.append(p)
        return result

    def getPostUser(self, param3):
        result = []
        for p in self.data:
            if int(param3) == p[3]:
                result.append(p)
        return result

    def getPostConvo(self, param4):
        result = []
        for p in self.data:
            if int(param4) == p[4]:
                result.append(p)
        return result

    def getPostHashtag(self, param5):
        result = []
        for p in self.data:
            if int(param5) == p[5]:
                result.append(p)
        return result

    def getPostReactions(self, param6):
        result = []
        for p in self.data:
            if int(param6) == p[6]:
                result.append(p)
        return result

    def getPostReplies(self, param7):
        result = []
        for p in self.data:
            if int(param7) == p[7]:
                result.append(p)
        return result

    def getPostReactionAmount(self, param8):
        result = []
        for p in self.data:
            if int(param8) == p[8]:
                result.append(p)
        return result

    def getPostRepliesAmount(self, param9):
        result = []
        for p in self.data:
            if int(param9) == p[9]:
                result.append(p)
        return result


"""Entrypoint for the Tractive REST API."""

from .api import API
from .channel import Channel
from .trackable_object import TrackableObject
from .tracker import Tracker

class Tractive:
    def __init__(self, *args, **kwargs):
        """Initialize the client."""
        self._api = API(*args, **kwargs)

    async def authenticate(self):
        return await self._api.authenticate()

    async def trackers(self):
        trackers = await self._api.request(f"user/{await self._api.user_id()}/trackers")
        return [Tracker(self._api, t) for t in trackers]

    def tracker(self, tracker_id):
        return Tracker(self._api, {"_id": tracker_id, "_type": "tracker"})

    async def trackable_objects(self):
        objects = await self._api.request(f"user/{await self._api.user_id()}/trackable_objects")
        return [TrackableObject(self._api, t) for t in objects]

    async def events(self):
        async for event in Channel(self._api).listen():
            yield event

    async def close(self):
        """Close open client session."""
        await self._api.close()

    async def __aenter__(self):
        """Async enter."""
        return self

    async def __aexit__(self, *exc_info):
        """Async exit."""
        await self.close()


def solution(dataSource, tags):
    answer = []
    Result = []

    for Doc,*Tag in dataSource:
        cnt=0
        for t in tags:
            if t in Tag:cnt+=1
        if cnt:answer.append((Doc,cnt))
    answer.sort(key=lambda x:x[1],reverse=True)

    rCnt=0
    for Doc,cnt in answer:
        if rCnt==10:break
        Result.append(Doc)
        rCnt+=1

    return Result

solution([
    ["doc1", "t1", "t2", "t3"],
    ["doc2", "t0", "t2", "t3"],
    ["doc3", "t1", "t6", "t7"],
    ["doc4", "t1", "t2", "t4"],
    ["doc5", "t6", "t100", "t8"]
],
["t1", "t2", "t3"])
print(ord('1'))
print(ord('4'))


from random import randint

def check_random_guess(func):
    def wraper(answer, attempts):
        if not answer in range(1, 100):
            answer = randint(1, 100)
        if not attempts in range(1, 10):
            attempts = randint(1, 10)
        func(answer, attempts)
    return wraper

@check_random_guess
def guess(answer, attempts):
    for _ in range(attempts):
        data = int(input('Введите число: '))
        if data == answer:
            print('Число угадано!')
            return
        elif data < answer:
            print('Больше!')
        else:
            print('Меньше!')
    print('Вы проиграли!')

if __name__ == '__main__':
    guess(300, 50)


from Call import Call
from Simulator import Simulator
from Calls import Calls
from Elevator import Elevator
from Building import Building
import sys
import json
import csv
import numpy as np

#
def init_elev_list():
    elev_l = []
    # initialize elevator list
    for current in elev_dict:
        e = Elevator(int(current['_id']), float(current['_speed']), int(current['_minFloor']),
                     int(current['_maxFloor']), float(current['_closeTime']), float(current['_openTime']),
                     float(current['_startTime']), float(current['_stopTime']))
        elev_l.append(e)
    return elev_l

if __name__ == "__main__":
    run = True
    args = sys.argv
    if len(args) == 3 or run:
        b_name = args[0]
        c_name = args[1]
        out_name = args[2]

        # Building.JSON
        b_string = open(b_name, )
        b_data = json.load(b_string)  # get data from json
        elev_dict = b_data['_elevators']  # convert elev dict to an elev list
        elev_list = init_elev_list()
        b = Building(b_data['_minFloor'], b_data['_maxFloor'], elev_list)  # init building

        # Calls.CSV
        with open(c_name, newline='') as f:
            reader = csv.reader(f)
            calls_data = list(reader)
        # get list of calls from CSV
        calls_list = []
        for i in range(len(calls_data)):
            # define each new call (start time, src, destination)
            c = Call(float(calls_data[i][1]), int(calls_data[i][2]), int(calls_data[i][3]))
            calls_list.append(c)

        # let end time = time the last call received *2
        last = calls_list.pop()
        end_time = last.time_called * 2
        calls_list.append(last)

        # initialize simulator and run
        sim = Simulator(building=b, elevators=elev_list, calls=calls_list, end_time=end_time)
        sim.run()
        # updated list of calls

        # # get output.CSV
        # with open('out.csv', 'w', encoding='UTF8', newline='') as csvfile:
        #     writer = csv.writer(csvfile)
        #     writer.writerow(sim.calls)

        np.savetxt('out.csv', [p for p in zip(sim.calls)], delimiter=',', fmt='%r')


### 052830 -- doing PCA on temporal neural patterns
### can I think be analogized to a PSTH (as the first component)
### both to examine the PCs, and to see how many are needed

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

from sklearn.decomposition import PCA
from analysis import FIG_DIR
from analysis.data_utils import get_neural_data, spike_counts, \
        trial_average

# set up data -- a few choices here
DATASET = 'tang' # want lots of trials for the trial-averaged part
CORR_THRESHOLD = 0.8 # doesn't hurt to be selective -- want real neurons
SORT = 'batch' # still some concerns about the Smith sort
WINDOW_SIZE = 20
START = 500
STOP = 1100 # why not get the response to the image disappearing?
num_bins = len(range(START, STOP, WINDOW_SIZE))

data = get_neural_data(DATASET, CORR_THRESHOLD, sort=SORT)
# will analyze both trial-averaged and trial-to-trial dynamics
# could be interesting if they're different (?)
avg_data = trial_average(data)

# think the PCA analysis means smoothing isn't really necessary
# since we have lots of data points
data = [spike_counts(data, start, start+WINDOW_SIZE) for
        start in range(START, STOP, WINDOW_SIZE)]
avg_data = [spike_counts(avg_data, start, start+WINDOW_SIZE) for
        start in range(START, STOP, WINDOW_SIZE)]

# at this point
# data is a T-lengh list of C-lenth lists of T_c x N tensors
# avg_data is a T-length list of CxN tensors
# want to convert them to (whatever) x T
data = np.array([np.concatenate(time).flatten() for time in data]).transpose(1, 0)
avg_data = np.array([time.flatten() for time in avg_data]).transpose(1, 0)

# now can do PCA on each of these
pca = PCA().fit(data)
avg_pca = PCA().fit(avg_data)

pca_ninety = np.argmax(np.cumsum(pca.explained_variance_ratio_) > 0.9)
avg_pca_ninety = np.argmax(np.cumsum(avg_pca.explained_variance_ratio_) > 0.9)

print(f'{pca_ninety} of {num_bins} PCs are needed to explain 90% of trial PSTH variance')
print(f'{avg_pca_ninety} of {num_bins} PCs are need to explain 90% of average PSTH variance')

# more important is looking at the PCs themselves -- interpretable as PSTHs
# (rather components that form PSTHs, but the same graphically)
# plot out the important ones

for i in range(pca_ninety+1):
    if i == 0:
        this_pc = pca.mean_ * (1000 / WINDOW_SIZE)
        ratio = 0
    else:
        this_pc = pca.components_[i-1] * (1000 / WINDOW_SIZE) # convert to Hz
        ratio = np.round(pca.explained_variance_ratio_[i-1], 2) * 100

    plt.figure()
    plt.plot(this_pc, color='black', linewidth=3)
    plt.xlabel(f'{WINDOW_SIZE}ms time bin')
    plt.ylabel('response change from mean (Hz)')
    plt.title(f'PC {i} of single-trial PSTHs, explaining {ratio}% var')
    plt.savefig(f'{FIG_DIR}trial_PSTH_pc{i:02}.png')

for i in range(avg_pca_ninety):
    if i == 0:
        this_pc = avg_pca.mean_ * (1000 / WINDOW_SIZE)
        ratio = 0
    else:
        this_pc = avg_pca.components_[i-1] * (1000 / WINDOW_SIZE) # convert to Hz
        ratio = np.round(avg_pca.explained_variance_ratio_[i-1], 2) * 100

    plt.figure()
    plt.plot(this_pc, color='black', linewidth=3)
    plt.xlabel(f'{WINDOW_SIZE}ms time bin')
    plt.ylabel('response change from mean (Hz)')
    plt.title(f'PC {i} of trial-averaged PSTHs, explaining {ratio}% var')
    plt.savefig(f'{FIG_DIR}avg_PSTH_pc{i:02}.png')


# -*- coding: utf-8 -*-
from setuptools.command import build_ext
from distutils.unixccompiler import UnixCCompiler

__author__ = 'Jon Nappi'
__all__ = ['GolangBuildExt', 'GolangCompiler']

class GolangBuildExt(build_ext.build_ext):
    """Custom extension builder that sets builds extensions using the
    :class:`GolangCompiler` as the compiler class
    """

    def initialize_options(self):
        super(GolangBuildExt, self).initialize_options()
        self.compiler = GolangCompiler

class GolangCompiler(UnixCCompiler):
    """A Custom Compiler class type detailing how to use gccgo to compile go
    code into a C binary that Python can consume
    """

    compiler_type = 'go'

    # These are used by CCompiler in two places: the constructor sets
    # instance attributes 'preprocessor', 'compiler', etc. from them, and
    # 'set_executable()' allows any of these to be set.  The defaults here
    # are pretty generic; they will probably have to be set by an outsider
    # (eg. using information discovered by the sysconfig about building
    # Python extensions).
    executables = {
        'preprocessor': None,
        'compiler': ['gccgo'],
        'compiler_so': ['gccgo'],
        'compiler_cxx': None,
        'linker_so': ['gccgo'],
        'linker_exe': None,
        'archiver': ['ar', '-cr'],
        'ranlib': None,
    }

    # `language_map` is used to detect a source file or Extension target
    # language, checking source filenames. language_order is used to detect
    # the language precedence, when deciding what language to use when mixing
    # source types. For example, if some extension has two files with ".c"
    # extension, and one with ".cpp", it is still linked as c++. However, given
    # that this Compiler is only concerned with compiling .go files we don't
    # need to worry about compilation precendence
    language_map = {'.go': 'go'}
    language_order = ['go']
    src_extensions = ['.go']

    def __init__(self, verbose=0, dry_run=0, force=0):
        """Custom compiler init override implicitly sets the required base
        gccgo include directories
        """
        super(GolangCompiler, self).__init__(verbose, dry_run, force)
        self.include_dirs = ['/usr/lib/gccgo', '/usr/local/lib/gccgo']

    def library_dir_option(self, dir):
        """Return the compiler option to add 'dir' to the list of libraries
        linked into the shared library or executable.
        """
        return ''.join(['-L', dir])

    def library_option(self, lib):
        """Return the compiler option to add 'dir' to the list of libraries
        linked into the shared library or executable.
        """
        return ''.join(['-l', dir])


# python3
import random
import math

def read_input():
    return (input().rstrip(), input().rstrip())

# Try to update this using list comprehension
# the 5 lines in this function can be converted to one
# 5 ^2 = 7 in python
# math.pow(5,2) = 25
# 5 **2 = 25 as well

def polyHash(pattern, p,x):
    return sum([ord(pattern[i]) * math.pow(x,i) for i in range(len(pattern))]) % p

# def polyHash(pattern, p, x):
#     hash = 0
#     for i in range (0, len(pattern)):
#         #used math.pow instead of ^ operator
#         # or just using x ** i will work
#         # not x^i
#         hash = hash + (ord(pattern[i]) * math.pow(x,i))

#     hash = hash % p
#     return hash

def precomputeHashes(text,lenPat,p,x):

        # I went from front to back and not from back to front
        # technically these both are the same
        # I just learnt it this way :xd

        H = [0]*(len(text) - lenPat + 1 )
        S = text[0: lenPat]

        H[0] = polyHash(S,p,x)
        for i in range(1, len(text) - lenPat+1):
            H[i] = ((H[i-1] - (ord(text[i-1])*math.pow(x,lenPat-1)))*x + ord(text[i+2]))
            print(H[i])

        return H

def print_occurrences(output):

    string = ""
    for i in output:
        string += str(i) + " "
    print(string)

def get_occurrences(pattern, text):
    p = 1000007 #large prime number
    x = 15 #random.randint(1, p-1)

    positions = []

    #hash the pattern
    pHash = polyHash(pattern, p, x)
    print("pHash =", pHash)

    #implement recurrence equation
    H = precomputeHashes(text,len(pattern),p,x)
    print("H =",H)

    for i in range(len(text) - len(pattern) + 1): #+1 is necessary
        #print ("i =",i)

        #check if pattern hash matches text hash
        if pHash == H[i]:
            if text[i:i+len(pattern)] == pattern:
                positions.append(i)
                #print(i,"added")

    return positions

if __name__ == '__main__':
    print_occurrences(get_occurrences(*read_input()))


import csv
import re
import pandas as pd
from konlpy.tag import Okt
from mbti_categories import *
from user import *

# 채팅의 한 줄을 이름과 메시지 형태로 파싱
def parsing(line):
    i = 1
    name = ""
    while line[i] != ']':
        name += line[i]
        i += 1
    i += 1
    while line[i] != ']':
        i += 1
    message = line[i+1:]
    return name, message

# 카카오톡 채팅방의 각 줄을 파싱하고, 태깅을 한 result를 반환
def parse_and_tag(file_path):
    okt = Okt()
    data = dict()
    # 첫번째 참가자 이름
    p1_name = ""
    # 두번째 참가자 이름
    p2_name = ""
    # use regular expression
    kakao_msg_pattern = "오\S [0-9]{1,2}:[0-9]{1,2}"
    # 채팅을 한줄씩 읽기
    for line in file_path:
        if re.search(kakao_msg_pattern, line):
            cur_name, message = parsing(line)

            # 대화 참여자 이름을 추출 및 저장 과정
            if p1_name == "":
                p1_name = cur_name
            elif p2_name == "" and p1_name != cur_name:
                p2_name = cur_name
            elif p1_name != cur_name and p2_name != cur_name:
                continue

            # 각 대화 참여자 별로 채팅 내역을 tag 후 저장
            pos = okt.pos(message)
            if cur_name in data:
                data[cur_name] += pos
            else:
                data[cur_name] = pos
        else:
            continue
    # 결과를 DataFrame 형태로 리턴
    result = pd.DataFrame([data])
    print(result)
    result.columns = [p1_name, p2_name]
    return result

# 채팅 내역을 비교, 두 유저의 mbti_score 를 update
def score_mbti(p1_user, p1_chat, p2_user, p2_chat):

    for axis in Mbti:
        p1_count, p2_count = score_each_axis(p1_chat, p2_chat, axis)
        if p1_count == 0 and p2_count == 0:
            print("채팅 표본이 너무 적습니다!:", p1_user, p2_user)
            exit(-1)
        else:
            ratio = p1_count / (p1_count + p2_count)
            p1_user.acc_score[axis] += ratio * 100
            p2_user.acc_score[axis] += (1 - ratio) * 100

# Mbti axis (E, N, F, J) 별로 해당 category 의 val 존재 counting
def score_each_axis(p1_chat, p2_chat, axis):
    p1_count, p2_count = 0, 0
    for val in morphemes[axis]:
        for tagged_word in p1_chat:
            if tagged_word == val:
                p1_count += 1
        for tagged_word in p2_chat:
            if tagged_word == val:
                p2_count += 1
    print("p1 유저", axis, "갯수:", p1_count)
    print("p2 유저", axis, "갯수:", p2_count)
    return p1_count, p2_count


from socket import *
from time import ctime

# ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

# ss = socket()
# # создание сокета сервера
# ss.bind()
# # привязка сокета сервера
# while True:
# # бесконечный цикл сервера
# 	cs = ss.recvfrom()/ss.sendto()
# 	# диалоговое окно (параметры приёма/передачи)
# ss.close()

# :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

# в этом сценарии создаётся сервер UDP, который принимает
# сообщения от клиентов и возвращает их с префиксом в виде
# времени

# ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

HOST = ''
# переменная песта, это указывает на то, что в методе bind()
# может использоваться любой доступный адрес
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

udp_ser_sock = socket(AF_INET, SOCK_DGRAM)
udp_ser_sock.bind(ADDR)

try:
	while True:
		print('UDP сервер запущен...')
		data, addr = udp_ser_sock.recvfrom(BUFSIZ)

		data = data.decode('utf-8')
		data = bytes('[{}], {}'.format(ctime(), data), 'utf-8')
		udp_ser_sock.sendto(data, addr)
		print('Сообщение полученно, обработано и отправленно для:', addr)

except KeyboardInterrupt:
	print('Сервер остановлен.')
	udp_ser_sock.close()


from typing import Optional

from omegaconf import DictConfig
from torch import Tensor

from eztorch.losses.ressl_loss import compute_ressl_loss, compute_ressl_mask
from eztorch.models.siamese.shuffle_momentum_queue_base import \
    ShuffleMomentumQueueBaseModel

LARGE_NUM = 1e9

class ReSSLModel(ShuffleMomentumQueueBaseModel):
    """ReSSL model.

    References:
        - ReSSL: https://proceedings.neurips.cc/paper/2021/file/14c4f36143b4b09cbc320d7c95a50ee7-Paper.pdf

    Args:
        trunk: Config tu build a trunk.
        optimizer: Config tu build optimizers and schedulers.
        projector: Config to build a project.
        predictor: Config to build a predictor.
        train_transform: Config to perform transformation on train input.
        val_transform: Config to perform transformation on val input.
        test_transform: Config to perform transformation on test input.
        normalize_outputs: If ``True``, normalize outputs.
        num_global_crops: Number of global crops which are the first elements of each batch.
        num_local_crops: Number of local crops which are the last elements of each batch.
        num_splits: Number of splits to apply to each crops.
        num_splits_per_combination: Number of splits used for combinations of features of each split.
        mutual_pass: If ``True``, perform one pass per branch per crop resolution.
        initial_momentum: Initial value for the momentum update.
        scheduler_momentum: Rule to update the momentum value.
        shuffle_bn: If ``True``, apply shuffle normalization trick from MoCo.
        num_devices: Number of devices used to train the model in each node.
        simulate_n_devices: Number of devices to simulate to apply shuffle trick. Requires ``shuffle_bn`` to be ``True`` and ``num_devices`` to be :math:`1`.
        queue: Config to build a queue.
        sym: If ``True``, symmetrised the loss.
        use_keys: If ``True``, add keys to negatives.
        temp: Temperature parameter to scale the online similarities.
        temp_m: Temperature parameter to scale the target similarities. Initial value if warmup applied.
    """

    def __init__(
        self,
        trunk: DictConfig,
        optimizer: DictConfig,
        projector: Optional[DictConfig] = None,
        predictor: Optional[DictConfig] = None,
        train_transform: Optional[DictConfig] = None,
        val_transform: Optional[DictConfig] = None,
        test_transform: Optional[DictConfig] = None,
        normalize_outputs: bool = True,
        num_global_crops: int = 2,
        num_local_crops: int = 0,
        num_splits: int = 0,
        num_splits_per_combination: int = 2,
        mutual_pass: bool = False,
        initial_momentum: int = 0.999,
        scheduler_momentum: str = "constant",
        shuffle_bn: bool = True,
        num_devices: int = 1,
        simulate_n_devices: int = 8,
        queue: Optional[DictConfig] = None,
        sym: bool = False,
        use_keys: bool = False,
        temp: float = 0.1,
        temp_m: float = 0.04,
        initial_temp_m: float = 0.04,
    ) -> None:
        super().__init__(
            trunk=trunk,
            optimizer=optimizer,
            projector=projector,
            predictor=predictor,
            train_transform=train_transform,
            val_transform=val_transform,
            test_transform=test_transform,
            normalize_outputs=normalize_outputs,
            num_global_crops=num_global_crops,
            num_local_crops=num_local_crops,
            num_splits=num_splits,
            num_splits_per_combination=num_splits_per_combination,
            mutual_pass=mutual_pass,
            initial_momentum=initial_momentum,
            scheduler_momentum=scheduler_momentum,
            shuffle_bn=shuffle_bn,
            num_devices=num_devices,
            simulate_n_devices=simulate_n_devices,
            queue=queue,
            sym=sym,
            use_keys=use_keys,
        )

        self.save_hyperparameters()

        self.temp = temp
        self.temp_m = temp_m

        self.initial_temp_m = initial_temp_m
        self.final_temp_m = temp_m

    def _precompute_mask(self) -> None:
        batch_size = self.trainer.datamodule.train_local_batch_size

        self.mask = compute_ressl_mask(
            batch_size=batch_size,
            num_negatives=self.queue.shape[1] if self.queue is not None else 0,
            use_keys=self.use_keys,
            rank=self.global_rank,
            world_size=self.trainer.world_size,
            device=self.device,
        )

    def on_fit_start(self) -> None:
        super().on_fit_start()

        self._precompute_mask()

    def compute_loss(
        self, q: Tensor, k: Tensor, k_global: Tensor, queue: Tensor | None
    ) -> Tensor:
        """Compute the ReSSL loss.

        Args:
            q: The representations of the queries.
            k: The representations of the keys.
            k_global: The global representations of the keys.
            queue: The queue of representations if not None.

        Returns:
            The loss.
        """
        k_loss = k_global if self.use_keys else k

        loss = compute_ressl_loss(
            q=q,
            k=k,
            k_global=k_loss,
            use_keys=self.use_keys,
            queue=queue,
            mask=self.mask,
            temp=self.temp,
            temp_m=self.temp_m,
            LARGE_NUM=LARGE_NUM,
        )

        return loss


# Given two strings s and t , write a function to determine if t is an anagram of s.

def is_valid_anagram(s, t):

    if len(s) != len(t):
        return False

    s_dict = {}
    t_dict = {}
    for i in range(len(s)):
        char = s[i]
        if char not in s_dict:
            s_dict[char] = 1
        else:
            s_dict[char] += 1

    for i in range(len(t)):
        char = t[i]
        if char not in t_dict:
            t_dict[char] = 1
        else:
            t_dict[char] += 1

    return s_dict == t_dict

if __name__ == '__main__':
    s = "anagram"
    t = "nagaram"

    s1 = 'car'
    t1 = 'rat'

    r = is_valid_anagram(s1, t1)
    print(r)


#CS project, A RANGE

import random

print("Welcome! Today we will be playing a slot machine game! You will both be given 5 dollar to start. The rules are as follows: Player one will go first, having the option to spin up to three times. Within each spin, you will be given a number 0-2. If you spin 3 of the same numbers, you lose all of your money and your turn ends. If the sum of the number is a multiple of 3, you will win half of your money. If the sum of the numbers is even, but not a multiple of 3, you will lose half of your money. Any other outcome you will win the amount of the sum of the number! Once player ones turn ends, player two, you will go! Whoever has the most money leftover wins! Good luck, let us begin!")
name1=input(str("Player 1, what is your name?"))
name2=input(str("Player 2, what is your name?"))
print("Ok,", name1, "and", name2, "lets begin!", name1, "you will go first!")

name1total=0
name1turns=0
name2total=0
name2turns=0

name1cash=5
name2cash=5

keepgoing1='yes'
keepgoing2="yes"

while name1turns<3 and name1cash>0 and keepgoing1=='yes':
    reel1=random.randint(0,2)
    reel2=random.randint(0,2)
    reel3=random.randint(0,2)
    total1=name1cash

    if (reel1==reel2==reel3):
        name1cash=name1cash*0
        print(reel1,reel2,reel3)
        print(name1, "it seems like you got three of the same numbers and lost! You now have, $",name1cash, "total and your turn is over. Now onto the second players turn! Goodluck!")
        name1turns=name1turns+1
    elif (reel1+reel2+reel3)%3==0:
        name1cash=name1cash+name1cash/2
        print(reel1,reel2,reel3)
        print(name1, "you won half of your money! You now have, $",name1cash, "total")
        name1turns=name1turns+1
        if name1turns<3 and name1cash>0 and keepgoing1=='yes':
            keepgoing1=input(str("do you want to go again? (yes/no)"))
    elif (reel1+reel2+reel3)%2==0 and (reel1+reel2+reel3)%3!=0:
        name1cash=name1cash/2
        print(reel1,reel2,reel3)
        print(name1, "you lost half of your money!,", "You now have, $",name1cash, "total")
        name1turns=name1turns+1
        if name1turns<3 and name1cash>0 and keepgoing1=='yes':
            keepgoing1=input(str("do you want to go again? (yes/no)"))
    else:
        name1cash=name1cash+(reel1+reel2+reel3)
        print(reel1,reel2,reel3)
        print(name1, "you won something!", "You now have, $",name1cash, "total")
        name1turns=name1turns+1
        if name1turns<3 and name1cash>0 and keepgoing1=='yes':
            keepgoing1=input(str("do you want to go again? (yes/no)"))

print("ok, now its your turn", name2)

while name2turns<3 and name2cash>0 and keepgoing2=="yes":
    reel1=random.randint(0,2)
    reel2=random.randint(0,2)
    reel3=random.randint(0,2)

    if (reel1==reel2==reel3):
        name2cash=name2cash*0
        print(reel1,reel2,reel3)
        print(name2, "it seems like you got three of the same numbers and lost! You now have, $",name2cash, "total and your turn is over!")
        name2turns=name2turns+1
    elif (reel1+reel2+reel3)%3==0:
        name2cash=name2cash+name2cash/2
        print(reel1,reel2,reel3)
        print(name2, "you won half! You now have, $",name2cash, "total")
        name2turns=name2turns+1
        if name2turns<3 and name2cash>0 and keepgoing2=='yes':
            keepgoing2=input(str("do you want to go again? (yes/no)"))
        elif keepgoing2=="no" and name2turns>3 and name2cash<0:
            print(name2, "your turn is over, you have won $",total2, " total!")
    elif (reel1+reel2+reel3)%2==0 and (reel1+reel2+reel3)%3!=0:
        name2cash=name2cash/2
        print(reel1,reel2,reel3)
        print(name2, "you lost half!,", "You now have, $",name2cash, "total")
        name2turns=name2turns+1
        if name2turns<3 and name2cash>0 and keepgoing2=='yes':
            keepgoing2=input(str("do you want to go again? (yes/no)"))
        elif keepgoing2=="no" and name2turns>3 and name2cash<0:
            print(name2, "your turn is over, you have won $",total2, " total!")
    else:
        name2cash=name2cash+(reel1+reel2+reel3)
        print(reel1,reel2,reel3)
        print(name2, "you won something!", "You now have, $",name2cash, "total")
        name2turns=name2turns+1
        if name2turns<3 and name2cash>0 and keepgoing2=='yes':
            keepgoing2=input(str("do you want to go again? (yes/no)"))
        elif keepgoing2=="no" and name2turns>3 and name2cash<0:
            print(name2, "your turn is over, you have won $",total2, " total!")

if name1cash==name2cash:
    print("Both players turns are over!", name1, "and", name2, "it looks like you both had the same amount of money in the end, its a tie! You both are taking", name1cash, "dollars home today! Enjoy whatever winnings you got!")
elif name1cash>name2cash:
    print("Both players turns are over! Congragulations", name1, "at the end of the game you won! You finished with", name1cash, "dollars total! Enjoy your winnings!")
else:
    print("Both players turns are over! Congragulations", name2+"!", "At the end of the game you won! You finished with", name2cash, "dollars total! Enjoy your winnings!")


from nsds_lab_to_nwb.components.stimulus.tokenizers.base_tokenizer import BaseTokenizer

class SingleTokenizer(BaseTokenizer):
    """
    Tokenize into a single stimulus trial, with possible baseline trials before/after.
    Suitable for DMR stimulus or baseline (no stimulus) blocks.
    """
    def __init__(self, block_name, stim_configs):
        BaseTokenizer.__init__(self, block_name, stim_configs)
        self.tokenizer_type = 'SingleTokenizer'

        # list of ('column_name', 'column_description')
        self.custom_trial_columns = [('sb', 'Stimulus (s) or baseline (b) period'),
                                     ('stim_name', 'Stimulus name')]

    def _validate_num_stim_onsets(self, stim_onsets):
        # in the continuous case, we only look for the *first* stim onset.
        num_onsets = len(stim_onsets)
        mismatch_msg = (
            f"{self.tokenizer_type}: "
            + "No stimulus onsets found "
            + f"in block {self.block_name}. "
            + "Expected at least one.")

        if num_onsets == 0:
            raise ValueError(mismatch_msg)

    def _tokenize(self, stim_vals, stim_onsets,
                  *, rec_end_time, audio_start_time=None, audio_end_time=None):
        stim_name = self.stim_configs['name']
        if stim_name == 'baseline':
            # add single trial
            trial_list = [dict(start_time=0.0,
                               stop_time=rec_end_time,
                               sb='b',
                               stim_name=stim_name)]
            return trial_list

        # -- in case of continuous stimulus, such as DMR --
        stim_start_time = stim_onsets[0]

        # bl_gap: gap between baseline and stimulus periods
        # (use the same value for both the pre- and post-stim baselines)
        bl_gap = self.stim_configs['baseline_start']
        if self.stim_configs.get('baseline_end', None) is not None:
            raise ValueError('baseline_end is assumed to have null/None value, '
                             'meaning that baselines extend to the ends of recoding')

        back_pad = self.stim_configs.get('back_pad', 0.0)   # for DMR stimulus

        trial_list = []

        # add pre-stimulus period to baseline
        stop_time = stim_start_time - bl_gap
        if stop_time > 0.0:
            trial_list.append(dict(start_time=0.0,
                                   stop_time=stop_time,
                                   sb='b',
                                   stim_name=''))

        # add single trial with continuous stimulus
        stim_stop_time = audio_end_time - back_pad
        trial_list.append(dict(start_time=stim_start_time,
                               stop_time=stim_stop_time,
                               sb='s',
                               stim_name=stim_name))

        # add post-stimulus period to baseline
        start_time = stim_stop_time + bl_gap
        if start_time < rec_end_time:
            trial_list.append(dict(start_time=start_time,
                                   stop_time=rec_end_time,
                                   sb='b',
                                   stim_name=''))
        return trial_list


def invertBendUI ():
  smartInvertBendVer = "0.1"
  c1 = [1.0, 1.0, 0.9]
  c2 = [1.0, 0.8, 1.0]

  if (mc.window ( "smartInvertBend", ex=True) == True) :
    mc.deleteUI ("smartInvertBend")
    mc.windowPref ("smartInvertBend", remove = True)

  mc.window ("smartInvertBend", t=("smartInvertBend ver "+smartInvertBendVer), w=230, h=200, s=False)

  mc.columnLayout (adjustableColumn=True, columnAttach=("both", 5), rowSpacing=5, columnWidth=200)
  aboutBtn = mc.button (w=110, align="center", bgc=(c2[0],c2[1],c2[2]), l=("About.."), c=("ibAboutUI") )
  mc.separator()
  createManipBtn = mc.button (w=110, align="center", l=("create Manipulator"), c=("ibManipulator") )
  mc.separator()
  cmds.checkBox( label='duplicate object', align='left' )
  cmds.checkBox( label='create bend deformer', align='left' )
  cmds.checkBox( label='connect mesh', align='left' )
  mc.separator()
  invertBendBtn = mc.button (w=110, align="center",bgc=(c1[0],c1[1],c1[2]), l=("invertBend"), c=("ibApply") )
  mc.showWindow ("smartInvertBend")
invertBendUI()


import tensorflow as tf
from dcgan_alt import discriminator, generator
from constants import BATCH_SIZE

def model_inputs(image_width, image_height, image_channels, z_dim, y_dim, batch_size = BATCH_SIZE):
    """
    Create the model inputs
    :param image_width: The input image width
    :param image_height: The input image height
    :param image_channels: The number of image channels
    :param z_dim: The dimension of Z
    :return: Tuple of (tensor of real input images, tensor of z data, learning rate)
    """
    real_input_images = tf.placeholder(tf.float32, [batch_size] + [image_width, image_height, image_channels], name='real_images')
    input_z = tf.placeholder(tf.float32, [None, z_dim], name='input_z')
    g_labels = tf.placeholder(tf.float32, [None, y_dim], name='g_labels')
    d_labels = tf.placeholder(tf.float32, [None, y_dim], name='d_labels')

    return real_input_images, input_z, d_labels, g_labels

def model_loss(input_real, input_z, input_d_y, input_g_y, smooth_factor=0.1, decaying_noise=None):
    """
    Get the loss for the discriminator and generator
    :param input_real: Images from the real dataset
    :param input_z: Z input
    :param out_channel_dim: The number of channels in the output image
    :return: A tuple of (discriminator loss, generator loss)
    """
    fake_samples = generator(input_z,input_g_y)
    tf.summary.image("G", fake_samples, max_outputs=2, collections=["g_imgs"])

    d_model_real, d_logits_real = discriminator(input_real, input_d_y, reuse=False, decaying_noise=decaying_noise)
    d_model_fake, d_logits_fake = discriminator(fake_samples, input_d_y, reuse=True, decaying_noise=decaying_noise)

    d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=tf.ones_like(d_model_real) * (1 - smooth_factor)))
    d_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.zeros_like(d_model_fake)))
    d_loss = d_loss_real + d_loss_fake

    g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.ones_like(d_model_fake)))

    return d_loss, g_loss

def model_opt(d_loss, g_loss, d_learning_rate, g_learning_rate, beta1):
    """
    Get optimization operations
    :param d_loss: Discriminator loss Tensor
    :param g_loss: Generator loss Tensor
    :param learning_rate: Learning Rate Placeholder
    :param beta1: The exponential decay rate for the 1st moment in the optimizer
    :return: A tuple of (discriminator training operation, generator training operation)
    """
    t_vars = tf.trainable_variables()
    d_vars = [var for var in t_vars if var.name.startswith('discriminator')]
    g_vars = [var for var in t_vars if var.name.startswith('generator')]

    # Optimize
    with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
        d_train_opt = tf.train.AdamOptimizer(d_learning_rate, beta1=beta1).minimize(d_loss, var_list=d_vars)
        g_train_opt = tf.train.AdamOptimizer(g_learning_rate, beta1=beta1).minimize(g_loss, var_list=g_vars)

    tf.summary.scalar("g_loss", g_loss, collections=["g_summ"])
    tf.summary.scalar("d_loss", d_loss, collections=["d_summ"])
    return d_train_opt, g_train_opt


import os
# import multiprocessing
import librosa
import soundfile as sf

# import soxbindings as sox

def preprocess(data, input_dir, dest_dir, target_sr=None, speed=None,
               overwrite=True):
    speed = speed or []
    speed.append(1)
    speed = list(set(speed))  # Make uniqe

    input_fname = os.path.join(input_dir,
                               data['input_relpath'],
                               data['input_fname'])

    # input_sr = sox.file_info.sample_rate(input_fname)
    f = open(input_fname, 'rb')
    file = sf.SoundFile(f)
    # metadata = soundfile.info(file, verbose=True)
    # file = audioread.rawread.RawAudioFile(input_fname)
    y, input_sr = librosa.load(file)
    target_sr = target_sr or input_sr

    os.makedirs(os.path.join(dest_dir, data['input_relpath']), exist_ok=True)

    output_dict = {}
    output_dict['transcript'] = data['transcript'].lower().strip()
    output_dict['files'] = []

    fname = os.path.splitext(data['input_fname'])[0]
    for s in speed:
        output_fname = fname + '{}.wav'.format('' if s==1 else '-{}'.format(s))
        output_fpath = os.path.join(dest_dir,
                                    data['input_relpath'],
                                    output_fname)

        # if not os.path.exists(output_fpath) or overwrite:
            # cbn = sox.Transformer().speed(factor=s).convert(target_sr)
            # cbn.build(input_fname, output_fpath)
        y_out = librosa.resample(y, orig_sr=input_sr, target_sr=target_sr)
        y_out = librosa.effects.time_stretch(y_out, rate=s)
        with open(output_fpath, 'wb') as wf:
            sf.write(wf, y_out, target_sr)

        # file_info = sox.file_info.info(output_fpath)
        # file_info = {
        #     "name": metadata.name,
        #     "samplerate": metadata.samplerate,
        #     "channels": metadata.channels,
        #     "frames": metadata.frames,
        #     "duration": metadata._duration_str,
        #     "format": f"{metadata.format_info} ({metadata.format})",
        #     "subtype": f"{metadata.subtype_info} ({metadata.subtype})",
        # }
        file_info = {
            "name": output_fname,
            "samplerate": target_sr,
            "channels": y_out.shape[0] if len(y_out.shape) > 1 else 1,
            "frames": y_out.shape[1] if len(y_out.shape) > 1 else y_out.shape[0],
            "duration": (y_out.shape[1] / target_sr) if len(y_out.shape) > 1 else (y_out.shape[0] / target_sr),
        }
        file_info['fname'] = os.path.join(os.path.basename(dest_dir),
                                          data['input_relpath'],
                                          output_fname)
        file_info['speed'] = s
        output_dict['files'].append(file_info)

        # if s == 1:
            # file_info = sox.file_info.info(output_fpath)
            # output_dict['original_duration'] = file_info['duration']
            # output_dict['original_num_samples'] = file_info['num_samples']

    f.close()

    return output_dict

# def parallel_preprocess(dataset, input_dir, dest_dir, target_sr, speed, overwrite, parallel):
#     with multiprocessing.Pool(parallel) as p:
#         func = functools.partial(preprocess,
#             input_dir=input_dir, dest_dir=dest_dir,
#             target_sr=target_sr, speed=speed, overwrite=overwrite)
#         dataset = list(tqdm(p.imap(func, dataset), total=len(dataset)))
#         return dataset


#!/usr/bin/python3
import sys

def main():
    args = sys.argv[1:]
    length = len(args)
    res = 0
    for arg in args:
        res += int(arg)
    print("{:d}".format(res))

if __name__ == "__main__":

    main()


import unittest
from linter import Linter
from lint_rule_final_classes import LintRuleFinalClasses

class TestCustomLinter(unittest.TestCase):

	def makeSUT(self):
		linter = Linter()
		linter.add_rule(LintRuleFinalClasses())
		return linter

	def test_linter(self):
		linter = self.makeSUT()
		warnings = linter.warnings_for_file("")
		self.assertEqual(len(warnings), 0, "Empty file should have 0 warnings")

	def test_non_final_class(self):
		linter = self.makeSUT()
		warnings = linter.warnings_for_file(
			""" let someGlobal = 5

        		class MyClass {
        			let property = 5
        		}
			"""
        	)

		self.assertEqual(len(warnings), 1)
		self.assertEqual(warnings[0].line, 2)
		self.assertEqual(warnings[0].message, "Classes should be final")

	def test_final_class(self):
		linter = self.makeSUT()
		warnings = linter.warnings_for_file(
			""" let someGlobal = 5

        		final class MyClass {
        			let property = 5
        		}
			"""
        	)

		self.assertEqual(len(warnings), 0)

	def test_class_protocol(self):
		linter = self.makeSUT()
		warnings = linter.warnings_for_file(
			""" let someGlobal = 5

        		protocol MyProtocol: class {
        			var property: { get }
        		}
			"""
        	)
		self.assertEqual(len(warnings), 0)

	def test_class_variable_var(self):
		linter = self.makeSUT()
		warnings = linter.warnings_for_file(
			"""
				class var someVariable: Int {
					return 5
				}
			"""
        	)
		self.assertEqual(len(warnings), 0)

	def test_class_variable_let(self):
		linter = self.makeSUT()
		warnings = linter.warnings_for_file(
			"""
				class let someVariable: Int = 5
			"""
        	)
		self.assertEqual(len(warnings), 0)

	def test_commented_out_class(self):
		linter = self.makeSUT()
		warnings = linter.warnings_for_file(
			"""
				//class MyClass {
        		//	let property = 5
        		//}
			"""
        	)
		self.assertEqual(len(warnings), 0)

	def test_class_in_string(self):
		linter = self.makeSUT()
		warnings = linter.warnings_for_file(
			"""
				print("This string contains the word class")
			"""
        	)
		self.assertEqual(len(warnings), 0)

	def test_class_non_final_attribute(self):
		linter = self.makeSUT()
		warnings = linter.warnings_for_file(
			"""
				// @NonFinal
				class MyClass {
        			let property = 5
        		}
			"""
        	)
		self.assertEqual(len(warnings), 0)

	def test_non_final_attribute_only_affects_first_class(self):
		linter = self.makeSUT()
		warnings = linter.warnings_for_file(
			"""
				// @NonFinal
				class MyClassOne {
        			let property = 5
        		}

        		class MyClassTwo {
        			let property = 5
        		}
			"""
        	)
		self.assertEqual(len(warnings), 1)
		self.assertEqual(warnings[0].line, 6)
		self.assertEqual(warnings[0].message, "Classes should be final")

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