import cv2
import numpy as np
import os

from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
import keras
from keras.models import Sequential, Model
from keras.layers import Dense, Activation, Input
import tensorflow as tf
from keras.utils import to_categorical
from keras.layers import Conv2D, MaxPool2D, Flatten

train_loc = "DataSet"
train_data = tf.keras.preprocessing.image.ImageDataGenerator(horizontal_flip=(True),rescale=(1/255.0),).flow_from_directory(train_loc,batch_size=25,subset=("training"),target_size=(128,128),shuffle=(False))
classes=list(train_data.class_indices.keys())

def detect_face(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = cv2.resize(img, (128, 128))
    return img
def print_progress(val, val_len, folder, bar_size=20):
    progr = "#"*round((val)*bar_size/val_len) + " "*round((val_len - (val))*bar_size/val_len)
    if val == 0:
        print("", end = "\n")
    else:
        print("[%s] (%d samples)\t label : %s \t\t" % (progr, val+1, folder), end="\r")

dataset_folder = "dataset/"

names = []
images = []
for folder in os.listdir(dataset_folder):
    files = os.listdir(os.path.join(dataset_folder, folder))[:250]
    if len(files) < 100 :
        continue
    for i, name in enumerate(files):
        if name.find(".jpg") > -1 :
            img = cv2.imread(os.path.join(dataset_folder + folder, name))
            img = detect_face(img) # detect face using mtcnn and crop to 100x100
            if img is not None :
                images.append(img)
                names.append(folder)

                print_progress(i, len(files), folder)
print("\nnumber of samples :", len(names))

def img_augmentation(img):
    h, w = img.shape
    center = (w // 2, h // 2)
    M_rot_5 = cv2.getRotationMatrix2D(center, 5, 1.0)
    M_rot_neg_5 = cv2.getRotationMatrix2D(center, -5, 1.0)
    M_rot_10 = cv2.getRotationMatrix2D(center, 10, 1.0)
    M_rot_neg_10 = cv2.getRotationMatrix2D(center, -10, 1.0)
    M_trans_3 = np.float32([[1, 0, 3], [0, 1, 0]])
    M_trans_neg_3 = np.float32([[1, 0, -3], [0, 1, 0]])
    M_trans_6 = np.float32([[1, 0, 6], [0, 1, 0]])
    M_trans_neg_6 = np.float32([[1, 0, -6], [0, 1, 0]])
    M_trans_y3 = np.float32([[1, 0, 0], [0, 1, 3]])
    M_trans_neg_y3 = np.float32([[1, 0, 0], [0, 1, -3]])
    M_trans_y6 = np.float32([[1, 0, 0], [0, 1, 6]])
    M_trans_neg_y6 = np.float32([[1, 0, 0], [0, 1, -6]])

    imgs = []
    imgs.append(cv2.warpAffine(img, M_rot_5, (w, h), borderValue=(255,255,255)))
    imgs.append(cv2.warpAffine(img, M_rot_neg_5, (w, h), borderValue=(255,255,255)))
    imgs.append(cv2.warpAffine(img, M_rot_10, (w, h), borderValue=(255,255,255)))
    imgs.append(cv2.warpAffine(img, M_rot_neg_10, (w, h), borderValue=(255,255,255)))
    imgs.append(cv2.warpAffine(img, M_trans_3, (w, h), borderValue=(255,255,255)))
    imgs.append(cv2.warpAffine(img, M_trans_neg_3, (w, h), borderValue=(255,255,255)))
    imgs.append(cv2.warpAffine(img, M_trans_6, (w, h), borderValue=(255,255,255)))
    imgs.append(cv2.warpAffine(img, M_trans_neg_6, (w, h), borderValue=(255,255,255)))
    imgs.append(cv2.warpAffine(img, M_trans_y3, (w, h), borderValue=(255,255,255)))
    imgs.append(cv2.warpAffine(img, M_trans_neg_y3, (w, h), borderValue=(255,255,255)))
    imgs.append(cv2.warpAffine(img, M_trans_y6, (w, h), borderValue=(255,255,255)))
    imgs.append(cv2.warpAffine(img, M_trans_neg_y6, (w, h), borderValue=(255,255,255)))
    imgs.append(cv2.add(img, 10))
    imgs.append(cv2.add(img, 30))
    imgs.append(cv2.add(img, -10))
    imgs.append(cv2.add(img, -30))
    imgs.append(cv2.add(img, 15))
    imgs.append(cv2.add(img, 45))
    imgs.append(cv2.add(img, -15))
    imgs.append(cv2.add(img, -45))

    return imgs
augmented_images = []
augmented_names = []
for i, img in enumerate(images):
    try :
        augmented_images.extend(img_augmentation(img))
        augmented_names.extend([names[i]] * 20)
    except :
        print(i)
print(len(augmented_images), len(augmented_names))
images.extend(augmented_images)
names.extend(augmented_names)
print(len(images), len(names))

unique, counts = np.unique(names, return_counts = True)

for item in zip(unique, counts):
    print(item)

n = 1000

def randc(labels, l):
    return np.random.choice(np.where(np.array(labels) == l)[0], n, replace=False)

mask = np.hstack([randc(names, l) for l in np.unique(names)])
names = [names[m] for m in mask]
images = [images[m] for m in mask]

print(len(names))

le = LabelEncoder()

le.fit(names)

labels = le.classes_

name_vec = le.transform(names)

categorical_name_vec = to_categorical(name_vec)

print("number of class :", len(labels))
print(labels)
print(name_vec)
print(categorical_name_vec)

x_train, x_test, y_train, y_test = train_test_split(np.array(images, dtype=np.float32),   # input data
                                                    np.array(categorical_name_vec),       # target/output data
                                                    test_size=0.15,
                                                    random_state=42)
print(x_train.shape, y_train.shape, x_test.shape,  y_test.shape)

x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], x_train.shape[2], 1)
x_test = x_test.reshape(x_test.shape[0], x_test.shape[1], x_test.shape[2], 1)
x_train.shape, x_test.shape

def cnn_model(input_shape):
    model = Sequential()

    model.add(Conv2D(64,
                    (3,3),
                    padding="valid",
                    activation="relu",
                    input_shape=input_shape))
    model.add(Conv2D(64,
                    (3,3),
                    padding="valid",
                    activation="relu",
                    input_shape=input_shape))

    model.add(MaxPool2D(pool_size=(2, 2)))

    model.add(Conv2D(128,
                    (3,3),
                    padding="valid",
                    activation="relu"))
    model.add(Conv2D(128,
                    (3,3),
                    padding="valid",
                    activation="relu"))
    model.add(MaxPool2D(pool_size=(2, 2)))

    model.add(Flatten())

    model.add(Dense(128, activation="relu"))
    model.add(Dense(64, activation="relu"))
    model.add(Dense(len(labels)))  # equal to number of classes
    model.add(Activation("softmax"))

    model.summary()

    model.compile(optimizer='adam',
                  loss='categorical_crossentropy',
                  metrics = ['accuracy'])

    return model

input_shape = x_train[0].shape

EPOCHS = 6
BATCH_SIZE = 32

model = cnn_model(input_shape)

history = model.fit(x_train,
                    y_train,
                    epochs=EPOCHS,
                    batch_size=BATCH_SIZE,
                    shuffle=True,
                    validation_split=0.25   # 15% of train dataset will be used as validation set
                    )
model.save("model-cnn-facerecognition.h5")

y_pred=model.predict(x_test)

print(classification_report(y_test.argmax(axis=1),
                            y_pred.argmax(axis=1),
                            target_names=labels))

from keras.models import load_model
def draw_ped(img, label, x0, y0, xt, yt, color=(255,127,0), text_color=(255,255,255)):

    (w, h), baseline = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
    cv2.rectangle(img,
                  (x0, y0 + baseline),
                  (max(xt, x0 + w), yt),
                  color,
                  2)
    cv2.rectangle(img,
                  (x0, y0 - h),
                  (x0 + w, y0 + baseline),
                  color,
                  -1)
    cv2.putText(img,
                label,
                (x0, y0),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.5,
                text_color,
                1,
                cv2.LINE_AA)
    return img

# --------- load Haar Cascade model -------------
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# --------- load Keras CNN model -------------
model = load_model("model-cnn-facerecognition.h5")
print("[INFO] finish load model...")

cap = cv2.VideoCapture(0)
while cap.isOpened() :
    ret, frame = cap.read()
    if ret:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.1, 5)
        for (x, y, w, h) in faces:

            face_img = gray[y:y+h, x:x+w]
            face_img = cv2.resize(face_img, (128, 128))
            face_img = face_img.reshape(1, 128, 128, 1)

            result = model.predict(face_img)
            idx = result.argmax(axis=1)
            confidence = result.max(axis=1)*100
            if confidence > 80:
                label_text = "%s (%.2f %%)" % (labels[idx], confidence)
            else :
                label_text = "N/A"
            frame = draw_ped(frame, label_text, x, y, x + w, y + h, color=(0,255,255), text_color=(50,50,50))

        cv2.imshow('Detect Face', frame)
    else :
        break
    if cv2.waitKey(10) == ord('q'):
        break

cv2.destroyAllWindows()
cap.release()

Raspberry pi (python)/face recognition/cnnModule.py


from urllib import request
from urllib import parse
from bs4 import BeautifulSoup
from urllib.request import urlopen

import time
import random
import json

class tencent(object):
	def __init__(self):
		self.switch = True
		self.page = 1
		self.url = "https://hr.tencent.com/"
		self.headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36"}
		self.counter = 1

	def pause(self):
		second = random.randint(1, 3)

		time.sleep(second)

	def write2json(self, list):
		print("Writing to file")

		print("\n")

		data = json.dumps(list, ensure_ascii=False)

		with open("tencent_jobs.json", "a") as f:
			f.write(data)

		print("Write complished")

		print("\n")

	def parseHtml(self, html):
		soup = BeautifulSoup(html, "lxml")

		list = soup.select("tr[class='even']")

		list = list + soup.select("tr[class='odd']")

		job_list = []

		for each in list:
			print("Process on job %d"%self.counter)

			print("\n")

			job = {}

			positionName = each.select("td a")[0].get_text()

			category = each.select("td")[1].get_text()

			number = each.select("td")[2].get_text()

			location = each.select("td")[3].get_text()

			publishDate = each.select("td")[4].get_text()

			link = self.url + each.select("td a")[0].attrs['href']

			job["positionName"] = positionName

			job["category"] = category

			job["number"] = number

			job["location"] = location

			job["publishDate"] = publishDate

			job["link"] = link

			job_list.append(job)

			print("Job %d was completed"%self.counter)

			self.counter += 1

			print("\n")

		self.write2json(job_list)

	def loadPage(self, page):
		self.pause()
		# https://hr.tencent.com/position.php?keywords=&start=30#a
		num = (page-1) * 10

		start = {"start" : str(num)}

		start = parse.urlencode(start)

		url = self.url + "position.php?keywords=&" + start + "#a"

		req = request.Request(url, headers=self.headers)

		html = urlopen(req).read().decode("utf-8")

		# print(html)
		# with open("tencent.html", "w") as f:
		# 	f.write(html)

		self.parseHtml(html)

	def go(self):
		input("Push the enter to crawl the jobs information")

		while self.switch:
			try:
				self.loadPage(self.page)
			except request.URLError as e:
				print(e.message)
				continue

			haha = input("Push the enter to crawl next page, or type quit to exit")

			print("\n")

			self.page += 1

			if haha == 'quit':
				self.switch = False

				print("%d jobs was crawled. Thanks for use, have a good day, bye!"%self.counter)

				break

