import sys, os
import keras
import cv2
import traceback

from src.alpr.keras_utils 			import load_model
from glob 						import glob
from os.path 					import splitext, basename
from src.alpr.utils 					import im2single, nms
from src.alpr.keras_utils 			import load_model, detect_lp
from src.alpr.label 					import Shape, writeShapes, dknet_label_conversion
from time import sleep
import datetime
import numpy as np
import zmq
import base64
import io
from imageio import imread
import tensorflow as tf
import time
import random
from src.lprnet.utils import TextImageGenerator,encode_label,sparse_tuple_from,decode_sparse_tensor,\
                    decode_a_seq,small_basic_block,conv,report_accuracy,\
                    test_report,do_batch,get_test_model,predict_oneimg
import socketio
import pickle
# import matplotlib.pyplot as plt
# def adjust_pts(pts,lroi):
# 	return pts*lroi.wh().reshape((2,1)) + lroi.tl().reshape((2,1))

'''lpr detection Load model'''
lp_threshold = .5
wpod_net_path = './models/alpr/v2_backup.h5'
wpod_net = load_model(wpod_net_path)

'''ocr lprnet'''
BATCH_SIZE = 1
TRAIN_SIZE = 1000
BATCHES = TRAIN_SIZE//BATCH_SIZE
test_num = 1

ti = 'train_lprnet/lpr_label1.csv'
vi = 'train_lprnet/lpr_label1.csv'
img_size = [94, 24]
tl = None
vl = None
num_channels = 3
label_len = 7
CHARS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
         'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
         'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
         'W', 'X', 'Y', 'Z',
         'ก', 'ข', 'ฃ', 'ค', 'ฅ', 'ฆ', 'ง', 'จ', 'ฉ', 'ช', 'ซ',
         'ฌ', 'ญ', 'ฎ', 'ฏ', 'ฐ', 'ฑ', 'ฒ', 'ณ', 'ด', 'ต', 'ถ',
         'ท', 'ธ', 'น', 'บ', 'ป', 'ผ', 'ฝ', 'พ', 'ฟ', 'ภ', 'ม',
         'ย', 'ร', 'ล', 'ว', 'ศ', 'ษ', 'ส', 'ห', 'ฬ', 'อ', 'ฮ',
         '_'
         ]
CHARS_DICT = {char:i for i, char in enumerate(CHARS)}
NUM_CHARS = len(CHARS)

#global_step = tf.Variable(0, trainable=False)
#print(num_channels, label_len, BATCH_SIZE, img_size)
#logits, inputs, seq_len = get_test_model(num_channels, label_len,BATCH_SIZE, img_size,NUM_CHARS)
#logits = tf.transpose(logits, (1, 0, 2))
#decoded, log_prob = tf.nn.ctc_beam_search_decoder(logits, seq_len, merge_repeated=False)
#init = tf.global_variables_initializer()
#config = tf.ConfigProto(device_count = {'GPU': 1, 'CPU': 16})
#config.gpu_options.allow_growth = True

alpr_graph = tf.Graph()
session2 = tf.Session(graph=alpr_graph)
with alpr_graph.as_default():
#with session2.as_default():
    init = tf.global_variables_initializer()
    saver = tf.train.Saver(tf.global_variables())
    #with alpr_graph.as_default():
    with session2.as_default():
        tf.global_variables_initializer().run()
        #saver = tf.train.Saver(tf.global_variables())
        saver.restore(session2, 'models/lprnet/LPRtf3.ckpt-300000')

#context = zmq.Context()
#print("Connecting to server...")
#socket = context.socket(zmq.SUB)
#socket.connect("tcp://zmq:6666")
#socket.setsockopt(zmq.SUBSCRIBE, "".encode('utf-8'))

sio = socketio.Client()
sio.connect('http://streamer_detector:5562')
print('Connected')

Ilp = None
#while(True):
@sio.on('raw')
def recive(data):
    #message = (sio.recv().decode('utf-8'))[3:-1]
    ''' Lpr detection and frontalizarion'''
    print ('Searching for license plates using WPOD-NET')
    start = datetime.datetime.now()
    #img = imread(io.BytesIO(base64.b64decode(message)))
    img = pickle.loads(data['frame'], fix_imports=True, encoding="bytes")
    Ivehicle = cv2.imdecode(img, cv2.IMREAD_COLOR)
    #Ivehicle = cv2.cvtColor(img,cv2.COLOR_RGB2BGR)

    ratio = float(max(Ivehicle.shape[:2]))/min(Ivehicle.shape[:2])
    side  = int(ratio*288.)
    bound_dim = min(side + (side%(2**4)),608)
    print( "\t\tBound dim: %d, ratio: %f" % (bound_dim,ratio))

    Llp,LlpImgs,_ = detect_lp(wpod_net,im2single(Ivehicle),bound_dim,2**4,(240,80),lp_threshold)
    if len(LlpImgs):
        Ilp = LlpImgs[0]
        Ilp = cv2.cvtColor(Ilp, cv2.COLOR_BGR2GRAY)
        Ilp = cv2.cvtColor(Ilp, cv2.COLOR_GRAY2BGR)
        s = Shape(Llp[0].pts)
        print(type(Ilp))
        ''' Lpr ocr '''
        #frame = cv2.resize(Llp*255.0, (img_size[0], img_size[1]), interpolation=cv2.INTER_CUBIC)
        #predict = predict_oneimg(frame,inputs,seq_len,session,decoded,CHARS)
        #print ('Performing OCR...')
        #print( '\tScanning\t')
        #print(predict)
        #cv2.imshow(frame)
        #cv2.waitkey(1)
    stop = datetime.datetime.now()
    print(stop-start)


from problem12 import get_factors
from collections import Counter
from itertools import product
import numpy as np

amicable_nums = []
l = [2, 3]
# print(get_factors(1))

def sum_divisors(factors):
    # 由素因子列表得出因子列表，包括1，再计算其和
    sub_factors = []
    for k, v in Counter(factors).items():
        # 比如k = 2, v = 3，就生成[1, 2, 4, 8]
        sub_factors.append([k ** i for i in range(v + 1)])  # 0的0次方居然不报错，会被记为1
    # 对sub_factors计算笛卡尔积，将得到的结果(列表的列表)中最内层列表求连乘积，即得到divisors列表，
    # 去掉外层列表最后一个元素，求和，即得结果
    return sum([np.prod(i) for i in product(*sub_factors)][:-1])  # 不计算最后一个元素（自己本身）

for n in range(2, 10000):
    if n in amicable_nums:
        continue
    l, factors = get_factors(n, l)
    # print('f1', factors)
    m = sum_divisors(factors)  # 8128自己和自己相等
    if m != n:
        l, factors = get_factors(m, l)
        # print('f2', factors)
        if sum_divisors(factors) == n:
            amicable_nums.extend([m, n])
            print(m, n)

# print(sum_divisors([0]))  # 会等于1
print(amicable_nums)
print(sum(amicable_nums))


import os
import sys

import requests

print(sys.executable)
print(sys.version)

def greetings(who_to_greet):
    greeting = "Hello, {}".format(who_to_greet)
    return greeting

r = requests.get("https://www.google.com")
print(r.status_code)
print("hello")


import logging

from flask import Flask, render_template, request
from google.cloud import datastore
import jsonlines, json
import pandas as pd

app = Flask(__name__)

def getSupplierContracts(ABN):
    client = datastore.Client()
    collection = 'supplier_contracts'
    query = client.query(kind=collection)
    query.add_filter('ABN', '=', ABN)
    query.order = ['-Value']

    results = list(query.fetch())
    contracts = []
    for r in results:
        s = datastore.Entity(r)
        contract = {}
        contract['ContractID'] = s.key.key.name
        contract['Title'] = s.key.get('Title')
        contract['Agency'] = s.key.get('Agency')
        contract['Category'] = s.key.get('Category')
        contract['Value'] = s.key.get('Value')
        contracts.append(contract)
    return contracts

@app.route('/')
def hello():
    """Return a friendly HTTP greeting."""
    return 'Hello World!'

@app.errorhandler(500)
def server_error(e):
    logging.exception('An error occurred during a request.')
    return """
    An internal error occurred: <pre>{}</pre>
    See logs for full stacktrace.
    """.format(e), 500

@app.route("/data/supplier/<ABN>/contracts_by_category")
def supplier_contracts_by_category(ABN):
    contracts = getSupplierContracts(ABN)

    df = pd.DataFrame(contracts)
    sorted_df = df[['Category', 'Value']].groupby('Category').sum().sort_values('Value', ascending=True)
    #sorted_df.reset_index().to_dict('records')
    #t = {'name': 'IT Services', 'value': 6644},{'name': 'Project Management', 'value': 9998}
    return json.dumps(sorted_df.reset_index().to_dict('records'))

@app.route("/data/supplier/<ABN>/contracts_by_agency")
def supplier_contracts_by_agency(ABN):
    contracts = getSupplierContracts(ABN)

    df = pd.DataFrame(contracts)
    sorted_df = df[['Agency', 'Value']].groupby('Agency').sum().sort_values('Value', ascending=True)
    #sorted_df.reset_index().to_dict('records')
    #t = {'name': 'IT Services', 'value': 6644},{'name': 'Project Management', 'value': 9998}
    return json.dumps(sorted_df.reset_index().to_dict('records'))

@app.route("/contracts/supplier/<ABN>")
def supplier_contracts(ABN):

    client = datastore.Client()
    collection = 'supplier_contracts'
    query = client.query(kind=collection)
    query.add_filter('ABN', '=', ABN)
    query.order = ['Title']

    results = list(query.fetch())
    contract_count = len(results)

    contracts = []
    for r in results:
        s = datastore.Entity(r)
        contract = {}
        contract['ContractID'] = s.key.key.name
        contract['Title'] = s.key.get('Title')
        contract['Agency'] = s.key.get('Agency')
        contract['Category'] = s.key.get('Category')
        contract['Value'] = s.key.get('Value')
        contracts.append(contract)

    query_suppliername = client.query(kind='suppliers')
    query_suppliername.add_filter('ABN', '=', ABN)
    results_suppliername = list(query_suppliername.fetch(limit=1))
    supplier_name = datastore.Entity(results_suppliername[0]).key.get('Name')

    return render_template('contracts.html',
        contracts=contracts,
        ABN=ABN,
        supplier_name=supplier_name,
        contract_count=contract_count)

@app.route("/all_suppliers")
def suppliers():

    client = datastore.Client()
    collection = 'suppliers'

    query = client.query(kind=collection)
    query.order = ['Name']

    results = list(query.fetch())
    supplier_count = len(results)

    suppliers = []
    for r in results:
        s = datastore.Entity(r)
        supplier = {}
        supplier['ABN'] = s.key.key.name
        supplier['Name'] = s.key.get('Name')
        supplier['State'] = s.key.get('State')
        supplier['Postcode'] = s.key.get('Postcode')
        suppliers.append(supplier)

    return render_template('suppliers.html', suppliers=suppliers, supplier_count=supplier_count)

if __name__ == '__main__':
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine. See entrypoint in app.yaml.
    app.run(host='127.0.0.1', port=8080, debug=True)


'''
Given n non-negative integers a1, a2, ..., an ,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0).
Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.

Notice that you may not slant the container.

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7].
In this case, the max area of water (blue section) the container can contain is 49.
'''

# Solution:
def maxArea (height):
    left = 0
    right = len(height) - 1
    result = 0

    while left < right:
        area = (right - left) * min(height[left], height[right])     # area of current left and right
        result = max(area, result)                                  # asign result to the higher of the two between current and new area
        if height[left] < height[right]:                           # move left right if left is lower
            left += 1
        else:                                                       # move right left if right is lower
            right -= 1
    return result

# Solution
height = [1,8,6,2,5,4,8,3,7]
print(maxArea(height))

