import os
from datetime import date, datetime
from shutil import copyfile
import json

class Reporting:

    def __init__(self, reports_root="../reports/"):

        self.reports_root = reports_root
        self.report_id = self.create_report_id()
        self.report_path = self.reports_root + self.report_id
        self.templates_root = os.path.abspath(self.reports_root + "../templates")
        try:
            os.mkdir(self.report_path)
            print("Successfully created the directory %s " % self.report_path)
        except OSError:
            print("Creation of the directory %s failed" % self.report_path)

        try:
            copyfile(self.templates_root + "/report_template.php", self.report_path + '/report.php')
        except:
            print("No report template created. Report data will still be saved. Continuing with tests...")

    def create_report_id(self):
        today = str(date.today())
        now = str(datetime.now()).split(" ")[1].split(".")[0].replace(":", "-")
        id = today + "-" + now
        return id

    def update_json_report(self, report_data):
        try:
            with open(self.report_path + '/report_data.json', 'w') as report_json_file:
                json.dump(report_data, report_json_file)
            report_json_file.close()
        except Exception as e:
            print(e)

def main():
    Reporting()

if __name__ == '__main__':
    main()


import datetime

def command_buy(event, user, line):
    return "Магазин закрыт на обед"

def command_help(event, user, line):
    return 'Помощь\nПерсонаж\nКупить'

class Character:

    def __init__(self, event):
        self.user_id = event.object.message["user_id"]
        #add SQL request

# main commander
def commander(event):

    commands = {
        'купить': command_buy,
        'помощь': command_help
    }

    output = "\n"

    lines = event.object.message["text"].split("\n")
    for line in lines:
        words = line.split(" ")
        if words[0] in commands:
            output += commands.get(words[0])() + "\n"

#    if peer_id == user_id:
#        group_status = 0 #личные сообщения
#    elif peer_id == 2000000001:
#        group_status = 1 #разрешённая группа
#    else:
#        group_status = 2 #запрещённая группа
#        return "Запрещённая группа"

    if output == "\n":
        output = "Команды не распознаны"
    return output


beatles=["John Lennon","Paul McCartney","George Harrison", "Ringo Starr"]
instrumentos=["guitarra rítmica e vocal","baixo, piano e vocal","guitarra solo e vocal","bateria e vocal"]

for cantor in beatles:
	print(cantor)

for instrumento in instrumentos:
	print(instrumento)

i=0
while i< len(beatles):
	print(beatles[i]+":"+instrumentos[i])
	i=i+1


import face_recognition
import cv2
import os

class know:
    def function(self):

        path1 = "E:/Project/known_people/"

        knownpics = []
        knownpic_face_encoding = []

        for filename in os.listdir(path1):
            if filename.endswith(".jpg"):
                knownpics.append(path1 + filename)

        for knownpic in knownpics:
            pic = face_recognition.load_image_file(knownpic)
            knownpic_face_encoding.append(face_recognition.face_encodings(pic)[0])

        return knownpics,knownpic_face_encoding
if __name__=="__main__":
    ob = know()
    ob.function()


# encoding:utf-8
"""
Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},
   1
    \
     2
    /
   3
return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?
===============================
后序遍历获得所有节点的值
即优先将右节点的值放入结果集
"""

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def postorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        temp = []
        res = []
        while root or temp:
            while root:
                res.insert(0, root.val)
                temp.append(root)
                root = root.right
            root = temp.pop()
            root = root.left
        return res


"""Main module."""
import tiff_stack_crop_tool.zStackUtils as zsu
import tiff_stack_crop_tool.selectinwindow as selectinwindow
import sys
import cv2
import math
import numpy as np
import tifffile
import os
sys.setrecursionlimit(10 ** 9)

stackDims = None
xProjDims = None

# Cropping globals for cv2 mouse callbacks
z0 = 0
z1 = 0
Z_CROPPING_WINDOW_ACTIVE_LEFT = False
Z_CROPPING_WINDOW_ACTIVE_RIGHT = False

def calc_z_crop_snap_value(x):

    # CROPPING CONFIG
    XY_CROP_SNAP_INCREMENT = float(1.0)
    Z_CROP_SNAP_INCREMENT = float(1.0)
    return int(math.ceil(x / Z_CROP_SNAP_INCREMENT)) * int(Z_CROP_SNAP_INCREMENT)

def click_and_z_crop(event, x, y, flags, param):

    global z0, z1, Z_CROPPING_WINDOW_ACTIVE_RIGHT, Z_CROPPING_WINDOW_ACTIVE_LEFT, xProjDims

    if event == cv2.EVENT_LBUTTONDOWN:

        temp = calc_z_crop_snap_value(y)

        if temp > xProjDims['y']:
            pass
        else:
            Z_CROPPING_WINDOW_ACTIVE_LEFT = True
            z0 = temp

    if event == cv2.EVENT_RBUTTONDOWN:

        temp = calc_z_crop_snap_value(y)

        if temp > xProjDims['y']:

            pass
        else:
            Z_CROPPING_WINDOW_ACTIVE_RIGHT = True
            z1 = temp

def select_cropping_colors():

    ZTextColor = (255, 255, 255)
    ZCropLineColor = (0, 255, 0)

    # Z crop conditions not OK
    if z0 >= z1:
        ZTextColor = (0, 0, 255)
        ZCropLineColor = (0, 0, 255)

    return [ZTextColor, ZCropLineColor]

def paint_cropping_text_z(xyProj, colors):

    bg_color = (0, 0, 0)

    bg = np.full((xyProj.shape), bg_color, dtype=np.uint8)
    cv2.putText(bg, "zSize=" + str(z1 - z0), (40, 50), cv2.FONT_HERSHEY_SIMPLEX, 2.0, colors[0], 4)
    x, y, w, h = cv2.boundingRect(bg[:, :, 2])
    xyProj[y:y + h + 10, x:x + w + 20] = bg[y:y + h + 10, x:x + w + 20]

def paint_cropping_line_lmb_z(xProj, colors, stackDims):

    cv2.line(xProj, (0, z0), (stackDims['x'] + stackDims['y'], z0), colors[1], 2)

def paint_cropping_line_rmb_z(xProj, colors, stackDims):

    cv2.line(xProj, (0, z1), (stackDims['x'] + stackDims['y'], z1), colors[1], 2)

def paint_cropping_overlays(xProj, colors, stackDims):

    if Z_CROPPING_WINDOW_ACTIVE_RIGHT:
        paint_cropping_line_rmb_z(xProj, colors, stackDims)

    if Z_CROPPING_WINDOW_ACTIVE_LEFT:
        paint_cropping_line_lmb_z(xProj, colors, stackDims)

    if Z_CROPPING_WINDOW_ACTIVE_LEFT and Z_CROPPING_WINDOW_ACTIVE_RIGHT:
        paint_cropping_text_z(xProj, colors)

def crop3D(scanFullPath, cropFullPath, maskFullPath=None, initW=0, initH=0):

    global stackDims, xProjDims

    print("\nLoading " + str(scanFullPath))
    scan = tifffile.imread(scanFullPath)
    zProj = zsu.save_and_reload_maxproj(scan)
    xProj = zsu.save_and_reload_maxproj_x(scan)
    yProj = zsu.save_and_reload_maxproj_y(scan)
    stackDims = zsu.gen_stack_dims_dict(scan)
    xProjDims = {'x': stackDims['y'], 'y': stackDims['z']}

    # Add mask if supplied
    if maskFullPath != None:

        print("\nLoading " + str(maskFullPath))
        mask = tifffile.imread(maskFullPath)
        zProjMask = zsu.save_and_reload_maxproj(mask)
        yProjMask = zsu.save_and_reload_maxproj_y(mask)
        xProjMask = zsu.save_and_reload_maxproj_x(mask)
        zProjMask = cv2.resize(zProjMask, (stackDims['x'], stackDims['y']), interpolation=cv2.INTER_CUBIC)
        yProjMask = cv2.resize(yProjMask, (stackDims['x'], stackDims['z']), interpolation=cv2.INTER_CUBIC)
        xProjMask = cv2.resize(xProjMask, (stackDims['y'], stackDims['z']), interpolation=cv2.INTER_CUBIC)

        zProj = cv2.addWeighted(zProj, 0.5, zProjMask, 0.5, 0.0)
        yProj = cv2.addWeighted(yProj, 0.5, yProjMask, 0.5, 0.0)
        xProj = cv2.addWeighted(xProj, 0.5, xProjMask, 0.5, 0.0)

    # MERGE X AND Y PROJECTIONS INTO 1 MAT
    xyProjPreAlloc = np.empty((stackDims['z'], stackDims['x'] + stackDims['y'], 3), dtype=np.uint8)
    xyProjPreAlloc[:, 0:stackDims['y'], :] = xProj
    xyProjPreAlloc[:, stackDims['y']:, :] = yProj
    xyProj = xyProjPreAlloc

    bg_color = (0, 0, 0)
    bg = np.full((xyProj.shape), bg_color, dtype=np.uint8)
    cv2.putText(bg, "X Projection", (int(stackDims['x'] / 2) - 500, 50), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), 4)
    x, y, w, h = cv2.boundingRect(bg[:, :, 2])
    xyProj[y:y + h + 10, x:x + w + 20] = bg[y:y + h + 10, x:x + w + 20]

    bg = np.full((xyProj.shape), bg_color, dtype=np.uint8)
    cv2.putText(bg, "Y Projection", (int(stackDims['x'] + (stackDims['y'] / 2)) - 500, 50), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), 4)
    x, y, w, h = cv2.boundingRect(bg[:, :, 2])
    xyProj[y:y + h + 10, x:x + w + 20] = bg[y:y + h + 10, x:x + w + 20]

    xyProjClone = xyProj.copy()

    # Cropping config
    CROP_WINDOW_Z_PROJ = "CROP_Z_PROJ"
    CROP_WINDOW_XY_PROJ = "CROP_XY_PROJ"
    cv2.namedWindow(CROP_WINDOW_XY_PROJ, cv2.WINDOW_NORMAL)
    cv2.moveWindow(CROP_WINDOW_XY_PROJ, 0, 0)

    cv2.resizeWindow(CROP_WINDOW_XY_PROJ, 1920, 1080)
    cv2.setMouseCallback(CROP_WINDOW_XY_PROJ, click_and_z_crop)
    print("Cropping " + str(scanFullPath))
    while True:

        # Render the cropping overlays for next frames
        colors = select_cropping_colors()
        paint_cropping_overlays(xyProj, colors, stackDims)

        # Display the frames with cropping overlays
        cv2.imshow(CROP_WINDOW_XY_PROJ, xyProj)
        key = cv2.waitKey(1) & 0xFF

        # Wipe the overlay so next overlay draw has fresh frame
        xyProj = xyProjClone.copy()

        # Check for user keyboard action
        if key == ord("c"):

            # Check cropping coordinates to make sure they make sense.
            if z0 >= z1:
                print("Z Crop Error: Bottom cannot be above Top. Try again.")
                continue
            else:
                cv2.destroyWindow(CROP_WINDOW_XY_PROJ)
                break

    # XY Cropping
    rectI = selectinwindow.dragRect
    selectinwindow.init(rectI, zProj, CROP_WINDOW_Z_PROJ, stackDims['x'], stackDims['y'], initW, initH)
    cv2.namedWindow(CROP_WINDOW_Z_PROJ, cv2.WINDOW_NORMAL)
    cv2.moveWindow(CROP_WINDOW_Z_PROJ, 0, 0)

    # figure out dimensions of XY_PROJ
    print(zProj.shape)
    zProj_yDim = zProj.shape[0]
    zProj_xDim = zProj.shape[1]
    scalingMultiple = math.ceil(zProj_yDim / 1080)
    windowY = math.ceil(zProj_yDim / scalingMultiple)
    windowX = math.ceil(zProj_xDim / scalingMultiple)

    cv2.resizeWindow(CROP_WINDOW_Z_PROJ, windowX, windowY)
    cv2.setMouseCallback(CROP_WINDOW_Z_PROJ, selectinwindow.dragrect, rectI)
    cv2.imshow(CROP_WINDOW_Z_PROJ, zProj)
    cv2.waitKey(0)
    x = rectI.outRect.x
    y = rectI.outRect.y
    w = rectI.outRect.w
    h = rectI.outRect.h

    # TODO: Insert draggable ROI box coords here
    croppedStack = scan[z0:z1, y:y+h, x:x+w]
    croppedStackDims = zsu.gen_stack_dims_dict(croppedStack)
    tifffile.imwrite(cropFullPath, croppedStack)
    zsu.print_crop_dims(croppedStackDims)
    return croppedStack