if __name__ == "__main__":
	spider = tencent()
	spider.go()


from csv import writer

def save_to_csv(name: str, job: list) -> None:
    """ Создание csv файла """
    file = open(f'_{name}_.csv', mode='w', encoding='cp1251')
    csv_writer = writer(file)
    csv_writer.writerow(['компания', 'профессия', 'от', 'до', 'ссылка', 'тип',
                        'дата', 'график', 'счетчик', 'адрес'])
    csv_writer.writerows(job)


import math

# Add any extra import statements you may need here

# Add any helper functions you may need here

class Node:
    def __init__(self, v):
        self.value = v
        self.next: None

class Stack:
    def __init__(self):
        self.last = None

    def peek(self):
        return self.last

    def pop(self):
        node = self.last
        self.last = self.last.next
        return node

    def push(self, val):
        node = Node(val)
        node.next = self.last
        self.last = node

def isBalanced(s):
    if not s:
        return True
    stack = Stack()
    stack.push(s[0])
    closed = {')', ']', '}'}
    opened = {'(', '[', '{'}
    tups = {('(', ')'), ('[', ']'), ('{', '}')}
    for e in s[1:]:
        if e in opened:
            stack.push(e)
        elif (stack.peek().value, e) in tups:
            stack.pop()
        elif e in closed:
            return False
        else:
            stack.push(e)
    if stack.last is None:
        return True
    return False

# These are the tests we use to determine if the solution is correct.
# You can add your own at the bottom.

def printString(string):
    print('[\"', string, '\"]', sep='', end='')

test_case_number = 1

def check(expected, output):
    global test_case_number
    result = False
    if expected == output:
        result = True
    rightTick = '\u2713'
    wrongTick = '\u2717'
    if result:
        print(rightTick, 'Test #', test_case_number, sep='')
    else:
        print(wrongTick, 'Test #', test_case_number, ': Expected ', sep='', end='')
        printString(expected)
        print(' Your output: ', end='')
        printString(output)
        print()
    test_case_number += 1

if __name__ == "__main__":
    s1 = "{[(])}"
    expected_1 = False
    output_1 = isBalanced(s1)
    check(expected_1, output_1)

    s2 = "{{[[(())]]}}"
    expected_2 = True
    output_2 = isBalanced(s2)
    check(expected_2, output_2)

    s3 = "([{()}][])"
    expected_3 = True
    output_3 = isBalanced(s3)
    check(expected_3, output_3)

    # Add your own test cases here

META/META Stacks and Queues/META Stack Balance Brackets.py


from twisted.words.protocols import irc
from txircd.modbase import Command
from txircd.utils import VALID_NICKNAME, irc_lower

class NickCommand(Command):
    def onUse(self, user, data):
        if user.registered == 0:
            user.nick(data["nick"])
        else:
            if not user.nickname:
                user.registered -= 1
            user.nickname = str(data["nick"])
            if user.registered == 0:
                user.register()

    def processParams(self, user, params):
        if not params:
            user.sendMessage(irc.ERR_NONICKNAMEGIVEN, ":No nickname given")
            return {}
        if not params[0]:
            user.sendMessage(irc.ERR_ERRONEUSNICKNAME, "*", ":Erroneous nickname")
            return {}
        if not VALID_NICKNAME.match(params[0]):
            user.sendMessage(irc.ERR_ERRONEUSNICKNAME, params[0], ":Erroneous nickname")
            return {}
        if params[0] == user.nickname:
            return {}
        if params[0] in self.ircd.users and (not user.nickname or irc_lower(params[0]) != irc_lower(user.nickname)):
            user.sendMessage(irc.ERR_NICKNAMEINUSE, self.ircd.users[params[0]].nickname, ":Nickname is already in use")
            return {}
        return {
            "user": user,
            "nick": params[0]
        }

class Spawner(object):
    def __init__(self, ircd):
        self.ircd = ircd

    def spawn(self):
        return {
            "commands": {
                "NICK": NickCommand()
            }
        }


import os
import gym
import pytest
import numpy as np
from numpy import pi
from pathlib import Path
from gym_ignition.utils import logger
from gym_ignition import gympp_bindings as bindings

# Set verbosity
logger.set_level(gym.logger.DEBUG)

@pytest.fixture
def create_std_vector():
    python_list = [1.0, 2.0, 3.0]
    vector = bindings.Vector_d(python_list)
    return vector

@pytest.fixture
def create_space_box_md():
    md = bindings.SpaceMetadata()
    md.setType(bindings.SpaceType_Box)
    max_float = float(np.finfo(np.float32).max)
    md.setLowLimit([-2.5, -max_float, -24, -max_float])
    md.setHighLimit([2.5, max_float, 24, max_float])
    return md

@pytest.fixture
def create_space_discrete_md():
    md = bindings.SpaceMetadata()
    md.setType(bindings.SpaceType_Discrete)
    md.setDimensions([2])
    return md

def test_vectors():
    python_list = [1.0, 2.0, 3.0]
    vector = bindings.Vector_d(python_list)
    for i in range(0, vector.size()-1):
        assert python_list[i] == vector[i], "Vectors do not match"

def test_sample(create_std_vector):
    vector = create_std_vector
    sample = bindings.Sample(vector)

    for i in range(0, vector.size()-1):
        assert sample.getBuffer_d()[i] == vector[i], \
            "Sample object does not contain correct data"

    sample.getBuffer_d()[2] = 42
    assert sample.get_d(2).value() == 42, "Failed to insert data in the Sample object"
    assert sample.getBuffer_d()[2] == 42, "Failed to update data of a Sample object"

def test_range():
    gympp_range = bindings.Range(-5.0, 10.0)
    assert gympp_range.contains(0), "Range object failed to verify if it containes a value"
    assert gympp_range.contains(-5), "Range object failed to verify if it containes a value"
    assert gympp_range.contains(10), "Range object failed to verify if it containes a value"
    assert not gympp_range.contains(-6), "Range object failed to verify if it containes a value"
    assert not gympp_range.contains(10.1), "Range object failed to verify if it containes a value"

def test_discrete_space():
    discrete_space = bindings.Discrete(12)

    assert not discrete_space.contains(bindings.Sample([-1])), \
        "Discrete object failed to verify if a sample belongs to its space"
    assert not discrete_space.contains(bindings.Sample([13])), \
        "Discrete object failed to verify if a sample belongs to its space"

    for n in range(50):
        sample = discrete_space.sample()
        assert sample.getBuffer_i().size() == 1, \
            "Wrong size of the sample extracted from a discrete space"
        assert isinstance(sample.getBuffer_i()[0], int), \
            "Wrong data type of the sample extracted from a discrete space"
        assert discrete_space.contains(sample), \
            "Sampled data is not contained in the discrete space object that created it"

def test_box_space():
    size = 4
    box = bindings.Box(-1, 42, [size])

    # By default the data precision of python list is float. Force double.
    assert box.contains(bindings.Sample(bindings.Vector_d([0, pi, 12, 42]))), \
        "Box object failed to verify if a sample belongs to its space"
    assert not box.contains(bindings.Sample(bindings.Vector_d([0, pi, 12, 43]))), \
        "Box object failed to verify if a sample belongs to its space"
    assert not box.contains(bindings.Sample(bindings.Vector_d([0]))), \
        "Box object failed to verify if a sample belongs to its space"
    assert not box.contains(bindings.Sample(bindings.Vector_d([0, pi, 12, 43, 0]))), \
        "Box object failed to verify if a sample belongs to its space"

    for n in range(50):
        sample = box.sample()
        assert sample.getBuffer_d().size() == size, \
            "Wrong size of the sample extracted from a box space"
        assert isinstance(sample.getBuffer_d()[0], float), \
            "Wrong data type of the sample extracted from the box space"
        assert box.contains(sample), \
            "Sampled data is not contained in the box space object that created it"

def test_space_box_metadata(create_space_box_md):
    md = create_space_box_md
    assert md.isValid(), "The space is not valid"
    assert md.getType() == bindings.SpaceType_Box, "The space type is not correct"

def test_space_discrete_metadata(create_space_discrete_md):
    md = create_space_discrete_md
    assert md.isValid(), "The space is not valid"
    assert md.getType() == bindings.SpaceType_Discrete, "The space type is not correct"

def test_metadata():
    md = bindings.PluginMetadata()
    assert not md.isValid(), "The metadata should not be valid"

    environment_name = "EnvironmentName"
    md.setEnvironmentName(environment_name)
    assert md.getEnvironmentName() == environment_name, "Failed to store the " \
                                                        "environment name"
    library_name = "plugin_foo"
    md.setLibraryName(library_name)
    assert md.getLibraryName() == library_name, "Failed to store the library name"

    class_name = "foo::bar::GymppPlugin"
    md.setClassName(class_name)
    assert md.getClassName() == class_name, "Failed to store the class name"

    model_name = "RobotModel.sdf"
    md.setModelFileName(model_name)
    assert md.getModelFileName() == model_name, "Failed to store the model file name"

    world_name = "Environment.world"
    md.setWorldFileName(world_name)
    assert md.getWorldFileName() == world_name, "Failed to store the world file name"

    agent_rate = 1000
    md.setAgentRate(agent_rate)
    assert md.getAgentRate() == agent_rate, "Failed to store the agent rate"

    real_time_factor = 1E9
    max_physics_step_size = 0.001
    md.setPhysicsData(bindings.PhysicsData(real_time_factor, max_physics_step_size))
    physics_data = md.getPhysicsData()
    assert physics_data.rtf == real_time_factor, "Failed to store RTF"
    assert physics_data.maxStepSize == max_physics_step_size, "Failed to store the " \
                                                              "max physics step size"