1-1000/1-100/11-20/11. Container With Most Water.py


from django_auth_ldap.backend import LDAPBackend, _LDAPUser
from django.contrib.auth.models import User

class LDAPSyncBackend(LDAPBackend):

    def get_or_create_user(self, username, ldap_user):
        """
        Overriding get_or_create_user to perform our own Django/Nadine User
        lookup.
        django-auth-ldap assumes we would want to create Django/Nadine users if
        they don't exist but we don't want to do this. Instead we throw a
        _LDAPUser.AuthenticationFailed exception.
        """
        try:
            # Use 'nadine.backends.EmailOrUsernameModelBackend' strategy to
            # look up a user. First by email, then by username.
            if '@' in username:
                user = User.helper.by_email(username)
            else:
                user = User.objects.get(username=username)

        except User.DoesNotExist:
            # If we can't match against a user in the database then we bail.
            # LDAP users are created & managed FROM Nadine; we don't want to be
            # creating Django users for existing LDAP accounts.
            user = None

        if (user):
            return (user, False)
        else:
            raise _LDAPUser.AuthenticationFailed(
                "User exists in LDAP but doesn't exist in Nadine"
            )

# Copyright 2021 Office Nomads LLC (https://officenomads.com/) Licensed under the AGPL License, Version 3.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.gnu.org/licenses/agpl-3.0.html. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.


from django.db import models
# from django.contrib.auth import get_user_model
# from django_cleanup import cleanup
from user.models import UserModel

class Board(models.Model):
    author = models.ForeignKey(UserModel(), on_delete=models.CASCADE)
    board_id = models.AutoField(primary_key=True)
    # title = models.CharField(max_length=50)
    img = models.FileField(null=True, upload_to="", blank=True)
    content = models.TextField(max_length=300)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    likes = models.ManyToManyField(UserModel, related_name='likes', blank=True)
    likes_count = models.PositiveIntegerField(default=0)

    class Meta:
        db_table = 'board'

    #좋아요 저장
    def update_likes_count(self):
        self.likes_count = self.likes.count()
        self.save()

    # def delete(self, *args, **kargs):
    #     os.remove(os.path.join(settings.MEDIA_ROOT, self.upload_file.name))
    #     super(Board, self).delete(*args, **kargs)


import threading
import time

import datetime
import queue

class SimulatedComms:

    def __init__(self, router):
        self.port = "simulator"
        self.router = router
        self.from_browser = queue.Queue()
        router.register_comms(self)
        self.live = True
        self.thread = threading.Thread(target=self.simulator_main, args=(0, 0))
        self.thread.daemon = True
        self.thread.start()

    def close(self):
        self.live = False

    def simulate_command(self, data):
        upper_data = data.upper()
        if(upper_data == "I"):
            self.on_rx("ID TH IS IS AF AK EI D")

    def router_to_board(self, data):
        self.from_browser.put(data)
        self.router.router_to_browser_echo(data)

    def on_rx(self, data):
        self.router.router_to_browser(data)

    def simulator_main(self, a,b):
        self.simulation_test_wake_command_prompt()

    def simulate_command_prompt(self):
        loop = 0
        while self.live:
            time.sleep(1)
            if (loop % 10 == 0):
                self.on_rx('=F0%@22CE;X0;T16 10 W0 48 F2 54 W255 0 F255 0;S6 6 18 e;C5;{"@":"12ab","vC|%":0,"L":0,"B|cV":321}')
            else:
                self.on_rx("")
                self.on_rx(">")
            loop = loop + 1

    def simulation_test_wake_command_prompt(self):
        loop = 0
        while self.live:
            if not self.from_browser.empty():
                rx = self.from_browser.get_nowait()
                self.simulate_command_prompt()
            time.sleep(0.1)


# -*- coding=utf-8 -*-
r"""
"""

import sys
from PyQt5.QtWidgets import QWidget, QApplication, QMdiArea, QTextEdit, QPushButton, QCalendarWidget
from PyQt5.Qt import Qt