def get_scan_paths(scansDir):

    if not os.path.isdir(scansDir):
        print(scansDir + " does not exist. Exiting.")
        exit()

    scanPaths = os.listdir(path=scansDir)
    for scanPath in scanPaths:
        if os.path.isfile(scansDir + "\\" + scanPath) and scanPath[-4:] == '.tif':
            continue
        else:
            scanPaths.remove(scanPath)

    return scanPaths

# Returns None if no mask directory was provided by CLI interface.
def get_mask_paths(args):

    maskPaths = None

    if 'MASKS_DIR' in args:

        masksDir = args.get('MASKS_DIR')

        if os.path.isdir(masksDir):
            maskPaths = os.listdir(path=masksDir)

            for maskPath in maskPaths:
                if os.path.isfile(masksDir + "\\" + maskPath) and maskPath[-4:] == '.tif':
                    continue
                else:
                    maskPaths.remove(maskPath)

    return maskPaths

def crop_all_stacks(args):

    scansDir = args.get('SCANS_DIR')
    scanPaths = get_scan_paths(scansDir)
    maskPaths = get_mask_paths(args)

    for i in range(0, len(scanPaths)):

        scanFullPath = scansDir + "\\" + scanPaths[i]
        croppedFullPath = scansDir + "\\" + scanPaths[i][:-4] + "_cropped.tif"

        if maskPaths != None:

            masksDir = args.get('MASKS_DIR')
            maskFullPath = masksDir + "\\" + scanPaths[i][:-4] + "_stroke_mask.tif"

            if not os.path.isfile(maskFullPath):
                print("No file was found at " + maskFullPath + " . Exiting.")
                exit(0)

            initW = int(args.get('INIT_W'))
            initH = int(args.get('INIT_H'))
            if initW >=0 and initH >= 0:
                crop3D(scanFullPath, croppedFullPath, maskFullPath, initW=initW, initH=initH)
            else:
                print("One or both of the following values are invalid: --W, --H.")
                exit(0)

        else:
            crop3D(scanFullPath, croppedFullPath, initW=initW, initH=initH)


"""
Tests for simulating a real-time client.
"""

import unittest
import time
import logging

from obspy import UTCDateTime
from obspy.clients.fdsn import Client

from rt_eqcorrscan.streaming.clients.obspy import RealTimeClient, StreamClient

SLEEP_STEP = 20

logging.basicConfig(
    level="INFO",
    format="%(asctime)s\t[%(processName)s:%(threadName)s]: %(name)s\t%(levelname)s\t%(message)s")

class TestStreamBuffer(unittest.TestCase):
    def test_maintain(self):
        client = Client("GEONET")
        buffer = StreamClient(client=client, buffer_length=60, min_buffer_fraction=0.25)
        buffer.initiate_buffer(["NZ.WVZ.10.HHZ", "NZ.RPZ.10.HHZ"], UTCDateTime(2020, 1, 1))
        time.sleep(1)
        initial_stream = buffer.stream
        print(f"Initialised buffer as: \n{initial_stream}")
        buffer.maintain_buffer()
        st = buffer.get_waveforms_bulk(
            [("NZ", "WVZ", "10", "HHZ",
              UTCDateTime(2020, 1, 1), UTCDateTime(2020, 1, 1, 0, 0, 6)),
             ("NZ", "RPZ", "10", "HHZ",
              UTCDateTime(2020, 1, 1), UTCDateTime(2020, 1, 1, 0, 0, 6))])
        self.assertEqual(len(st), 2)
        trimmed_stream = buffer.stream
        print(f"Cut out first 6 seconds to give buffer: \n{trimmed_stream}")
        self.assertLess(trimmed_stream[0].stats.npts, initial_stream[0].stats.npts)
        # remove more than 75% of buffer
        st2 = buffer.get_waveforms_bulk(
            [("NZ", "WVZ", "10", "HHZ",
              UTCDateTime(2020, 1, 1), UTCDateTime(2020, 1, 1, 0, 0, 50)),
             ("NZ", "RPZ", "10", "HHZ",
              UTCDateTime(2020, 1, 1), UTCDateTime(2020, 1, 1, 0, 0, 50))])
        self.assertEqual(len(st), 2)
        print("Sleeping to allow buffer to refill")
        time.sleep(20)  # Sleep for more than half the min buffer fraction
        out_buffer = buffer.stream
        for tr in out_buffer:
            self.assertGreaterEqual(tr.stats.endtime - tr.stats.starttime, 60)
        buffer.background_stop()

class FDSNTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.client = Client("GEONET")
        cls.buffer = StreamClient(
            client=cls.client, buffer_length=60, min_buffer_fraction=0.25)
        cls.rt_client = RealTimeClient(
            server_url="Unreal-streamer",
            client=cls.buffer, buffer_capacity=10,
            starttime=UTCDateTime(2018, 1, 1), speed_up=2., query_interval=5.,
            pre_empt_data=True)

    def test_background_streaming(self):
        rt_client = self.rt_client.copy()
        rt_client.select_stream(net="NZ", station="JCZ", selector="HHZ")
        rt_client.select_stream(net="NZ", station="RPZ", selector="HHZ")
        rt_client.background_run()
        try:
            self.assertFalse(rt_client.buffer_full)
        except Exception as e:
            rt_client.background_stop()
            raise e
        print(f"Sleeping for {SLEEP_STEP}s")
        time.sleep(SLEEP_STEP)
        print("Stopping buffer")
        rt_client.background_stop()
        print("Running checks")
        self.assertTrue(rt_client.buffer_full)
        self.assertEqual(rt_client.buffer_length,
                         rt_client.buffer_capacity)

    def test_always_started(self):
        rt_client = self.rt_client.copy()
        rt_client.start()
        self.assertTrue(rt_client.started)
        rt_client.stop()
        self.assertFalse(rt_client.started)

    def test_can_add_streams(self):
        self.assertTrue(self.rt_client.can_add_streams)

    # def test_copy_with_buffer(self):
    #     rt_client = self.rt_client.copy()
    #     rt_client.select_stream(net="NZ", station="FOZ", selector="HHZ")
    #     rt_client.background_run()
    #     time.sleep(SLEEP_STEP)
    #     rt_client.background_stop()
    #     new_client = rt_client.copy(empty_buffer=False)
    #     new_client.select_stream(net="NZ", station="FOZ", selector="HHZ")
    #     self.assertEqual(new_client.get_stream(), rt_client.stream)
    #     new_client.background_run()
    #     time.sleep(SLEEP_STEP * 2)
    #     new_client.background_stop()
    #     # Make sure that we don't change the old buffer.
    #     self.assertNotEqual(new_client.get_stream(), rt_client.stream)

    def test_reprint(self):
        print_str = self.rt_client.__repr__()
        self.assertEqual(print_str, "Client at http://service.geonet.org.nz, "
                                    "status: Stopped, buffer capacity: 10.0s\n	"
                                    "Current Buffer:\nBuffer(0 traces, "
                                    "maxlen=10)")

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


# LIBTBX_PRE_DISPATCHER_INCLUDE_SH export PHENIX_GUI_ENVIRONMENT=1

from __future__ import annotations

from dials.algorithms.shoebox import MaskCode
from dials.array_family import flex
from dials.viewer.slice_viewer import show_3d

if __name__ == "__main__":
    lst_flex = []
    lst_flex_norm = []

    for size_xyz in range(8, 6, -1):

        size_x = size_xyz * 2

        data_xyz_flex = flex.double(flex.grid(size_xyz, size_xyz, size_x), 15)
        data_flex_norm = flex.double(flex.grid(size_xyz, size_xyz, size_x), 15)
        data_flex_mask = flex.int(flex.grid(size_xyz, size_xyz, size_x), 0)

        tot = 0.0
        for frm in range(size_xyz):
            for row in range(size_xyz):
                for col in range(size_x):
                    data_xyz_flex[frm, row, col] += row * 2 + col * 2 + frm * 2
                    tot += data_xyz_flex[frm, row, col]
                    if row > 1 and row < size_xyz - 2 and col > 1 and col < size_x - 2:
                        data_flex_mask[frm, row, col] = MaskCode.Foreground

                        different_mask_values = """
            MaskCode.Valid           =  "\\\\\\"
            MaskCode.Foreground      =  "//////"
            MaskCode.Background      =  "||||||"
            MaskCode.BackgroundUsed  =  "------"
            """

        for frm in range(size_xyz):
            for row in range(size_xyz):
                for col in range(size_x):
                    data_flex_norm[frm, row, col] += data_xyz_flex[frm, row, col] / tot

        lst_flex.append(data_xyz_flex)
        lst_flex_norm.append(data_flex_norm)

    show_3d(data_xyz_flex, data_flex_mask)
    show_3d(data_xyz_flex)
    show_3d(lst_flex)
    show_3d(lst_flex_norm)
    print("Test Done")


import os
import json

image_path = "images/"  # Replace with the actual path to your image directory

jpeg_files = [f for f in os.listdir(image_path) if f.endswith(".jpg") or f.endswith(".jpeg")]
sorted_files = sorted(jpeg_files)

with open(f"{image_path}/filelist.json", "w") as file:
    json.dump(sorted_files, file)


"""
Module directories
"""
import os

class Directories:
    """
    Class Directories: Preparing directories
    """

    def __init__(self, var):
        """
        The constructor

        :param var: A dot map of parameters
        """

        self.var = var

    def cleanup(self):
        """
        Clears the directories for archived & de-archived data

        :return: None
        """

        # Foremost, delete files
        for path in [self.var.data]:
            files_ = [os.remove(os.path.join(base, file))
                      for base, _, files in os.walk(path) for file in files]

            if any(files_):
                raise Exception('Unable to delete all files within path {}'.format(path))

        # ... then, directories
        for path in [self.var.data]:
            directories_ = [os.removedirs(os.path.join(base, directory))
                            for base, directories, _ in os.walk(path, topdown=False) for directory in directories
                            if os.path.exists(os.path.join(base, directory))]

            if any(directories_):
                raise Exception('Unable to delete all directories within path {}'.format(path))

    def paths(self):
        """
        Creates directories for (a) archived files, (b) de-archived files

        :return: None
        """

        for path in [self.var.data]:
            if not os.path.exists(path):
                os.makedirs(path)

    def exc(self):
        """
        Entry point
        :return:
        """

        self.cleanup()
        self.paths()


class Solution:
    def groupStrings(self, strings):
        """
        :type strings: List[str]
        :rtype: List[List[str]]
        """
        groups = collections.defaultdict(list)
        for s in strings:
            groups[self.hashStr(s)].append(s)

        res = []
        for k, v in groups.iteritems():
            res.append(sorted(v))

        return res

    def hashStr(self, s):
        base = ord(s[0])
        hashcode = ""
        for i in range(len(s)):
            if ord(s[i]) - base >= 0:
                hashcode += unichr(ord('a') + ord(s[i]) - base)
            else:
                hashcode += unichr(ord('a') + ord(s[i]) - base + 26)
        return hashcode


# coding: latin-1

# para executar no google colab:
# https://colab.research.google.com/drive/1aEJctvuwbCDZs2YTFtXa-27FHQ3hzwdr?usp=sharing