def test_gymfactory():
    # Get the factory
    factory = bindings.GymFactory.Instance()

    # Register a plugin with empty metadata
    md = bindings.PluginMetadata()
    assert not factory.registerPlugin(md), "The empty plugin metadata should not be valid"

    # Get a not registered environment
    env = factory.make("foo")
    assert not env, "The environment should not be valid"

    # Check that the CartPole plugin exists
    assert "IGN_GAZEBO_SYSTEM_PLUGIN_PATH" in os.environ, \
        "Variable IGN_GAZEBO_SYSTEM_PLUGIN_PATH not set in the environment"
    directories = os.environ['IGN_GAZEBO_SYSTEM_PLUGIN_PATH'].split(os.pathsep)

    found = False
    for directory in directories:
        matching_plugins = list(Path(directory).glob("*CartPole*"))
        found = found or (len(matching_plugins) is not 0)
    assert found, "Failed to find CartPole plugin"

    # Create the metadata
    md = bindings.PluginMetadata()
    md.setEnvironmentName("CartPole")
    md.setLibraryName("CartPolePlugin")
    md.setClassName("gympp::plugins::CartPole")
    md.setWorldFileName("DefaultEmptyWorld.world")
    md.setModelFileName("CartPole/CartPole.sdf")
    md.setAgentRate(1000)
    md.setPhysicsData(bindings.PhysicsData(1.0, 0.001))
    action_space_md = bindings.SpaceMetadata()
    action_space_md.setType(bindings.SpaceType_Discrete)
    action_space_md.setDimensions([2])
    observation_space_md = bindings.SpaceMetadata()
    observation_space_md.setType(bindings.SpaceType_Box)
    max_float = float(np.finfo(np.float32).max)
    observation_space_md.setLowLimit([-2.5, -max_float, -24, -max_float])
    observation_space_md.setHighLimit([2.5, max_float, 24, max_float])
    md.setActionSpaceMetadata(action_space_md)
    md.setObservationSpaceMetadata(observation_space_md)
    assert md.isValid(), "Metadata for CartPole environment is not valid"

    # Register the metadata
    assert factory.registerPlugin(md), "Failed to register the plugin metadata in the " \
                                       "factory"

    # Get the environment
    env = factory.make("CartPole")
    assert env, "Failed to create CartPoleIgnition environment from the factory"

    # Get the gazebo wrapper
    gazebo = bindings.envToGazeboWrapper(env)
    assert gazebo, "Failed to get gazebo wrapper"

    # Get the ignition environment
    ign_env = bindings.envToIgnEnv(env)
    assert ign_env, "Failed to get the ignition environment"

    # Set verbosity
    bindings.GazeboWrapper.setVerbosity(4)

    # Use the environment
    env.reset()
    action = env.action_space.sample()
    state_opt = env.step(action)
    assert state_opt.has_value()

    state = state_opt.value()
    assert list(state.observation.getBuffer_d())

    observation = list(state.observation.getBuffer_d())
    assert len(observation) == 4

    # Try to register another environment
    assert factory.registerPlugin(md), "Failed to re-register the plugin metadata in " \
                                       "the factory"

    # Try to get another environment
    env2 = factory.make("CartPole")
    assert env2, "Failed to create CartPoleIgnition environment from the factory"
    assert env != env2, "Environment created from the factory are the same"
    env2.reset()
    env2.step(action)


class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        bit_arr = []
        for num in arr:
            total = 0
            for i in range(32):
                total += (num>>i) & 1
            bit_arr.append((num, total))
        output = sorted(bit_arr, key=lambda pair: (pair[1], pair))
        return [num for num, total in output]


import collections

from django import forms
from django.core.cache import cache
from django.utils.safestring import mark_safe

from taggit.managers import TaggableManager
from taggit.models import Tag

class SelectTagField(forms.TypedMultipleChoiceField):
    widget = forms.CheckboxSelectMultiple

class CustomTaggableManager(TaggableManager):
    def __unicode__(self):
        return u"<%s:%s>" % (type(self), self.name)

    def formfield(self, form_class=SelectTagField, **kwargs):
        """
        Used when a model form is built. This determines what the
        form field should do
        """
        defaults = {
            'choices': ((t.name, t.name) for t in Tag.objects.all()),
        }
        defaults.update(kwargs)
        return super(CustomTaggableManager, self).formfield(
            form_class=form_class,
            **defaults
        )

    def value_from_object(self, instance):
        """
        Used when creating initial data for the form. We send all the tags,
        because their pks are put in the select widget
        """
        return getattr(instance, self.name).all()

class CheckboxSelectMultipleWithGroups(forms.CheckboxSelectMultiple):
    """
    Groups the choices based on their prefixes
    """
    def render(self, name, value, attrs=None, choices=()):
        groups = collections.defaultdict(list)
        for categ_name, categ_val in self.choices:
            if ':' in categ_name:
                group, categ = categ_name.split(':')
                groups[group.strip()].append((categ_name, categ.strip()))
            else:
                groups[''].append((categ_name, categ_val))

        # We want to display the categories in the groups that they
        # are a part of:
        # group
        #   category
        #   category
        # Now, we need to generate all choices with a single call to
        # the `render` of the base class to avoid ID duplication. Then
        # we need to insert at the right location the groups themselves
        # between the choices.

        # We start with index 1 to take into account the <ul> starting tag
        index = 1
        indexed_groups = {}
        formatted_choices = []

        for group, group_choices in groups.iteritems():
            indexed_groups[index] = u'<h3>%s</h3>' % group
            formatted_choices.extend(group_choices)
            # We extend the index by the group and all its choices
            index += (1 + len(group_choices))

        # We replace the initial choices, because they don't have the
        # group and category separate. There, they are in the format
        # group:category
        self.choices = formatted_choices

        # We split the output to have a list which we can modify
        output = super(CheckboxSelectMultipleWithGroups, self).render(
            name=name, value=value, attrs=attrs, choices=choices
        ).split('\n')

        # We insert the groups between the categories
        for index, group in indexed_groups.iteritems():
            output[index:index] = [group]

        return mark_safe(u'\n'.join(output))

class CategsForm(forms.Form):
    categs = forms.MultipleChoiceField(
        label='',
        widget=CheckboxSelectMultipleWithGroups(),
        choices=()
    )

    def __init__(self, role, *args, **kwargs):
        super(CategsForm, self).__init__(*args, **kwargs)

        cache_key = 'tag_choices_role_%s' % role
        tag_choices = cache.get(cache_key)
        if tag_choices is None:
            tags = Tag.objects.filter(
                taggit_taggeditem_items__collection__role=role
            ).distinct()
            tag_choices = [(t.name, t.name) for t in tags]
            # Cache for 24 hours
            cache.set(cache_key, tag_choices, 60 * 60 * 24)

        self.fields['categs'].choices = tag_choices


import sys, random, time, os
import random
import pygame
import tkinter as tk
from tkinter import messagebox

#CONSTANTS SCREEN WIDTH AND HEIGHT
WIDTH = 500
HEIGHT = 500
ROWS = 20
WHITE = (255,255,255)
RED = (255,0,0)
BLACK = (0,0,0)
YELLOW = (255,255,0)
GREEN = (0,255,0)
FPS = 20 # FPS for the game
CLOCK = pygame.time.Clock()
FRUIT_WIDTH = 50
FRUIT_HEIGHT = 50
SNAKE_SIZE = 10

#FRUIT
BANANA = pygame.transform.scale(pygame.image.load(os.path.join('assets','banana.jpg')),(30,30))

# INITIATE PYGAME
pygame.init()
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Snake Game')

def draw_window():
    global snake, fruit
    WIN.fill(BLACK)
    draw_grid(WIDTH,ROWS)
    snake.draw_snake()
    fruit.draw(WIN)
    pygame.display.update()

def draw_grid(width, row):
    size_between = WIDTH//ROWS
    x = 0
    y=0
    for i in range(ROWS):
        x = x + size_between
        y = y + size_between
        pygame.draw.line(WIN,(255,255,255), (x,0),(x,WIDTH))
        pygame.draw.line(WIN,(255,255,255), (0,y),(WIDTH, y))

def randomize_fruit(rows, snake):
    # print(positions)
    positions = snake.body

    while True:
        x = random.randrange(rows)
        y = random.randrange(rows)
        if len(list(filter(lambda z: z.pos==(x,y),positions))) > 0:
            continue
        else:
            break
    return (x,y)

def message_box(subject,content):
    root = tk.Tk()
    root.attributes("-topmost",True)
    root.withdraw()
    messagebox.showinfo(subject,content)
    try:
        root.destroy()
    except:
        pass

class Cube: # use to represent the snake
    rows = 20
    w = 500
    def __init__(self, start, _dirnx=1, _dirny=0, color=RED):
        self.pos = start
        self._dirnx = _dirnx
        self._dirny = _dirny
        self.color = color

    def move(self, _dirnx, _dirny):
        self._dirnx = _dirnx
        self._dirny = _dirny
        self.pos = (self.pos[0]+ self._dirnx, self.pos[1]+self._dirny)

    def draw(self, surface=WIN, eyes= False):
        dis = self.w // self.rows
        i = self.pos[0]
        j = self.pos[1]

        pygame.draw.rect(surface, self.color,(i*dis+1, j*dis+1,dis-2,dis-2) )
        if eyes:
            centre = dis//2
            radius = 3
            circleMiddle = (i*dis+centre-radius,j*dis+8)
            circleMiddle2 = (i*dis + dis -radius*2, j*dis+8)
            pygame.draw.circle(WIN, (0,0,0), circleMiddle, radius)
            pygame.draw.circle(WIN, (0,0,0), circleMiddle2, radius)