class AppDemo(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(800, 600)

        workspace = QMdiArea(self)
        workspace.resize(self.rect().width(), self.rect().height())

        self.calendar = QCalendarWidget()
        # self.calendar.clicked.connect(lambda _: print(self.calendar.date))
        workspace.addSubWindow(self.calendar, Qt.Window)
        self.button = QPushButton('My Button')
        workspace.addSubWindow(self.button)
        self.editor = QTextEdit()
        workspace.addSubWindow(self.editor)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    demo = AppDemo()
    demo.show()

    sys.exit(app.exec_())

PyQt5/Video Tutorial/day05/Create a Workspace to Organize Your Widgets Together.py


import os
import logging
from BotCommands.BotResponse import BotResponse

class BotRole:
    NONE="NONE"
    DE="DE"
    MANAGERS="MANAGERS"
    ALL="ALL"

class ABotCommand:

    def __init__(self, text=None):
        self.text = text
        self.token = None
        self.channel = None

    def execute(self, role:BotRole) -> BotResponse:
        br = BotResponse('', '', self.text)
        return br


import jax
import haiku as hk
import numpy as np
import jax.numpy as jnp

from model.prior import Prior

class Embedding(hk.Module):
    """
    Embeds tokens and positions into an array of shape [n_batch, n_seq, n_hidden].
    Choose between learnable and VI embeddings.
    """
    def __init__(self, config, vocab_size, hidden_size, name):
        """
        Build Embedding from configuration.
        :params config: configuration dictionary.
        """
        super().__init__(name=name)
        self.config = config
        self.vocab_size = vocab_size
        self.hidden_size = hidden_size
        if self.config["bayesian_emb"]:
            self.embedding = BayesianEmbedding(config, vocab_size=vocab_size, hidden_size=hidden_size)
        else:
            self.embedding = LearnableEmbedding(config, vocab_size=vocab_size, hidden_size=hidden_size)

    def __call__(self, ids, key, training=True):
        """
        Forward pass on the embedding layer.
        :params ids: input of shape (batch, n_seq).
        :params key: random key.
        :params training: if True, apply dropout.
        """
        if self.config["bayesian_emb"]:
            return self.embedding(ids, key, training)
        else:
            return self.embedding(ids, key, training),  0.

class LearnableEmbedding(hk.Module):
    """
    Embeds tokens and positions into an array of shape [n_batch, n_seq, n_hidden].
    """
    def __init__(self, config, vocab_size, hidden_size):
        """
        Build Embedding from configuration.
        :params config: configuration dictionary.
        """
        super().__init__(name="LearnableEmbedding")
        self.config = config
        self.vocab_size=vocab_size
        self.hidden_size = hidden_size

    def __call__(self, token_ids, key, training=True):
        """
        Forward pass on the embedding layer.
        :params token_ids: input of shape (batch, n_seq).
        :params key: random key.
        :params training: if True, apply dropout.
        """
        # Reshape ids
        flat_token_ids = jnp.reshape(token_ids, [token_ids.shape[0]*token_ids.shape[1]])

        # Embed tokens
        flat_token_embeddings = hk.Embed(
            vocab_size=self.vocab_size,
            embed_dim=self.hidden_size
        )(flat_token_ids)

        # After we've embedded our token IDs, we reshape to recover our batch dimension
        embeddings = jnp.reshape(
            flat_token_embeddings,
            [token_ids.shape[0], token_ids.shape[1], -1]
        )

        # Combine our token embeddings with a set of learned positional embeddings
        ### embeddings = token_embeddings + PositionEncoding(self.config)() # Will do outside this

        # Apply layer norm
        ###
        ### embeddings = hk.LayerNorm(
        ###    axis=-1, create_scale=True, create_offset=True
        ### )(embeddings) # Will do outside this function

        # # Apply dropout layer during training
        # if training:
        #     embeddings = hk.dropout(
        #         key,
        #         rate=self.config['embed_dropout_rate'],
        #         x=embeddings
        #     ) # Will do outside this

        return embeddings

class BayesianEmbedding(hk.Module):
    """
    Embeds tokens and positions into an array of shape [n_batch, n_seq, n_hidden].
    Apply Variational Inference to the embedding vectors.
    """
    def __init__(self, config, vocab_size, hidden_size):
        """
        Build Embedding from configuration.
        :params config: configuration dictionary.
        """
        super().__init__(name="BayesianEmbedding")
        self.config = config
        self.vocab_size=vocab_size
        self.hidden_size = hidden_size
        # Posterior weight distribution
        self.w_mean = hk.get_parameter(
            name="w_mean",
            shape=[self.vocab_size, self.hidden_size],
            init=hk.initializers.TruncatedNormal(),
        )
        self.w_rho = hk.get_parameter(
            name="w_rho",
            shape=[self.vocab_size, self.hidden_size],
            init=hk.initializers.RandomNormal(stddev=1e-2, mean=-7)
        )
        self.w_sig = jax.nn.softplus(self.w_rho)
        # Prior weight distribution
        prior_distribution = self.config['emb_prior_distribution']
        prior_params = self.config['emb_prior_params']
        self.prior_w = Prior(self.vocab_size*self.hidden_size, prior_distribution, prior_params)

    def __call__(self, ids, key, training=True):
        """
        Forward pass on the embeddings.
        :params ids: input of shape (batch, n_seq).
        :params key: random key.
        :params training: if True, apply dropout.
        """
        # Split keys
        keys = jax.random.split(key, num=2)

        # Sample embedding matrix from embedding distribution
        eps = jax.random.normal(keys[0], shape=self.w_sig.shape)
        sample_embeddings = self.w_mean + jnp.multiply(self.w_sig, eps)

        # Select embeddings corresponding to input ids, add positional embedding
        # embeddings = jnp.asarray(sample_embeddings)[(ids,)] + PositionEncoding(self.config)()
        # Will do position embeddings outside this
        embeddings = jnp.asarray(sample_embeddings)[(ids,)]

        # Apply layer norm
        # embeddings = hk.LayerNorm(
        #     axis=-1, create_scale=True, create_offset=True,
        # )(embeddings)

        # When training apply dropout
        # if training:
        #     embeddings = hk.dropout(
        #         rng=keys[1],
        #         rate=self.config['embed_dropout_rate'],
        #         x=embeddings
        #     )

        kl_div = self.KL_divergence(
            self.w_mean, self.w_sig**2, self.prior_w.params["loc"], self.prior_w.params["scale"]**2
        )

        return embeddings, kl_div

    def KL_divergence(self, posterior_mean, posterior_cov, prior_mean, prior_cov):
        """
        Compute KL divergence between the Gaussian posterior and prior distributions.
        :params posterior_mean: mean vector of the posterior.
        :params posterior_cov: vector with the diagonal elements of the covariance matrix.
        :params prior_mean: scalar or mean vector of the prior.
        :params prior_cov: scalar with the value of the variation of the isotropic Gaussian prior.
        """
        eps = 1e-9
        d = np.prod(posterior_mean.shape)
        kl = 0.5*(jnp.sum((posterior_cov+(posterior_mean-prior_mean)**2)/prior_cov - jnp.log(posterior_cov+eps)) - d + d*jnp.log(prior_cov))

        return kl

class PositionEncoding(hk.Module):
    """
    A position encoding of shape [n_seq, n_hidden].
    """
    def __init__(self, config):
        """
        Build positional encoding.
        :params config: configuration dictionary.
        """
        super().__init__(name="PositionEncoding")
        self.config = config

    def __call__(self):
        """
        Returns sinusoidal position encoding.
        """
        positional_encoding = np.zeros((self.config["max_length"], self.config["hidden_size"]), dtype=np.float32)
        position = np.arange(0, self.config["max_length"])[:, np.newaxis]
        scale_factor = -np.log(self.config["max_scale"] / self.config["min_scale"]) / (self.config["hidden_size"] // 2 - 1)
        div_term = self.config["min_scale"] * np.exp(np.arange(0, self.config["hidden_size"] // 2) * scale_factor)
        positional_encoding[:, :self.config["hidden_size"] // 2] = np.sin(position * div_term)
        positional_encoding[:, self.config["hidden_size"] // 2: 2 * (self.config["hidden_size"] // 2)] = np.cos(position * div_term)

        return positional_encoding


#!/usr/bin/env python

import os
import logging
from dataclasses import dataclass

from tqdm import tqdm

from detectron2.data import DatasetCatalog

logger = logging.getLogger(__name__)

LABELS = (
    'aeroplane',
    'bicycle',
    'bird',
    'boat',
    'bottle',
    'bus',
    'car',
    'cat',
    'chair',
    'cow',
    'diningtable',
    'dog',
    'horse',
    'motorbike',
    'person',
    'pottedplant',
    'sheep',
    'sofa',
    'train',
    'tvmonitor',
)

@dataclass
class CocoDataset(object):

    coco_names: str
    name: str = 'coco_2017_train'
    class_label = None

    def __post_init__(self):
        assert os.path.isfile(self.coco_names)

        with open(self.coco_names, 'r') as f:
            lines = f.read().split('\n')

        self.class_label = {}
        self.match_index = {}
        for i, line in enumerate(lines, 1):
            if line not in LABELS:
                continue
            self.class_label[line] = i
            self.match_index[i] = [len(self.match_index) + 1, line]

    def filter(self):
        logger.warning(f'Reading Catalog for {self.name}')
        coco_data = DatasetCatalog.get(self.name)

        self.dataset = []
        for data in tqdm(coco_data):
            annotations = []
            for anno in data['annotations']:
                category_id = anno['category_id']
                if category_id in self.class_label.values():
                    anno['category_id'] = self.match_index[category_id][0]
                    annotations.append(anno)
            if len(annotations) > 0:
                data['annotations'] = annotations
                self.dataset.append(data)

        logger.warning(f'New dataset size {len(self.dataset)}')
        assert len(self.dataset) > 0

    def __call__(self):
        self.filter()
        return self.dataset

if __name__ == '__main__':

    import sys

    c = CocoDataset(coco_names=sys.argv[1])

    import IPython

    IPython.embed()


import csv
import random

"""
Script de génération du challenge.

Fichier CSV en sorie de la forme suivante :

wallet_source,wallet_destination,montant
"""

def generer_adresse(longueur=32):
	caracteres_hexadecimaux = '0123456789abcdef'
	chaine_hexadecimale = ''

	for _ in range(longueur):
		caractere = random.choice(caracteres_hexadecimaux)
		chaine_hexadecimale += caractere

	return chaine_hexadecimale

# adresse du wallet de départ
premier_wallet = '9e7e75841c73a0b391a1a0485948c30a'
# adresse du wallet d'arrivé == flag
dernier_wallet = '0d26d74d0daad532ac50852fd5742099'
# wallets intermédiaires / non impliqués dans le mixage
wallets_intermediaires = []
for _ in range(100): wallets_intermediaires.append(generer_adresse())

"""
Retourne l'ensemble des transactions entre premier_wallet et dernier_wallet en suivant les intermédiaires.
"""
def mixer(premier_wallet, dernier_wallet, wallets_intermediaires, montant='10'):
	# on créé des transactions entre les wallets intermédiaires
	data = ''
	#print('wallets intermédiaires', wallets_intermediaires)
	for i in range(len(wallets_intermediaires)):
		if i+1 <= len(wallets_intermediaires):
			if i == 0:
				data += premier_wallet+','+wallets_intermediaires[i]+','+montant+'\n'
			else:
				data += wallets_intermediaires[i-1]+','+wallets_intermediaires[i]+','+montant+'\n'
			if i == len(wallets_intermediaires)-1:
				data += wallets_intermediaires[i]+','+dernier_wallet+','+montant
	return data

def ajouter_bruit(signal, nb_transac):
	d = '\n'
	dataset = ''
	dataset = [e+d for e in signal.split(d) if e]

	# on génère la transaction
	for i in range(nb_transac):
		bruit = ''
		w1 = generer_adresse()
		w2 = generer_adresse()

		ws = []

		nb_inter = random.randint(1, 40)
		for j in range(nb_inter): ws.append(generer_adresse())
		bruit += mixer(w1, w2, ws, montant=str(random.randint(1, 11)))
		#print('bruit')
		#print(bruit)

		# on ajoute la transaction au dataset
		# pour chaque sous-transaction de ma transaction
		index = 0
		for transaction in bruit.split('\n'):
			transaction += '\n'
			if index != 0: index = random.randint(index+1, len(dataset))
			else: index=1
			dataset.insert(index, transaction)
			#print('index',index)
	return dataset

signal = mixer(premier_wallet, dernier_wallet, wallets_intermediaires)
#print(signal)

dataset = ajouter_bruit(signal, 1000)
f = open('transactions.csv', 'w')
data = ''
for ligne in dataset: data+=ligne
f.write(data)

f.close()
#print('premier wallet', premier_wallet, '\ndernier_wallet', dernier_wallet, '\nautres wallets', wallets_intermediaires)


import requests
import os

account_id = os.getenv('META_API_ACCOUNT_ID')
token = os.getenv("META_API_TOKEN")
region = os.getenv("META_API_REGION")

class Trading():
    def fetch_candlesticks(symbol, timeframe):
        symbol = symbol.replace('/', '')
        symbol = symbol.upper()
        timeframe_map = {
            "1 minute": "1m",
            "1 min": "1m",
            "1min": "1m",
            "M1": "1m",
            "5 minutes": "5m",
            "5 min": "5m",
            "5min": "5m",
            "M5": "1m",
            "15 minutes": "15m",
            "15 min": "15m",
            "15min": "15m",
            "M15": "15m",
            "30 minutes": "30m",
            "30 min": "30m",
            "30min": "30m",
            "M30": "30m",
            "1 hour": "1h",
            "1hour": "1h",
            "1hr": "1h",
            "H1": "1h",
            "4 hours": "4h",
            "4hours": "4h",
            "4 hrs": "4h",
            "H4": "4h",
            "1 day": "1d",
            "1day": "1d",
            "D1": "1d",
            "1 week": "1w",
            "1week": "1w",
            "W1": "1w",
            "1 month": "1mn",
            "1month": "1mn",
            "MN": "1mn"
        }
        # Check if the user input matches any of the keys in the dictionary
        if timeframe in timeframe_map:
            timeframe = timeframe_map[timeframe]
        else:
            # Assume that the user input is already in the correct format
            pass

        url = f"https://mt-market-data-client-api-v1.{region}.agiliumtrade.ai/users/current/accounts/{account_id}/historical-market-data/symbols/{symbol}/timeframes/{timeframe}/candles?limit=15"
        headers = {
            "auth-token": token,
            "Content-Type": "application/json"
        }
        response = requests.get(url, headers=headers)
        if response:
            candlesticks = response.json()
            return candlesticks
        else:
            return 'Failed to get candlesticks.'

    def close_trade(position_id) -> None:
        trade_data = {
            'actionType': 'POSITION_CLOSE_ID',
            'positionId': position_id
        }
        headers = {
            "auth-token": token,
            "Content-Type": "application/json"
        }
        url = f"https://mt-client-api-v1.{region}.agiliumtrade.ai/users/current/accounts/{account_id}/trade"
        response = requests.post(
            url, headers=headers, json=trade_data)
        response = response.json()
        return response

    def close_all_trades():
        url2 = f"https://mt-client-api-v1.{region}.agiliumtrade.ai/users/current/accounts/{account_id}/positions"
        headers = {
            "auth-token": token,
            "Content-Type": "application/json"
        }
        positions = requests.get(url2, headers=headers)
        positions = positions.json()
        responses = []
        for position in positions:
            trade_data = {
                'actionType': 'POSITION_CLOSE_ID',
                'positionId': position['id']
            }
            url = f"https://mt-client-api-v1.{region}.agiliumtrade.ai/users/current/accounts/{account_id}/trade"
            response = requests.post(
                url, headers=headers, json=trade_data)
            if response:
                print(f"Successfully closed trade for {position['symbol']}")
            else:
                print(f"Failed to close trade for {position['symbol']}")
            if response:
                responses.append(f"Successfully closed trade for {position['symbol']}")
            else:
                responses.append(f"Failed to close trade for {position['symbol']}")

        if responses:
            return responses
        else:
            return f'No trades to close.'

    def get_positions():
        url2 = f"https://mt-client-api-v1.{region}.agiliumtrade.ai/users/current/accounts/{account_id}/positions"
        headers = {
            "auth-token": token,
            "Content-Type": "application/json"
        }
        positions = requests.get(url2, headers=headers)
        if positions:
            positions = positions.json()
            return positions
        else:
            return f'Failed to get positions'

    def get_account_information():
        url = f"https://mt-client-api-v1.{region}.agiliumtrade.ai/users/current/accounts/{account_id}/account-information"
        headers = {
            "auth-token": token,
            "Content-Type": "application/json"
        }
        response = requests.get(url, headers=headers)
        if response:
            response = response.json()
            return response
        else:
            return f'Failed to get account information'

    def place_trade(symbol, volume, signal) -> None:
        signal = signal.upper()
        symbol = symbol.upper()
        symbol = symbol.replace('/', '')
        # Place the new trade
        if signal == 'BUY':
            trade_data = {
                'symbol': symbol,
                'actionType': 'ORDER_TYPE_BUY',
                'volume': float(volume),
                'comment': 'Auto-GPT MetaTrader Plugin'
            }
            headers = {
                "auth-token": token,
                "Content-Type": "application/json"
            }
            url = f"https://mt-client-api-v1.{region}.agiliumtrade.ai/users/current/accounts/{account_id}/trade"
            response = requests.post(url, headers=headers, json=trade_data)

            response = response.json()
            return response

        elif signal == 'SELL':
            trade_data = {
                'symbol': symbol,
                'actionType': 'ORDER_TYPE_SELL',
                'volume': float(volume),
                'comment': 'Auto-GPT MetaTrader Plugin'
            }
            headers = {
                "auth-token": token,
                "Content-Type": "application/json"
            }
            url = f"https://mt-client-api-v1.{region}.agiliumtrade.ai/users/current/accounts/{account_id}/trade"
            response = requests.post(url, headers=headers, json=trade_data)

            response = response.json()
            return response


import pytest

@pytest.mark.parametrize(
    'status',
    [
        'released',
        'in progress',
        'archived',
        'deleted',
        'revoked',
    ]
)
def test_pipeline_valid_statuses(status, testapp, pipeline):
    testapp.patch_json(pipeline['@id'], {'status': status})
    res = testapp.get(pipeline['@id'] + '@@embedded').json
    assert res['status'] == status

def test_pipeline_invalid_statuses(testapp, pipeline):
    with pytest.raises(Exception):
        testapp.patch_json(pipeline['@id'], {'status': 'active'})


import PySimpleGUI as sg
from determinante import *

def janela_m2():
    layout = [
            [sg.Text('Matriz 2x2')],
            [sg.Text('Linha 1', size = (7, 0)), sg.Input(size = (8, 0), k = 'l1')],
            [sg.Text('Linha 2', size = (7, 0)), sg.Input(size = (8, 0), k = 'l2')],
            [sg.Text('Det.', size = (7, 0)), sg.Input(k = 'out', size = (8, 0), readonly = True)],
            [sg.Button('Calcular'), sg.Button('Sair')]
            ]
    return sg.Window('2x2', layout, finalize = True)

tela = janela_m2()
while True:
    evento, dados = tela.read()
    if evento in ['Sair', sg.WIN_CLOSED]:
        break
    elif evento == 'Calcular':
        linha1 = [int(x) for x in dados['l1'] if x.isnumeric()]
        linha2 = [int(x) for x in dados['l2'] if x.isnumeric()]
        matriz = [linha1, linha2]
        try:
            tela['out'].update((matriz_2x2(matriz)))
        except:
            sg.popup('Erro')


# Задача 1: Записать в файл все числа от 0 до числа заданного пользователем

a = int(input('Введите число '))

with open('test.txt','a',encoding='utf-8') as file:
    for i in range(a+1):
        #file.write(f'{i}\n')
        file.writelines('%s\n' % i)


from chimerax.core.models import Model

class SurfaceZone:
    '''
    Add this as a property to a Volume object to provide it with the
    necessary information to update its triangle mask after re-contouring.
    '''
    def __init__(self, session, distance, atoms = None, coords = None):
        '''
        Args:
          distance (float in Angstroms):
            distance from points to which the map will be masked
          atoms:
            Atoms to mask to (coordinates will be updated upon re-masking)
          coords:
            (x,y,z) coordinates to mask to (will not be updated upon
            re-masking).

          Set both atoms and coords to None to disable automatic re-masking.
        '''
        self.session = session
        self.update(distance, atoms, coords)

    def update(self, distance, atoms = None, coords = None):
        self.distance = distance
        self.atoms = atoms
        self.coords = coords

    @property
    def all_coords(self):
        if self.atoms is not None:
            import numpy
            if self.coords is not None:
                return numpy.concatenate(self.atoms.coords, self.coords)
            return self.atoms.coords
        return self.coords

    # from chimerax.surface import zone
    # for m in models:
    #     for s in m.surfaces:
    #         spoints = s.position.inverse(is_orthonormal=True) * points
    #         zone.surface_zone(s, spoints, distance, auto_update=True)

class MapMgr(Model):
    '''
    Top-level manager for all maps associated with a model.
    '''
    DEFAULT_MAX_VOXELS = 1500000

    # SESSION_SAVE=False
    def __init__(self, crystal_manager, spotlight_radius=12, default_oversampling_rate=2.0,
            auto_add = True):
        cm = self._mgr = crystal_manager
        super().__init__('Map Manager', cm.session)
        self._default_oversampling_rate=default_oversampling_rate

        self.contour_mgr = ContourResultMgr(self.session)
        self._zone_mgr = None

        if not hasattr(self, 'triggers'):
            from chimerax.core.triggerset import TriggerSet
            self.triggers = TriggerSet()

        trigger_names = (
            # Deprecated
            'map box changed',
            # Ask each MapSet to expand its volumes to cover an arbitrary set
            # of coordinates as efficiently as possible.
            'cover coords',
            # Change the radius of the "spotlight" sphere. It is up to each
            # MapSet to work out how to accommodate it
            'spotlight changed',
            'spotlight moved',    # Just changed the centre of the box
        )
        for t in trigger_names:
            self.triggers.add_trigger(t)

        self._max_voxels_for_live_remask = self.DEFAULT_MAX_VOXELS

        # Handler for live box update
        self._box_update_handler = None

        # Is the map box moving with the centre of rotation?
        self._spotlight_center = None

        self._initialize_zone_mgr()

        # Radius of the sphere in which the map will be displayed when
        # in live-scrolling mode
        self.spotlight_radius = spotlight_radius

        if self.spotlight_mode:
            self._start_spotlight_mode()

        # self.display=False
        self._rezone_pending = False
        # Apply the surface mask

        mh = self._mgr_handlers = []
        mh.append((cm, cm.triggers.add_handler('mode changed',
            self._spotlight_mode_changed_cb)))

        # self.session.triggers.add_handler('frame drawn', self._first_init_cb)
        if auto_add:
            cm.add([self])

    # def added_to_session(self, session):
    #     super().added_to_session(session)
    #     session.triggers.add_handler('frame drawn', self._first_init_cb)

    def _initialize_zone_mgr(self):
        if self._zone_mgr is None:
            from .mask_handler import ZoneMgr
            coords = [self.spotlight_center]
            self._zone_mgr = ZoneMgr(self.session, 1.5,
                5)

    @property
    def zone_mgr(self):
        return self._zone_mgr

    @property
    def xmapsets(self):
        '''
        Sets of crystallographic maps associated with this model. Each XmapSet
        handles the set of maps derived from a single crystallographic dataset.
        '''
        from .xmapset import XmapSet
        return [m for m in self.child_models() if isinstance(m, XmapSet)]

    @property
    def nxmapset(self):
        '''
        Handler for all real-space (non-crystallographic) maps associated with
        this model.
        '''
        from .nxmapset import NXmapSet
        for m in self.child_models():
            if isinstance(m, NXmapSet):
                return m
        return NXmapSet(self, 'Non-crystallographic maps')

    @property
    def all_xtal_maps(self):
        from .map_handler_base import XmapHandlerBase
        return [m for m in self.all_models() if isinstance(m, XmapHandlerBase)]

    @property
    def all_non_xtal_maps(self):
        from .nxmapset import NXmapHandler
        return [m for m in self.all_models() if isinstance(m, NXmapHandler)]

    @property
    def all_maps(self):
        from chimerax.map import Volume
        return [m for m in self.all_models() if isinstance(m, Volume)]

    @property
    def all_surfaces(self):
        return [s for m in self.all_maps for s in m.surfaces]

    @property
    def crystal_mgr(self):
        return self._mgr

    @property
    def box_center(self):
        return self.crystal_mgr.spotlight_center

    @property
    def structure(self):
        return self.crystal_mgr.structure

    # @property
    # def triggers(self):
    #     return self._triggers

    @property
    def spacegroup(self):
        return self.crystal_mgr.spacegroup

    @property
    def cell(self):
        return self.crystal_mgr.cell

    @property
    def spotlight_radius(self):
        '''Get/set the radius (in Angstroms) of the live map display sphere.'''
        return self._spotlight_radius

    @spotlight_radius.setter
    def spotlight_radius(self, radius):
        import numpy
        self._spotlight_radius = radius
        center = self.crystal_mgr.spotlight_center
        self.triggers.activate_trigger('spotlight changed',
            (center, radius)
        )
        # self._surface_zone.update(radius, coords = numpy.array([center]))
        self._zone_mgr.radius = radius
        self._zone_mgr.pad = radius
        # self._reapply_zone()

    @property
    def box_params(self):
        return (self._box_corner_xyz, self._box_corner_grid, self._box_dimensions)

    @property
    def spotlight_mode(self):
        '''
        Is live map scrolling turned on? Can only be changed via the master
        symmetry manager.
        '''
        return self.crystal_mgr.spotlight_mode

    @spotlight_mode.setter
    def spotlight_mode(self, switch):
        raise NotImplementedError(
            'Mode can only be changed via the master symmetry manager!')

    @property
    def spotlight_center(self):
        '''
        Current (x,y,z) position of the centre of the "spotlight". Read-only.
        '''
        return self.crystal_mgr.spotlight_center

    @property
    def last_covered_selection(self):
        '''
        Last set of coordinates covered by
        `self.crystal_mgr.isolate_and_cover_selection()`. Read-only.
        '''
        return self.crystal_mgr.last_covered_selection

    @property
    def display(self):
        return super().display

    @display.setter
    def display(self, switch):
        Model.display.fset(self, switch)
        if switch:
            if self.spotlight_mode:
                self._start_spotlight_mode()
            self._reapply_zone()

    def add_xmapset_from_mtz(self, mtzfile, oversampling_rate=None,
            auto_choose_reflection_data=True, auto_choose_free_flags=True):
        if oversampling_rate is None:
            oversampling_rate = self._default_oversampling_rate
        return self.add_xmapset_from_file(mtzfile, oversampling_rate,
            auto_choose_reflection_data, auto_choose_free_flags)

    def add_xmapset_from_file(self, sffile, oversampling_rate=None,
            auto_choose_reflection_data=True, auto_choose_free_flags=True):
        if oversampling_rate is None:
            oversampling_rate = self._default_oversampling_rate
        from ..clipper_mtz import ReflectionDataContainer
        mtzdata = ReflectionDataContainer(self.session, sffile,
            shannon_rate = oversampling_rate,
            auto_choose_reflection_data=auto_choose_reflection_data,
            auto_choose_free_flags=auto_choose_free_flags)
        cm = self.crystal_mgr
        if not cm.has_symmetry:
            self.session.logger.info('(CLIPPER) NOTE: No symmetry information found '
                'in model. Using symmetry from MTZ file.')
            cm = self.crystal_mgr
            cm.add_symmetry_info(mtzdata.cell, mtzdata.spacegroup, mtzdata.grid_sampling,
                mtzdata.resolution)

        elif not self.symmetry_matches(mtzdata):
            old_dim = ', '.join([f'{d:.3f}' for d in cm.cell.dim])
            new_dim = ', '.join([f'{d:.3f}' for d in mtzdata.cell.dim])
            old_angles = ', '.join([f'{d:.1f}' for d in cm.cell.angles_deg])
            new_angles = ', '.join([f'{d:.1f}' for d in mtzdata.cell.angles_deg])

            info_str = (f'Old spacegroup: {cm.spacegroup.symbol_hm}\t New:{mtzdata.spacegroup.symbol_hm}\n'
                    f'Old cell dimensions: ({old_dim})\t New: ({new_dim})\n'
                    f'Old cell angles: ({old_angles})\t New: ({new_angles})')
            if len(self.xmapsets):
                raise RuntimeError('(CLIPPER) Symmetry info from new structure factor file does not match '
                    'symmetry info from existing data!\n'+info_str)
            else:
                self.session.logger.warning('(CLIPPER) WARNING: Symmetry info from new structure factor file does '
                    'not match the symmetry info currently associated with the model. Since no other '
                    'crystal datasets are open, the new symmetry will be used.\n'+info_str
                    )
                cm.add_symmetry_info(mtzdata.cell, mtzdata.spacegroup, mtzdata.grid_sampling,
                mtzdata.resolution, override=True)
        from .xmapset import XmapSet
        return XmapSet(self, mtzdata)

    def symmetry_matches(self, xtal_data):
        return (
            xtal_data.cell.equals(self.cell, 1.0)
            and xtal_data.spacegroup.spacegroup_number == self.spacegroup.spacegroup_number
        )

    def _spotlight_mode_changed_cb(self, *_):
        if self.spotlight_mode:
            self._start_spotlight_mode()
        else:
            self._stop_spotlight_mode()

    def _start_spotlight_mode(self):
        zm = self._zone_mgr
        zm.radius = zm.pad = self.spotlight_radius
        zm.allow_remask_on_coord_updates()
        # zm.coords = [self.spotlight_center]
        self.triggers.activate_trigger('spotlight changed',
            (self.spotlight_center, self.spotlight_radius)
        )
        if self._box_update_handler is None:
            self._box_update_handler = self.crystal_mgr.triggers.add_handler(
                'spotlight moved', self.update_spotlight)
            self.update_spotlight(None, self.spotlight_center)
        from chimerax.geometry import Places
        self.positions = Places()
        self._reapply_zone()

    def _stop_spotlight_mode(self):
        if self._box_update_handler is not None:
            self.crystal_mgr.triggers.remove_handler(self._box_update_handler)
            self._box_update_handler = None

    def cover_box(self, minmax):
        '''
        Set the map box to fill a volume encompassed by the provided minimum
        and maximum xyz coordinates. Automatically turns off live scrolling.
        '''
        self.spotlight_mode = False
        xyz_min, xyz_max = minmax
        center = (xyz_min + xyz_max)/2
        self.triggers.activate_trigger('map box changed',
            (center, xyz_min, xyz_max))

    def cover_atoms(self, atoms, transforms=None, transform_indices=None,
            mask_radius=3, extra_padding=12):
        '''
        Expand all maps to a region large enough to cover the atoms, plus
        mask_radius+extra_padding in every direction. If provided, transforms
        should be a Places object, and transform_indices a Numpy array giving
        the index of the Place to be used to transform the coordinates of each
        atom. Unlike cover_coords(), the mask will be periodically updated in
        response to atom movements.
        '''
        zm = self._zone_mgr
        zm.set_symmetry_map(atoms, transforms, transform_indices)
        zm.radius = mask_radius
        zm.pad = extra_padding
        self.triggers.activate_trigger('cover coords',
            (zm.coords, mask_radius+extra_padding))
        displayed_volumes = [v for v in self.all_maps if v.display]
        num_displayed_voxels = sum(v.region_matrix(v.region).size for v in displayed_volumes)
        if num_displayed_voxels > self._max_voxels_for_live_remask:
            zm.block_remask_on_coord_updates()
        else:
            zm.allow_remask_on_coord_updates()
        # self._reapply_zone()

    def cover_coords(self, coords, mask_radius=3, extra_padding=3):
        '''
        Expand all maps to a region large enough to cover the coords, plus
        mask_radius+extra_padding in every direction.
        '''
        self.triggers.activate_trigger('cover coords',
            (coords, mask_radius+extra_padding))
        zm = self._zone_mgr
        zm.coords = coords
        zm.radius = mask_radius
        zm.pad = extra_padding
        # self._surface_zone.update(mask_radius, coords=coords)
        # self._reapply_zone()

    def update_zone_mask(self, coords):
        self._zone_mgr.coords = coords

    def update_spotlight(self, trigger_name, new_center):
        '''
        Update the position of the "spotlight" to surround the current centre of
        rotation. If this manager is not currently displayed, then filling the
        volumes with data around the new position will be deferred unless
        force is set to True.
        '''
        if self.spotlight_mode:
            import numpy
            self.triggers.activate_trigger('spotlight moved',
                new_center)
            zm = self._zone_mgr
            zm.coords = numpy.array([new_center])
            # self._surface_zone.update(self.spotlight_radius, coords = numpy.array([new_center]))
            # self._reapply_zone()

    def rezone_needed(self):
        if not self._rezone_pending:
            self._rezone_pending=True
            self.session.triggers.add_handler('new frame', self._rezone_once_cb)

    # Callbacks

    def _first_init_cb(self, *_):
        self.display = True
        self.update_spotlight(_, self.spotlight_center)
        from chimerax.core.triggerset import DEREGISTER
        return DEREGISTER

    def _rezone_once_cb(self, *_):
        self._reapply_zone()
        self._rezone_pending=False
        from chimerax.core.triggerset import DEREGISTER
        return DEREGISTER

    def _reapply_zone(self):
        '''
        Reapply any surface zone applied to the volume after changing box
        position.
        '''
        from .mask_handler import ZoneMask
        for s in self.all_surfaces:
            asm = s.auto_remask_triangles
            if asm is None:
                ZoneMask(s, self._zone_mgr, None)
            else:
                asm()

    def delete(self):
        self._stop_spotlight_mode()
        for (mgr, h) in self._mgr_handlers:
            try:
                mgr.triggers.remove_handler(h)
            except:
                continue
        self.contour_mgr.delete()
        super().delete()

    def take_snapshot(self, session, flags):
        from chimerax.core.models import Model
        data = {
            'symmetry manager': self._mgr,
            'model state': Model.take_snapshot(self, session, flags)
        }
        from .. import CLIPPER_STATE_VERSION
        data['version']=CLIPPER_STATE_VERSION
        return data

    @staticmethod
    def restore_snapshot(session, data):
        from chimerax.core.models import Model
        sh = data['symmetry manager']
        if sh is None:
            return None
        mmgr = MapMgr(sh, auto_add=False)
        Model.set_state_from_snapshot(mmgr, session, data['model state'])
        session.triggers.add_handler('end restore session', mmgr._end_restore_session_cb)
        return mmgr

    def _end_restore_session_cb(self, *_):
        self._reapply_zone()
        from chimerax.core.triggerset import DEREGISTER
        return DEREGISTER

class ContourResultMgr:
    def __init__(self, session):
        self.session = session
        self._pending = []
        self._handler = self.session.triggers.add_handler('new frame', self._new_frame_cb)

    def enqueue(self, surface, rendering_options):
        self._pending.append((surface, rendering_options))

    def _new_frame_cb(self, *_):
        if len(self._pending):
            s, ro = self._pending.pop(0)
            if not s.deleted:
                s._use_fast_thread_result(ro)

    def delete(self):
        try:
            self.session.triggers.remove_handler(self._handler)
        except Exception as e:
            self.session.logger.warning(f'Failed to clean up ContourResultMgr new frame handler with the following error:\n{str(e)}')


import json
import os

import country_converter as coco
import pandas as pd
from country_converter import country_converter

from scripts.config import PATHS

WEO_YEAR: int = 2023
CAUSES_OF_DEATH_YEAR = 2019
DEBT_YEAR: int = 2023

def get_full_africa_iso3() -> list:
    africa = (
        coco.CountryConverter()
        .data[["ISO3", "continent"]]
        .query("continent == 'Africa'")
        .ISO3.to_list()
    )

    # Add sub saharan Africa
    africa.append("SSA")
    africa.append("SSF")
    africa.append("AFE")
    africa.append("AFW")

    # Add World
    africa.append("WLD")

    # Add Africa
    africa.append("AFR")

    # ADD Global
    africa.append("GLOBAL")

    return africa

def sort_name_first(
    df: pd.DataFrame,
    name: str,
    name_column: str,
    date_column: str,
    keep_current_sorting=True,
):
    if not keep_current_sorting:
        df = df.sort_values([date_column, name_column], ascending=[True, False])

    top = df.query(f"{name_column} == '{name}'").reset_index(drop=True)
    other = df.query(f"{name_column} != '{name}'").reset_index(drop=True)

    return pd.concat([top, other], ignore_index=True)

def base_africa_df():
    """Create a map with geometries for all african countries"""

    return (
        country_converter.CountryConverter()
        .data[["ISO3", "continent"]]
        .rename(columns={"ISO3": "iso_code"})
        .query("continent == 'Africa'")
        .drop(columns="continent")
    )

def _download_wb_regions():
    df = pd.read_excel(
        "http://databank.worldbank.org/" "data/download/site-content/CLASS.xlsx",
        sheet_name="Groups",
    ).rename(
        columns={
            "GroupCode": "group_code",
            "GroupName": "group_name",
            "CountryCode": "iso_code",
            "CountryName": "country_name",
        }
    )
    df.to_csv(f"{PATHS.raw_data}/wb_groupings.csv", index=False)

def read_wb_regions(region_code: str) -> dict:
    """Read World Bank regions from csv file"""

    df = pd.read_csv(f"{PATHS.raw_data}/wb_groupings.csv")

    data = df.groupby("group_code").apply(lambda d: d.iso_code.to_list()).to_dict()

    return data[region_code]

def regions() -> dict:
    north_africa_wb = [
        "DZA",
        "EGY",
        "LBY",
        "MAR",
        "TUN",
    ]

    un_mapping = {
        "Northern Africa": "NAF",
        "Middle Africa": "MAF",
        "Western Africa": "WAF",
        "Eastern Africa": "EAF",
        "Southern Africa": "SAF",
    }

    data = (
        country_converter.CountryConverter()
        .data[["ISO3", "continent", "UNregion"]]
        .rename(columns={"ISO3": "iso_code"})
        .query("continent == 'Africa'")
        .assign(un=lambda d: d.UNregion.map(un_mapping))
    )

    regions_dict = {
        "NAF_WB": north_africa_wb,
        "SSA_WB": data.query("iso_code not in @north_africa_wb").iso_code.to_list(),
        "AFR": data.iso_code.to_list(),
        "SSA_UN": data.query("un != 'NAF'").iso_code.to_list(),
        "AFE_WB": read_wb_regions("AFE"),
        "AFW_WB": read_wb_regions("AFW"),
    }

    # UN regions
    for region in data.un.unique():
        regions_dict[region] = data.query("un == @region").iso_code.to_list()

    return regions_dict

def region_names() -> dict:
    return {
        "NAF_WB": "North Africa (WB)",
        "SSA_WB": "Sub-Saharan Africa (WB)",
        "SSA": "Sub-Saharan Africa (WB exc. high income)",
        "SSF": "Sub-Saharan Africa (WB)",
        "AFE_WB": "Eastern and Southern Africa",
        "AFE": "Eastern and Southern Africa",
        "AFW_WB": "Western and Central Africa",
        "AFW": "Western and Central Africa",
        "AFR": "Africa",
        "SSA_UN": "Sub-Saharan Africa (UN)",
        "NAF": "Northern Africa",
        "MAF": "Middle Africa",
        "WAF": "Western Africa",
        "EAF": "Eastern Africa",
        "SAF": "Southern Africa",
        "WLD": "World",
    }

def clean_wb_overview(df: pd.DataFrame) -> pd.DataFrame:
    """Clean World Bank data for overview charts

    returns a dataframe for a line chart with values for World and SSA
    """

    return (
        df.loc[lambda d: d["iso_code"].isin(["WLD", "SSA"])]
        .pivot(index="date", columns="iso_code", values="value")
        .round(2)
        .reset_index()
        .dropna(subset=["SSA", "WLD"])
        .rename(columns={"SSA": "Sub-Saharan Africa", "WLD": "World"})
    )

def df_to_key_number(
    df: pd.DataFrame,
    indicator_name: str,
    id_column: str,
    value_columns: str | list[str],
) -> dict:
    if isinstance(value_columns, str):
        value_columns = [value_columns]

    return (
        df.assign(indicator=indicator_name)
        .filter(["indicator", id_column] + value_columns, axis=1)
        .groupby(["indicator"])
        .apply(
            lambda x: x.set_index(id_column)[value_columns]
            .astype(str)
            .to_dict(orient="index")
        )
        .to_dict()
    )

def update_key_number(path: str, new_dict: dict) -> None:
    """Update a key number json by updating it with a new dictionary"""

    # Check if the file exists, if not create
    if not os.path.exists(path):
        with open(path, "w") as f:
            json.dump({}, f)

    with open(path, "r") as f:
        data = json.load(f)

    for k in new_dict.keys():
        data[k] = new_dict[k]

    with open(path, "w") as f:
        json.dump(data, f, indent=4)


N = int(input())
answer = []

for i in range(N):
    answer.append(input())

answer = list(set(answer))
answer = sorted(answer, key=lambda x: (len(x),x) )

for i in answer :
    print(i)


from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/user_info/')
def get_user_info():
    return jsonify({'slackUsername':'tshergzeh',
                    'backend':True,
                    'age':21,
                    'bio':'I am a backend developer participating in the HNG9 internship.'})

@app.route('/operate', methods=['POST'])
def operate():
    if not request.json or not 'operation_type' in request.json or not 'x' in request.json or not 'y' in request.json:
        abort(400)
    operation = {
        'operation_type': request.json['operation_type'],
        'x': request.json['x'],
        'y': request.json['y']
    }
    if operation['operation_type'] == 'addition':
        result = operation['x'] + operation['y']
    elif operation['operation_type'] == 'subtraction':
        result = operation['x'] - operation['y']
    elif operation['operation_type'] == 'multiplication':
        result = operation['x'] * operation['y']
    else:
        abort(400)
    return jsonify({'slackUsername': 'tshergzeh',
        'operation_type': operation['operation_type'],
        'result': result
    })

@app.route('/')
def hello_world():
    return 'Hello World!'


import asyncio
import concurrent.futures
import subprocess
import threading

from . import selector, socket as _socket
from .exceptions import SolipsismError

__all__ = ('EventLoop', 'stream_pairs')

class EventLoop(asyncio.selector_events.BaseSelectorEventLoop):
    def __init__(self):
        super().__init__(selector=selector.Selector())
        self._selector = selector.Selector()
        self._clock_resolution = self._selector.clock.resolution
        # Map from (host, port) pair to ListenSocket
        self.__listening_sockets = {}
        self.__next_port = 1

    def time(self):
        return self._selector.clock.time()

    def call_soon_threadsafe(self, callback, *args, context=None):
        if self._thread_id == threading.get_ident():
            return self.call_soon(callback, *args, context=context)
        raise SolipsismError("call_soon_threadsafe is not supported")

    async def run_in_executor(self, executor, func, *args):
        # Mostly copies the base class code, but runs synchronously
        self._check_closed()
        if self._debug:
            self._check_callback(func, 'run_in_executor')
        if executor is None:
            executor = self._default_executor
            if executor is None:
                executor = concurrent.futures.ThreadPoolExecutor()
                self._default_executor = executor
        return executor.submit(func, *args).result()

    async def getaddrinfo(self, host, port, *,
                          family=0, type=0, proto=0, flags=0):
        raise SolipsismError("getaddrinfo is not supported")

    async def getnameinfo(self, sockaddr, flags=0):
        raise SolipsismError("getnameinfo is not supported")

    async def create_connection(
            self, protocol_factory, host=None, port=None,
            *, ssl=None, sock=None, **kwargs):
        if ssl:
            raise SolipsismError("create_connection with SSL is not supported")
        if sock is None:
            if host is None and port is None:
                raise ValueError('host and port was not specified and no sock specified')
            addr = (host, port, 0, 0)
            try:
                listener = self.__listening_sockets[addr]
            except KeyError:
                raise ConnectionRefusedError(f'No socket listening on {host}:{port}') from None
            port = self.__next_port
            self.__next_port += 1
            sock = await listener.make_connection(('::1', port, 0, 0))
        return await super().create_connection(
            protocol_factory, None, None,
            ssl=ssl, sock=sock, **kwargs
        )

    async def start_tls(self, transport, protocol, sslcontext, *,
                        server_side=False,
                        server_hostname=None,
                        ssl_handshake_timeout=None):
        raise SolipsismError("start_tls is not supported")

    async def create_datagram_endpoint(self, protocol_factory,
                                       local_addr=None, remote_addr=None, *,
                                       family=0, proto=0, flags=0,
                                       reuse_address=None, reuse_port=None,
                                       allow_broadcast=None, sock=None):
        raise SolipsismError("create_datagram_endpoint is not supported")

    async def create_server(
            self, protocol_factory, host=None, port=None,
            *,
            sock=None,
            ssl=None,
            reuse_address=None,
            reuse_port=None,
            **kwargs):
        if ssl is not None:
            raise SolipsismError("create_server with ssl is not supported")
        if sock is None:
            if host is None and port is None:
                raise ValueError('Neither host/port nor sock were specified')
            # TODO: what if host is actually a list?
            addr = (host, port, 0, 0)
            sock = _socket.ListenSocket(addr)
        addr = sock.getsockname()
        if addr[1] == 0:  # Port 0: pick a free port
            addr_list = list(addr)
            addr_list[1] = 60000
            while tuple(addr_list) in self.__listening_sockets:
                addr_list[1] += 1
            addr = tuple(addr_list)
            sock._sockname = addr
        if addr in self.__listening_sockets:
            raise SolipsismError("Reuse of listening addresses is not supported")
        self.__listening_sockets[addr] = sock
        return await super().create_server(
            protocol_factory, None, None,
            sock=sock,
            ssl=ssl,
            reuse_address=False,
            reuse_port=False,
            **kwargs
        )

    async def connect_read_pipe(self, protocol_factory, pipe):
        raise SolipsismError("connect_read_pipe is not supported")

    async def connect_write_pipe(self, protocol_factory, pipe):
        raise SolipsismError("connect_write_pipe is not supported")

    async def subprocess_shell(self, protocol_factory, cmd, *,
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               universal_newlines=False,
                               shell=True, bufsize=0,
                               encoding=None, errors=None, text=None,
                               **kwargs):
        raise SolipsismError("subprocess_shell is not supported")

    async def subprocess_exec(self, protocol_factory, program, *args,
                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE, universal_newlines=False,
                              shell=False, bufsize=0,
                              encoding=None, errors=None, text=None,
                              **kwargs):
        raise SolipsismError("subprocess_exec is not supported")

    async def sock_connect(self, sock, address):
        raise SolipsismError("sock_connect is not supported")

    async def sock_accept(self, sock):
        raise SolipsismError("sock_accept is not supported")

    def add_signal_handler(self, sig, callback, *args):
        raise SolipsismError("add_signal_handler is not supported")

    def remove_signal_handler(self, sig):
        raise SolipsismError("remove_signal_handler is not supported")

    async def create_unix_connection(
            self, protocol_factory, path=None, *,
            ssl=None, sock=None,
            server_hostname=None,
            ssl_handshake_timeout=None):
        raise SolipsismError("create_unix_connection is not supported")

    async def create_unix_server(
            self, protocol_factory, path=None, *,
            sock=None, backlog=100, ssl=None,
            ssl_handshake_timeout=None,
            start_serving=True):
        raise SolipsismError("create_unix_server is not supported")

    # Methods in base class that we need to implement/override

    def _make_self_pipe(self):
        pass

    def _close_self_pipe(self):
        pass

    def _stop_serving(self, sock):
        addr = sock.getsockname()
        self.__listening_sockets.pop(addr)
        super()._stop_serving(sock)

async def stream_pairs(capacity=None):
    sock1, sock2 = _socket.socketpair(capacity=capacity)
    streams1 = await asyncio.open_connection(sock=sock1)
    streams2 = await asyncio.open_connection(sock=sock2)
    return streams1, streams2


import statistics
#Splitting the file name into variables
FOLDER = "../swimdata/"

def read_swim_data(filename):
    swimer, age, distance, stroke = filename.removesuffix(".txt").split("-")

    # Retrieving data from file
    with open(FOLDER + filename) as file:
        lines = file.readlines()
        # Remember, that strip remove the break line
        times = lines[0].strip().split(",")

    converts = []

    for t in times:
        if ":" in t:
            minutes, rest = t.split(":")
            seconds, hundredths = rest.split(".")

        else:
            minutes = 0
            seconds, hundredths = t.split(".")

        converts.append((int(minutes) * 60 * 100) + (int(seconds) * 100) + int(hundredths))

    average = statistics.mean(converts)

    round(average/ 100, 2) #86.56, where 86 - seconds, 56 - hundredths

    mins_secs, hundredths = str(round(average / 100, 2)).split(".") # ['86', '58']

    mins_secs = int(mins_secs)

    minutes = mins_secs // 60
    seconds = mins_secs - minutes * 60

    average = str(minutes) + ":" + str(seconds) + "." + hundredths

    #print(average)

    return average, swimer, age, distance, stroke, times


"""
Stopwatch program
This program is a stopwatch timer which tests
your reflexes to get a tenth of a second arriving
at a zero value
"""
import simplegui
import random

# Step 1 - Initialise Global Variables
"""
Step to consider for simplegui stopwatch implemtation
1 - Initialize global variables
2 - Define helper functions
3 - Define classes
4 - Define event handlers
5 - Create frame
6 - Register event handlers
7 - Start frame and timers
"""
# Initialise global variables
canvas_width, canvas_height = 220, 200
stopwatch_time, stopped_time = 0, 0 # stopped_time is the reflex part
started = False # Used to see if the stopwatch should be started
stop_count, matched_count = 0, 0  # matched_count is the reflex counter

# Step 2 - define helper functions
def format( time_val ) :
    """
    Helper function to convert int to str type of Mins:Secs:TenthsofSecs format
    Set the time string to Minutes:Seconds:Tenths from TenthsofSecs integer
    """
    return ( '%01d:%02d.%01d' % ( time_val / 600, \
                                 (time_val / 10) % 60, \
                                 time_val % 10 ))

# Step 3 - Define classes increment, start_button, stop_button, draw and restart
def increment():
    global stopwatch_time
    stopwatch_time += 1

def start_button() :
    global started

    started = True
    stopwatch_timer.start()

def stop_button():
    global stop_count
    global started
    global matched_count
    global stopped_time

    if started:
        stopwatch_timer.stop()
        started = False
        stop_count += 1
        if ( stopped_time % 10 == 0 ) :
            matched_count += 1

def draw(canvas):
    global stopped_time

    stopped_time = stopwatch_time

    #canvas.draw_text( str(stopwatch_time), [100, 100], 36, "White")
    canvas.draw_text( format(stopwatch_time), [50, 100], 36, "White")
    canvas.draw_text( str(matched_count) + " / " + str(stop_count), \
                     [140, 30], 30, "Green")

def restart():
    global started, stopwatch_time, stop_count, matched_count

    started = False
    stopwatch_time, matched_count, stop_count, stopped_time = 0, 0, 0, 0

    stopwatch_timer.stop()

# Step 5 - Creating a frame
frame = simplegui.create_frame( "Stopwatch", canvas_width, canvas_height )

# Step 6 - Register event handlers
frame.set_draw_handler(draw)
stopwatch_timer = simplegui.create_timer(100, increment)
frame.add_button("Start", start_button, 100)
frame.add_button("Stop", stop_button, 100)
frame.add_button("Restart", restart, 100)

# Step 7 - Start Frame and stopwatch_timer
frame.start()
# stopwatch_timer.start()


from modules.motors import *
from modules.colors import *
from modules.detect import *
from modules.claw import *
from modules.delivery import *
from pybricks.tools import StopWatch

pointed_to = 1
cardinal_points = ["N", "E", "S", "W"]
cronometer = StopWatch()
size_of_tube = 0
color_of_tube = ""
initial_path = [0, 0, 0, 0]
current_path = [0, 0, 0, 0]

# server
from pybricks.messaging import BluetoothMailboxServer, TextMailbox
server = BluetoothMailboxServer()
mbox = TextMailbox('greeting', server)

# The server must be started before the client!
print('waiting for connection...')
server.wait_for_connection()
print('connected!')

def find_blue_line(numero_de_paredes):
    if numero_de_paredes < 4:
        brake_motors()

        cor_vista = ""

        print("procurando")
        while not is_blue() and not is_black_left() and not is_black_right() and not is_yellow_left() and not is_yellow_right() and not is_red_left() and not is_red_right() and not has_obstacle():
            andar_reto(360)
            #print("RGB Esquerdo: ", red_left(), green_left(), blue_left(), "RGB Direito: ", red_right(), green_right(), blue_right())
        brake_motors()

        if is_red_left() or is_red_right():
            cor_vista = "RED"
        elif is_black_left() or is_black_right():
            cor_vista = "BLACK"
        elif is_yellow_left() or is_yellow_right():
            cor_vista = "YELLOW"
        time_forward = cronometer.time()
        if not is_blue() and not (is_red_left() or is_red_right()) and not (is_black_left() or is_black_right()) and not (is_yellow_left() or is_yellow_right()) and not has_obstacle():
            while not is_blue_left() and not is_blue_right() and not is_black_left() and not is_black_right() and not is_yellow_left() and not is_yellow_right() and not is_red_left() and not is_red_right():
                andar_reto(-360)
            brake_motors()
        if cor_vista != "":
            ajust_color(cor_vista) # eu não estou suportando mais por favor alguem me ajuda

        if (is_red_left() or is_red_right()):
            print("Achou RED")
            brake_motors()
            move_backward(43)
            turn_left_pid(90)
            brake_motors()
            while not is_blue():
                andar_reto(360)
                if (is_black_left() or is_black_right()) or (is_yellow_left() or is_yellow_right()) or is_wall():
                    brake_motors()
                    turn_right_pid(180)
                elif has_obstacle():
                    brake_motors()
                    while ultrasound_sensor.distance() > 145:
                        andar_reto(360)
                    brake_motors()
                    while ultrasound_sensor.distance() < 145:
                        andar_reto(-150)
                    brake_motors()
                    turn_right_pid(90)
                    cronometer.reset()
                    while not is_red_left() and not is_red_right() and not has_obstacle():
                        andar_reto(360)
                    brake_motors()
                    if cronometer.time() < 6000 or has_obstacle():
                        turn_right_pid(180)
                        while ultrasound_sensor.distance() > 145 and not is_red_left() and not is_red_right():
                            andar_reto(360)
                        brake_motors()
                        if is_red_left() or is_red_right():
                            move_backward(43)
                            turn_right_pid(90)
                    else:
                        move_backward(43)
                        turn_left_pid(90)
                        find_blue_line(0)
            brake_motors()

        elif (is_black_left() or is_black_right()) or (is_yellow_left() or is_yellow_right()) or is_wall() or has_obstacle():
            print("Achou parede")
            print("Voltando...")
            if is_black_left() or is_black_right() or is_yellow_left() or is_yellow_right():
                move_backward(8)
            elif has_obstacle():
                while ultrasound_sensor.distance() > 145:
                    andar_reto(360)
                while ultrasound_sensor.distance() < 145:
                    andar_reto(-150)
                brake_motors()
            turn_right_pid(90)
            print("Vai somar mais um no numero_de_paredes")
            print(numero_de_paredes)
            find_blue_line(numero_de_paredes + 1)

    else:
        turn_right_pid(90)
        while ultrasound_sensor.distance() > 145 and not is_black_left() and not is_black_right() and not is_yellow_left() and not is_yellow_right():
            andar_reto(360)
        brake_motors()
        if is_black_left() or is_black_right() or is_yellow_left() or is_yellow_right():
            cor_vista = "BLACK"
            ajust_color(cor_vista)
            move_backward(8)
        find_blue_line(0)

def align_to_begin_scan():
    brake_motors()
    print("Achei o azul")
    move_backward(0.6)
    turn_right_pid(90)

    branco = 90 # 80
    azul = 10
    threshold = (branco + azul) / 2  # = 40
    vel = 100
    chegou_no_fim = False

    while not chegou_no_fim:

        delta = threshold - red_left()
        kp = 0.45
        erro = delta * kp
        motors.drive(vel, erro)

        if is_red_right():
            chegou_no_fim = True
            brake_motors()

    wait(500)
    move_backward(0.7)
    brake_motors()

    wait(500)
    turn_left_pid(90)
    brake_motors()

    wait(500)
    move_forward(14)
    brake_motors()

    wait(500)
    turn_left_pid(90)
    brake_motors()

def scan():
    global color_of_tube
    global size_of_tube

    cronometer.reset()
    print("Procurando tubo...")
    while not tube_is_detected():
        andar_reto(150)
    brake_motors()
    tempo = cronometer.time()

    mbox.send('chave')
    mbox.wait()

    size_of_tube = mbox.read()
    size_of_tube = int(size_of_tube)

    Close()

    if is_red_tube():
        color_of_tube = "RED"
    elif is_green_tube():
        color_of_tube = "GREEN"
    elif is_blue_tube():
        color_of_tube = "BLUE"
    else:
        color_of_tube = "BROWN"

    print("Tubo encontrado:", size_of_tube, "de cor", color_of_tube)

    cronometer.reset()

    while cronometer.time() < tempo:
        andar_reto(-150)
    brake_motors()
    wait(250)

    move_forward(1)
    print("Sai do scan")

def set_path():
    global color_of_tube
    global size_of_tube

    print("Entrei")
    if size_of_tube == 15:
        print("Tem 15 cm")#$%¨&*(
        if color_of_tube == "RED": #Farmacia
            tube_drugstore()
        if color_of_tube == "GREEN": #Prefeitura
            tube_city_hall()
        if color_of_tube == "BLUE": #Museu
            tube_museum()
        if color_of_tube == "BROWN": #Padaria
            tube_bakery()
    else:
        print("Entrei no else")#$%¨&*(

        if color_of_tube == "GREEN": #Parque
            tube_park()
        if color_of_tube == "BLUE": #Escola
            tube_school()
        if color_of_tube == "BROWN": #Biblioteca
            tube_library()
        if color_of_tube == "RED":
            tube_drugstore()


# !/usr/bin/env python
# -*- coding:utf-8 -*-
from math import sqrt

def get_float(msg = "Bitte Zahl eingeben: "):
    while True:
        try:
            f = float(input(msg))
            return f
        except ValueError:
            print("Ops! Ungültige Eingabe. Bitte nochmals probieren: ")

def main():
    print("-----Schnittpunkte einer Quadratische Gleichungen und Geraden lösen-----")
    print("------------ ax^2+bx+c = mx + q -------------")
    a = get_float(msg = "Bitte Koeffizienten a eingeben: ")
    b = get_float(msg = "Bitte Koeffizienten b eingeben: ")
    c = get_float(msg = "Bitte Koeffizienten c eingeben: ")
    m = get_float(msg = "Bitte Koeffizienten m eingeben: ")
    p = get_float(msg = "Bitte Koeffizienten q eingeben: ")
    b_neu = b-m
    q_neu = c-p

    if a == 0.0:
        x = -q_neu/b_neu
        print(f"Es gibt eine reelle Lösung: x = {x}")
    else:
        p = b_neu/a
        q = q_neu/a
        diskriminante = ((p/2)*(p/2)) - q

        #Es gibt zwei verschiedene reelle Lösungen
        if diskriminante > 0:
            x1 = -p/2 + sqrt(diskriminante)
            x2 = -p/2 - sqrt(diskriminante)
            print(f"Es gibt zwei reelle Lösungen: x1 = {x1}, x2 = {x2}")
        #Es gibt eine reelle Lösung
        elif diskriminante == 0:
            x = -p/2
            print(f"Es gibt eine reelle Lösung: x = {x}")
        #Es gibt keine reelle Lösungen
        else: #diskriminante < 0
            print(f"Es keine reelle Lösung")

if __name__ == '__main__':
    main()


'''Задача 103: Задана натуральная степень k. Сформировать случайным образом список коэффициентов (значения от 0 до 100) многочлена и записать в файл file1.txt многочлен степени k.

Пример:  k=2
Возможные варианты многочленов:
2*x*x + 4*x + 5 = 0
x*x + 5 = 0
10*x*x = 0

'''
import random
import os

def get_polynomial(k):
    result = []
    ktemp = k
    if k < 1:
        raise Exception(f'invalid parametr k={k}, must be greater than 0 ')
    while True:
        k = ktemp
        result = []
        while k >= 0:
            kf = random.randint(0, 101)
            if k == 0:
                if kf > 0:
                    result.append(str(kf))
                break

            if kf == 0:
                k -= 1
                continue

            operand = ('*x^{}'.format(k)) if k > 1 else '*x'
            if kf == 1:
                operand = operand[1:]
                result.append(operand)
            else:
                result.append('{}{}'.format(kf, operand))
            k -= 1
        if 'x' in result:  # проверка, что коэффициенты при X^n не равны 0
            # если в многочлене все коэффициенты при X равны нулю, то генерируем заново
            break
    # print(result)
    return (' + '.join(result)+' = 0\n')

def saveFiles(k, n):
    for index in range(1, 3):
        lines = set()
        while len(lines) < n:  # собираем неповторяющиеся многочлены
            lines.add(get_polynomial(k))
        with open(f'task103_file{index}.txt', 'w') as outputFile:
            outputFile.writelines(lines)

os.system('cls')
k = int(input('введите степень многочлена: '))
n = int(input('укажите число примеров для генерации: '))
saveFiles(k, n)


import os
from datetime import datetime, timedelta
from aiogram import Bot, Dispatcher, executor, types
from aiogram.types import ReplyKeyboardRemove, ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ContentType

button_hi = KeyboardButton('Сливы')
button_hi2 = KeyboardButton('Архивы')
button_hi3 = KeyboardButton('Приватка')
greet_kb = ReplyKeyboardMarkup(resize_keyboard=True)
greet_kb.add(button_hi,button_hi2,button_hi3)

Arhivi = KeyboardButton('Школьницы')
Arhivi2 = KeyboardButton('Милфы')
menu = KeyboardButton('Главное меню')
Arhivis = ReplyKeyboardMarkup(resize_keyboard=True)
Arhivis.add(Arhivi,Arhivi2,menu)

Privatka = KeyboardButton('Купить')
Otzivi = KeyboardButton('Отзывы')
menu = KeyboardButton('Главное меню')
press = ReplyKeyboardMarkup(resize_keyboard=True)
press.add(Privatka,Otzivi,menu)

Pokypka_arhiv = KeyboardButton('Купить Архив со Шк')
menu = KeyboardButton('Главное меню')
arif = ReplyKeyboardMarkup(resize_keyboard=True)
arif.add(Pokypka_arhiv,menu)

Pokypka_arhiv2 = KeyboardButton('Купить Архив со Милфами')
menu = KeyboardButton('Главное меню')
arif2 = ReplyKeyboardMarkup(resize_keyboard=True)
arif2.add(Pokypka_arhiv2,menu)

sub_inline_markup = InlineKeyboardMarkup(row_width=1)
ssilka_oplata = InlineKeyboardButton(text="Месяц приватки 250р", callback_data="submonth")
sub_inline_markup.insert(ssilka_oplata)

sub_inline_shkool_markup = InlineKeyboardMarkup(row_width=1)
ssilka_oplata_shkool = InlineKeyboardButton(text="Покупка архива школьниц", callback_data="shkool")
sub_inline_shkool_markup.insert(ssilka_oplata_shkool)

sub_inline_milfs_markup = InlineKeyboardMarkup(row_width=1)
ssilka_oplata_milfs = InlineKeyboardButton(text="Покупка архива милф", callback_data="milfs")
sub_inline_milfs_markup.insert(ssilka_oplata_milfs)

TOKEN_KASSA = "381764678:TEST:33651"
API_TOKEN = "5220046644:AAEHt4ki_jK3mH8S0ds8-2UNxfSqJ5xZCtw"
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)

@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
    await message.answer("Привет, я бот приват Сливов @slivu97\n<◇>~•~ОБЬЯВЛЕНИЕ~•~<◇>\nБот в ранем доступе! прошу не покупать архивы\nПотратите деньги в пустую.\n<◇>~•~ОБЬЯВЛЕНИЕ~•~<◇>\nВыбери что тебя интересует",reply_markup=greet_kb)

@dp.message_handler(text=['Главное меню'])
async def glav_menu(message: types.Message):
    await message.answer("~~~~Вы_Перешли_В~~~~\n~~~главное меню~~~",reply_markup=greet_kb)

@dp.message_handler(text=['Сливы'])
async def nashi_slivu(message: types.Message):
    await message.answer("Наши сливы\n№1 - @slivu97\n№2 - @slivu96")

@dp.message_handler(text=['Архивы'])
async def arhifs_menu(message: types.Message):
    await message.answer("Есть архивы вот такие:\n№1-Школьницы\n№2-Милфы",reply_markup=Arhivis)

@dp.message_handler(text=['Приватка'])
async def privatochka(message: types.Message):
    await message.answer("Вход в приватку стоит 250р\nУспей пока цены не поднялись",reply_markup=press)

@dp.message_handler(text=['Школьницы'])
async def shk(message: types.Message):
    await message.answer("Архив со шк 1гб Цена 500р", reply_markup=arif)

@dp.message_handler(text=['Милфы'])
async def mifs(message: types.Message):
    await message.answer("Архив со Милфами 1гб Цена 250р",reply_markup=arif2)

@dp.message_handler(text=['Купить Архив со Шк'])
async def arhif_shk(message: types.Message):
    await message.answer("◇ВОТ ИНЛАЙН КНОПКА ДЛЯ ОПЛАТЫ◇", reply_markup=sub_inline_shkool_markup)

@dp.message_handler(text=['Купить Архив со Милфами'])
async def arhif_mifs(message: types.Message):
    await message.answer("◇ВОТ ИНЛАЙН КНОПКА ДЛЯ ОПЛАТЫ◇", reply_markup=sub_inline_milfs_markup)

@dp.message_handler(text=['Рефиральная Ссылка'])
async def ref_silka(message: types.Message):
    await message.answer("Ещё не создана")

@dp.message_handler(text=['Купить'])
async def process_h2_command(message: types.Message):
    await message.answer("◇ВОТ ИНЛАЙН КНОПКА ДЛЯ ОПЛАТЫ◇", reply_markup=sub_inline_markup)

@dp.message_handler(text=['Отзывы'])
async def procss_hi2_command(message: types.Message):
    await message.answer("Лови")
    await bot.send_photo(message.chat.id,photo=open('1.jpg', 'rb'))
    await bot.send_photo(message.chat.id,photo=open('2.jpg', 'rb'))
    await bot.send_photo(message.chat.id,photo=open('3.jpg', 'rb'))

@dp.message_handler(text=['Пополнить'])
async def esli_kupil_privat(message: types.Message):
    await message.answer("◇ВОТ ИНЛАЙН КНОПКА ДЛЯ ОПЛАТЫ◇", reply_markup=sub_inline_markup)

@dp.callback_query_handler(text=['shkool'])
async def submonth(callp: types.CallbackQuery):
    await bot.delete_message(callp.from_user.id, callp.message.message_id)
    await bot.send_invoice(chat_id=callp.from_user.id, title="Покупка архива школьниц", description="Покупка архива со школьницами", payload="month_shkool", provider_token=TOKEN_KASSA, currency="RUB", start_parameter="bot_shk",prices=[{"label": "Руб", "amount": 50000}])

@dp.pre_checkout_query_handler()
async def process_pre_checkout_query(pre_checkout_query: types.PreCheckoutQuery):
    await bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True)

@dp.message_handler(content_types=ContentType.SUCCESSFUL_PAYMENT)
async def process_pay_shk(message: types.Message):
    if message.successful_payment.invoice_payload == "month_shkool":
        await message.answer(f"Держи ссылку\nhttps://mega.nz/folder/vaYHlYTJ#jlFyV7T2uq3-J4X1nenP1A")

@dp.callback_query_handler(text=['milfs'])
async def milfs_arhiv(calls: types.CallbackQuery):
    await bot.delete_message(calls.from_user.id, calls.message.message_id)
    await bot.send_invoice(chat_id=calls.from_user.id, title="Покупка архива милфами", description="Покупка архива с милфами", payload="month_filfs", provider_token=TOKEN_KASSA, currency="RUB", start_parameter="bot_milfs",prices=[{"label": "Руб", "amount": 25000}])

@dp.pre_checkout_query_handler()
async def process_pre_checkout_query(pre_checkout_query: types.PreCheckoutQuery):
    await bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True)

@dp.message_handler(content_types=ContentType.SUCCESSFUL_PAYMENT)
async def process_pay_milf(message: types.Message):
    if message.successful_payment.invoice_payload == "month_filfs":
        await message.answer(f"Держи ссылку\nНа милф")

@dp.callback_query_handler(text=['submonth'])
async def submonth(call: types.CallbackQuery):
    await bot.delete_message(call.from_user.id, call.message.message_id)
    await bot.send_invoice(chat_id=call.from_user.id, title="Покупка привата", description="Покупка доступа к приват каналу", payload="month_sub", provider_token=TOKEN_KASSA, currency="RUB", start_parameter="test_bots",prices=[{"label": "Руб", "amount": 25000}])

@dp.pre_checkout_query_handler()
async def process_pre_checkout_query(pre_checkout_query: types.PreCheckoutQuery):
    await bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True)

@dp.message_handler(content_types=ContentType.SUCCESSFUL_PAYMENT)
async def process_pay(message: types.Message):
    if message.successful_payment.invoice_payload == "month_sub":
        chat_id = -1001554743391
        expire_date = datetime.now()
        timedelta(days=1)
        link = await bot.create_chat_invite_link(chat_id, expire_date.timestamp, 1)
        await message.answer(f"Держи ссылку\n{link.invite_link}")

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)


"""
Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

Performing BFS using queue to find the route between two nodes.S
"""
from collections import  deque
class Graph:
    def __init__(self, edges, N):
        self.adjacent = [[] for i in range(N)]
        for (source,dest) in edges:
             self.adjacent[source].append(dest)

def isConnected(graph,source,dest, visited):
    q  = deque()
    visited[source] = True    #source vertex is visited
    q.append(source)
    while q:
        v = q.popleft()
        if v == dest:    #if destination found
            return True
        for u in graph.adjacent[v]:    #for every adjacent node(v -> u)
            if not visited[u]:
                visited[u] = True       #marking as visited
                q.append(u)             #append to the queue
    return False
if __name__ == '__main__':
    edges = [(0,3),(1,0),(1,2),(1,4),(2,7),(3,4),(3,5),(4,3),(4,6),(5,6),(6,7) ]   #edges of the graph
    N = 8   #number of nodes in the graph
    graph = Graph(edges,N)
    visited =  [False] * N
    (source, dest) = (0,1)   #sourcea and destination vertex
    if isConnected(graph,source,dest,visited):
        print("Route exists between ", source, " to ", dest)
    else:
        print("No Route exists between ", source, " to ", dest)


import sys

input = sys.stdin.readline
INF = int(1e4)

n,m = map(int,input().split())

graph = [[INF] * (n) for _ in range(n)]

for a in range(n):
    for b in range(n):
        if a == b:
            graph[a][b] = 0

for _ in range(m):
    s, e = map(int, input().split())
    graph[s-1][e-1] = 1
    graph[e-1][s-1] = 1

for k in range(n):
    for a in range(n):
        for b in range(n):
            if a == b:
                graph[a][b] = 0
            else:
                graph[a][b] = min(graph[a][b], graph[a][k] + graph[k][b])

result = []
for each in graph:
    result.append(sum(each))

Min = min(result)
for idx, each in enumerate(result):
    if each == Min:
        print(idx+1)
        break

백준/Silver/1389. 케빈 베이컨의 6단계 법칙/케빈 베이컨의 6단계 법칙.py

케빈 베이컨의 6단계 법칙.py


#-*- coding:utf-8 -*-
__author__ = 'liubf'

from django.views.decorators.csrf import csrf_exempt
from django.core.paginator import Paginator
from django.shortcuts import render
from base.utils import MethodUtil as mtu,DateUtil
from base.models import BasPurLog
import datetime;

__EACH_PAGE_SHOW_NUMBER = 10

@csrf_exempt
def purlog(request):
    pageNum = mtu.getReqVal(request,"pageNum","1")
    start = mtu.getReqVal(request,"start")
    end = mtu.getReqVal(request,"end")
    ucode = mtu.getReqVal(request,"ucode","")
    pname = mtu.getReqVal(request,"pname","")

    try:
        karrs = {}
        if not start:
            start = (datetime.date.today().replace(day=1)).strftime("%Y-%m-%d")
        if not end:
            end = datetime.datetime.today().strftime("%Y-%m-%d")

        karrs.setdefault("createtime__gte", "{start} 00:00:00".format(start=start))
        karrs.setdefault("createtime__lte", "{end} 23:59:59".format(end=end))
        karrs.setdefault("ucode__contains", "{ucode}".format(ucode=ucode))
        karrs.setdefault("name__contains", "{pname}".format(pname=pname))

        rlist = BasPurLog.objects.all().filter(**karrs).order_by("-createtime")
    except Exception as e:
        rlist = []
        print(e)

    page = Paginator(rlist, __EACH_PAGE_SHOW_NUMBER, allow_empty_first_page=True).page(int(pageNum))
    result = {"page": page, "pageNum": str(pageNum), "start": start,"end":end,"ucode":ucode,"pname":pname,"qtype_dict":{"1":"查询","2":"下载"}}
    return render(request, "admin/sysConf_retail_purlog.html", result)

def report(request):
    pageNum = mtu.getReqVal(request, "pageNum", "1")
    start = mtu.getReqVal(request, "start")
    end = mtu.getReqVal(request, "end")
    ucode = mtu.getReqVal(request, "ucode", "")
    pname = mtu.getReqVal(request, "pname", "")
    try:
        if not start:
            start = (datetime.date.today().replace(day=1)).strftime("%Y-%m-%d")
        if not end:
            end = datetime.datetime.today().strftime("%Y-%m-%d")

        conn = mtu.getMysqlConn()
        cur = conn.cursor()

        condition = " where 1=1 "
        condition += " and createtime BETWEEN '{start} 00:00:00' AND '{end} 23:59:59'"\
                     .format(start=start,end=end)
        if ucode:
             condition += " and ucode like '%{ucode}%'".format(ucode=ucode)
        if pname:
            condition += " and name like '%{pname}%'".format(pname=pname)

        sql = "SELECT DATE_FORMAT(createtime,'%Y-%m-%d') createtime,`name`,url," \
              "SUM(CASE WHEN qtype = 1 THEN 1 ELSE 0 END) views," \
              "SUM(CASE WHEN qtype = 2 THEN 1 ELSE 0 END) downs " \
              "FROM bas_pur_log {condition} GROUP BY DATE_FORMAT(createtime,'%Y-%m-%d'),`name` "\
              "order by DATE_FORMAT(createtime,'%Y-%m-%d') DESC "\
              .format(condition=condition)

        cur.execute(sql)
        rlist = cur.fetchall()
        mtu.close(conn,cur)
    except Exception as e:
        rlist = []
        print(e)

    page = Paginator(rlist, __EACH_PAGE_SHOW_NUMBER, allow_empty_first_page=True).page(int(pageNum))
    result = {"page": page, "pageNum": str(pageNum),"start": start,"end":end,"ucode":ucode,"pname":pname,}
    return render(request, "admin/sysConf_retail_purlog_report.html", result)


# 반복 구조로 스왑 (24. Swap Nodes in Pairs)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        root = prev = ListNode(None)
        prev.next = head
        while head and head.next:
            # b가 a(head)를 가리키도록 할당
            b = head.next
            head.next = b.next
            b.next = head

            # prev가 b를 가리키도록 할당
            prev.next = b

            # 다음번 비교를 위해 이동
            head = head.next
            prev = prev.next.next
        return root.next

파이썬 알고리즘 인터뷰/08_연결 리스트/17_페어의 노드 스왑/반복 구조로 스왑.py

반복 구조로 스왑.py


'''
Напишите программу, которая принимает на вход
координаты точки (X и Y), причём X ≠ 0 и Y ≠ 0
и выдаёт номер четверти плоскости,
в которой находится эта точка (или на какой оси она находится).
Пример:
- x=34; y=-30 -> 4
- x=2; y=4-> 1
- x=-34; y=-30 -> 3
'''

def Input (inputText):
    number = int(input(f'{inputText}'))
    return number

def Calculate(x, y):
    if  x > 0 and y > 0:
        print('координаты соответствуют 1й четверти')
    elif x < 0 and y > 0:
        print('координаты соответствуют 2й четверти')
    elif x < 0 and y < 0:
        print('координаты соответствуют 3й четверти')
    elif x > 0 and y < 0:
        print('координаты соответствуют 4й четверти')
    else:
        print('Что-то пошло не так')

coordinate_X = Input("Введите координату x: ")
coordinate_Y = Input("Введите координату y: ")
Calculate(coordinate_X, coordinate_Y)