from math import e, sin, log, sqrt

class MetodoSecante:
    def __init__(self, X0, X1, numCasasDecimais, precisao_1, precisao_2=None):
        self.X0 = X0
        self.X1 = X1
        self.precisao_1 = precisao_1
        self.precisao_2 = precisao_2 if precisao_2 != None else precisao_1
        self.numCasasDecimais = numCasasDecimais

    def funcao(self,x):
        return 4*sin(x)-e**x

    def funcaoMetodo(self,Xn, Xn2):
        return (Xn * self.funcao(Xn2) - Xn2 * self.funcao(Xn)) / (self.funcao(Xn2) - self.funcao(Xn))

    def metodoSecante(self):
        primeiro = True
        Xn = round(self.X0, self.numCasasDecimais)
        Xn2 = round(self.X1, self.numCasasDecimais)
        iteracao = 1

        print("Iteração" , " " * (self.qtdEspacos("Iteração")) , "Xn" , " " * ((self.qtdEspacos("Xn"))) ,
              "|Xn - Xn-1|" , " " * (18) , "|f(Xn)|", sep="")

        while abs(self.funcao(Xn)) > self.precisao_2:

            if primeiro:
                Xn = round(self.funcaoMetodo(Xn,Xn2), self.numCasasDecimais)
                primeiro = False
                continue

            if abs(Xn - Xn2) < self.precisao_1:
                break

            if iteracao == 50:
                print("O limite de iterações foi atingido!")
                break

            print(str(iteracao) , " " * self.qtdEspacos(iteracao)  , str(Xn) , " " * self.qtdEspacos(Xn) ,
                  str(abs(Xn-Xn2)) , " " * (30 - self.qtdCaracteres(abs(Xn-Xn2))) , str(abs(self.funcao(Xn))), sep="")
            xAux = Xn
            Xn = round(self.funcaoMetodo(Xn,Xn2), self.numCasasDecimais)
            Xn2 = xAux
            iteracao += 1

        print(str(iteracao) , " " * self.qtdEspacos(iteracao)  , str(Xn) , " " * self.qtdEspacos(Xn) , str(abs(Xn-Xn2)) ,
              " " * (30 - self.qtdCaracteres(abs(Xn-Xn2))) , str(abs(self.funcao(Xn))), sep="")

    def qtdCaracteres(self,num):
        num = str(num)
        return len(num)

    def qtdEspacos(self, num):
        num = str(num)
        return self.numCasasDecimais * 2 - len(num) + 5

x = MetodoSecante(0,1, 9, 10**-5)

x.metodoSecante()


import sqlite3
import settings
import discord
from utils import logger

conn = sqlite3.connect(settings.SQL_DB)
cursor = conn.cursor()
conn.commit()

async def create_leaderboard_embed(ctx):
    logger.info("IN create leaderboard")

    cursor = conn.cursor()
    cursor.execute("SELECT title, user_id, upvotes, downvotes, keywords, author, cover, pageCount FROM suggested_books ORDER BY (upvotes - downvotes) DESC")
    suggested_books = cursor.fetchall()

    if suggested_books:
        embed = discord.Embed(title="Vote Results", color=discord.Color.gold())
        details = ""
        first_place_points = suggested_books[0][2] - suggested_books[0][3]
        next_placement = 0
        pin_thumbnail = False  # Track if we should pin the thumbnail

        for i, (title, user_id, upvotes, downvotes, keywords, author, cover, pageCount) in enumerate(suggested_books):
            user = ctx.bot.get_user(user_id)
            if user is not None:
                user_name = user.name
            else:
                user_name = "Unknown User"

            # Determine medal
            score = upvotes - downvotes
            # medal = "ðŸ¥‡" if score == first_place_points else (next_placement if score == previous_score else (i+1))

            if score == first_place_points:
                medal = "ðŸ¥‡"
            elif score == previous_score:
                medal = next_placement
            else:
                # medal = (i+1)

                if (i+1) == 2:
                    medal = "2nd"
                elif (i+1) == 3:
                    medal = "3rd"
                else:
                    medal = f"{(i+1)}th"
                next_placement = medal

            # if score != first_place_points and score != previous_score:
            #     next_placement += 1  # Increment the placement for ties in the score
            details += f"{medal} **{title}**\n *{author}* \n" \
                       f"**Total Points**: *{upvotes-downvotes}*\n" \
                       f"**Page Count**: {pageCount}\n" \
                       f"**Suggested By**: {user_name}\n\n"

            previous_score = score

            # If it's the first place suggestion, add the cover as an inline image
            if medal == "ðŸ¥‡" and cover and not pin_thumbnail:
                embed.set_thumbnail(url=cover)
                pin_thumbnail = True  # Set to True after the first-place suggestion's image is added

        # Set the details in the embed's description
        embed.description = details

        return embed
    else:
        return None


#  Solve an MIP with block structure using the BNP solver.
#
#  The problem:
#
#      Minimize x1 + x2 + x3 + x4 + x5 + x6
#      s.t.
#               [r1]x1 + x2 + x3 + x4 + x5 + x6  >=3; !block 0 - linking constraint;
#               [r2]x1 + x2                      <=1; !block 1;
#               [r3]     x2 + x3                 <=1; !block 1;
#               [r4]               x4 + x5 + x6  <=2; !block 2;
#               [r5]               x4 +      x6  <=1; !block 2;
#
#               x1,x2,x3,x4,x5,x6 are binary variables

from pyLindo import *
import os
#model data
nCons = 5
nVars = 6
nDir = 1
dObjConst = 0.0
adC = N.array([1.,1.,1.,1.,1.,1.],dtype=N.double)
adB = N.array([3.0,1.0,1.0,2.0,1.0],dtype=N.double)
acConTypes = N.array(['G','L','L','L','L'],dtype=N.character)
nNZ = 15;
anBegCol = N.array([0,2,5,7,10,12,15],dtype=N.int32)
pnLenCol = N.asarray(None)
adA = N.array([1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0],dtype=N.double)
anRowX = N.array([0,1,0,1,2,0,2,0,3,4,0,3,0,3,4],dtype=N.int32)
pdLower = N.array([0,0,0,0,0,0],dtype=N.double)
pdUpper = N.array([1.,1.,1.,1.,1.,1.],dtype=N.double)
pachVarType = N.array(['B','B','B','B','B','B'],dtype=N.character)

#create LINDO environment and model objects
LicenseKey = N.array('',dtype='S1024')
lindo.pyLSloadLicenseString(os.getenv('LINDOAPI_HOME')+'/license/lndapi130.lic',LicenseKey)
pnErrorCode = N.array([-1],dtype=N.int32)
pEnv = lindo.pyLScreateEnv(pnErrorCode,LicenseKey)

pModel = lindo.pyLScreateModel(pEnv,pnErrorCode)
geterrormessage(pEnv,pnErrorCode[0])

#load data into the model
print("Loading LP data...")
errorcode = lindo.pyLSloadLPData(pModel,nCons,nVars,nDir,
                                 dObjConst,adC,adB,acConTypes,nNZ,anBegCol,
                                 pnLenCol,adA,anRowX,pdLower,pdUpper)
geterrormessage(pEnv,errorcode)

errorcode = lindo.pyLSloadVarType(pModel,pachVarType)

#load block structure
panRblock = N.array([0,1,1,2,2],dtype=N.int32)
panCblock = N.array([1,1,1,2,2,2],dtype=N.int32)
nBlock = 2
nType = LSconst.LS_LINK_BLOCKS_FREE
errorcode = lindo.pyLSloadBlockStructure(pModel,
                                         nBlock + 1,
                                         panRblock,
                                         panCblock,
                                         nType)
geterrormessage(pEnv,errorcode)

#set the method for finding block
nMethod = 5
errorcode = lindo.pyLSsetModelIntParameter(pModel,
                                           LSconst.LS_IPARAM_BNP_FIND_BLK,
                                           nMethod)
geterrormessage(pEnv,errorcode)

#solve the model using BNP
print("\nSolving the model...")
pnStatus = N.array([-1],dtype=N.int32)
errorcode = lindo.pyLSsolveMipBnp(pModel,nBlock,"ddd",pnStatus)
geterrormessage(pEnv,errorcode)

#retrieve the objective value
dObj = N.array([-1.0],dtype=N.double)
errorcode = lindo.pyLSgetInfo(pModel,LSconst.LS_DINFO_MIP_OBJ,dObj)
geterrormessage(pEnv,errorcode)
print("Objective is: %.5f" %dObj[0])
print("")

#retrieve the primal solution
padPrimal = N.empty((nVars),dtype=N.double)
errorcode = lindo.pyLSgetMIPPrimalSolution(pModel,padPrimal)
geterrormessage(pEnv,errorcode)
print("Primal solution is: ")
for x in padPrimal: print("%.5f" % x)

#delete LINDO model pointer
errorcode = lindo.pyLSdeleteModel(pModel)
geterrormessage(pEnv,errorcode)

#delete LINDO environment pointer
errorcode = lindo.pyLSdeleteEnv(pEnv)
geterrormessage(pEnv,errorcode)


import Genetic_Algoritm
import Display
import files

def print_population(population):
    schedules = population.get_chromosomes()

    x = str(round(schedules[0].get_fitness(), 3)) + " " + str(schedules[0].get_numberOfConflicts()) + " " + str(
        print_group(schedules[0].get_classes()))

    print(x)

def print_group(table):
    x = "[ "
    a = 0

    for i in range(len(table) - 1):
        x = x + str(table[i]) + ", "
        a = i + 1

    x = x + str(table[a]) + " ]"

    return x

class Configuration:

    def __init__(self):
        self.classrooms = []
        self.teachers = []
        self.groups = []
        self.time = ['mon1', 'mon2', 'mon3', 'mon4', 'mon5', 'mon6', 'mon7', 'mon8',
                     'tue1', 'tue2', 'tue3', 'tue4', 'tue5', 'tue6', 'tue7', 'tue8',
                     'wed1', 'wed2', 'wed3', 'wed4', 'wed5', 'wed6', 'wed7', 'wed8',
                     'thu1', 'thu2', 'thu3', 'thu4', 'thu5', 'thu6', 'thu7', 'thu8',
                     'fri1', 'fri2', 'fri3', 'fri4', 'fri5', 'fri6', 'fri7', 'fri8']

        self.time_hasmap = {
            'mon1': 'Monday\n8:00-8:45', 'mon2': 'Monday\n9:00-9:45', 'mon3': 'Monday\n10:00-10:45',
            'mon4': 'Monday\n11:00-11:45', 'mon5': 'Monday\n12:00-12:45', 'mon6': 'Monday\n13:00-13:45',
            'mon7': 'Monday\n14:00-14:45', 'mon8': 'Monday\n15:00-15:45',
            'tue1': 'Tuesday\n8:00-8:45', 'tue2': 'Tuesday\n9:00-9:45', 'tue3': 'Tuesday\n10:00-10:45',
            'tue4': 'Tuesday\n11:00-11:45', 'tue5': 'Tuesday\n12:00-12:45', 'tue6': 'Tuesday\n13:00-13:45',
            'tue7': 'Tuesday\n14:00-14:45', 'tue8': 'Tuesday\n15:00-15:45',
            'wed1': 'Wednesday\n8:00-8:45', 'wed2': 'Wednesday\n9:00-9:45', 'wed3': 'Wednesday\n10:00-10:45',
            'wed4': 'Wednesday\n11:00-11:45', 'wed5': 'Wednesday\n12:00-12:45', 'wed6': 'Wednesday\n13:00-13:45',
            'wed7': 'Wednesday\n14:00-14:45', 'wed8': 'Wednesday\n15:00-15:45',
            'thu1': 'Thursday\n8:00-8:45', 'thu2': 'Thursday\n9:00-9:45', 'thu3': 'Thursday\n10:00-10:45',
            'thu4': 'Thursday\n11:00-11:45', 'thu5': 'Thursday\n12:00-12:45', 'thu6': 'Thursday\n13:00-13:45',
            'thu7': 'Thursday\n14:00-14:45', 'thu8': 'Thursday\n15:00-15:45',
            'fri1': 'Friday\n8:00-8:45', 'fri2': 'Friday\n9:00-9:45', 'fri3': 'Friday\n10:00-10:45',
            'fri4': 'Friday\n11:00-11:45', 'fri5': 'Friday\n12:00-12:45', 'fri6': 'Friday\n13:00-13:45',
            'fri7': 'Friday\n14:00-14:45', 'fri8': 'Friday\n15:00-15:45'
        }

        self.subjects = [
            ['math', 5], ['ang', 3], ['history', 3], ['polish', 4], ['IT', 3], ['Physic', 3]
        ]

        self.subject_hasmap_tab = {
            'math': 0, 'ang': 1, 'history': 2, 'polish': 3, 'IT': 4, 'Physic': 5
        }

        self.classrooms = files.rooms_tab()
        self.teachers = files.teacher_tab()
        self.groups = files.groups_tab()

    def get_time(self):
        return self.time

    def get_group_hashmap(self):
        hashmap = {}

        for i in range(len(self.groups)):
            hashmap[self.groups[i]] = i

        return hashmap

    def get_time_hasmap(self):
        hashmap = {}

        for i in range(len(self.time)):
            hashmap[self.time[i]] = i

        return hashmap

    def get_reverse_time_hasmap(self):
        hashmap = {}

        for i in range(len(self.time)):
            hashmap[i] = self.time[i]

        return hashmap

    def get_subject_for_fitness(self):
        tab = []

        for i in range(len(self.subjects)):
            tab.append(self.subjects[i][1])

        return tab

    def get_time_hasmap_to_string(self):
        return self.time_hasmap