class Snake:
    body = []
    turns = {} #REMEMBER THE POSITION WHERE THE SNAKE TURNS
    def __init__(self,color,pos):
        self.color = color
        self.head = Cube(pos)
        self.body.append(self.head)
        #SETTING THE DIRECTION OF THE SNAKE
        self._dirnx = 0
        self._dirny = 0
    def move(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

            key_pressed = pygame.key.get_pressed()
            for key in key_pressed:
                if key_pressed[pygame.K_a]:
                    self._dirnx = -1
                    self._dirny = 0
                    self.turns[self.head.pos[:]] = [self._dirnx, self._dirny]
                elif key_pressed[pygame.K_s]:
                    self._dirnx = 0
                    self._dirny = 1
                    self.turns[self.head.pos[:]] = [self._dirnx, self._dirny]
                elif key_pressed[pygame.K_d]:
                    self._dirnx = 1
                    self._dirny = 0
                    self.turns[self.head.pos[:]] = [self._dirnx, self._dirny]
                elif key_pressed[pygame.K_w]:
                    self._dirnx = 0
                    self._dirny = -1
                    self.turns[self.head.pos[:]] = [self._dirnx, self._dirny]

        #MAKE OTHER PART OF THE SNAKE TURN AT THE INDICATED POSITION
        for i, c in enumerate(self.body):
            p = c.pos[:]
            if p in self.turns:
                turn = self.turns[p]
                c.move(turn[0],turn[1])
                if i == len(self.body)-1:
                    self.turns.pop(p)
            else:
                if c._dirnx == -1 and c.pos[0]<=0 : c.pos = (c.rows-1, c.pos[1])
                elif c._dirnx == 1 and c.pos[0]>=c.rows-1:c.pos=(0,c.pos[1])
                elif c._dirny == 1 and c.pos[1]>=c.rows-1:c.pos=(c.pos[0],0)
                elif c._dirny == -1 and c.pos[1] <= 0: c.pos=(c.pos[0],c.rows-1)
                else:
                    c.move(c._dirnx,c._dirny )
    def draw_snake(self):
        for i,c in enumerate(self.body):
            if i == 0:
                c.draw(WIN,eyes=True)
            else:
                c.draw(WIN)
    def addCube(self):
        tail = self.body[-1]
        dx,dy = tail._dirnx, tail._dirny
        if dx ==1 and dy ==0:
            self.body.append(Cube((tail.pos[0]-1,tail.pos[1])))
        elif dx==-1 and dy==0:
            self.body.append(Cube((tail.pos[0]+1,tail.pos[1])))
        elif dx==0 and dy==1:
            self.body.append(Cube((tail.pos[0],tail.pos[1]-1)))
        elif dx==0 and dy==-1:
            self.body.append(Cube((tail.pos[0],tail.pos[1]+1)))

        self.body[-1]._dirnx = dx
        self.body[-1]._dirny = dy
    def reset(self,pos):
        self.head = Cube(pos)
        self.body=[]
        self.body.append(self.head)
        self.turns = {}
        self._dirnx = 1
        self._dirny = 0

def main():

    global snake, fruit
    game = True
    fruit_rec = pygame.Rect(50,50, FRUIT_WIDTH, FRUIT_WIDTH)
    snake = Snake((255,0,0),(10,10))
    fruit = Cube(randomize_fruit(ROWS,snake), color=GREEN)
    direction = "right"
    while game:
        pygame.time.delay(80)
        CLOCK.tick(FPS)
        snake.move()
        if snake.body[0].pos == fruit.pos:
            snake.addCube()
            fruit = Cube(randomize_fruit(ROWS,snake),color=(0,255,0))
        for x in range(len(snake.body)):
            if snake.body[x].pos in list(map(lambda z: z.pos,snake.body[x+1:])):
                print("Score: ",len(snake.body))
                message_box('You Lost!', 'Play Again')
                snake.reset((10,10))
                break

        draw_window()

if __name__ == "__main__":
    main()


import re
import argparse
import webbrowser
from filestack import Client
client = Client("AO0lhLyhmQJqnVt7juhQHz")

params = {'mimetype': 'text/plain'}

parser = argparse.ArgumentParser()
parser.add_argument('file',  type=str, help='Add the main entrypoint of the api file most probbaly app.js or index.js')
parser.add_argument('baseurl', type=str, help='Add API base url')
args = parser.parse_args()
def generate(file,baseurl):
        y=open(file,"r")
        x=y.read()

        ss=re.findall(r'app\.(?:get|post).*',x)
        y.close()
        #print(ss)
        html=''''''

        for post in ss:
                try:
                        a,t='',''
                        i=x.find(post)
                        v=0
                        while a!="})":

                                if a=="({":
                                        v+=1
                                a=x[i]+x[i+1]
                                t+=x[i]
                                i+=1
                                if v>=1 and a=="})":
                                        a=''
                                        v-=1
                        t+=x[i]
                        #print(t)
                        auth=re.findall(r"app.+",t)[0].split(",")
                        method="GET" if "get" in auth[0] else "POST"

                        if len(auth)==4:
                                auth=re.findall(r"app.+",t)[0].split(",")[1]
                        else:auth=False

                        endpoint=baseurl+re.findall(r'\".*\"',re.findall(r"app.+",t)[0])[0].replace('"','')
                        cc=re.findall(r"new .+\(",t) if len(re.findall(r"new .+\(",t))>0 else re.findall(r"await .+\.find",t)
                        #print()
                        schema=cc[0].replace("await",'').replace(".find","").replace("new ","").strip()
                        if "(" in schema:
                                schema=re.findall(r"^(.*?)\(",cc[0])[0].replace("new ","").strip()+"SH"
                        else:schema+="SH"
                        #print(schema)
                        ss=re.findall(f'const {schema}.+\=.+',x) if len(re.findall(f'const {schema}.+\=.+',x))>0 else re.findall(f'const {schema}\=.+',x)
                        if len(ss)==0:
                                schema=schema.replace("SH","schema")
                                ss=re.findall(f'const {schema}.+\=.+',x) if len(re.findall(f'const {schema}.+\=.+',x))>0 else re.findall(f'const {schema}\=.+',x)

                        #print(ss)
                        a=''
                        t=''
                        i=x.find(ss[0])
                        v=0
                        while a!="})":

                                if a=="({":
                                        v+=1
                                a=x[i]+x[i+1]
                                t+=x[i]
                                i+=1
                                if v>=1 and a=="})":
                                        a=''
                                        v-=1
                        t+=x[i]
                        body=re.findall(r'\([^)]*\)',t)[0].replace("(","").replace(")","")
                        authstatus='content-type:application/json' if not auth else f"Authorization:{auth}\n,content-type:application/json"
                        html+=f'''

  {method} {endpoint}

HEADERS:

{authstatus}

BODY:

{body}

Description:

if the endpoint have [[ /:something ]] <-- this type of syntex you must replace it with the actual value\n
now if it wants Authorization token that means you have to pass a authentication token which ig gevn at the time of login,

**NOTE:You can edit the avobe description as well as body and headers, after editing just press ctrl+s it will save on your local pc

'''

                except:pass

        return html

if(args.file and args.baseurl):

        with open("Documentation_of_"+re.findall(r'([A-Za-z]+(\.[A-Za-z]+)+)',args.baseurl)[0][0]+'.html',"w") as x:
                x.write(generate(args.file,args.baseurl))
        new_filelink =client.upload(filepath="Documentation_of_"+re.findall(r'([A-Za-z]+(\.[A-Za-z]+)+)',args.baseurl)[0][0]+'.html',store_params=params)
        print(new_filelink.url)
        print("Document generated \nDocumentation_of_"+re.findall(r'([A-Za-z]+(\.[A-Za-z]+)+)',args.baseurl)[0][0]+'.html')
        #webbrowser.open("Documentation_of_"+re.findall(r'([A-Za-z]+(\.[A-Za-z]+)+)',args.baseurl)[0][0]+'.html')


import re
from requests import get
from helpers.command import Command

def get_quote(symbol):
    params = {'q': "select BidRealtime,Bid,Name,ChangeinPercent,YearRange from yahoo.finance.quotes WHERE symbol='%s'" % symbol,
              'format': 'json', 'env': 'store://datatables.org/alltableswithkeys'}
    data = get("http://query.yahooapis.com/v1/public/yql", params=params).json()
    return data['query']['results']

def gen_stock(msg):
    quote = None
    num = 0
    while quote is None:
        if num > 5:
            break
        num += 1
        quote = get_quote(msg)
    if quote is not None:
        quote = quote['quote']
    else:
        return "No Results"
    if quote['Name'] is None:
        return "Invalid Symbol."
    else:
        if quote['BidRealtime']:
            val = quote['BidRealtime']
        elif quote['Bid']:
            val = quote['Bid']
        else:
            val = "No Data"
        return "%s (%s) -- %s %s 52wk: %s" % (quote['Name'], msg, val, quote['ChangeinPercent'], quote['YearRange'])

def random_stock():
    html = get('http://www.openicon.com/rsp/rsp_n100.php').text
    return re.search('\((.*)\)', html).group(1)

@Command('stock')
def cmd(send, msg, args):
    """Gets a stock quote.
    Syntax: !stock <symbol>
    """
    if not msg:
        msg = random_stock()
    send(gen_stock(msg))


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def goodNodes(self, root: TreeNode) -> int:
        def dfs(root, p):
            if root:
                if not p:
                    p.append(root.val)
                else:
                    if root.val > p[-1]:
                        p.append(root.val)
                    else:
                        p.append(p[-1])
                if root.val >= p[-1]:
                    self.ans += 1
                dfs(root.left, p)
                dfs(root.right, p)
                p.pop()
        self.ans = 0
        dfs(root, [])
        return self.ans


# 387. First Unique Character in a String
# Easy

# Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

# Examples:

# s = "leetcode"
# return 0.

# s = "loveleetcode",
# return 2.
# Note: You may assume the string contain only lowercase letters.

class Solution:
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        # build hash map : character and how often it appears
        count = collections.Counter(s)

        # find the index
        # Iterate over string, character by character
        # Check if the count of the character is 1 in the map
        # return index
        for idx, ch in enumerate(s):
            print(idx, ch)
            if count[ch] == 1:
                return idx
        return -1


#%%
import torch
import numpy as np
import math

def sdBox(p, b):
    d = torch.abs(p) - b

    external_dist = torch.norm(torch.max(d, torch.zeros_like(d)), dim=0)

    d_maxed = torch.max(d, axis=0).values
    internal_dist = torch.min(d_maxed, torch.zeros_like(d_maxed))

    return external_dist + internal_dist

def sdStar(p, r, n , m):
    '''
    https://iquilezles.org/articles/distfunctions2d/
    '''

    assert m >= 2 and m <= n
    an = np.pi / n
    en = np.pi / m
    acs = np.array([np.cos(an), np.sin(an)])[:, None]
    ecs = np.array([np.cos(en), np.sin(en)])[:, None]

    bn = np.arctan2(p[0], p[1])%(2 * an) - an

    p = np.linalg.norm(p, axis=0) * np.array([np.cos(bn), np.abs(np.sin(bn))])
    p -= r * acs
    p += ecs * np.clip(-np.dot(p.T, ecs), 0.0, r * acs[1]/ecs[1]).T
    return np.linalg.norm(p, axis=0) * np.sign(p[0])

def sdStarTorch(p,r,n,m):
    '''
        https://iquilezles.org/articles/distfunctions2d/
    '''
    an = np.pi / n
    en = np.pi / m

    acs = torch.tensor([math.cos(an), math.sin(an)])[:, None]
    ecs = torch.tensor([math.cos(en), math.sin(en)])[:, None]
    bn = torch.atan2(p[0], p[1])%(2 * an) - an

    bcs = torch.stack([torch.cos(bn), torch.abs(torch.sin(bn))])

    p = torch.norm(p, dim=0) * bcs
    p_prime = p -  r * acs

    clamped_values = torch.clamp(-(p_prime.T @ ecs), 0.0, (r * acs[1]/ecs[1]).item()).T

    p_prime_prime = p_prime + ecs * clamped_values

    signed_dist = torch.norm(p_prime_prime, dim=0) * torch.sign(p_prime_prime[0])
    return signed_dist
    # mask = (signed_dist > 0)
    # print(an, en, acs, ecs, bn, bcs, p, p_prime, clamped_values, p_prime_prime, sep="\n")

#%%
if __name__ == "__main__":
    import matplotlib.pyplot as plt
    PTS = 10000
    # p = torch.rand(2, PTS) - 0.5
    p_np = np.random.random((2, PTS)) - 0.5
    p = torch.tensor(p_np).float()
    r = 0.5
    n = 5
    m = 3
    signed_dist_t = sdStarTorch(p, r, n, m)
    mask_t = (signed_dist_t > 0).detach().cpu()

    signed_dist = sdStar(p_np, r, n, m)
    mask = signed_dist > 0

    p_draw = p_np
    mask = mask_t

    fig, ax = plt.subplots(1,1,figsize=(4,4))
    ax.scatter(p_draw[0][mask], p_draw[1][mask])
    ax.set_aspect(1)
    plt.show()

#%%


# -*- coding: UTF-8 -*-
class g:
    def __getattr__(self, item):
        print("nnn")
    def __setattr__(self, key, value):
        print("111")
        self.__dict__[key] = value
a = g()
print(a.a)

a.x = 1
print(a.x)


"""Provides the setting model and functionality for saving and reading settings"""

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

from functionality.Database import Database

BASE = declarative_base()
DATABASE = Database()

class Setting(BASE):
    """Provides the setting model and functionality for saving and reading settings"""

    __tablename__ = 'settings'
    setting_id = Column(Integer, primary_key=True)
    setting_name = Column(String)
    setting_value = Column(String)

    @staticmethod
    def make(setting_name, setting_value):
        """Adds a new setting to the database or updates an existing setting"""

        setting_in_db = DATABASE.session.query(Setting).filter(Setting.setting_name == setting_name).first()
        if not setting_in_db:
            setting = Setting()
            setting.setting_name = setting_name
            setting.setting_value = setting_value
            DATABASE.session.add(setting)

        else:
            setting_in_db.setting_value = setting_value

        DATABASE.session.commit()

    @staticmethod
    def read(setting_name):
        """Reads a setting's value from the database"""

        setting_in_db = DATABASE.session.query(Setting).filter(Setting.setting_name == setting_name).first()
        if not setting_in_db:
            return None

        return setting_in_db.setting_value

    @staticmethod
    def delete(setting_name):
        """Removes a setting from the database"""

        setting_in_db = DATABASE.session.query(Setting).filter(Setting.setting_name == setting_name).delete()
        DATABASE.session.commit()


def removeDuplicates(nums):
    ptr = 1
    i = 1
    while i < len(nums):
        if nums[i] != nums[i - 1]:
            nums[ptr] = nums[i]
            ptr += 1
        i += 1
    print(nums)
    return ptr

def removeElement(nums, val):
    ptr = 0
    i = 0
    while i < len(nums):
        if nums[i] != val:
            nums[ptr] = nums[i]
            ptr += 1
        i += 1
    print(nums)
    return ptr

nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
# nums1 = [1, 1, 2]
nums2 = [0, 1, 2, 2, 3, 0, 4, 2]
val = 2
# print(removeDuplicates(nums))
print(removeElement(nums2, val))


"""
This sample demonstrates a simple skill built with the Amazon Alexa Skills Kit.
The Intent Schema, Custom Slots, and Sample Utterances for this skill, as well
as testing instructions are located at http://amzn.to/1LzFrj6

For additional samples, visit the Alexa Skills Kit Getting Started guide at
http://amzn.to/1LGWsLG
"""

# GLOBALS
import random

intent = None
session = None
session_attributes = {}
USERNAME = "username"

# --------------- Helpers that build all of the responses ----------------------

def build_speechlet_response(title, output, reprompt_text, should_end_session):
    return {
        'outputSpeech': {
            'type': 'PlainText',
            'text': output
        },
        'card': {
            'type': 'Simple',
            'title': "SessionSpeechlet - " + title,
            'content': "SessionSpeechlet - " + output
        },
        'reprompt': {
            'outputSpeech': {
                'type': 'PlainText',
                'text': reprompt_text
            }
        },
        'shouldEndSession': should_end_session
    }

def build_response(session_attributes, speechlet_response):
    return {
        'version': '1.0',
        'sessionAttributes': session_attributes,
        'response': speechlet_response
    }

# --------------- Functions that control the skill's behavior ------------------

def get_welcome_response():
    """ If we wanted to initialize the session to have some attributes we could
    add those here
    """

    session_attributes = {}
    card_title = "Welcome"
    speech_output = "Hello dear. Here's your cute honey bunny. If your name isn't " + \
                    get_username() + ", then please tell me what your actual name is. Afterwards we can exchange " + \
                    " some pleasant compliments. Be creative. What would you like to tell me?"
    # If the user either does not reply to the welcome message or says something
    # that is not understood, they will be prompted again with this text.
    reprompt_text = "What would you like to tell me?"
    should_end_session = False
    return build_response(session_attributes, build_speechlet_response(
        card_title, speech_output, reprompt_text, should_end_session))

def handle_session_end_request():
    card_title = "Session Ended"
    speech_output = "Bye, I love you {}. Hope to see you again soon." % get_username()
    # Setting this to true ends the session and exits the skill.
    should_end_session = True
    return build_response({}, build_speechlet_response(
        card_title, speech_output, None, should_end_session))

# UTIL
# ==================
def get_username():
    name = get_session_attribute(USERNAME)
    if name is None:
        return "Jessica"
    return name

def get_session_attribute(attribute_name):
    if attribute_name in session_attributes:
        return session_attributes[attribute_name]
    return None

# INTENTS
# ==================

def MyNameIsIntent():
    """ Sets the user name in the session and prepares the speech to reply to the
    user.
    """
    global intent, session, session_attributes

    card_title = intent['name']
    should_end_session = False
    reprompt_text = None

    if 'Name' in intent['slots']:
        username = intent['slots']['Name']['value']
        session_attributes[USERNAME] = username
        speech_output = "I will call you {} then. ".format(username)
    else:
        speech_output = "I'm sorry. I afraid I didn't understand what your name is. Please try again."
    return build_response(session_attributes, build_speechlet_response(
        card_title, speech_output, reprompt_text, should_end_session))

def ILoveYouIntent():
    global intent, session
    card_title = intent['name']
    reprompt_text, should_end_session = None, False

    speech_output = random_i_love_you_compliment()
    return build_response(session_attributes, build_speechlet_response(
        card_title, speech_output, reprompt_text, should_end_session))

def EasterEggIntent():
    global intent, session
    card_title = intent['name']
    reprompt_text, should_end_session = None, False

    speech_output = random_easter_egg_compliment()
    return build_response(session_attributes, build_speechlet_response(
        card_title, speech_output, reprompt_text, should_end_session))

def YouAreIntent():
    global intent, session
    card_title = intent['name']
    reprompt_text, should_end_session = None, False

    speech_output = random_person_compliment()
    return build_response(session_attributes, build_speechlet_response(
        card_title, speech_output, reprompt_text, should_end_session))

def BodyIntent():
    global intent, session
    card_title = intent['name']
    reprompt_text, should_end_session = None, False

    speech_output = random_body_compliment()
    return build_response(session_attributes, build_speechlet_response(
        card_title, speech_output, reprompt_text, should_end_session))

def get_fallback_response():
    speech_output = "Wow, I've never heard that compliment before. Here is one for you: "
    speech_output += random_misc_compliment()
    return build_response(session_attributes, build_speechlet_response(
        "AMAZON.FallbackIntent", speech_output, None, False))

# --------------- Events ------------------

def on_session_started(session_started_request):
    """ Called when the session starts """
    global session
    print("on_session_started requestId=" + session_started_request['requestId']
          + ", sessionId=" + session['sessionId'])

def on_launch(launch_request):
    """ Called when the user launches the skill without specifying what they
    want
    """
    global session

    print("on_launch requestId=" + launch_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    # Dispatch to your skill's launch
    return get_welcome_response()

def on_intent(intent_request):
    """ Called when the user specifies an intent for this skill """

    print("on_intent requestId=" + intent_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    global intent
    intent = intent_request['intent']
    intent_name = intent_request['intent']['name']

    # Dispatch to your skill's intent handlers
    if intent_name == "ILoveYouIntent":
        return ILoveYouIntent()
    elif intent_name == "MyNameIsIntent":
        return MyNameIsIntent()
    elif intent_name == "YouAreIntent":
        return YouAreIntent()
    elif intent_name == "EasterEggIntent":
        return EasterEggIntent()
    elif intent_name == "BodyIntent":
        return BodyIntent()
    elif intent_name == "AMAZON.HelpIntent":
        return get_welcome_response()
    elif intent_name == "AMAZON.FallbackIntent":
        return get_fallback_response()
    elif intent_name in ("AMAZON.CancelIntent", "AMAZON.StopIntent"):
        return handle_session_end_request()
    return get_fallback_response()

def on_session_ended(session_ended_request):
    """ Called when the user ends the session.

    Is not called when the skill returns should_end_session=true
    """
    print("on_session_ended requestId=" + session_ended_request['requestId'] +
          ", sessionId=" + session['sessionId'])
    # add cleanup logic here

# --------------- Main handler ------------------

def lambda_handler(event, context):
    """ Route the incoming request based on type (LaunchRequest, IntentRequest,
    etc.) The JSON body of the request is provided in the event parameter.
    """
    print("event.session.application.applicationId=" +
          event['session']['application']['applicationId'])

    """
    Uncomment this if statement and populate with your skill's application ID to
    prevent someone else from configuring a skill that sends requests to this
    function.
    """
    global session, session_attributes
    session = event['session']
    if session is not None and session.get('attributes', {}):
        session_attributes = session['attributes']
    # if (event['session']['application']['applicationId'] !=
    #         "amzn1.echo-sdk-ams.app.[unique-value-here]"):
    #     raise ValueError("Invalid Application ID")

    if event['session']['new']:
        on_session_started({'requestId': event['request']['requestId']})

    if event['request']['type'] == "LaunchRequest":
        return on_launch(event['request'])
    elif event['request']['type'] == "IntentRequest":
        return on_intent(event['request'])
    elif event['request']['type'] == "SessionEndedRequest":
        return on_session_ended(event['request'])

def mymain1():
    print("mymain()")
    slots = {
        "Color": {
            "value": "red"
        },
        "Name": {
            "value": "martin"
        }
    }
    intent = {
        "name": "MyNameIsIntent",
        "slots": slots
    }
    request = {
        'type': 'IntentRequest',
        'requestId': 'myRequestId123',
        'intent': intent
    }
    session = {
        'new': False,
        'sessionId': 'mySessionId123',
        'application': {
            'applicationId': "myApplicationId123"
        }
    }

    event = {
        'request': request,
        'session': session,
    }

    print("result:")
    from pprint import pprint
    pprint(lambda_handler(event, None))
    intent["name"] = "MyColorIsIntent"
    pprint(lambda_handler(event, None))
    print("quitting...")

def mymain():
    # mymain1()
    # test()
    pass

def test():
    compliments = i_love_you_compliments + body_compliments + easter_egg_compliments + you_are_compliments + misc_compliments
    for com in compliments:
        for i in range(10):
            print(i, preprocess_compliment(com))

def preprocess_compliment(compliment):
    compliment = compliment.replace("$name", get_username())
    compliment = compliment.replace("$body", random.choice(body_parts))
    compliment = compliment.replace("$cool", random.choice(person_adjectives))
    compliment = compliment.replace("$pretty", random.choice(pretty_adjectives))
    compliment = compliment.replace("$very", random.choice(positive_adverbs))
    for c in "aeiou":
        compliment = compliment.replace("$aan " + c, "an " + c)
    compliment = compliment.replace("$aan", "a")
    compliment = compliment.replace("feet $isare", "feet are")
    compliment = compliment.replace("s $isare", "s are")
    compliment = compliment.replace("$isare", "is")
    return compliment

def random_easter_egg_compliment():
    return preprocess_compliment(random.choice(easter_egg_compliments))

def random_body_compliment():
    return preprocess_compliment(random.choice(body_compliments))

def random_person_compliment():
    return preprocess_compliment(random.choice(you_are_compliments))

def random_i_love_you_compliment():
    return preprocess_compliment(random.choice(i_love_you_compliments))

def random_misc_compliment():
    return preprocess_compliment(random.choice(misc_compliments))

easter_egg_compliments = """
Whatever might happen between us in the future, $name, I really hope you'll be happy.
Things have not always worked out perfectly between us, $name, but I would like you to know that I'm extremely happy to have met you either way. I do hope you'll feel the same.
""".strip().split("\n")

i_love_you_compliments = """
And I. love you $name.
I love you too $name.
Oh, and I will always love you $name.
""".strip().split("\n")

you_are_compliments = """
You are $aan $very $cool person.
You are $very $cool $name.
Everybody knows, you're $very $cool.
""".strip().split("\n")

body_compliments = """
Your $body $isare $very $pretty $name.
I like your $pretty $body.
I really love your $very $pretty $body.
Your $very $pretty $body $isare irresistible.
Wherever I am, I can't stop thinking about your $pretty $body $name.
""".strip().split("\n")

positive_adverbs = """
very
really
extremely
incredibly
super
unimaginably
""".strip().split("\n")

person_adjectives = """
cool
awesome
beautiful
pretty
talented
smart
intelligent
witty
classy
strong
motivated
hard working
determined
funny
charming
inspiring
independent
amazing
""".strip().split("\n")

pretty_adjectives = """
pretty
beautiful
graceful
hot
cute
elegant
lovely
seducing
""".strip().split("\n")

body_parts = """
body
hair
face
nose
eyes
ears
butt
hands
legs
feet
cheeks
voice
laugh
""".strip().split("\n")

misc_compliments = """
I'd love to cuddle you right now.
I would love to survive a Zombie apocalypse with you.
I would love to go back in time with you to see some dinosaurs.
You're an awesome friend.
You're a gift to those around you.
You have the best laugh.
I'm grateful to know you.
You light up the room.
You deserve a hug right now.
You have a great sense of humor.
You are really courageous.
You're like a ray of sunshine on a really dreary day.
You are making a difference.
Thank you for being there for me.
Hanging out with you is always a blast.
You may dance like no one's watching, but everyone's watching because you're an amazing dancer!
You're more fun than a ball pit filled with candy. And seriously, what could be more fun than that?
You should be thanked more often. So thank you!
You have the best ideas.
Being around you is like being on a happy little vacation.
You're always learning new things and trying to better yourself, which is awesome.
Your voice is magnificent.
The people you love are lucky to have you in their lives.
Your creative potential seems limitless.
Somehow you make time stop and fly at the same time.
When you make up your mind about something, nothing stands in your way.
You're even better than a unicorn, because you're real.
""".strip().split("\n")

if __name__ == "__main__":
    mymain()


from __future__ import annotations

import random
from pathlib import Path
from typing import Annotated as _Annotated
from typing import Literal

import click
import typer

from aloud import cli_utils

del _Annotated.__init_subclass__
Undefined = object()

class Annotated(_Annotated):
    def __class_getitem__(cls, params: tuple):
        default = Undefined
        if len(params) == 3:
            *params, default = params
        # noinspection PyUnresolvedReferences
        inst = super().__class_getitem__(tuple(params))
        inst.__dict__['default'] = default
        return inst

def random_voice(ctx, param, value):
    if value == 'random':
        return random.choice(voices)
    return value

voices = ('alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer')
default_voice = 'random'
Voice = Literal[voices]
Voice.default = default_voice
VoiceOption = Annotated[
    str,
    typer.Option(
        '-v',
        '--voice',
        show_default=True,
        click_type=click.Choice((*voices, 'random')),
        callback=random_voice,
    ),
    default_voice,
]

voice_models = ('tts-1', 'tts-1-hd')
default_voice_model = 'tts-1'
VoiceModel = Literal[voice_models]
VoiceModel.default = default_voice_model
VoiceModelOption = Annotated[
    str,
    typer.Option('--voice-model', click_type=click.Choice(voice_models)),
    default_voice_model,
]

voice_response_formats = ('mp3', 'opus', 'aac', 'flac')
default_voice_response_format = 'mp3'
VoiceResponseFormat = Literal[voice_response_formats]
VoiceResponseFormat.default = default_voice_response_format
VoiceResponseFormatOption = Annotated[
    str,
    typer.Option('--voice-response-format', click_type=click.Choice(voice_response_formats)),
    default_voice_response_format,
]

OpenAIKey = Annotated[
    str,
    typer.Option('-k', '--openai-api-key', callback=cli_utils.get_openai_api_key, envvar='OPENAI_API_KEY'),
]

default_output_dir = Path('/tmp')
OutputDir = Annotated[Path, typer.Option('-o', '--output-dir'), default_output_dir]


from inventory_report.inventory.product import Product

def test_relatorio_produto():
    # pass  # Seu teste deve ser escrito aqui
    id = 1
    nome_do_produto = "Test product name"
    nome_da_empresa = "Test company name"
    data_de_fabricacao = "00-00-0000"
    data_de_validade = "00-00-0000"
    numero_de_serie = "123456789"
    instrucoes_de_armazenamento = "No instructions"

    report = (
        f"O produto {nome_do_produto}"
        f" fabricado em {data_de_fabricacao}"
        f" por {nome_da_empresa} com validade"
        f" até {data_de_validade}"
        f" precisa ser armazenado {instrucoes_de_armazenamento}."
    )

    product = Product(
        id,
        nome_do_produto,
        nome_da_empresa,
        data_de_fabricacao,
        data_de_validade,
        numero_de_serie,
        instrucoes_de_armazenamento,
    )

    print(product)

    assert report == product.__repr__()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 31 18:24:36 2019

@author: qwang
"""

import os
import random

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader

os.chdir('/home/qwang/rob/rob-kiwi')

from utils import metrics
from arg_parser import get_args
from data_loader import RoBDataset, PadDoc
from model import ConvNet, AttnNet
from train import train_evaluate

#%% Get arguments from command line
args = get_args()
#args_dict = vars(args)

## Save args to json
#with open(os.path.join(log_dir, 'args.json'), 'w') as fout:
#    json.dump(args_dict, fout, indent=4)

#%% Set seed and device
random.seed(args.seed)
#np.random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed)
torch.cuda.manual_seed(args.seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False   # This makes things slower

# device
if torch.cuda.device_count() > 1:
    device = torch.cuda.current_device()
    print('Use {} GPUs: '.format(torch.cuda.device_count()), device)
elif torch.cuda.device_count() == 1:
    device = torch.device("cuda")
    print('Use 1 GPU: ', device)
else:
    device = torch.device('cpu')

#%% Set logger
#log_dir = os.path.join(args.exp_path, args.exp_name)
#if os.path.exists(log_dir) == False:
#    os.makedirs(log_dir)
##utils.set_logger(os.path.join(log_dir, 'train.log'))

#%% Create dataset and loader
train_set = RoBDataset(info_file = args.info_path, mat_dir = args.pkl_dir,
                       rob_item = args.rob_item, max_len = args.max_doc_len,
                       group = 'train')

valid_set = RoBDataset(info_file = args.info_path, mat_dir = args.pkl_dir,
                       rob_item = args.rob_item, max_len = args.max_doc_len,
                       group = 'valid')

train_loader = DataLoader(train_set, batch_size=args.batch_size, shuffle=True, num_workers=0, collate_fn=PadDoc())
valid_loader = DataLoader(valid_set, batch_size=args.batch_size, shuffle=True, num_workers=0, collate_fn=PadDoc())

#test_set = RoBDataset(info_file = args.info_path, mat_dir = args.pkl_dir,
#                       rob_item = args.rob_item, max_len = args.max_doc_len,
#                       group='test')
#test_loader = DataLoader(test_set, batch_size=args.batch_size, shuffle=True, num_workers=0, collate_fn=PadDoc())

#%% Define the model
if args.net_type == 'cnn':
    sizes = args.filter_sizes.split(',')
    sizes = [int(s) for s in sizes]
    model = ConvNet(embedding_dim = args.embed_dim,
                    n_filters = args.num_filters,
                    filter_sizes = sizes,
                    output_dim = 2,
                    dropout = args.dropout)

if args.net_type == 'attn':
    model = AttnNet(embedding_dim = args.embed_dim,
                    rnn_hidden_dim = args.rnn_hidden_dim,
                    rnn_num_layers = args.rnn_num_layers,
                    output_dim = 2,
                    bidirection = args.bidirection,
                    rnn_cell_type = args.rnn_cell_type,
                    dropout = args.dropout)

n_pars = sum(p.numel() for p in model.parameters() if p.requires_grad)
print(model)
print("Number of trainable parameters: {}".format(n_pars))

#%% Define the optimizer, criterion and metrics
optimizer = optim.Adam(model.parameters())
metrics_fn = metrics

# Weight balancing
if args.weight_balance == True and torch.cuda.device_count() == 0:
    criterion = nn.CrossEntropyLoss(weight=torch.FloatTensor(train_set.cls_weight()))
elif args.weight_balance == True and torch.cuda.device_count() > 0:
    criterion = nn.CrossEntropyLoss(weight=torch.FloatTensor(train_set.cls_weight()).cuda())
else:
    criterion = nn.CrossEntropyLoss()

if torch.cuda.device_count() > 1:  # multiple GPUs
    model = nn.DataParallel(module=model)
model = model.to(device)
criterion = criterion.to(device)

#%% Train the model
train_evaluate(model, train_loader, valid_loader, criterion, optimizer, metrics_fn, args)


import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="django-conn-pool",
    version="2.1.0",
    author="kerol",
    author_email="ikerol@163.com",
    description="Connection Pooling with Django and SQLAlchemy",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/kerol/django-conn-pool",
    packages=setuptools.find_packages(),
    classifiers=(
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ),
    install_requires=[
        'Django>2.0.0',
        'SQLAlchemy>=1.2.7',
    ]
)


# -*- coding: utf-8 -*-

#   Programmer: xsmile
#   E-mail:     xsmile117@gmail.com
#
#
#   Distributed under the terms of the GPL (GNU Public License)
#
#   iTip is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

import wx

class iTipRepair(wx.App):
    def OnInit(self):
        config=wx.Config("iTipConfig")
        if config.Exists("isRun"):
            config.Write('openlist',"")
            run=config.ReadInt("isRun")
            if run==1:
                config.WriteInt("isRun",0)

                dlg = wx.MessageDialog(None, u'修复成功，请不要非法关闭iTip!',
                               u'提示',
                               wx.OK | wx.ICON_INFORMATION
                               )
                dlg.ShowModal()
                dlg.Destroy()
            else:
                dlg = wx.MessageDialog(None, u'iTip正常，无需修复!',
                               u'提示',
                               wx.OK | wx.ICON_INFORMATION
                               )
                dlg.ShowModal()
                dlg.Destroy()
        else:
            dlg = wx.MessageDialog(None, u'您还未运行iTip!',
                               u'提示',
                               wx.OK | wx.ICON_INFORMATION
                               )
            dlg.ShowModal()
            dlg.Destroy()
        return 1

# end of class iTipApp

if __name__ == "__main__":
    iTip = iTipRepair(0)


# Goldbach's other conjecture
# Problem 46

# It was proposed by Christian Goldbach that every odd composite number can be
# written as the sum of a prime and twice a square.

# 9 = 7 + 2×1^2
# 15 = 7 + 2×2^2
# 21 = 3 + 2×3^2
# 25 = 7 + 2×3^2
# 27 = 19 + 2×2^2
# 33 = 31 + 2×1^2

# It turns out that the conjecture was false.

# What is the smallest odd composite that cannot be written as the sum of a
# prime and twice a square?

import time

def square(n):
  return int(n ** 0.5)**2 == n

class Primes:
  def __init__(self):
    self.max_num = 1
    self.prime_bitmap = [False for i in xrange(2)]
    self.prime_lst = []

  def mark_prime(self, n):
    if n > self.max_num:
      new_max_num = max(n, self.max_num * 2)
      self.prime_bitmap += [True for i in xrange(new_max_num + 1)]
      self.prime_lst = []
      for i in xrange(new_max_num + 1):
        if self.prime_bitmap[i]:
          self.prime_lst.append(i)
          for j in xrange(i**2, new_max_num + 1, i):
            self.prime_bitmap[j] = False
      self.max_num = new_max_num

  def is_prime(self, n):
    self.mark_prime(n)
    return self.prime_bitmap[n]

def composite_sum_of_prime_and_twice_square(i, p):
  assert not p.is_prime(i)
  for prime in p.prime_lst:
    if prime > i:
      return False
    if square((i - prime) / 2):
      return True

def goldbach():
  p = Primes()
  i = 9
  while True:
    if not p.is_prime(i) and not composite_sum_of_prime_and_twice_square(i, p):
        return i
    i += 1

t0 = time.time()
result = goldbach()
t1 = time.time()
print(result)
print('time %f' % (t1 - t0))
# 5777
# time 0.122437


from ejercicios.carrera_caballos.models.GranPremio import GranPremio

class GranPremioDAO:
    _INSERTAR = "INSERT INTO `grandes_premios` (`nombre`, `distancia`, `num_carreras`) VALUES (%s, %s, %s)"
    _SELECCIONAR = 'SELECT id,nombre,distancia, num_carreras FROM grandes_premios'

    @classmethod
    def insertar(cls, gran_premio, cursor):
        valores = (gran_premio.nombre, gran_premio.distancia, gran_premio.num_carreras)
        cursor.execute(cls._INSERTAR, valores)

    @classmethod
    def insertar_grandespremios(cls, gran_premios, cursor):
        for gran_premio in gran_premios:
            cls.insertar(gran_premio, cursor)

    @classmethod
    def seleccionar(cls, cursor):
        cursor.execute(cls._SELECCIONAR)
        registros = cursor.fetchall()
        list_gran_premio = []

        for registro in registros:
            gran_premio = GranPremio(id=registro[0], nombre=registro[1], distancia=registro[2], num_carreras= registro[3])
            list_gran_premio.append(gran_premio)

        return list_gran_premio


import os
from langchain.document_loaders import ReadTheDocsLoader, TextLoader, DirectoryLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Pinecone
import pinecone
from dotenv import load_dotenv

load_dotenv()

pinecone.init(
    api_key=os.environ["PINECONE_API_KEY"],
    environment=os.environ["PINECONE_ENVIRONMENT_REGION"],
)

def ingest_docs() -> None:
    loader = DirectoryLoader(
        path="GNS3-Labs/MPLS_LAB/configs-txt/", glob="**/*.txt", loader_cls=TextLoader
    )
    raw_documents = loader.load()
    print(f"loaded {len(raw_documents) }documents")
    text_splitter = RecursiveCharacterTextSplitter(
        chunk_size=1000, chunk_overlap=100, separators=["\n\n", "\n", " ", ""]
    )
    documents = text_splitter.split_documents(documents=raw_documents)
    print(f"Splitted into {len(documents)} chunks")

    for doc in documents:
        old_path = doc.metadata["source"]
        new_url = old_path.replace("langchain-docs", "https:/")
        doc.metadata.update({"source": new_url})

    print(f"Going to insert {len(documents)} to Pinecone")
    embeddings = OpenAIEmbeddings()
    Pinecone.from_documents(documents, embeddings, index_name="langchain-doc-index")
    print("****** Added to Pinecone vectorstore vectors")

if __name__ == "__main__":
    ingest_docs()


import requests

# url = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2022-01-01&endtime=2022-10-12&latitude=54.35&longitude=18.65&maxradiuskm=400"
url = "https://earthquake.usgs.gov/fdsnws/event/1/query?"
response = requests.get(url, headers={"Accept": "application/json"}, params={
                "format": "geojson",
                "starttime": "2022-01-01",
                "endtime": "2022-10-12",
                "latitude": "54.35",
                "longitude": "18.65",
                "maxradiuskm": "400"
})

print(f"Request to {url}. Response code is {response.status_code}.")

# print(response.text)    # type str
data = response.json()    # type dict
print(data["features"][0]["properties"]["place"])

print(response.headers["Date"])
print(response.headers["Content-Type"])

# for key in response.headers:
#     print(key)


from functools import partial
import json
from flask import Blueprint

from api.schemas import ObservableSchema
from api.utils import get_json, get_jwt, jsonify_data
from api import gmail

enrich_api = Blueprint('enrich', __name__)

get_observables = partial(get_json, schema=ObservableSchema(many=True))

@enrich_api.route('/deliberate/observables', methods=['POST'])
def deliberate_observables():
    _ = get_jwt()
    _ = get_observables()
    return jsonify_data({})

@enrich_api.route('/observe/observables', methods=['POST'])
def observe_observables():
    auth = get_jwt()
    ob = get_observables()
    for o in ob:
        if o['type'] == 'email':
            if o['value'].split('@')[1] in auth['internal_domains']:
                g = gmail.Gmail(auth['service_account'], auth['delegated_email'])
                sightings = g.get_messages(o['value'])
                return jsonify_data(sightings)
    return jsonify_data({})

@enrich_api.route('/refer/observables', methods=['POST'])
def refer_observables():
    _ = get_jwt()
    _ = get_observables()
    return jsonify_data([])


import os

from pyspark.sql.functions import explode

os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages com.databricks:spark-xml_2.10:0.4.1 pyspark-shell'

def xmlToCsv(xml_file, spark):
    df = spark.read.format('com.databricks.spark.xml').options(rootTag='returns').options(rowTag='return').load(xml_file)
    print("Schema Before")
    df.printSchema()

    explode_df = df.withColumn("structCol", explode("returnItem")).selectExpr("accountingTypeCode", "parentPortId",
                                                                              "portId", "structCol.*")
    print("Schema After")
    explode_df.printSchema()

    return explode_df


'''
본대 산책2 성공

시간 제한	메모리 제한	제출	정답	맞힌 사람	정답 비율
1 초	512 MB	1267	1051	926	85.900%
문제
숭실 대학교 정보 과학관은 유배를 당해서  캠퍼스의 길 건너편에 있다.
그래서 컴퓨터 학부 학생들은 캠퍼스를 ‘본대’ 라고 부르고 정보 과학관을 ‘정보대’ 라고 부른다.
준영이 또한 컴퓨터 학부 소속 학생이라서 정보 과학관에 박혀있으며 항상 꽃 이 활짝 핀 본 대를 선망한다.
어느 날 준영이는 본 대를 산책하기로 결심하였다. 숭실 대학교 캠퍼스 지도는 아래와 같다.

[
    [0, 1, 1, 0, 0, 0, 0, 0],
    [1, 0, 1, 1, 0, 0, 0, 0],
    [1, 1, 0, 1, 1, 0, 0, 0],
    [0, 1, 1, 0, 1, 1, 0, 0],
    [0, 0, 1, 1, 0, 1, 1, 0],
    [0, 0, 0, 1, 1, 0, 0, 1],
    [0, 0, 0, 0, 1, 0, 0, 1],
    [0, 0, 0, 0, 0, 1, 1, 0]]

정보과학관을 0번 건물이라고 했을 때, 그래프는 위와 같다.
(편의 상 문제에서는 위 건물만 등장한다고 가정하자)

한 건물에서 바로 인접한 다른 건물로 이동 하는 데 1분이 걸린다.
준영이는 산책 도중에 한번도 길이나 건물에 멈춰서 머무르지 않는다.
준영이는 할 일이 많아서 딱 D분만 산책을 할 것이다.
(산책을 시작 한 지 D분 일 때, 정보 과학관에 도착해야 한다.)
이때 가능한 경로의 경우의 수를 구해주자.

입력
D 가 주어진다 (1 ≤ D ≤ 1,000,000,000)

출력
가능한 경로의 수를 1,000,000,007로 나눈 나머지를 출력한다.

예제 입력 1
100000000
예제 출력 1
261245548
'''
# https://www.acmicpc.net/problem/12850
from array import array
from sys import stdin
input = stdin.readline
DIV = 1_000_000_007

def solution(D: int) -> int:
    def dp(num: int) -> dict[int: array]:
        if num in cache:
            return

        left, right = num//2, num//2 + num % 2
        if left not in cache:
            dp(left)
        if right not in cache:
            dp(right)

        cache[num] = multiply(cache[left], cache[right])

    fr, to = 0, 0
    cache = {1: [
        array('L', [0, 1, 1, 0, 0, 0, 0, 0]),
        array('L', [1, 0, 1, 1, 0, 0, 0, 0]),
        array('L', [1, 1, 0, 1, 1, 0, 0, 0]),
        array('L', [0, 1, 1, 0, 1, 1, 0, 0]),
        array('L', [0, 0, 1, 1, 0, 1, 1, 0]),
        array('L', [0, 0, 0, 1, 1, 0, 0, 1]),
        array('L', [0, 0, 0, 0, 1, 0, 0, 1]),
        array('L', [0, 0, 0, 0, 0, 1, 1, 0])]}
    dp(D)
    return cache[D][fr][to]

def multiply(mat1, mat2, n=8) -> list[array]:
    ret = [array('L', [0] * n) for _ in range(n)]

    for i in range(n):
        for j in range(n):
            for k in range(n):
                ret[i][j] += (mat1[i][k] * mat2[k][j]) % DIV
                ret[i][j] %= DIV
    return ret

def square(mat, n=8):
    return multiply(mat, mat, n)

def main() -> int:

    D = int(input())

    answer = solution(D)
    print(answer)

    return 1

if __name__ == '__main__':
    assert solution(1) == 0
    assert solution(2) == 2
    assert solution(3) == 2
    main()


#
# @lc app=leetcode id=1403 lang=python3
#
# [1403] Minimum Subsequence in Non-Increasing Order
#

# @lc code=start

class Solution:
    def minSubsequence(self, nums: List[int]) -> List[int]:
        nums.sort(reverse=True)
        total = 0
        for n in nums:
            total += n
        sub = 0
        result = []
        for n in nums:
            if sub > total-sub:
                break
            else:
                sub += n
                result.append(n)
        return result
# @lc code=end


import msvcrt as m
k = b't'
while True:
    kb = 0
    n = 100
    while kb != 1:
        try:
            x = int(input("podaj liczbe: "))
            if x == 0:
                if n == 100:
                    print("nie podano zadnej wartosc")
                else:
                    kb = 1
            else:
                if x > 10 and x < 100:
                    if x<n:
                        n=x
                else:
                    print("podana wartosc nie jest 2 cyfrowa dodatnia")
        except ValueError:
            print("podana watosc nie prawidlowa")
    print("najmniejsza liczba to:",n)
    print("czy chcesz powtorzyc program (T/N)")
    k = m.getch().lower()
    if k != b't':
        break


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

plt.style.use('seaborn-whitegrid')

customers = pd.read_csv('./data/Dim_customer.csv')

#count the number of each gender type
gender_count = customers['gender'].value_counts()
male_count = gender_count.get('M',0)
female_count = gender_count.get('F',0)
notspecified_count = gender_count.get('Not Specified',0)

Gender = ['M','F','Not Specified']
Count = [male_count,female_count,notspecified_count]

#draw a bar chart
plt.figure(figsize=(6,6))
plt.bar(Gender, Count, color=['#F09B59','#1783DB','#BC9DC7'])

#label each axis
plt.xlabel('Giới tính', fontsize=10, fontweight='bold')
plt.ylabel('Số lượng', fontsize=10, fontweight='bold')
plt.title('Số lượng khách hàng theo giới tính', fontsize=16, fontweight='bold')

#show the value of each bar
for i, value in enumerate(Count):
    plt.text(i, value, str(value), ha='center', va='bottom', fontweight='bold', fontsize=9)

plt.show()


from controller import watch, obtain
from library import conf
# from source.bitmex import future, account

def test():
    # obtain
    symbol_list = [conf.BITMEX_XBTUSD, conf.BITMEX_BXBT]
    for symbol in symbol_list:
        obtain.bitmex(symbol, conf.BINSIZE_ONE_MINUTE, 7200)
        obtain.bitmex(symbol, conf.BINSIZE_FIVE_MINUTE, 1440)
        obtain.bitmex(symbol, conf.BINSIZE_THIRTY_MINUTE, 240)
        obtain.bitmex(symbol, conf.BINSIZE_FOUR_HOUR, 300)
        obtain.bitmex(symbol, conf.BINSIZE_ONE_DAY, 300)

    # future
    # result = future.history(conf.BITMEX_BXBT, conf.BINSIZE_THIRTY_MINUTE, 3)
    # result = future.history_thirty_minute(conf.BITMEX_XBTUSD, 100)
    # result = future.history_four_hour(conf.BITMEX_XBTUSD, 100)
    # print(result)

    # order
    # result = order.book(conf.BITMEX_XBTUSD, 10)
    # result = order.list(conf.BITMEX_XBTUSD, 10, 0)
    # result = order.create_simple(conf.BITMEX_XBTUSD, order.SIDE_BUY, 0.001, order.TYPE_LIMIT, 10000.00)
    # result = order.create_contract(conf.BITMEX_XBTUSD, order.SIDE_BUY, 10, order.TYPE_LIMIT, 10000.00)
    # result = order.amend_simple('1c1bfbe6-6c2c-3d4a-3271-5145d3171a28', 0.002, 8000.00)
    # result = order.amend_contract('1c1bfbe6-6c2c-3d4a-3271-5145d3171a28', 20, 8000.00)
    # result = order.cancel_all_after(10000)
    # result = order.cancel('1c1bfbe6-6c2c-3d4a-3271-5145d3171a28')
    # result = order.cancel_all(conf.BITMEX_XBTUSD)

    # account
    # account.wallet_history(100, 0)
    # result = account.wallet()
    # result = account.position(10)
    # print(result)
    return

def monitor():
    code_list = [conf.BITMEX_XBTUSD]
    # watch
    watch.bitmex(code_list)
    return


# open data, split into groups
# with open("2020/day6testdata.txt") as f:
with open("2020/day6answers.txt") as f:
    groups = f.read().split("\n\n")

sum_of_counts = 0
for group in groups:
    same_answers = {}
    no_of_people = group.count("\n") + 1
    answers = group.replace("\n", "")

    # print(no_of_people)
    # print(answers)

    # create a count
    for answer in answers:
        # the number of answers == no_of_people == everyone provided that answer
        if answers.count(answer) == no_of_people:
            # use a dict to remove duplicates
            same_answers[answer] = True

    count = len(same_answers.keys())
    sum_of_counts += count

print(sum_of_counts)


# Author: Ivana Pilizota
# Date: 1 November 2016

import logging
import os
import time

from Bio import SeqIO
from pyparsing import ParseException
import tempfile

from .base_treebuilder import TreeBuilder, AlignmentInput, DataType
from .parsers import FasttreeParser

from ..abstract_cli import AbstractCLI
from ..options import OptionSet, StringOption, IntegerOption
from ...file_utils import TempFile, TempDir

logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO)

class FasttreeCLI(AbstractCLI):
    @property
    def _default_exe(self):
        return 'FastTree'

def set_default_dna_options(treebuilder):
    """
    Dummy function as sensible default
    """
    treebuilder.options = get_default_options()

def set_default_protein_options(treebuilder):
    """
    Dummy function as sensible default
    """
    treebuilder.options = get_default_options()

class Fasttree(TreeBuilder):

    def __init__(self, alignment, *args, **kwargs):
        self.options = get_default_options()
        super(Fasttree, self).__init__(alignment=alignment, *args, **kwargs)
        if self.input is not None:
            if self.datatype == DataType.DNA:
                set_default_dna_options(self)
            else:
                set_default_protein_options(self)

    def __call__(self, *args, **kwargs):
        """
        Sets up temporary output file location and calls FastTree using _call() function.
        Writes temporary input file if we're working with SeqIO object
        Saves the stdout and stderr and returns
        """
        start = time.time()  # time the execution
        if self.input_type == AlignmentInput.OBJECT:  # different operation depending on what it is
            with tempfile.NamedTemporaryFile(mode='wt') as fh:
                SeqIO.write(self.input, fh, 'phylip-relaxed') # default interleaved
                fh.seek(0)
                output, error = self._call(fh.name, *args, **kwargs)
                self.result = self._read_result(output, error)  # store result
        else:
            filename = os.path.abspath(self.input)
            output, error = self._call(filename, *args, **kwargs)
            self.result = self._read_result(output, error)  # store result

        end = time.time()
        self.elapsed_time = end - start
        return self.result["tree"]
        # End call

    # Any other accessory methods
    def _call(self, filename, *args, **kwargs):
        """
        Call underlying low level FastTree wrapper.
        Options are passed via *args and **kwargs
        [This only covers the simplest automatic
         case]
        """
        #hard code tmp_output as the output name since we don't save it anyway
        #self.cli('{} -log {log_output} {seqfile} > {tmp_path}'.format(self.command(), tmp_path=os.path.join(tmpd,'tmp_output'), log_output=logfile, seqfile=filename), wait=True)
        self.cli('{} {seq_file}'.format(self.command(), seq_file=filename), wait=True)

        return (self.cli.get_stdout(), self.cli.get_stderr())

    def command(self):
        return str(self.options)

    def _read_result(self, stdout, stderr):
        """
        Read back the result.
        """
        parser = FasttreeParser()

        try:
            parser.parse(tree=stdout, other=stderr)
            result = parser.to_dict()
        except IOError as ioerr:
            logger.error('Error reading results')
            result = None
        except ParseException as parseerr:
            logger.error('Other parse error', parseerr)
            result = None

        return result

    def _init_cli(self, binary):
        return FasttreeCLI(executable=binary)

def get_default_options():

    return OptionSet([
        # Algorithm

        # Set datatype to DNA (nt) or AA alignment: AA by default. If set to True will assume DNA format.
        StringOption('-nt', active=False),

        # Set the WAG model for AA alignment. Default Jones-Taylor-Thorton
        StringOption('-wag', active=False),

        # Set the GTR model for nt alignment. Default Jones-Taylor-Thorton
        StringOption('-gtr', active=False),

        # Set the gamma model. Default Jones-Taylor-Thorton
        StringOption('-gamma', active=False),

        # Specify the number of rate categories of sites. Default 20.
        IntegerOption('-cat', 20, active=False),

        # Specify starting tree
        StringOption('-intree', '', active=False),

        # Speed up the neighbor joining phase & reduce memory usage (recommended for >50,000 sequences)
        StringOption('-fastest', active=False),

        # Set the number of rounds of maximum-likelihood NNIs. Deafault 4*log2(N), N = the number of unique sequences
        IntegerOption('-mlnni', 0, active=False),

    ])


# Project Euler Problem 116

k = 50
def E_116(i, k):
    ways = [1] * i + [0] * (k-i+1)
    print(ways)
    for j in range(i, k+1):
        ways[j] += ways[j - 1] + ways[j - i]
    return ways[k] - 1
print("Number of black tiles =", k, "units")
print("Number of ways to fill:", E_116(2, k) + E_116(3, k) + E_116(4, k))