data = Configuration()

x = input("Do you want to use default param? [Y,N]")

mutation_ratio = 0.01
population_size = 50
no_elite_chromosomes = 1

if x == "N":
    print("Input values")
    mutation_ratio = input("mutation_ratio: ")
    population_size = input("population_size: ")
    no_elite_chromosomes = input("no_elite_chromosomes: ")

genetic = Genetic_Algoritm.GA(mutation_ratio=0.01, population_size=50, no_elite_chromosomes=1, data=data)

best_table = genetic.get_best_table()

Display.display_table(groups=data.groups, time=data.time, tab_schedule=best_table, group_hashmap=data.get_group_hashmap(),
                      time_hasmap=data.get_time_hasmap(), time_hasmap_to_string=data.get_time_hasmap_to_string())


import pygame as pg
from settings import *
from menu import Menu
from colorpalette import *

class Game:
    def __init__(self):
        pg.init()
        self.screen = pg.display.set_mode((Width, Height))
        pg.display.set_caption('Menu')
        self.rgb = RGBColors()
        self.clock = pg.time.Clock()
        self.frameRate = frameRate
        self.frameCounter = 0
        self.running = True
        self.loadAssets()

    def loadAssets(self):
        self.all_sprites = pg.sprite.LayeredUpdates()
        self.Menu = Menu(self)
        self.Menu.Items.items = ['item1','item2','item3','VeryNiceMenu!']

    def events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.running = False
            if event.type == pg.KEYDOWN and event.key == pg.K_DOWN:
                self.Menu.Cursor.down()
            if event.type == pg.KEYDOWN and event.key == pg.K_UP:
                self.Menu.Cursor.up()
            if event.type == pg.KEYDOWN and event.key == pg.K_SPACE:
                self.Menu.Cursor.select()

    def update(self):
        self.all_sprites.update()

    def draw(self):
        self.screen.fill(self.rgb.black)
        self.all_sprites.draw(self.screen)
        self.Menu.Items.draw()

    def run(self):
        while self.running:
            self.frameCounter += 1
            self.clock.tick(self.frameRate)
            self.events()
            self.update()
            self.draw()
            pg.display.flip()
            if self.frameCounter == self.frameRate:
                self.frameCounter = 0

g = Game()
while g.running:
    g.run()
pg.quit()


# $Id: utils_tags.py,v 1.1 2013-06-30 17:08:56-07 dmf - $
# Derek Frank
#
# NAME
#   utils_tags.py - utils
#
# DESCRIPTION
#   Custom template tags and filters.
#

from django import template
register = template.Library()

####
## TAGS

# djangosnippets.org/snippets/2196/
@register.tag
def collect(parser, token):
    bits = list(token.split_contents())
    if len(bits) > 3 and bits[-2] == 'as':
        varname = bits[-1]
        items = bits[1:-2]
        return CollectNode(items, varname)
    else:
        raise template.TemplateSyntaxError('%r expected format is "item [item ...] as varname"' % bits[0])

class CollectNode(template.Node):
    def __init__(self, items, varname):
        self.items = map(template.Variable, items)
        self.varname = varname

    def render(self, context):
        context[self.varname] = [ i.resolve(context) for i in self.items ]
        return ''


from setuptools import setup, find_packages

classifiers = [
  'Development Status :: 5 - Production/Stable',
  'Intended Audience :: Education',
  'Operating System :: Ubuntu',
  'License :: OSI Approved :: MIT License',
  'Programming Language :: Python :: 3'
]

setup(
  name='ZAPZAPPY',
  version='0.0.1',
  description='zapzappy is a simple Whatsapp API',
  long_description=open('README.txt').read() + '\n\n' + open('CHANGELOG.txt').read(),
  url='',
  author='Lucas Ribeiro',
  author_email='Lucas Ribeiro',
  license='MIT',
  classifiers=classifiers,
  keywords='Whatsapp API',
  packages=find_packages(),
  install_requires=['']
)


# boj 17086 아기상어2
from collections import deque

n, m = map(int, input().split())
graph = []
queue = deque()
dx = [1, -1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, 1, -1, -1]
for i in range(n):
    input_data = list(map(int, input().split()))
    for j in range(m):
        if input_data[j] == 1:
            queue.append((i, j))
    graph.append(input_data)

def bfs():
    max_dist = 0
    while queue:
        x, y = queue.popleft()
        for i in range(8):
            nx = x+dx[i]
            ny = y+dy[i]
            if nx < 0 or ny < 0 or nx >=n or ny >= m:
                continue
            if graph[nx][ny] == 0:
                graph[nx][ny] = graph[x][y]+1
                queue.append((nx, ny))
    for i in range(n):
        for j in range(m):
            max_dist = max(max_dist, graph[i][j])
    return max_dist-1

print(bfs())


# 导入必要的软件包
import cv2

# 视频文件输入初始化
filename = "E:\JJ\Download\p1.mp4"
camera = cv2.VideoCapture(filename)
#camera = cv2.VideoCapture(0)

# 视频文件输出参数设置
out_fps = 10.0  # 输出文件的帧率
fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', '2')
out1 = cv2.VideoWriter('E:/video/v1.avi', fourcc, out_fps, (500, 400))
#out2 = cv2.VideoWriter('E:/video/v2.avi', fourcc, out_fps, (500, 400))

# 初始化当前帧的前帧
lastFrame = None

# 遍历视频的每一帧
while camera.isOpened():

    # 读取下一帧
    (ret, frame) = camera.read()

    # 如果不能抓取到一帧，说明我们到了视频的结尾
    if not ret:
        break

        # 调整该帧的大小
    frame = cv2.resize(frame, (500, 400), interpolation=cv2.INTER_CUBIC)

    # 如果第一帧是None，对其进行初始化
    if lastFrame is None:
        lastFrame = frame
        continue

        # 计算当前帧和前帧的不同
    frameDelta = cv2.absdiff(lastFrame, frame)

    # 当前帧设置为下一帧的前帧
    lastFrame = frame.copy()

    # 结果转为灰度图
    thresh = cv2.cvtColor(frameDelta, cv2.COLOR_BGR2GRAY)

    # 图像二值化
    thresh = cv2.threshold(thresh, 25, 255, cv2.THRESH_BINARY)[1]

    '''
    #去除图像噪声,先腐蚀再膨胀(形态学开运算)
    thresh=cv2.erode(thresh,None,iterations=1)
    thresh = cv2.dilate(thresh, None, iterations=2)
    '''

    # 阀值图像上的轮廓位置
    binary, cnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 遍历轮廓
    for c in cnts:
        # 忽略小轮廓,排除大轮廓，排除误差
        if cv2.contourArea(c) < 300 or cv2.contourArea(c)>1000:
            continue

            # 计算轮廓的边界框，在当前帧中画出该框
        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

        # 显示当前帧
    cv2.imshow("frame", frame)
    cv2.imwrite('frame.png', frame)
    cv2.imshow("frameDelta", frameDelta)
    cv2.imwrite('frameDelta.png', frameDelta)
    cv2.imshow("thresh", thresh)
    cv2.imwrite('thresh.png', thresh)

    # 保存视频
    out1.write(frame)
    #out2.write(frameDelta)

    # 如果q键被按下，跳出循环
    if cv2.waitKey(200) & 0xFF == ord('q'):
        break

        # 清理资源并关闭打开的窗口
out1.release()
out2.release()
camera.release()
cv2.destroyAllWindows()


# client side
import socket
import sys
import random
from random import randint
import time

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def connect_server( message, server_ip,sock):
    global num_success
    global num_unsuccessfull
    global nack
    global num_false
    #connect the socket to the port where the server is listening to
    server_address = (server_ip, 10000)
    #sock.connect(server_address)
    print('client is now connecting to the port {server}' .format(server = server_address))
    try:
        # random model to ask put and get request from the server.. the client can know whether the server has it locally or not ... it can tell the server client 3 has it
        # Send data
        #message = 'MessageFromApplication.'+' ' +  message
        print('Sending the data from application """ {data}'.format(data=message))
        try:
            sock.sendall(message.encode())
        except:
            sock =socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect(server_address)
            print('this is reconnection because of a broken pipeline')
            sock.sendall(message.encode())
            print('data has been sent after reconnection')
        # here we receive message back from the server which tells us whether the operation was done successfully or not then we calculate the performance
        #amount_expected = len(message) # I will get true or false and then count the number of true as successful and False as unsuccessful
        data = sock.recv(1024).decode('utf-8')
        print('Receiving the result from server ::: {data} '.format(data=data))
        if data == 'True':
            num_success = num_success+1
        if data == 'Nack':
            nack = nack + 1
            return 'Nack'
        if data == "None":
            num_unsuccessfull = num_unsuccessfull +1
            #print('The process was not done')

        if data== 'False':
            num_false = num_false +1

    finally:
        0
        #print('closing socket in client side')
        print('')
        #sock.close()
    return # end of function connect_server

# the main function goes here ...
# Initialize the variables ..
# Update this part by reading this information from the property file
number_operations = 1000 # do them in a for loop after doing for one operation
num_success=0
num_unsuccessfull=0
num_false =0
nack = 0
start_time = time.time()
#ips ...
#remove
# server_ip_mac_mini = '128.180.220.113' #university
# #server_ip_mac_mini = '192.168.1.8' #at home
# server_ip_mac_book = '128.180.204.171'
# #server_ip_mac_book = '192.168.1.5'
# server_ip_sunlab = '128.180.120.73'

#sunlab machines
server_ip_sunlab_eris = '128.180.120.73'
server_ip_sunlab_ariel = '128.180.120.65'
server_ip_sunlab_caliban ='128.180.120.66'
# sockets ..
sock = {}
sock['s1'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock['s2'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock['s3'] = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# sock['s1'].connect((server_ip_mac_mini,10000))
# sock['s2'].connect((server_ip_mac_book,10000))
# sock['s3'].connect((server_ip_mac_book,10000))
sock['s1'].connect((server_ip_sunlab_eris,10000))
sock['s2'].connect((server_ip_sunlab_ariel,10000))
sock['s3'].connect((server_ip_sunlab_caliban,10000))
for i in range(number_operations):
    number_keys = 1000000 # these keys are stored equally between nodes ( to know where they are stored, we can have
    node_numbers = 3 # change it to 3 after testing ..
    value = randint(1,999999)
    key = randint(1,number_keys)
    # create the hash table of the current node, based on the starting key it reads from the property file ..
    # this hash table is global for the current client side ..

    if (random.random() <0.4): # the operation type
        request = 'put'
        message =  request+' '+str(key)+' '+str(value)
    else:
        request = 'get'
        message =  request+' '+str(key)

    #calculate which node should serve this request :
    node_id = key%node_numbers
    message = message+' '+str(node_id)
    if node_id ==0:
        #corresponding_sock = socket['s1']
        #server_ip = server_ip_mac_mini
        server_ip = server_ip_sunlab_eris
        res_itr = connect_server(message, server_ip,sock['s1'])
        if res_itr == 'Nack':
            t = 1 #
            while(connect_server(message, server_ip, sock['s1']) =='Nack'):
                time.sleep(0.000001*t)
                #t = t*2
    elif node_id ==1:
        #corresponding_sock = socket['s2']
        #server_ip = server_ip_mac_book
        server_ip = server_ip_sunlab_ariel
        res_itr = connect_server(message, server_ip,sock['s2'])
        if res_itr == 'Nack':
            t = 1 #
            while(connect_server(message, server_ip, sock['s2']) =='Nack'):
                time.sleep(0.000001*t)
                #t = t*2
    elif node_id ==2:
        #server_ip = server_ip_sunlab
        server_ip = server_ip_sunlab_caliban
        res_itr = connect_server(message, server_ip, sock['s3'])
        if res_itr == 'Nack':
            t = 1 #
            while(connect_server(message, server_ip, sock['s3']) =='Nack'):
                time.sleep(0.000001*t)
                #t = t*2

    print('iteration: '+str(i))
    print(server_ip)

end_time = time.time()
time_period = end_time -start_time
print('percent of return true (put the new key-value pair):'+str(num_success/number_operations))
print('number of true :'+str(num_success))
print('percent of return False (a value is associated with the key):'+str(num_false/number_operations))
print('number of false:'+str(num_false))
print('percent of Un-success (return null in get):'+str(num_unsuccessfull/number_operations))
print('number of null:'+str(num_unsuccessfull))
print('percent of un-acknowledged requests: '+str(nack/number_operations))

print('{opr} number of operations has been executed in {sec} seconds'.format(sec=time_period, opr=(number_operations)))
print('throughput is: {thro}'.format(thro=(number_operations/time_period)))


from django.conf.global_settings import *
import os

DEBUG = True

STATIC_ROOT = MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'static')
STATIC_URL = MEDIA_URL = "/static/"

STATICFILES_DIRS = (
    os.path.join(os.path.dirname(__file__), 'staticfiles_dir'),
    ("prefix", os.path.join(os.path.dirname(__file__), 'staticfiles_dir_with_prefix')),
)

SECRET_KEY = "SECRET_KEY"

INSTALLED_APPS = (
    "django_scss",
)
SCSS_MTIME_DELAY = 2
SCSS_OUTPUT_DIR = "SCSS_CACHE"

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
        'django_scss': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
    }
}


#
# @lc app=leetcode.cn id=543 lang=python3
#
# [543] 二叉树的直径
#
from typing import Optional
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
# @lc code=start
# Definition for a binary tree node.
class Solution:

    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        self.maxDiameter = 0
        self.maxDepth(root)
        return self.maxDiameter

    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0

        left = self.maxDepth(root.left)
        right = self.maxDepth(root.right)

        self.maxDiameter = max(self.maxDiameter, left+right)

        return 1 + max(right,left)

# @lc code=end

二叉树/543.二叉树的直径.py


"""
Parses the RuSentiLex file of csv sentiment language in the following format.
Only 'adj' terms marked positive or negative are output, and sent to positive.txt and negative.txt of raw signal terms.
NOTE: Cyrillic is preserved and text is not normalized; the lexicon is as given by RuSentiLex
NOTE: Only single term signals are retained; the lexicon contains many multi-term phrases
	-blank lines are omitted
	-lines beginning with ! are comments
	-sentiment lines are words or phrases, as:
		аборт, Noun, аборт, negative, fact

	!RuSentiLex Structure
	!1. word or phrase,
	!2. part of speech or type of syntactic group,
	!3. initial word (phrase) in a lemmatized form,
	!4. Sentiment: positive, negative, neutral or positive/negative (indefinite, depends on the context),
	!5. Source: opinion, feeling (private state), or fact (sentiment connotation),
	!6. Ambiguity: if sentiment is different for senses of an ambiguous word, then sentiment orientations for all senses are described, the senses
	!are labeled with the RuThes concept names.
"""

lines = [line.strip() for line in open("rusentilex.txt","r").readlines() if len(line.strip()) > 0 and line[0] != "!"]
posFile = open("positive.txt", "w+")
negFile = open("negative.txt", "w+")
phraseCount = 0
wordCount = 0
posCount = 0
negCount = 0

for line in lines:
	tokens = line.split(",")
	if len(tokens) == 5:
		if " " not in tokens[0]: #eliminates phrases on the rhs
			wordCount += 1
			if "negative" in tokens[3].lower():
				negFile.write(tokens[0]+"\n")
				negCount += 1
			if "positive" in tokens[3].lower():
				posFile.write(tokens[0]+"\n")
				posCount += 1
		else:
			phraseCount += 1

print("{} phrase count {} word count, {} positives {} negatives".format(phraseCount, wordCount, posCount, negCount))
posFile.close()
negFile.close()


tup = 1, 2, 3
print(type(tup))

a = 1, 2, "a", "wkehd"
x, *_, y = a  #_ is convention when you dnt intend to use the
#variable, though _ is perfectly valid variable name
print(x,y)

class Point2D:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return "{}({}, {})".format(self.__class__.__name__,\
                                                    self.x, self.y)

pt = Point2D(2, 3)
print(pt)
print(hex(id(pt)))
pt.x = 100
print(pt)
print(hex(id(pt)))

a = Point2D(2, 4) , Point2D(89, 9)
print(a)

london  = 'London', 'UK', 90813848
new_york = 'New York', 'USA', 48256384656
beijing = 'Beijing', 'China', 3845283499
cities = [london, new_york, beijing]

total = sum(city[2] for city in cities)
print(total)

record = 'DJIA', 2018, 1, 19, 25_987, 26_072, 25_942, 26_072
symbol, *_, close  = record
print(symbol, close)

for city,country,population in cities:
    print(city, country, population)

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

from random import uniform
from math import sqrt

def random_shot(radius):
    random_x = uniform(-radius, radius)
    random_y = uniform(-radius, radius)

    if sqrt(random_x ** 2 + random_y ** 2) <=  radius:
        is_in_circle = True
    else:
        is_in_circle = False

    return random_x, random_y, is_in_circle

num_attempts = 100
count_inside = 0

for i in range(num_attempts):
    *_, is_in_circle = random_shot(1)
    if is_in_circle:
        count_inside += 1

print("Pi approx is {} ". \
                    format((4*count_inside)/ num_attempts ))


class FScore(object):
  """FScore."""

  def __init__(self, correct=0, predcount=0, goldcount=0):
    self.correct = correct  # correct brackets
    self.predcount = predcount  # total predicted brackets
    self.goldcount = goldcount  # total gold brackets

  def precision(self):
    if self.predcount > 0:
      return (100.0 * self.correct) / self.predcount
    else:
      return 0.0

  def recall(self):
    if self.goldcount > 0:
      return (100.0 * self.correct) / self.goldcount
    else:
      return 0.0

  def fscore(self):
    precision = self.precision()
    recall = self.recall()
    if (precision + recall) > 0:
      return (2 * precision * recall) / (precision + recall)
    else:
      return 0.0

  def __str__(self):
    precision = self.precision()
    recall = self.recall()
    fscore = self.fscore()
    return '(P= {:0.2f}, R= {:0.2f}, F= {:0.2f})'.format(
        precision,
        recall,
        fscore,
    )

  def __repr__(self):
    return str(self)

  def __iadd__(self, other):
    self.correct += other.correct
    self.predcount += other.predcount
    self.goldcount += other.goldcount
    return self

  def __add__(self, other):
    return FScore(self.correct + other.correct,
                  self.predcount + other.predcount,
                  self.goldcount + other.goldcount)

  def __lt__(self, other):
    if isinstance(other, FScore):
      return self.fscore() < other.fscore()
    else:
      return self.fscore < other

  def __gt__(self, other):
    if isinstance(other, FScore):
      return self.fscore() > other.fscore()
    else:
      return self.fscore > other

  def detailed_str(self):
    return ('(Pred= {}, Gold={}, Correct={})'.format(
        self.predcount, self.goldcount, self.correct) + '\t' + self.__str__())


## Source:   https://github.com/j2kun/ucb1/blob/master/ucb1.py
import math
import random
from matplotlib import pyplot as plt
from numpy import *
import numpy as np
import sys
import pandas as pd

### UCB Parameters ###
num_bandits = 4
numRounds = 50000
######################

# upperBound: int, int -> float
# the size of the upper confidence bound for ucb1
def upperBound(step, numPlays):
   return math.sqrt(2 * math.log(step + 1) / numPlays)

# ucb1: int, (int, int -> float) -> generator
# perform the ucb1 bandit learning algorithm.  num_bandits is the number of
# actions, indexed from 0. reward is a function (or callable) accepting as
# input the action and producing as output the reward for that action

numPlays_array = []
payoffSums_array = []

def ucb1(num_bandits, reward):
    global numPlays_array
    global payoffSums_array
    payoffSums = [0] * num_bandits
    numPlays = [1] * num_bandits
    ucbs = [0] * num_bandits

    #initialize empirical sums
    for t in range(num_bandits):
        payoffSums[t] = reward(t,t)
        yield t, payoffSums[t], ucbs

    t = num_bandits

    while True:
        ucbs = [payoffSums[i] / numPlays[i] + upperBound(t, numPlays[i]) for i in range(num_bandits)]
        action = max(range(num_bandits), key=lambda i: ucbs[i])

        theReward = reward(action, t)

        numPlays[action] += 1
        numPlays_array = np.append(numPlays_array, numPlays)

        payoffSums[action] += theReward
        payoffSums_array = np.append(payoffSums_array, payoffSums)

        yield action, theReward, ucbs
        t = t + 1

# Assign biases tapering off (arm 0 is most biased toward reward)
biases = [1.0 / k for k in range(5,5+num_bandits)]
means = [0.5 + b for b in biases]
deltas = [means[0] - x for x in means[1:]]
deltaSum = sum(deltas)
invDeltaSum = sum(1/x for x in deltas)

# Must choose theoretical best action
bestAction = 0

rewards = lambda choice, t: random.random() + biases[choice]

cumulativeReward = 0
bestActionCumulativeReward = 0

regret_list =[]
regretBound_list=[]
t_list=[]

t = num_bandits

for (choice, reward, ucbs) in ucb1(num_bandits, rewards):
    #randomAction = random.randint(0, num_bandits)

    cumulativeReward += reward
    bestActionCumulativeReward += reward if choice == bestAction else rewards(bestAction, t)

    regret = bestActionCumulativeReward - cumulativeReward
    regret_list.append(regret)
    regretBound = 8 * math.log(t + 5) * invDeltaSum + (1 + math.pi*math.pi / 3) * deltaSum
    regretBound_list.append(regretBound)
    t += 1

    #print("regret: %d\tregretBound: %.2f" % (regret, regretBound))
    t_list.append(t)
    if t >= numRounds:
        break

# Reshape to be N by Number of Bandits
numPlays_vert = numPlays_array.reshape((-1, num_bandits))
payoffSums_vert = payoffSums_array.reshape((-1, num_bandits))
true_row_count = len(numPlays_vert)

# Plot regret
n = arange(true_row_count)+1

from pylab import *
subplot(211)
plot(t_list, regret_list, label="Regret")
plot(t_list, regretBound_list, label="UCB")
title('Overall Regret from UCB1 Algorithm')
ylabel('Cumulative Regret')

legend()
show()

# Plot bandit reward evolution
subplot(211)

for k in range(num_bandits):
    plot(n, payoffSums_vert[:, k], label="Arm %d" % k)

title('Rewards per Arm (%i Simulated Events)' % true_row_count)
xlabel("Number of Events")
ylabel("Cumulative Reward")

legend()
show()

# Plot bandit evolution
subplot(211)

for k in range(num_bandits):
    plot(n, numPlays_vert[:, k], label="Arm %d" % k)

title('Simulated Allocations per Arm (%i Simulated Events)' % true_row_count)
xlabel("Number of Events")
ylabel("Allocations")

legend()
show()


# python3

from collections import namedtuple
from collections import deque

Request = namedtuple("Request", ["arrived_at", "time_to_process"])
Response = namedtuple("Response", ["was_dropped", "started_at"])

class Buffer:
    def __init__(self, size):
        self.size = size
        self.finish_time = deque()

    def process(self, request):
        """
        Function that takes request and make decision that simulates network decisions:
         - Start process at the time with necessary time to process it;
         - Put process to buffer;
         - Call process from buffer;
         - Drop process.
        :param request: named tuple "Request"["arrived_at", "time_to_process"]
        :return:
        """
        # End all process, that already done by comparing with new process arrived time
        while self.finish_time and request.arrived_at >= self.finish_time[0]:
            self.finish_time.popleft()

        # Make decision drop process/put process in queue
        if self.finish_time and len(self.finish_time) >= self.size:
            return Response(True, -1)
        elif self.finish_time:
            request = Request(self.finish_time[-1], request.time_to_process)

        # Putting in queue
        self.finish_time.append(request.arrived_at + request.time_to_process)
        return Response(False, request.arrived_at)

def process_requests(requests, buffer):
    """
    Function that iterates throw all requests and simulates buffer process.
    :param requests: list of of named tuples "Request" ["arrived_at", "time_to_process"]
    :param buffer: class Buffer, initialised with integer equals buffer size
    :return: list of named tuple "Response" ["was_dropped", "started_at"]
    """
    responses = []
    for request in requests:
        responses.append(buffer.process(request))
    return responses

def get_data(path: "path to testing folder"):
    """
    Data file named 00 and contain buffer_size and number = [n] of requests on first line.
    Next [n] lines contains starting time and time to process.
    :param path: absolute path to test folder
    :return: integer equals to buffer size and list of named tuples "Request" ["arrived_at", "time_to_process"]
    """

    with open(path, "r") as file:
        buffer_size, n_requests = map(int, file.readline().split())

        requests = []
        for _ in range(n_requests):
            arrived_at, time_to_process = map(int, file.readline().split())
            requests.append(Request(arrived_at, time_to_process))
    return buffer_size, requests

def testing(path: "path to test folder"):
    """
    Function that tests code with some cases, stored in Test folder
    Test folder have to contain numbered pairs of files started with 01 that means it contain data and 01.a for answer.
    :param path: absolute path to Test folder, indicated from external testing module.
    :return: list of starting time for case sample. It should be compared with right answer in external testing module.
    """
    # reading data from file
    buffer_size, requests = get_data(path)

    # starting simulation
    buffer = Buffer(buffer_size)
    responses = process_requests(requests, buffer)

    # Output simulation result
    out = []
    for response in responses:
        out.append(response.started_at if not response.was_dropped else -1)
    return out

def main():
    # reading data from input
    buffer_size, n_requests = map(int, input().split())
    requests = []
    for _ in range(n_requests):
        arrived_at, time_to_process = map(int, input().split())
        requests.append(Request(arrived_at, time_to_process))

    # start simulation
    buffer = Buffer(buffer_size)
    responses = process_requests(requests, buffer)

    # output simulation result
    for response in responses:
        print(response.started_at if not response.was_dropped else -1)

if __name__ == "__main__":
    main()


from aiogram import types
from loguru import logger

from keyboards.inline.callback_datas import buy_callback
from keyboards.inline.choise_buttons import choise, pear_keyboard
from loader import dp, bot
from aiogram.dispatcher.filters import Command

@dp.message_handler(Command('items'))
async def show_items(message: types.Message):
    await message.answer(text='For sale we have 2 pieces: 5 apples an 2 pear.\n'
                              'If you want some, press button, if not Cancel',
                         reply_markup=choise)

@dp.callback_query_handler(buy_callback.filter(item_name='pear'))
async def buying_pear(call: types.CallbackQuery, callback_data: dict):
    # await bot.answer_callback_query(callback_query_id=call.id)
    await call.answer(cache_time=60)
    logger.info(f'callback_data = {call.data}')
    logger.info(f'callback_data dict = {call}')
    quantity = callback_data.get('quantity')
    await call.message.answer(f'You selected to buy pear. Pears count {quantity}. Thx',
                              reply_markup=pear_keyboard)

@dp.callback_query_handler(buy_callback.filter(item_name='apple'))
async def buying_apple(call: types.CallbackQuery, callback_data: dict):
    # await bot.answer_callback_query(callback_query_id=call.id)
    await call.answer(cache_time=60)
    logger.info(f'callback_data = {call.data}')
    logger.info(f'callback_data dict = {call}')
    quantity = callback_data.get('quantity')
    await call.message.answer(f'You selected to buy apple. Apples count {quantity}. Thx')

@dp.callback_query_handler(text="cancel")
async def cancel_buying(call: types.CallbackQuery):
    await call.answer("Canceled!", show_alert=True)

    await call.message.edit_reply_markup(reply_markup=None)

    # await bot.edit_message_reply_markup(chat_id=call.from_user.id,
    #                                     message_id=call.message.message_id,
    #                                     reply_markup=None)


from flask import Flask

app = Flask(__name__)

DATA = [
    {
    "first_name": "Reuben",
    "last_name": "Osborne",
    "age": 26
    },
    {
    "first_name": "Ed",
    "last_name": "Cox",
    "age": 26
    }
]

@app.route('/data')
def get_data():
    return DATA

@app.route('/data/<name>')
def get_by_name(name):
    results = []
    for person in DATA:
        if person['first_name'] == name:
            results.append(person)
        elif person['last_name'] == name:
            results.append(person)
    return results

if __name__ == "__main__":
    app.run(debug=True)


# type: ignore

import discord

from typing import Dict
from ...__obj__ import TypeHintedToolboxObject as Object
import logging; log = logging.getLogger(__name__)

from ...types import Embed

LOG_TYPES = {
    "ban": {
        "channel": "mod_log",
        "key": "log_ban",
        "color": 0xf04a47,
        "emote": "HAMMER",
        "action": "User banned"
    },
    "kick": {
        "channel": "mod_log",
        "key": "log_kick",
        "color": 0xf79554,
        "emote": "SHOE",
        "action": "User kicked"
    },
    "hackban": {
        "channel": "mod_log",
        "key": "log_ban",
        "color": 0xf04a47,
        "emote": "HAMMER",
        "action": "User forcebanned"
    },
    "softban": {
        "channel": "mod_log",
        "key": "log_ban",
        "color": 0xf79554,
        "emote": "HAMMER",
        "action": "User softbanned"
    },
    "tempban": {
        "channel": "mod_log",
        "key": "log_tempban",
        "color": 0xf04a47,
        "emote": "HAMMER",
        "action": "User tempbanned"
    },
    "tempban_extended": {
        "channel": "mod_log",
        "key": "log_tempban_extended",
        "color": 0xf04a47,
        "emote": "MORE",
        "action": "Tempban extended"
    },
    "unban": {
        "channel": "mod_log",
        "key": "log_unban",
        "color": 0x4cff4c,
        "emote": "UNLOCK",
        "action": "User unbanned"
    },
    "manual_unban": {
        "channel": "mod_log",
        "key": "log_manual_unban",
        "color": 0x4cff4c,
        "emote": "UNLOCK",
        "action": "User manually unbanned"
    },
    "manual_ban": {
        "channel": "mod_log",
        "key": "log_manual_ban",
        "color": 0xf04a47,
        "emote": "HAMMER",
        "action": "User manually banned"
    },

    "mute": {
        "channel": "mod_log",
        "key": "log_mute",
        "color": 0xe67e22,
        "emote": "MUTE",
        "action": "User muted"
    },
    "mute_extended": {
        "channel": "mod_log",
        "key": "log_mute_extended",
        "color": 0xe67e22,
        "emote": "MORE",
        "action": "Mute extended"
    },
    "unmute": {
        "channel": "mod_log",
        "key": "log_unmute",
        "color": 0x4cff4c,
        "emote": "UNMUTE",
        "action": "User unmuted"
    },
    "tempunban": {
        "channel": "mod_log",
        "key": "log_tempunban",
        "color": 0x4cff4c,
        "emote": "UNLOCK",
        "action": "User unbanned"
    },

    "warn": {
        "channel": "mod_log",
        "key": "log_warn",
        "color": 0xffdc5c,
        "emote": "FLAG",
        "action": "User warned"
    },
    "unwarn": {
        "channel": "mod_log",
        "key": "log_unwarn",
        "color": 0x4cff4c,
        "emote": "WHITE_FLAG",
        "action": "User unwarned"
    },
    "manual_unmute": {
        "channel": "mod_log",
        "key": "log_manual_unmute",
        "color": 0x4cff4c,
        "emote": "UNMUTE",
        "action": "User manually unmuted"
    },

    "automod": {
        "color": 0x131313
    },
    "filter": {
        "color": 0x131313
    },
    "regex": {
        "color": 0x131313
    },

    "message_deleted": {
        "channel": "message_log",
    },
    "message_edited": {
        "channel": "message_log",
    },

    "user_joined": {
        "channel": "join_log",
    },
    "user_left": {
        "channel": "join_log",
    },
    "bot_added": {
        "channel": "join_log",
    },

    "role_created": {
        "channel": "server_log",
    },
    "role_deleted": {
        "channel": "server_log",
    },
    "role_updated": {
        "channel": "server_log",
    },

    "channel_created": {
        "channel": "server_log",
    },
    "channel_deleted": {
        "channel": "server_log",
    },
    "channel_updated": {
        "channel": "server_log",
    },

    "thread_created": {
        "channel": "server_log",
    },
    "thread_deleted": {
        "channel": "server_log",
    },
    "thread_updated": {
        "channel": "server_log",
    },

    "emoji_created": {
        "channel": "server_log",
    },
    "emoji_deleted": {
        "channel": "server_log",
    },

    "sticker_created": {
        "channel": "server_log",
    },
    "sticker_deleted": {
        "channel": "server_log",
    },

    "member_updated": {
        "channel": "member_log",
    },

    "joined_voice": {
        "channel": "voice_log",
    },
    "left_voice": {
        "channel": "voice_log",
    },
    "switched_voice": {
        "channel": "voice_log",
    },

    "automod_rule_triggered": {
        "channel": "automod_log",
        "key": "log_automod",
        "color": 0x131313,
        "emote": "SWORDS",
        "action": "Automod rule triggered"
    },
    "regex_triggered": {
        "channel": "automod_log",
        "key": "log_regex",
        "color": 0x131313,
        "emote": "NO_ENTRY",
        "action": "Regex filter triggered"
    },
    "filter_triggered": {
        "channel": "automod_log",
        "key": "log_filter",
        "color": 0x131313,
        "emote": "NO_ENTRY",
        "action": "Word filter triggered"
    },

    "report": {
        "channel": "report_log"
    }
}

class LogProcessor:
    def __init__(self, bot) -> None:
        self.bot = bot
        self.db = bot.db

    async def execute(self, guild: discord.Guild, log_type: str, **log_kwargs) -> None:
        if not guild.id in self.bot.log_queue:
            self.bot.log_queue[guild.id] = {
                "mod_log": [],
                "message_log": [],
                "server_log": [],
                "join_log": [],
                "member_log": [],
                "voice_log": [],
                "report_log": [],
                "automod_log": []
            }

        config = Object(LOG_TYPES[log_type])
        if log_kwargs.get("_embed", None) == None:
            log_embed = Embed(
                None,
                color=config.color,
                description="{} **{}{}{}**".format(
                    self.bot.emotes.get(config.emote),
                    f"#{log_kwargs.get('case')} " if "case" in log_kwargs else "",
                    config.action,
                    f" ({log_kwargs.get('old_warns')} ➜ {log_kwargs.get('new_warns')})" if "old_warns" in log_kwargs else ""
                )
            )
            log_embed.add_fields([
                {
                    "name": "User",
                    "value": f"<@{log_kwargs.get('user_id')}> (``{log_kwargs.get('user_id')}``)",
                    "inline": True
                },
                log_embed.blank_field(inline=True),
                {
                    "name": "Moderator",
                    "value": f"<@{log_kwargs.get('mod_id')}> (``{log_kwargs.get('mod_id')}``)",
                    "inline": True
                }
            ])
            final_log_embed = self.resolve_kwargs(log_embed, **log_kwargs)

            fields = log_kwargs.get("extra_fields", [])
            if len(fields) > 0: final_log_embed.add_fields(fields)
        else:
            final_log_embed = log_kwargs.get("_embed")

        self.bot.log_queue[guild.id][config.channel].append(
            {
                "embed": final_log_embed,
                "has_case": log_kwargs.get("case", False)
            }
        )

    def resolve_kwargs(self, e: Embed, **kwargs) -> Embed:
        out = []
        for k, v in {
            x: y for x, y in kwargs.items() if y != None
        }.items():
            if k == "reason":
                out.append(self.create_field("Reason", f"{v}"))
            if k == "until":
                out.append(self.create_field("Expiration", f"{v}"))
            if k == "rule":
                out.append(self.create_field("Automod Rule", f"{v}"))
            elif k == "pattern" and v != "None":
                out.append(self.create_field("Filter/Regex", f"{v}"))
            if k == "found":
                out.append(self.create_field("Found Matches", f"{v}"))
            if k == "channel_id":
                out.append(self.create_field("Channel", f"<#{v}> (``{v}``)"))
            if k == "content":
                out.append(self.create_field("Message", f"```\n{v[:2000]}\n```"))

        e.add_fields(out)
        return e

    def create_field(self, name: str, value: str, inline: bool = False) -> Dict[str, str]:
        return {
            "name": name,
            "value": value,
            "inline": inline
        }


def solution(s, skip, index):
    sk = [ord(c)-97 for c in skip]
    li = []
    for c in s:
        n = ord(c)-97
        for _ in range(index):
            n = (n+1)%26
            while n in sk:
                n = (n+1)%26
        li.append(chr(n+97))
    return "".join(li)


# built-in libraries
import os
import json  # save ignored leads
import logging
import os
import pickle
import time
from typing import Generator, List, Optional, Union, Any

# third-party libraries
from selenium.common import exceptions
from selenium.webdriver import chrome
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.expected_conditions import visibility_of_element_located as elem_visible
from selenium.webdriver.support.expected_conditions import presence_of_all_elements_located as elems_located
from selenium.webdriver.support.expected_conditions import element_to_be_clickable as elem_clickable
from selenium.webdriver.support.ui import WebDriverWait

# local libraries
from .singleton import MetaSingleton

from typehints import Cookies, WebElement

from settings import LOGIN_PAGE, LEADS_PAGE, REGIONS, CIAN_PHONE

class SeleniumOperator(object):
    """
    Operator class which holds low-level operations with Selenium WebDriver.
    Overwrite JS syntax with couple of functions.
    Contain functions to operate windows, tabs and cookies.
    """

    driver: chrome.webdriver.WebDriver = None

    @property
    def current_url(self) -> str:
        return self.driver.current_url

    def wait(self, timeout: int, *args: Any, **kw: Any) -> WebDriverWait:
        return WebDriverWait(self.driver, timeout, *args, **kw)

    def chain(self, *args: Any, **kw: Any) -> ActionChains:
        return ActionChains(self.driver, *args, **kw)

    def switch(self, index: int) -> None:
        self.driver.switch_to_window(self.driver.window_handles[index])

    def set_driver(self, driver: chrome.webdriver.WebDriver) -> None:
        """
        Set driver explicitly following Open-Closed Principle
        """

        if self.driver != driver:
            self.driver = driver

    def _enter_input(self, elem: Union[WebElement, str], value: str) -> None:

        if isinstance(elem, str):
            elem = self.driver.find_element_by_name(elem)

        elem.send_keys(value)
        elem.send_keys(Keys.ENTER)

    def load_cookies(self) -> None:
        """
        Loading cookies to current driver using pickle
        """

        logging.info("Loading cookies")

        if not os.path.exists(os.environ['COOKIES_PATH']):
            logging.warning("No cookies found")
            return

        try:
            # load cookies for given websites
            cookies: Cookies = pickle.load(open(os.environ['COOKIES_PATH'], "rb"))

            self.driver.get(LOGIN_PAGE)

            for cookie in cookies:
                self.driver.add_cookie(cookie)

            self.driver.refresh()

        except Exception as e:
            logging.exception(e, exc_info=True)

    def save_cookies(self) -> None:
        """
        Dump current browser's cookies to a file with pickle
        """

        logging.warning("Saving cookies")

        cookies: Cookies = self.driver.get_cookies()

        pickle.dump(cookies, open(os.environ['COOKIES_PATH'], "wb"))

    def close_all(self) -> None:
        """
        Close all tabs in current browser
        """

        if len(self.driver.window_handles) < 1:
            return

        for window_handle in self.driver.window_handles[:]:

            self.driver.switch_to.window(window_handle)
            self.driver.close()

    def quit(self) -> None:
        """
        Saving cookies and closing all tabs
        """

        self.switch(0)

        self.save_ignore_leads()
        self.save_cookies()

        # self.close_all()
        self.driver.quit()

        self.set_driver(None)

class CianBot(SeleniumOperator, metaclass=MetaSingleton):
    """
    CianBot made for automate buying leads
    """

    ignore_leads: List[str] = None

    def __init__(self) -> None:

        self.load_ignore_leads()

    def load_ignore_leads(self) -> None:
        """
        Load ignored leads' dates from json.
        """

        logging.info("Loading ignored leads ...")

        if os.stat(os.environ['IGN_LEADS_PATH']).st_size > 0:

            try:
                with open(os.environ['IGN_LEADS_PATH'], 'r') as f:
                    self.ignore_leads = json.loads(f.read())
                return

            except Exception as e:
                logging.exception(e, exc_info=True)

        # If file is empty or
        # Exception raised set to an empty list
        self.ignore_leads = []

    def save_ignore_leads(self) -> None:

        logging.info(f"Store {len(self.ignore_leads)} ignored leads")

        with open(os.environ['IGN_LEADS_PATH'], 'w') as f:
            f.write(json.dumps(self.ignore_leads))

    def is_connection_lost(self) -> bool:

        try:
            self.driver.find_element_by_xpath("//*[@data-name='ErrorPanelComponent']")
            return True
        except exceptions.NoSuchElementException:
            return False

    def is_logged_in(self, trg_url: Optional[str] = None) -> bool:
        """
        Check that login button is presented on login page

        Returns
        -------
        bool
            Whether user logged in or not

        """

        trg_url = trg_url or LOGIN_PAGE

        try:
            self.driver.get(trg_url)
            self.driver.find_element_by_id('login-btn')
            return False
        except exceptions.NoSuchElementException:
            return True

    def login(self, trg_url: Optional[str] = None) -> bool:
        """
        Fill username and password with values from environment.
        If it's a first time login, code will be required
        with blocking sync input()
        """

        print(os.environ['CIAN_ID'])

        trg_url = trg_url or LOGIN_PAGE

        # Getting target url loaded
        self.driver.get(trg_url)

        # Click on login button
        self.driver.find_element_by_id('login-btn').click()

        # Find username field with Email or ID input
        self._enter_input('username', os.environ['CIAN_ID'])

        # After hitting enter password field becomes available
        self._enter_input('password', os.environ['CIAN_PASSWORD'])

        try:

            # After entering password we should enter phone number
            # Associated with this Cian ID
            # input_phone = self.driver.find_element_by_name('phone')
            self.wait(5).until(elem_visible((By.NAME, 'phone')))

        except exceptions.TimeoutException:

            # When we already logged in after entering password
            # The page will be reloaded and we will be logged in
            if self.is_logged_in():
                logging.warning("Logged in without entering new code")
                return True

            raise

        input_phone = self.wait(5).until(elem_visible((By.NAME, 'phone')))

        self._enter_input(input_phone, CIAN_PHONE)
        # Need to enter phone validation code
        return False

    def login_with_code(self, code: str):

        input_code = self.wait(5).until(elem_visible((By.NAME, 'code')))

        input_code.send_keys(code)

    def set_filters(self) -> None:
        """
        Filtering leads on leads_url
        """

        if not self.is_logged_in(LEADS_PAGE):
            self.login(LEADS_PAGE)

        self.driver.get(LEADS_PAGE)

        # Check the box "Скрыть заявки от агентов"
        self.driver.find_element_by_xpath(
            ".//*[contains(text(), 'Скрыть заявки от агентов')]").click()

        # Change leads type to "Продать"

        dropdown_menu = self.driver.find_element_by_xpath(
            '//*[@aria-haspopup="listbox"]')

        dropdown_menu.click()

        dropdown_menu.send_keys(Keys.ARROW_DOWN)
        dropdown_menu.send_keys(Keys.ENTER)

        # Open all filters list

        all_filters = self.driver.find_element_by_xpath(
            '//*[@data-name="MoreFiltersBtn"]')

        all_filters.click()

        region_input = self.driver.find_element_by_id('geo-suggest-input')

        for region in REGIONS:

            region_input.send_keys(region)

            # wait for render the region autocomplete suggestions drop-down list
            region_suggestions = self.wait(5).until(elem_visible(
                (By.XPATH, "//*[contains(@class, 'group-container')]")))

            time.sleep(0.3)

            # Select first suggestion
            region_suggestions.find_element_by_xpath(
                "//*[contains(@class, 'item-selected')]").click()

            # Wait until it'll be added to choosen region list
            self.wait(5).until(elem_visible(
                (By.XPATH, "//*[contains(@class, 'tag_content')]")))

        # set object type

        object_type_dropdown = self.driver.find_element_by_xpath(
            "//div[@role='button' and @aria-haspopup='listbox' and .//*[text()='Любой объект']]"
        )

        object_type_dropdown.click()

        # Check first checkbox - flat type

        self.driver.find_element_by_xpath("//div[@role='option']").click()

    def refresh_leads(self) -> None:

        self.switch(0)

        submit_button = self.driver.find_element_by_xpath(
            '//button[@data-name="SubmitContainer"]')

        # selenium.common.exceptions.ElementClickInterceptedException
        # Click on submit button

        try:
            submit_button.click()
        except exceptions.ElementClickInterceptedException:
            self.driver.execute_script("arguments[0].click();", submit_button)

        time.sleep(1)

        if self.is_connection_lost():
            logging.info("Connection lost. Sleeping")
            time.sleep(120)
            self.set_filters()
            self.refresh_leads()

    def iter_leads(self) -> Generator[str, bool, None]:

        self.refresh_leads()

        # Iterate through lead cards
        # Implicitly wait for leads to load
        time.sleep(2)

        try:
            self.wait(5).until(elems_located((By.XPATH, '//*[@data-name="LeadsCardsWrapper"]')))

            leads: List[WebElement] = self.driver.find_elements_by_xpath('//div[@data-name="LeadsCardsWrapper"]')

        except exceptions.TimeoutException:

            logging.warning("No new leads found")

            yield 'no-new-leads'
            return False

        for lead in leads:

            try:

                # Open tab with leads list
                self.switch(0)

                lead_url = self.open_lead(lead)

                if lead_url == 'ignore-lead':
                    # Lead was cached and not opened

                    continue

                logging.warning(f"Purchased {lead_url}")

                self.driver.close()

                if lead_url is not None:

                    yield lead_url

            except exceptions.StaleElementReferenceException:

                yield 'no-new-leads'
                return False

            except Exception as e:
                logging.exception(e, exc_info=True)

    def open_lead(self, lead: WebElement) -> Optional[str]:

        # Move to current lead
        self.chain().move_to_element(lead).perform()

        lead_creation_time = lead.find_element_by_xpath(".//*[@data-name='SecondInfo']").find_element_by_xpath(".//span").text

        if lead_creation_time in self.ignore_leads:

            logging.warning(f"Lead {lead_creation_time} was ignored")

            return 'ignore-lead'

        # Open new tab with lead information

        open_lead = lead.find_element_by_xpath(
            './/button[@data-name="OpenLead"]')

        try:

            self.wait(10).until(elem_clickable((By.XPATH, '//button[@data-name="OpenLead"]')))
            open_lead.click()

        except exceptions.ElementClickInterceptedException as e:

            logging.exception(e, exc_info=True)
            self.driver.execute_script("arguments[0].click();", open_lead)

        self.switch(-1)

        # Check that nobody already bought it
        lead_price = self.driver.find_element_by_xpath(
            "//h3[contains(@class, 'header_text')]")

        if lead_price.text.startswith('100'):

            # Lead already in proccess
            logging.debug("Lead is already purchased by someone")

            self.ignore_leads.append(lead_creation_time)

            return None

        lead_locations = self.driver.find_element_by_xpath("//*[@data-mark='location']").find_elements_by_xpath(".//*")

        lead_location = " ".join([location.text for location in lead_locations])

        if not any(region in lead_location for region in REGIONS):

            logging.warning(f"Location {lead_location} is not what I want...")

            self.ignore_leads.append(lead_creation_time)

            return None

        try:

            # NOTE: Not tested functionality

            lead_type = self.driver.find_element_by_xpath("//*[@data-mark='demand_message-info_title']").text

            if not all(x in lead_type.lower() for x in ('продать', 'квартиру')):

                logging.warning(f"Lead {self.current_url} has improper type")

                return None

        except Exception as e:

            logging.exception(e, exc_info=True)

        # Open buy lead modal dialog

        open_buy_modal = self.driver.find_element_by_xpath(
            "//button[contains(@class, 'button_component-blue')]")

        open_buy_modal.click()

        buy_lead_btn = self.driver.find_element_by_xpath(
            "//button[contains(text(), 'Оплатить ')]")

        buy_lead_btn.click()

        time.sleep(1)
        logging.warning(f"Buy lead {self.current_url}")

        return self.current_url


import re
import os

path = os.path.abspath(os.path.join(__file__, os.path.pardir))

def request_counting_by_type():
    post_result = 0
    get_result = 0
    put_result = 0
    head_result = 0
    delete_result = 0
    connect_result = 0
    options_result = 0
    trace_result = 0
    patch_result = 0
    with open(path + '/files/access.logs',
              "r") as f:
        for line in f:
            line_list = re.split(' ', line)
            if re.search(r'POST', line_list[5]) is not None:
                post_result += 1
            if re.search(r'GET', line_list[5]) is not None:
                get_result += 1
            if re.search(r'PUT', line_list[5]) is not None:
                put_result += 1
            if re.search(r'HEAD', line_list[5]) is not None:
                head_result += 1
            if re.search(r'DELETE', line_list[5]) is not None:
                delete_result += 1
            if re.search(r'CONNECT', line_list[5]) is not None:
                connect_result += 1
            if re.search(r'OPTIONS', line_list[5]) is not None:
                options_result += 1
            if re.search(r'TRACE', line_list[5]) is not None:
                trace_result += 1
            if re.search(r'PATCH', line_list[5]) is not None:
                patch_result += 1
    dict_total_number_of_requests = {"POST REQUESTS": post_result, 'GET REQUESTS': get_result,
                                     'PUT REQUESTS': put_result, 'HEAD REQUESTS': head_result,
                                     'DELETE REQUESTS': delete_result,
                                     'CONNECT REQUESTS': connect_result,
                                     'OPTIONS REQUESTS': options_result,
                                     'TRACE REQUESTS': trace_result,
                                     'PATCH REQUESTS': patch_result}
    return dict_total_number_of_requests


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

import pandas as pd
import datetime, time
import numpy as np
import click
import selenium

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup

#url = 'www.expedia.com'
flight_tab = "//button[ @id='tab-flight-tab-hp']"
return_ticket = "//label[@id='flight-type-roundtrip-label-hp-flight']"
one_way_ticket = "//label[@id='flight-type-one-way-label-hp-flight']"
multi_ticket = "//label[@id='flight-type-multi-dest-label-hp-flight']"
depature_country = "//input[@id='flight-origin-hp-flight']"
arrival_country = "//input[@id='flight-destination-hp-flight']"
search_tab = "//button[@class='btn-primary btn-action gcw-submit']"
country_list = [depature_country,arrival_country]

def ticket_chooser(ticket):
    try:
        ticket_type = driver.find_element_by_xpath(ticket)
        ticket_type.click()
    except Exception as e:
        print(e)

def select_country(country_list,dep_cou,arr_cou):
    try:
        for country in country_list:
            if country == depature_country:
                fly_from = driver.find_element_by_xpath(country)
                time.sleep(1)
                fly_from.clear()
                time.sleep(1)
                fly_from.send_keys(dep_cou)
                time.sleep(0.5)
                first_item = driver.find_element_by_xpath("//a[@id='aria-option-0']")
                time.sleep(1)
                first_item.click()
            elif country == arrival_country:
                fly_to = driver.find_element_by_xpath(country)
                time.sleep(1)
                fly_to.clear()
                time.sleep(1)
                fly_to.send_keys(" " + arr_cou)
                time.sleep(0.5)
                second_item = driver.find_element_by_xpath("//a[@id='aria-option-0']")
                time.sleep(1)
                second_item.click()
            else:
                raise ValueError
    except Exception as e:
        print(e)

def dep_date(month, day, year):
    dep_date_button = driver.find_element_by_xpath("//input[@id='flight-departing-hp-flight']")
    dep_date_button.clear()
    dep_date_button.send_keys(month + '/' + day + '/' + year)

def return_date(month,day,year):
    dep_date_button = driver.find_element_by_xpath("//input[@id='flight-returning-hp-flight']")
    dep_date_button.clear()
    for _ in range(10):
        dep_date_button.send_keys(selenium.webdriver.common.keys.Keys.BACK_SPACE)
    time.sleep(1)
    dep_date_button.send_keys(month + '/' + day + '/' + year)
    dep_date_button.click()

def search(search):
    search_button = driver.find_element_by_xpath(search)
    search_button.click()

def flight(flight):
    flight_tab = driver.find_element_by_xpath(flight)
    flight_tab.click()

def get_url(url):
    driver.get(url)

df = pd.DataFrame()
def compile_data():
    #departure times
    dep_times = driver.find_elements_by_xpath("//span[@data-test-id='departure-time']")
    dep_times_list = [value.text for value in dep_times]

    #arrival times
    arr_times = driver.find_elements_by_xpath("//span[@data-test-id='arrival-time']")
    arr_times_list = [value.text for value in arr_times]
    #airline name
    airlines = driver.find_elements_by_xpath("//span[@data-test-id='airline-name']")
    airlines_list = [value.text for value in airlines]
    empty = airlines_list.pop(0)
    #prices
    prices = driver.find_elements_by_xpath("//span[@data-test-id='listing-price-dollars']")
    price_list = [value.text.split('$')[1] for value in prices]
    #durations
    durations = driver.find_elements_by_xpath("//span[@data-test-id='duration']")
    durations_list = [value.text for value in durations]
    #stops
    stops = driver.find_elements_by_xpath("//span[@class='number-stops']")
    stops_list = [value.text for value in stops]
    #layovers
    layovers = driver.find_elements_by_xpath("//span[@data-test-id='layover-info']")
    layovers_list = [value.text for value in layovers]

    rating = driver.find_elements_by_xpath("//a[@data-click-handler='omnitureClickHandler']")
    rating_list = [value.text for value in rating]

    joined_list = [dep_times_list,arr_times_list,airlines_list,price_list,durations_list,stops_list,layovers_list\
                  ,rating_list]
    columns = ['departure_time','arrival_time','airlines','price','durations','stopovers','layovers',
              'ratings']
    dic = {}
    for col,val in zip(columns,joined_list):
        dic[col] = val
        with open(f'data/{col}.txt','w') as f:
            for v in val:
                f.write(f'{v}\n')
    df = pd.DataFrame.from_dict(dic)

@click.command()
@click.argument('url')
@click.argument('dep_cou')
@click.argument('arr_cou')

def cli(url,dep_cou,arr_cou):
    get_url(url)
    flight(flight_tab)
    ticket_chooser(return_ticket)
    select_country(country_list,dep_cou,arr_cou)
    dep_date('10','5','2020')
    return_date('10','9','2020')
    search(search_tab)
    time.sleep(15)
    compile_data()
    #df.to_excel('flights.xlsx')

# In[47]:
if __name__ == '__main__':
    driver = selenium.webdriver.Chrome(executable_path="/Users/akinwande.komolafe/Downloads/chromedriver")
    cli()


import ja3_distance
import ja3_converter as converter
import sys
import numpy as np
import matplotlib.pyplot as plt

data_path = "../data"

prod1 = sys.argv[1]
prod2 = sys.argv[2]
print("Drawing coordinates for {} and {} JA3s".format(prod1, prod2))

prod1_ja3 = converter.prod_to_ja3(prod1)
prod2_ja3 = converter.prod_to_ja3(prod2)

if prod1_ja3==None or prod2_ja3==None:
    print("Product does not exist in database.")
    prods = converter.all_prods()
    print("Available Products: {}".format(", ".join(prods)))
    exit()

ja3_distance.plot_scatter(prod1, prod2, prod1_ja3,prod2_ja3,1,3,"../graphs/{}_{}_ciph_goups.png".format(prod1,prod2))
ja3_distance.plot_scatter(prod1, prod2, prod1_ja3,prod2_ja3,1,2,"../graphs/{}_{}_ciph_extensions.png".format(prod1,prod2))

exit()

coordinates1 = ja3_distance.ja3s_to_coords(prod1_ja3)
coordinates2 = ja3_distance.ja3s_to_coords(prod2_ja3)

#print(str(coordinates1))
#print(str(coordinates2))

v,c,e,g,f = zip(*coordinates1)
v2,c2,e2,g2,f2 = zip(*coordinates2)

#plot ciph vs groups

fig = plt.figure()
plt.scatter(c,g,c="red",marker="o", label="{}".format(prod1))
#plt.scatter(x, y, c="red", alpha=0.5)
plt.scatter(c2, g2, c="blue", marker="x",label="{}".format(prod2))
plt.xlabel("Cipher suites")
plt.ylabel("Supported Groups")
plt.legend(bbox_to_anchor =(0.65, 1.15))
#plt.show()
fig.savefig("../graphs/{}_{}_ciph_goups.png".format(prod1,prod2))
plt.close(fig)

fig2 = plt.figure(2)
plt.scatter(c,e,c="red",marker="o", label="{}".format(prod1))
plt.scatter(c2, e2, c="blue", marker="x",label="{}".format(prod2))
plt.xlabel("Cipher suites")
plt.ylabel("Extensions")
plt.legend(bbox_to_anchor =(0.65, 1.15))
#plt.show()
fig2.savefig("../graphs/{}_{}_ciph_extensions.png".format(prod1,prod2))
plt.close(fig2)