"""Tests for ``highcharts.no_data``."""
from copy import deepcopy
import pytest

from json.decoder import JSONDecodeError
from validator_collection import checkers

from highcharts_core.headless_export import ExportServer as cls
from highcharts_core.options import HighchartsOptions
from highcharts_core import errors
from tests.fixtures import input_files, check_input_file, to_camelCase, to_js_dict, \
    Class__init__, Class__to_untrimmed_dict, Class_from_dict, Class_to_dict, \
    Class_from_js_literal, run_download_tests, create_output_directory

STANDARD_PARAMS = [
    ({}, None),
]

@pytest.mark.parametrize('kwargs, error', STANDARD_PARAMS)
def test__init__(kwargs, error):
    Class__init__(cls, kwargs, error)

@pytest.mark.parametrize('kwargs, error', STANDARD_PARAMS)
def test__to_untrimmed_dict(kwargs, error):
    Class__to_untrimmed_dict(cls, kwargs, error)

@pytest.mark.parametrize('kwargs, error',  STANDARD_PARAMS)
def test_from_dict(kwargs, error):
    Class_from_dict(cls, kwargs, error)

@pytest.mark.parametrize('kwargs, error',  STANDARD_PARAMS)
def test_to_dict(kwargs, error):
    from tests.fixtures import trim_expected_dict, does_kwarg_value_match_result
    from validator_collection import checkers

    kwargs_copy = deepcopy(kwargs)
    if not kwargs:
        kwargs_copy['url'] = 'https://export.highcharts.com'
        kwargs_copy['format'] = 'png'
        kwargs_copy['scale'] = 1
        kwargs_copy['use_base64'] = False
        kwargs_copy['no_download'] = False
        kwargs_copy['async_rendering'] = False
        kwargs_copy['constructor'] = 'Chart'

        untrimmed_expected = {
            'url': kwargs_copy['url'],
            'type': kwargs_copy['format'],
            'scale': kwargs_copy['scale'],
            'constr': kwargs_copy['constructor'],
            'b64': kwargs_copy['use_base64'],
            'noDownload': kwargs_copy['no_download'],
            'asyncRendering': kwargs_copy['async_rendering']
        }

    else:
        untrimmed_expected = to_js_dict(deepcopy(kwargs))

    expected = trim_expected_dict(untrimmed_expected)
    check_dicts = True
    for key in expected:
        if not checkers.is_type(expected[key], (str, int, float, bool, list, dict)):
            check_dicts = False
        elif isinstance(expected[key], str) and expected[key].startswith('function'):
            check_dicts = False
        elif isinstance(expected[key], str) and expected[key].startswith('class'):
            check_dicts = False

    if not error:
        instance = cls(**kwargs)
        result = instance.to_dict()
        assert result is not None
        assert isinstance(result, dict) is True
        print('EXPECTED:')
        print(expected)
        print('RESULT:')
        print(result)
        if check_dicts:
            assert len(expected) == len(result)
            for key in expected:
                print(f'CHECKING: {key}')
                assert does_kwarg_value_match_result(expected[key],
                                                     result.get(key)) is True
    else:
        with pytest.raises(error):
            instance = cls(**kwargs)
            result = instance.to_dict()

@pytest.mark.parametrize('value, error', [
    ({
        'url': 'https://export.highcharts.com',
        'protocol': 'https',
        'domain': 'export.highcharts.com',
        'port': None,
        'path': None
    }, None),
    ({
        'url': 'https://export.highcharts.com:1234/some_path_goes_here/andcontinueshere',
        'protocol': 'https',
        'domain': 'export.highcharts.com',
        'port': 1234,
        'path': 'some_path_goes_here/andcontinueshere'
    }, None),
    ({
        'url': 'http://www.highcharts.com/some_path_goes_here/andcontinueshere',
        'protocol': 'http',
        'domain': 'www.highcharts.com',
        'port': None,
        'path': 'some_path_goes_here/andcontinueshere'
    }, None),
    ({
        'url': 'http://www.highcharts.com:8080',
        'protocol': 'http',
        'domain': 'www.highcharts.com',
        'port': 8080,
        'path': None
    }, None),
])
def test_url(value, error):
    instance = cls()
    if not error:
        if 'expected_url' not in value and 'url' in value:
            value['expected_url'] = value.get('url')

        url = value.get('url', None)

        instance.url = url
        assert instance.url is not None
        assert instance.url == value.get('expected_url')
        assert instance.protocol == value.get('protocol')
        assert instance.domain == value.get('domain')
        assert instance.port == value.get('port')
        assert instance.path == value.get('path')
    else:
        with pytest.raises(error):
            instance.url = value.get('url')

@pytest.mark.parametrize('input_filename, target_filename, kwargs, error', [
    ('headless_export/basic.json',
     'headless_export/output/test-basic.png',
     {
      'timeout': 5,
      'format_': 'png',
      'constructor': 'Chart'
     },
     None),
    ('headless_export/with-series-types.js',
     'headless_export/output/test-with-series-types.png',
     {
      'timeout': 5,
      'format_': 'png',
      'constructor': 'Chart'
     },
     None),
    ('headless_export/with-chart-type.js',
     'headless_export/output/test-with-chart-type.png',
     {
      'timeout': 5,
      'format_': 'png',
      'constructor': 'Chart'
     },
     None),
    ('headless_export/with-chart-type.js',
     'headless_export/output/test-with-chart-type.svg',
     {
      'timeout': 5,
      'format_': 'svg',
      'constructor': 'Chart'
     },
     None),
])
def test_get_chart(input_files,
                   run_download_tests,
                   create_output_directory,
                   input_filename,
                   target_filename,
                   kwargs,
                   error):
    if run_download_tests:
        input_file = check_input_file(input_files, input_filename)
        target_file = check_input_file(input_files,
                                       target_filename,
                                       create_directory = create_output_directory)

        with open(input_file, 'r') as file_:
            as_str = file_.read()

        options = HighchartsOptions.from_js_literal(as_str)

        kwargs['options'] = options

        if target_filename:
            kwargs['filename'] = target_file

        if not error:
            result = cls.get_chart(**kwargs)

            format = kwargs.get('format_', None)
            print(f'TESTING FORMAT: {format}')

            assert result is not None
            if target_filename:
                assert checkers.is_on_filesystem(target_file) is True
                if format == 'svg':
                    with open(target_file, 'r', encoding = 'utf-8') as file_:
                        file_contents = file_.read()
                    contents = str(file_contents)
                    assert contents.startswith(
                        '<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"'
                    ) is True


'''MIXED CONTENT

You have a string of words and digits divided by comma. Write a program which
separates words with digits. You shouldn't change the order elements.

INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Input
example is the following

8,33,21,0,16,50,37,0,melon,7,apricot,peach,pineapple,17,21
24,13,14,43,41

OUTPUT SAMPLE:
melon,apricot,peach,pineapple|8,33,21,0,16,50,37,0,7,17,21
24,13,14,43,41
As you cas see you need to output the same input string if it has words only or
digits only.
'''
def f(test='8,33,21,0,16,50,37,0,melon,7,apricot,peach,pineapple,17,21'):
    test = test.rstrip().split(',')
    strings, numbers = [], []
    for content in test:
        if content.isnumeric():
            numbers.append(content)
        else:
            strings.append(content)
    print(','.join(strings) + (strings != []) * '|' + ','.join(numbers))


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

import pickle
import streamlit as st

st.set_page_config(page_title = 'Titanic Survival Predictor')

pickle_in = open("decision_tree.pkl","rb")
classifier=pickle.load(pickle_in)

def predict_survival(Pclass,sex,SibSp,Parch,Embarked,Age_band,Fare_band):

    prediction=classifier.predict([[Pclass,sex,SibSp,Parch,Embarked,Age_band,Fare_band]])
    print(prediction)
    return prediction

def main():
    st.title("Titanic Survival Predictor")
    html_temp = """

Streamlit Titanic Survival Predictor ML App

    """
    st.markdown(html_temp,unsafe_allow_html=True)

    #Passenger Classes
    Pclass = st.selectbox("Which Passenger Class are you?",
                          ('First Class','Second Class','Third Class'))

    if Pclass == 'First Class':
        Pclass = 1
    elif Pclass == 'Second Class':
        Pclass = 2
    elif Pclass == 'Third Class':
        Pclass = 3

    #Gender of the passenger
    sex = st.radio("What's your gender?",('Male', 'Female'))

    if sex == 'Male':
         sex = 1
    else:
         sex = 0

    #Sibling or spouse present on board
    Ss = st.radio("Do you have siblings/spouse on board?",('No', 'Yes'))

    if Ss == 'Yes':
         SibSp = st.text_input("How many siblings/spouse?","Type Here")
    else:
         SibSp = 0

    #Parents or children present on board
    PC = st.radio("Do you have parents/children on board?",('No', 'Yes'))

    if PC == 'Yes':
         Parch = st.text_input("How many parents/children?","Type Here")
    else:
         Parch = 0

    #Boarding location of passenger
    Location = st.selectbox("Where did you depart?",
                          ('Cherbourg, France','Queenstown, Ireland','Southampton, England'))

    if Location == 'Cherbourg, France':
        Embarked = 0
    elif Location == 'Queenstown, Ireland':
        Embarked = 1
    elif Location == 'Southampton, England':
        Embarked = 2

    #Age of passenger
    Age = st.slider('How old are you?', 0, 100, 25)

    if Age <= 19:
        Age_band = 0
    elif Age > 19 & Age < 60:
        Age_band = 1
    elif Age >= 60:
        Age_band = 2

    #ticket fare of passenger
    tfare = st.number_input("Enter ticket fare, starting from £7", min_value = 7.0, step = 0.5)

    if tfare <= 13:
        Fare_band = 0
    elif Age > 13 & Age < 30:
        Fare_band = 1
    elif Age >= 30:
        Fare_band = 2

    #prediction output
    result=""
    if st.button("Predict"):
        result=predict_survival(Pclass,sex,SibSp,Parch,Embarked,Age_band,Fare_band)
        if result == 1:
            result = "Congratulations, you survived!"
            st.success(result)
        else:
            result = "Unfortunately, you did not make it :("
            st.error(result)

    #Fun fact
    if st.button("Fun Fact"):
        st.write("""A third class ticket cost around £7 in 1912 which is nearly £800 in today's money.
                    A second class ticket cost around £13 or nearly £1500 today and a first class ticket
                    would have set you back a minimum of £30 or more than £3300 today.""")

    #Hiding hamburger menu
    hide_streamlit_style = """

            """
    st.markdown(hide_streamlit_style, unsafe_allow_html=True)

    #contact info
    footer="""

Connect with me on LinkedIn!

"""

    st.markdown(footer, unsafe_allow_html=True)

if __name__=='__main__':
    main()


def get_count1(sentence):
    bad = ['a','e','i','o','u']
    n = 0
    for s in sentence:
        for b in bad:
            if b == s:
                n+=1
    return n

vo = ['a','e','i','o','u']
def get_count(sentence):
    return len([1 for s in sentence if [True for v in vo if v==s]])


import math
import torch
from torch import nn
import torch.nn.functional as F
import torchvision
import torchaudio
from denoising_diffusion_pytorch import Unet, GaussianDiffusion

class DPTBlock(nn.Module):
    def __init__(self, t_len, f_len, batch_first):
        super(DPTBlock, self).__init__()
        self.t_len = t_len
        self.f_len = f_len
        self.batch_first = batch_first
        # 512=args.frames, 128=args.n_mels
        self.encoder_layer_time = nn.TransformerEncoderLayer(d_model=self.t_len, nhead=8, dim_feedforward=self.t_len*4,
                                                             batch_first=self.batch_first, activation='gelu')
        self.transformer_encoder_time = nn.TransformerEncoder(self.encoder_layer_time, num_layers=1)
        self.encoder_layer_freq = nn.TransformerEncoderLayer(d_model=self.f_len, nhead=8, dim_feedforward=self.f_len*4,
                                                             batch_first=self.batch_first, activation='gelu')
        self.transformer_encoder_freq = nn.TransformerEncoder(self.encoder_layer_freq, num_layers=1)

    # example of shape
    def forward(self, x):
        out = self.transformer_encoder_time(x) # out shape: (B, T, F) / (T, B, F)
        if self.batch_first:
            out = torch.transpose(out, dim0=1, dim1=2) # out shape: (B, F, T)
        else:
            out = torch.transpose(out, dim0=0, dim1=2) # out shape: (F, B, T)
        out = self.transformer_encoder_freq(out) # out shape: (B, F, T) / (F, B, T)
        if self.batch_first:
            out = torch.transpose(out, dim0=1, dim1=2) # out shape: (B, T, F)
        else:
            out = torch.transpose(out, dim0=0, dim1=2) # out shape: (T, B, F)
        return out

'''
Trials: conv2d vs. avg. pooling
'''
class SSDPT(nn.Module):
    def __init__(self, t_len, f_len, batch_first=True):
        super(SSDPT, self).__init__()
        self.t_len = t_len
        self.f_len = f_len
        self.batch_first = batch_first

        self.DPT1 = DPTBlock(t_len=self.t_len, f_len=self.f_len, batch_first=batch_first)
        self.DPT2 = DPTBlock(t_len=self.t_len, f_len=self.f_len, batch_first=batch_first)
        self.conv1 = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=5, stride=2, padding=2)
        self.DPT3 = DPTBlock(t_len=self.t_len//2, f_len=self.f_len//2, batch_first=batch_first)
        self.DPT4 = DPTBlock(t_len=self.t_len//2, f_len=self.f_len//2, batch_first=batch_first)
        self.conv2 = nn.Conv2d(in_channels=1, out_channels=1, kernel_size=5, stride=2, padding=2)

    def forward(self, x):
        out = self.DPT1(x)
        out = self.DPT2(out)
        if self.batch_first:
            out = self.conv1(out.unsqueeze(1))
        else:
            out = torch.transpose(out, dim0=0, dim1=1) # out shape: (B, T, F)
            out = self.conv1(out.unsqueeze(1)) # out shape: (B, 1, T, F)
            out = torch.transpose(out, dim0=0, dim1=2) # out shape: (T, 1, B, F)
        out = self.DPT3(out.squeeze(1))
        out = self.DPT4(out)
        if self.batch_first:
            out = self.conv2(out.unsqueeze(1))
        else:
            out = torch.transpose(out, dim0=0, dim1=1) # out shape: (B, T, F)
            out = self.conv2(out.unsqueeze(1)) # out shape: (B, 1, T, F)
            out = torch.transpose(out, dim0=0, dim1=2) # out shape: (T, 1, B, F)
        return out.squeeze(1)

''' FINAL ARCHITECTURE '''

class DPTDiffSeg(nn.Module):
    def __init__(self, t_len, f_len, batch_first=True):
        super(DPTDiffSeg, self).__init__()
        self.t_len = t_len
        self.f_len = f_len
        self.batch_first = batch_first

        # 1. Pass through SSDPT
        self.SSDPT = SSDPT(t_len=self.t_len, f_len=self.f_len, batch_first=self.batch_first)

        # 2. Latent Diffusion -> Loss1, unsqueeze(1) Needed.
        self.model = Unet(
            dim = 64,
            dim_mults = (1, 2, 4, 8),
            channels = 1
        )
        self.diffusion = GaussianDiffusion(
            self.model,
            image_size = (self.f_len//4, self.t_len//4), # note that h, w must be divisible by 2
            timesteps = 1000,   # number of steps
            sampling_timesteps = 1000//5, # number of sampling steps -> DDIM if s_t < t
            objective = 'pred_v', # See : https://arxiv.org/abs/2202.00512
            beta_schedule = 'cosine'
        )

        # 3. Decoder -> Loss2
        self.decoder = nn.Sequential(
            nn.ConvTranspose2d(in_channels=1, out_channels=1, kernel_size=5, stride=2, padding=2, output_padding=1),
            nn.ReLU(),
            nn.InstanceNorm2d(1),
            nn.ConvTranspose2d(in_channels=1, out_channels=1, kernel_size=5, stride=2, padding=2, output_padding=1),
            nn.ReLU(),
            nn.InstanceNorm2d(1),
        )

        self.loss2 = nn.SmoothL1Loss()

    def forward(self, x):
        latent = self.SSDPT(x) # (B, T, F) -> (B, T//4, F//4)

        # Loss1
        loss1 = self.diffusion(latent.unsqueeze(1))
        sampled = self.diffusion.sample(batch_size=x.shape[0]) # (B, 1, T//4, F//4)

        # Loss2
        out = self.decoder(sampled) # (B, 1, T, F) <- (B, 1, T//4, F//4)
        loss2 = self.loss2(x.unsqueeze(1), out)

        return loss1 + loss2

def _DPTDiffSeg(f_len, t_len, batch_first):
    return DPTDiffSeg(f_len=f_len, t_len=t_len, batch_first=batch_first)


# --coding:utf8--

age = input ("How old are you? ")
height = input ("How tall are you (m)? ")
weight = input ("How much do you weigh (Kg)? ")

# BMI 公式为 体重 除以身高的平方
BMI = weight / height ** 2

print ("Your BMI is %r " % BMI)

# 这是今天在路上想到昨天的练习，觉得可以试着用BMI的公式写写看。
# 意外的完成了变数跟input的练习还有print的练习。
# 公式的部分，有点错误，所以运算结果有出点问题，但是修正后，还可以接受
# 这算是Hello World之外，我真正写的第一个程式。值得纪念！

# 其中使用input 与 变数，其中透过print将变数最后的值显示出来。与使用者及计算机互动


import math
r = float(input("Enter radius of the cylinder: "))
h = float(input("Enter height of the cylinder: "))

a = math.pi*r*r
sa = ((2*math.pi*r)*h) + ((math.pi*r**2)*2)
v = math.pi * r * r * h

print("The area is : %.2f" %a)
print("The surface area is: %.2f" %sa)
print("the volume is %.2f" %v)


from typing import Sequence
import math
import torch
from torch.utils.data.sampler import Sampler, RandomSampler

class StratifiedEventBatchSampler(Sampler):
    """Samples elements with from a set with binary labelling to ensure
    the event label (1) is evenly distributed across batches.

    This sampler is useful when the loss function requires at least one event,
    such as in the case of a Cox Proportional Hazard based loss.
    """

    events: torch.Tensor
    batch_size: int

    def __init__(self, events: Sequence[int], batch_size: int) -> None:
        """Generate an StratifiedBinaryBatchSampler instance

        Args:
            events: int sequence of binary event labels (0, 1)
            batch_size: int that defines size of mini-batch.
        """
        if not isinstance(batch_size, int) or batch_size <= 0:
            raise ValueError("batch_size should be a positive integer value, "
                             "but got batch_size={}".format(batch_size))
        self.events = torch.as_tensor(events, dtype=torch.int64)
        self.batch_size = batch_size

        self.events0_idx = torch.where(self.events == 0)[0]
        self.events1_idx = torch.where(self.events == 1)[0]

        self._len = math.ceil(len(self.events) / self.batch_size)

        if self.events1_idx.shape[0] < self._len:
            raise ValueError("the number of events ({}) must be equal or "
                             "larger than the number of batches ({})"
                             .format(self.events1_idx.shape[0], self._len))

        # Get batch sizes for each
        self.batch0_size = math.ceil(
            self.events0_idx.shape[0] / self.events.shape[0] * batch_size)
        self.batch1_size = math.floor(
            self.events1_idx.shape[0] / self.events.shape[0] * batch_size)

        self.sampler0 = RandomSampler(self.events0_idx, replacement=False)
        self.sampler1 = RandomSampler(self.events1_idx, replacement=False)

    def __iter0__(self):
        """Iterate the non-event (0) label sampler"""
        batch = torch.tensor([], dtype=torch.int64)
        for idx in self.sampler0:
            idx0 = self.events0_idx[idx, None]
            batch = torch.cat((batch, idx0), 0)
            if batch.shape[0] == self.batch0_size:
                yield batch
                batch = torch.tensor([], dtype=torch.int64)
        if batch.shape[0] > 0:
            yield batch

    def __iter1__(self):
        """Iterate the event (0) label sampler"""
        batch = torch.tensor([], dtype=torch.int64)
        for idx in self.sampler1:
            idx1 = self.events1_idx[idx, None]
            batch = torch.cat((batch, idx1), 0)
            if batch.shape[0] == self.batch1_size:
                yield batch
                batch = torch.tensor([], dtype=torch.int64)
        if batch.shape[0] > 0:
            yield batch

    def __iter__(self):
        """Generate the indices for the next batch of elements"""
        for batch0, batch1 in zip(self.__iter0__(), self.__iter1__()):
            batch = torch.cat((batch0, batch1), 0).sort()[0]
            yield batch

    # Removed - https://github.com/Lightning-AI/lightning/issues/2429
    # def __len__(self):
    #     """Return the number of batches"""
    #     return self._len


#  SOFTEX-RECIFE
# Aluno: Fábio de Tássio

# Atividade 06 do Módulo 02 (Contornar problemas previstos no sistema)

# Desenvolva um programa que recebe do usuário nome completo e ano de nascimento que seja entre 1922 e 2021.
# A partir dessas informações, o sistema mostrará o nome do usuário e a idade que completou, ou completará,
# no ano atual (2022).

# Caso o usuário não digite um número ou apareça um inválido no campo do ano, o sistema informará o erro e continuará
# perguntando até que um valor correto seja preenchido.

# Início

def func_AnoNasc(AnoNasc):
    if AnoNasc >= 1922 and AnoNasc <= 2021:
        Idade = 2022 - AnoNasc
    elif AnoNasc < 1922 or AnoNasc > 2021:
        raise Exception('Ano inválido!!!')
    return Idade

Nome = input('Digite seu nome completo: \n')
while True:
    try:
        AnoNasc = int(input('Digite o ano de nascimento que seja entre 1922 e 2021:\n'))
        Idade = func_AnoNasc(AnoNasc)
        print(Nome, 'sua idade é', Idade, 'ano(s) em 2022!')
        break

    except ValueError:
        print('ERRO!!!')
        print('\n')

    except Exception as err:
        print(err)
        print('\n')


import warnings
from PIL import Image,ImageFilter

def down_sample_fit(pil_img, num):
    ds = [2 ** (i + 1) for i in range(num)]
    for d in ds:
        a, b = pil_img.size
        add = (a % d)
        na = a + add
        add = (b % d)
        nb = b + add
        pil_img = pil_img.resize((na, nb),Image.BICUBIC)
    return pil_img

def max_size_fit(pil_img, max_size):
    max_ = max(pil_img.size)
    if max_ <= max_size:
        return pil_img
    else:
        warnings.warn("The image is over the max size:{}".format(max_size))
        a, b = pil_img.size
        if a >= b:
            na = max_size
            nb = int(na * (b / a))
        else:
            nb = max_size
            na = int(nb * (a / b))

        return pil_img.resize((na, nb),Image.BICUBIC)

def blur_image(pil_img,mode,r):
    if mode == "g":
        kernel = ImageFilter.GaussianBlur(radius=r)
    elif mode == "m":
        kernel = ImageFilter.MedianFilter(size=r)
    else:
        raise ValueError("{} not support".format(mode))
    return pil_img.filter(kernel)


from requests.exceptions import RequestException

class RateQuoteServiceException(Exception):
    def __init__(self, *args, **kwargs):
        if kwargs:
            for key, value in kwargs:
                setattr(self, key, value)

class RateQuoteNetworkException(RateQuoteServiceException):
    """Exceptions for network requests/responses."""
    pass

class RateQuoteAPIException(RateQuoteServiceException):
    """Exceptions for service api."""

    def __init__(self, message, method, status=None, headers=None, network_response=None):
        super(RateQuoteAPIException, self).__init__()
        self.message = message
        self.method = method
        self.status = status
        self.headers = headers
        self.network_response = network_response

    def __unicode__(self):
        return "\nException: {0}\nStatus: {1}\nMethod: {2}\nHeaders: {3}\nNetwork Response:{4}".format(
            self.message,
            self.status,
            self.method,
            self.headers,
            self.network_response
        )


#!/usr/bin/env python3

import os
import sys
from dataclasses import dataclass, field

"""
author: dmaynor@gmail.com
The script will scan through my ~/code and ~/home directory to look for virtual enviroments for python by looking for a venv directory structure.
It can be called from my ~/tools/bin directory so first it has to change working directory to my home directory, It will then scan ~/code and ~/work
looking for venv directories. If it finds one the full path to venv is sotred in a list. When the scan is complete the list of all discovered venv directories
is displayed to the user. The user can then select a venv directory and the script will then change the working directory to that directory and execute the venv/bin/activate script.
"""
#Build a dataclass to store the path to the venv directory and metadata about the venv and project.
@dataclass
class ProjectList:
    project_lists: list = field(default_factory=dict)

    def __repr__(self) -> str:

        pass

#Initialize the ProjectList dataclass
pl = ProjectList()

#Check wthe current directory is my home directory, if not change to my homme directory
if os.getcwd() != os.path.expanduser('~'):
    os.chdir(os.path.expanduser('~'))

#build a list with code and work directories
directories = [os.path.expanduser('~/code'), os.path.expanduser('~/work')]

#recursively scan through the directories and look for venv directories
venv_list = []
found_count=1
for directory in directories:
    for root, dirs, files in os.walk(directory):
        for dir in dirs:
            if dir == 'venv':
                venv_dir = os.path.join(root, dir)
                venv_list.append(venv_dir)
                pl.project_lists[found_count] = venv_dir
                found_count += 1

#print the list of venv directories
print('\n')
if len(venv_list) == 0:
    print('No venv directories found')
else:
    print('The following venv directories were found:')
    for venv in venv_list:
        print(venv)
    print("Dataclass:", pl.project_lists)


import re
from glob import glob

import numpy as np
import pandas as pd

def parse_results(fname, sample=None):
    results = []
    rtt_results = []
    regex = (
        r"Target: (([0-9a-f]{2}:*){6}), " +
        r"status: ([0-9]), rtt: ([0-9\-]+) psec, " +
        r"distance: ([0-9\-]+) cm"
    )
    regex_new = (
        r"Target: (([0-9a-f]{2}:*){6}), " +
        r"status: ([0-9]), rtt: ([0-9\-]+) \(  ([0-9\-]+)\) psec, " +
        r"distance: ([0-9\-]+) \(  ([0-9\-]+)\) cm, rssi: ([0-9\-]+) dBm"
    )
    with open(fname) as f:
        data_ori = f.readlines()
    if sample is None:
        data = data_ori
    else:
        data = np.random.choice(data_ori, size=sample, replace=False)
    for line in data:
        match = re.search(regex_new, line)
        if match:
            mac = match.group(1)
            status = int(match.group(3))
            rtt = int(match.group(4))
            rtt_var = int(match.group(5))
            raw_distance = int(match.group(6))
            raw_distance_var = int(match.group(7))
            rssi = int(match.group(8))
        else:
            match = re.search(regex, line)
            if match:
                mac = match.group(1)
                status = int(match.group(3))
                rtt = int(match.group(4))
                raw_distance = int(match.group(5))
            else:
                continue
        if status != 0 or raw_distance < -1000:
            continue
        results.append(raw_distance)
        rtt_results.append(rtt)

    return results

if __name__ == '__main__':
    # Parse measurements into a dict of arrays
    ftm_matrix = []
    for ftm_data in glob('*.out'):

        # Parse one distance to obtain array of ftm measurements
        distance = float(ftm_data.split("_")[0][1:])
        ftm_vals = parse_results(ftm_data)

        for ftm_val in ftm_vals:
            ftm_matrix.append([distance, ftm_val])

    ftm_matrix = np.array(ftm_matrix, dtype=np.float64)
    np.random.shuffle(ftm_matrix)

    ftm_df = pd.DataFrame(ftm_matrix, columns=["distance", "ftmdist"])
    ftm_df.to_csv('ftm.csv', index=None)


import copy
import random
from typing import Optional, List

from ..services.spu_feature_service import SpuFeatureService
from ...entity.rec_item import RecItem

class HotsRecall(object):
    def get_candidates(self, k: Optional[int] = None) -> List[RecItem]:
        """
        获取前k个热映商品
        :param k: 待获取的数量，如果为None，表示获取所有
        :return: 结果
        """
        return self._get_hot_items(k)

    @staticmethod
    def _get_hot_items(k: Optional[int] = None) -> List[RecItem]:
        spu_ids = SpuFeatureService.get_hot_ids()  # 获取所有的热映商品id列表
        if spu_ids is None or len(spu_ids) == 0:
            return []
        if k is not None and k > 0:
            spu_ids = copy.deepcopy(spu_ids)
            random.shuffle(spu_ids)
            spu_ids = spu_ids[:k]
        items: List[RecItem] = []
        for spu_id in spu_ids:
            items.append(RecItem.get_recall_rec_item(spu_id, 1.0, 'hots', 'hots'))
        return items


from Process import Process
from Generators import Generators
from UnitOfBlood import UnitOfBlood

class StandardOrder(Process):

    counter_standard_order = 0

    def __init__(self, bdp, blood_type):
        super().__init__(bdp)
        self.time = 300
        self.blood_type_order = blood_type
        self.active = False

    def execute(self):
        self.active = True
        while(self.active):

            if(self.phase == 0):
                self.phase0()
            elif(self.phase == 1):
                self.phase1()

    def phase0(self):
        self.activate(Generators().get_exponential(1700))
        self.phase = 1
        self.active = 0
        print("Zamowiono krew grupy " +
              self.blood_type_order + " metoda standardowa.")
        if(self.bdp.system_time > self.bdp.initial_phase):
            Blood.counter_standard_order += 1

    def phase1(self):
        for _i in range(self.bdp.n):
            self.bdp.add_blood(UnitOfBlood(
                self.bdp, self.bdp.system_time + self.time, self.blood_type_order, "Standard"))
            print("Zamawiam krew grupy " +
                  self.blood_type_order + " w trybie standardowym.")
        self.active = False
        print("Dostarczono standardowe zamowinie na krew grupy " +
              self.blood_type_order + ".")

    def get_process_info(self):
        return("Standardowe zamowienie | czas: " + str(self.proces_event.event_time))


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

# In[10]:

'''
비만을 판단하기 위해서 BMI 수치가 필요하다.

BMI 수치가 입력되면 비만을 판단하시오.

* BMI에 따른 비만 판정

BMI 수치	비만 판정
~10 이하	정상
~20 이하	과체중
20 초과	비만

'''
a=input()
a=int(a)
if a<11:
    print("정상")
elif a<21:
    print("과체중")
else:
    print("비만")

# In[ ]:


# -*- coding: utf-8 -*-
"""
Created on Thu Jan 26 18:15:35 2017

@author: twu
"""

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dictionary = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M' : 1000}
        num = []

        while len(s) >= 2:
            if dictionary[s[-2]] < dictionary[s[-1]]:
                int = dictionary[s[-1]] - dictionary[s[-2]]
                num.append(int)
                s = s[:-2]
            else:
                int = dictionary[s[-1]]
                num.append(int)
                s = s[:-1]

        for i in s:
            num.append(dictionary[i])
        num = sum(num)
        return num

class Solution2(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dictionary = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M' : 1000}
        num = 0
        for i in range(len(s)-1):
            if dictionary[s[i]] < dictionary[s[i+1]]:
                num -= dictionary[s[i]]
            else:
                num += dictionary[s[i]]

        return num + dictionary[s[-1]]

class Solution3(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = {'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}

        res, p = 0, 'I'
        for c in s[::-1]:
            res, p = res - d[c] if d[c] < d[p] else res + d[c], c
        return res

if __name__ == '__main__':
    result = Solution3().romanToInt('DCXIX')
    print(result)


import pygame, sys, random
import pygame.camera
from pygame.locals import *
from PIL import Image
import pytesseract as pt

"""S_L = 'eng'
D_L = 'en'"""
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
FPS = 30

BLACK =         (  0,   0,   0)
WHITE =         (255, 255, 255)
BRIGHTBLUE =    (  0,  50, 255)

BUTTONCOLOR = WHITE
BUTTONTEXTCOLOR = BLACK
MESSAGECOLOR = WHITE

BGCOLOR = BLACK
BASICFONTSIZE = 20

pygame.init()
pygame.camera.init()

camlist = pygame.camera.list_cameras()
if camlist:
    cam = pygame.camera.Camera(camlist[0],(640,480))

def terminate():
    pygame.quit()
    sys.exit()

def startScreen():
    pygame.display.set_caption('Linguista')
    DISPLAYSURF.fill(BLACK)
    TITLEFONT = pygame.font.Font('Fonts/calibri.ttf', 40)
    titleText = TITLEFONT.render('Linguista', True, WHITE)
    titleRect = titleText.get_rect()
    titleRect.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
    DISPLAYSURF.blit(titleText, titleRect)
    pygame.display.flip()
    chooseScreen()
    going = True
    while going:
        events = pygame.event.get()
        for e in events:
            if (e.type == KEYDOWN and e.key == K_ESCAPE):
                # close the camera safely
                terminate()
                going = False
            elif (e.type == MOUSEBUTTONDOWN):
                obj = Capture()
                obj.main()
            elif (e.type == KEYDOWN and e.key == K_BACKSPACE):
                startScreen()

def chooseScreen():

    #DISPLAYSURF.fill(BGCOLOR)
    global S_L
    global D_L

    srcLang = BASICFONT.render('Source Language', True, WHITE)
    srcLangRect = srcLang.get_rect()
    srcLangRect.center = (WINDOWWIDTH / 4, WINDOWHEIGHT / 30)

    s_eng = BASICFONT.render('English', True, WHITE)
    s_engRect = s_eng.get_rect()
    s_engRect.center = (WINDOWWIDTH / 4, WINDOWHEIGHT / 12)

    s_ger = BASICFONT.render('German', True, WHITE)
    s_gerRect = s_ger.get_rect()
    s_gerRect.center = (WINDOWWIDTH / 4, 2 * WINDOWHEIGHT / 12)

    s_spa = BASICFONT.render('Spanish', True, WHITE)
    s_spaRect = s_spa.get_rect()
    s_spaRect.center = (WINDOWWIDTH / 4, 3 * WINDOWHEIGHT / 12)

    s_hin = BASICFONT.render('Hindi', True, WHITE)
    s_hinRect = s_hin.get_rect()
    s_hinRect.center = (WINDOWWIDTH / 4, 4 * WINDOWHEIGHT / 12)

    s_ben = BASICFONT.render('Bengali', True, WHITE)
    s_benRect = s_ben.get_rect()
    s_benRect.center = (WINDOWWIDTH / 4, 5 * WINDOWHEIGHT / 12)

    s_pun = BASICFONT.render('Punjabi', True, WHITE)
    s_punRect = s_pun.get_rect()
    s_punRect.center = (WINDOWWIDTH / 4, 6 * WINDOWHEIGHT / 12)

    s_fre = BASICFONT.render('French', True, WHITE)
    s_freRect = s_fre.get_rect()
    s_freRect.center = (WINDOWWIDTH / 4, 7 * WINDOWHEIGHT / 12)

    s_ita = BASICFONT.render('Italian', True, WHITE)
    s_itaRect = s_ita.get_rect()
    s_itaRect.center = (WINDOWWIDTH / 4, 8 * WINDOWHEIGHT / 12)

    dstLang = BASICFONT.render('Destination Language', True, WHITE)
    dstLangRect = dstLang.get_rect()
    dstLangRect.center = ((3*WINDOWWIDTH) / 4, WINDOWHEIGHT / 30)

    d_eng = BASICFONT.render('English', True, WHITE)
    d_engRect = d_eng.get_rect()
    d_engRect.center = ((3*WINDOWWIDTH) / 4, WINDOWHEIGHT / 12)

    d_ger = BASICFONT.render('German', True, WHITE)
    d_gerRect = d_ger.get_rect()
    d_gerRect.center = ((3*WINDOWWIDTH) / 4, 2 * WINDOWHEIGHT / 12)

    d_spa = BASICFONT.render('Spanish', True, WHITE)
    d_spaRect = d_spa.get_rect()
    d_spaRect.center = ((3*WINDOWWIDTH) / 4, 3 * WINDOWHEIGHT / 12)

    d_hin = BASICFONT.render('Hindi', True, WHITE)
    d_hinRect = d_hin.get_rect()
    d_hinRect.center = ((3*WINDOWWIDTH) / 4, 4 * WINDOWHEIGHT / 12)

    d_ben = BASICFONT.render('Bengali', True, WHITE)
    d_benRect = d_ben.get_rect()
    d_benRect.center = ((3*WINDOWWIDTH) / 4, 5 * WINDOWHEIGHT / 12)

    d_pun = BASICFONT.render('Punjabi', True, WHITE)
    d_punRect = d_pun.get_rect()
    d_punRect.center = ((3*WINDOWWIDTH) / 4, 6 * WINDOWHEIGHT / 12)

    d_fre = BASICFONT.render('French', True, WHITE)
    d_freRect = d_fre.get_rect()
    d_freRect.center = ((3*WINDOWWIDTH) / 4, 7 * WINDOWHEIGHT / 12)

    d_ita = BASICFONT.render('Italian', True, WHITE)
    d_itaRect = d_ita.get_rect()
    d_itaRect.center = ((3*WINDOWWIDTH) / 4, 8 * WINDOWHEIGHT / 12)

    DISPLAYSURF.blit(srcLang, srcLangRect)
    DISPLAYSURF.blit(s_hin, s_hinRect)
    DISPLAYSURF.blit(s_spa, s_spaRect)
    DISPLAYSURF.blit(s_ger, s_gerRect)
    DISPLAYSURF.blit(s_eng, s_engRect)
    DISPLAYSURF.blit(s_pun, s_punRect)
    DISPLAYSURF.blit(s_fre, s_freRect)
    DISPLAYSURF.blit(s_ita, s_itaRect)

    DISPLAYSURF.blit(dstLang, dstLangRect)
    DISPLAYSURF.blit(d_hin, d_hinRect)
    DISPLAYSURF.blit(d_spa, d_spaRect)
    DISPLAYSURF.blit(d_ger, d_gerRect)
    DISPLAYSURF.blit(d_eng, d_engRect)
    DISPLAYSURF.blit(d_pun, d_punRect)
    DISPLAYSURF.blit(d_fre, d_freRect)
    DISPLAYSURF.blit(d_ita, d_itaRect)

    pygame.display.update()

    going = True
    count_s = 0
    count_d = 0

    while going:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            elif event.type == MOUSEBUTTONUP:
                mouseX, mouseY = event.pos
                if s_hinRect.collidepoint(mouseX, mouseY):
                    S_L = 'hin'
                    count_s = count_s + 1
                elif s_gerRect.collidepoint(mouseX, mouseY):
                    S_L = 'deu'
                    count_s = count_s + 1
                elif s_engRect.collidepoint(mouseX, mouseY):
                    S_L = 'eng'
                    count_s = count_s + 1
                elif s_spaRect.collidepoint(mouseX, mouseY):
                    S_L = 'spa'
                    count_s = count_s + 1
                elif s_punRect.collidepoint(mouseX, mouseY):
                    S_L = 'pan'
                    count_s = count_s + 1
                elif s_freRect.collidepoint(mouseX, mouseY):
                    S_L = 'fra'
                    count_s = count_s + 1
                elif s_itaRect.collidepoint(mouseX, mouseY):
                    S_L = 'ita'
                    count_s = count_s + 1
                elif d_hinRect.collidepoint(mouseX, mouseY):
                    D_L = 'hi'
                    count_d = count_d + 1
                elif d_engRect.collidepoint(mouseX, mouseY):
                    D_L = 'en'
                    count_d = count_d + 1
                elif d_gerRect.collidepoint(mouseX, mouseY):
                    D_L = 'de'
                    count_d = count_d + 1
                elif d_spaRect.collidepoint(mouseX, mouseY):
                    D_L = 'es'
                    count_d = count_d + 1
                elif d_punRect.collidepoint(mouseX, mouseY):
                    D_L = 'pa'
                    count_d = count_d + 1
                elif d_freRect.collidepoint(mouseX, mouseY):
                    D_L = 'fr'
                    count_d = count_d + 1
                elif d_itaRect.collidepoint(mouseX, mouseY):
                    D_L = 'it'
                    count_d = count_d + 1
                if (count_s == 1 and count_d == 1):
                    going = False
                    break

class Capture(object):
    def __init__(self):
        self.size = (640,480)
        #self.size2 = (640, 380)
        # create a display surface. standard pygame stuff
        self.display = pygame.display.set_mode(self.size, 0)

        # this is the same as what we saw before
        self.clist = pygame.camera.list_cameras()
        if not self.clist:
            raise ValueError("Sorry, no cameras detected.")
        self.cam = pygame.camera.Camera(self.clist[0], self.size)
        self.cam.start()

        # create a surface to capture to.  for performance purposes
        # bit depth is the same as that of the display surface.
        self.snapshot = pygame.surface.Surface(self.size, 0, self.display)
        self.img = pygame.image.load('Images/black.jpg')
        self.display.blit(self.img,(0,360))
        pygame.display.update()

    def black_region(self, blck):
        self.display.blit(blck,(0,360))
        pygame.display.update()

    def get_and_flip(self, blck):
        # if you don't want to tie the framerate to the camera, you can check
        # if the camera has an image ready.  note that while this works
        # on most cameras, some will never return true.
        if self.cam.query_image():
            self.snapshot = self.cam.get_image(self.snapshot)

        # blit it to the display surface.  simple!
        self.display.blit(self.snapshot, (0,0))
        self.black_region(blck)

    def main(self):
        going = True
        while going:
            events = pygame.event.get()
            for e in events:
                if e.type == QUIT:
                    # close the camera safely
                    self.cam.stop()
                    going = False
                elif (e.type == KEYDOWN and e.key == K_SPACE):
                    ini_image = self.cam.get_image()
                    self.filename = '2.jpg'
                    pygame.image.save(ini_image, self.filename)
                    self.display.blit(ini_image, (0,0))
                    self.get_text()
                elif (e.type == KEYDOWN and e.key == K_ESCAPE):
                    self.cam.stop()
                    startScreen()

            self.get_and_flip(self.img)

    def get_text(self):
        fin_file = pt.func(self.filename, S_L, D_L)
        fin_img = pygame.image.load(fin_file)
        going = True
        while going:
            self.black_region(fin_img)
            events = pygame.event.get()
            for e in events:
                if (e.type == KEYDOWN and e.key == K_BACKSPACE):
                    going = False
                    self.main()
                elif (e.type == KEYDOWN and e.key == K_ESCAPE):
                    self.cam.stop()
                    startScreen()
                elif e.type == QUIT:
                    # close the camera safely
                    self.cam.stop()
                    going = False
"""self.display.blit(fin_img,(0,360))
        pygame.display.update()"""

def main():
    global DISPLAYSURF, BASICFONT, FPSCLOCK, S_L, D_L
    pygame.init()
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
    BASICFONT = pygame.font.Font('Fonts/calibri.ttf', BASICFONTSIZE)
    S_L = 'eng'
    D_L = 'en'
    startScreen()

if __name__ == '__main__':
	main()


class Node:
    def __init__(self, data=None):
        self.data = data
        self.nextNode = None

class SingleLinkedList:
    def __init__(self):
        self.headval = None

    def traversList(self):
        currval = self.headval;
        while currval is not None:
            print(currval.data)
            currval = currval.nextNode

    def addAtBeginning(self, newdata):
        newNode = Node(newdata)
        newNode.nextNode = self.headval
        self.headval = newNode

    def addAtEnd(self, newdata):
        newNode = Node(newdata)
        if self.headval == None:
            self.headval = newNode
            return
        last = self.headval
        while (last.nextNode):
            last = last.nextNode
        last.nextNode = newNode

    def addAt(self, atnode, newnode):
        if atnode is None:
            print ("At Node is not avaibla ..")
            return
        newNode = Node(newnode)
        newNode.nextNode = atnode.nextNode
        atnode.nextNode = newNode

    def popElem(self, key):
        headVal =  self.headval
        if headVal is None:
            print("list empty already...")
            return
        if headVal.data == key:
            self.headval  = headVal.nextNode
            headVal = None
            return
        while(headVal is not None):
            if headVal.data == key:
                break
            prev = headVal
            headVal = headVal.nextNode

        if (headVal is None):
            print("Key not found...")
            return

        prev.nextNode = headVal.nextNode
        headVal = None

if __name__ == "__main__":
    list = SingleLinkedList()
    list.headval = Node("February")
    secondElement = Node("March")
    list.headval.nextNode = secondElement
    thirdElement = Node("April")
    secondElement.nextNode = thirdElement
    list.traversList()
    print("--------------------------")

    list.addAtBeginning("January")
    list.traversList()
    print("--------------------------")

    list.addAtEnd("May")
    list.traversList()
    print("--------------------------")

    list.addAt(thirdElement,"April 14 - New Year day")
    list.traversList()
    print("--------------------------")
    list.popElem("April 14 - New Year day")
    print("--------------------------")
    list.traversList()
    list.popElem("August")
    print("------removing head----------")
    list.popElem("January")
    list.traversList()


from api_request import *

def main():

    menu_text = "\n\t----Menu----\n"
    intro_text = " 1. Get Character Data\n 2. Get Location Data\n 3. Get Episode Data\n\r"
    print(menu_text)
    user_id_input = input(intro_text)

    if(user_id_input == "1"):
        character_id_input = input("What is the Character Id? \n")
        print("Your Character is " +
              get_character_name_by_id(character_id_input))
    elif(user_id_input == "2"):
        location_id_input = input("What is the Location Id? \n")
        print("Your Location is " +
              get_character_name_by_location(location_id_input))
    elif(user_id_input == "3"):
        episode_id_input = input("What is the Episode Id? \n")
        print("Your Episode is " +
              get_character_name_by_episode(episode_id_input))

main()


import datetime

from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import CommandStart
from aiogram.types import InputFile

from handlers.helps.met_support import create_array_account_proxy, replaceter_text_in_aiogram
from handlers.users.som_inviter.a_invite import get_user_invaiter_tg_asyncio
from handlers.users.som_spam.a_spam import Spammer_in_tg_asyncio
from keyboards.default import menu_start
from keyboards.default.start_menu import menu_beck, menu_beck_inv, menu_beck_spam
from loader import dp, bot

@dp.message_handler(text='🧛🏿♂Рассылка', state='*')
async def start(message: types.Message, state: FSMContext):
    proxy_file, sessions_len = create_array_account_proxy()
    __userid = message.from_user.id
    await message.answer(f"👑{message.from_user.first_name}👑 Вы перешели в - 🧙🏿Инвайт\n\n"
                         f"Аккаунтов для рассылки - {len(sessions_len)}\n"
                         f"Прокси для рассылки - {len(proxy_file)}\n\n"
                         f"Что бы начать спамить пришлите базу\n"
                         f"Пример",reply_markup=menu_beck)

    file = InputFile(
        fr"data/spam_bd.csv"
    )
    await bot.send_document(chat_id=message.chat.id, document=file,
                            reply_markup=menu_beck)
    await state.set_state('spamdoc')

@dp.message_handler(state='spamdoc',content_types=['document'])
async def add_channel_get_photo(message, state: FSMContext):
    await message.document.download(rf'data\spam_bd.csv')
    await message.answer("Пришлите сообщение для рассылки\n"
                         "В данный момент поддерживается:\n"
                         "Упитанный шрифт\n"
                         "Италик\n"
                         "Гиперссылки\n"
                         "Фото")
    await state.set_state('spamtext')

@dp.message_handler(state='spamtext',content_types=['photo'])
async def add_channel_get_photo(message, state: FSMContext):
    new_text = await replaceter_text_in_aiogram(new_text=message.caption, array_caption=message.caption_entities)
    new_text = f"{new_text}~photo"
    with open(rf'data/text_spam.txt','w+',encoding='utf-8') as file:
        file.write(new_text)
    await state.finish()
    await message.answer("Начинаем рассылать?", reply_markup=menu_beck_spam)

@dp.message_handler(state='spamtext')
async def add_channel_get_photo(message: types.Message, state: FSMContext):
    new_text = await replaceter_text_in_aiogram(new_text=message.text, array_caption=message.entities)
    new_text = f"{new_text}~text"
    with open(rf'data/text_spam.txt','w+',encoding='utf-8') as file:
        file.write(new_text)
    await state.finish()
    await message.answer("Начинаем рассылать?", reply_markup=menu_beck_spam)

@dp.message_handler(text='🚀 Рассылаем', state='*')
async def start(message: types.Message, state: FSMContext):
    await message.answer('Рассылка началась', reply_markup=menu_beck)
    msg = await message.answer('Статус запущенно')
    pc = Spammer_in_tg_asyncio(msg=msg)
    await pc.__start__()
    await state.finish()


def convertMillis(millis):
        totalSecond=millis//1000
        currentSecond=totalSecond%60
        totalMinute=totalSecond//60
        currentMinute=totalMinute%60
        currentHour=totalMinute//60
        time=str(currentHour)+':'+str(currentMinute)+':'+str(currentSecond)
        return time
def main():
        millis=eval(input("enter a millis:"))
        print(convertMillis(millis))
main()


import sys
from ._argument_parser import get_giscli_argument_parser
from .command_handler import get_handler

def main():
    parser = get_giscli_argument_parser()
    args = parser.parse_args()
    module_name = _get_fully_qualified_module_name(args)
    try:
        handler = get_handler(module_name)
        handler.execute(args)
    except NotImplementedError as ex:
        command_not_implemented = f'gis {module_name.replace(".", " ")}'
        print(f"Sorry, not implemented: `{command_not_implemented}`")
        subparser = parser.get_subparser(module_name)
        if subparser:
            subparser.print_help()
        elif module_name == None:
            parser.print_help()
        sys.exit(127)

def _get_fully_qualified_module_name(args):
    module_name = args.module
    args_dict = vars(args)
    if args_dict.get("submodule"):
        module_name = f"{args.module}.{args.submodule}"
    return module_name


"""
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv

with open('texts.csv', 'r') as f:
    reader = csv.reader(f)
    texts = list(reader)

with open('calls.csv', 'r') as f:
    reader = csv.reader(f)
    calls = list(reader)

"""
TASK 3:
(080) is the area code for fixed line telephones in Bangalore.
Fixed line numbers include parentheses, so Bangalore numbers
have the form (080)xxxxxxx.)

Part A: Find all of the area codes and mobile prefixes called by people
in Bangalore. In other words, the calls were initiated by "(080)" area code
to the following area codes and mobile prefixes:
 - Fixed lines start with an area code enclosed in brackets. The area
   codes vary in length but always begin with 0.
 - Mobile numbers have no parentheses, but have a space in the middle
   of the number to help readability. The prefix of a mobile number
   is its first four digits, and they always start with 7, 8 or 9.
 - Telemarketers' numbers have no parentheses or space, but they start
   with the area code 140.

Print the answer as part of a message:
"The numbers called by people in Bangalore have codes:"
 <list of codes>
The list of codes should be print out one per line in lexicographic order with no duplicates.

Part B: What percentage of calls from fixed lines in Bangalore are made
to fixed lines also in Bangalore? In other words, of all the calls made
from a number starting with "(080)", what percentage of these calls
were made to a number also starting with "(080)"?

Print the answer as a part of a message::
"<percentage> percent of calls from fixed lines in Bangalore are calls
to other fixed lines in Bangalore."
The percentage should have 2 decimal digits
"""

# Worst case Big-O: 10n + nlogn

def isBangaloreNumber(num):
    return num.startswith('(080)')

def getAreaCodeOrPrefix(num):
    if num[0] == '(':
        # landline
        return getAreaCode(num)
    elif num.startswith('140'):
        # telemarketer
        return '140'
    else:
        # mobile
        return getMobilePrefix(num)

def getAreaCode(num):
    code = ''
    for c in num:
        code += c
        if c == ')':
            break
    return code

def getMobilePrefix(num):
    prefix = ''
    for i in range(4):
        prefix += num[i]
    return prefix

calledNums = []
outgoingBangaloreNumsCount = 0;
calledBangaloreNumsCount = 0;
for c in calls:
    if isBangaloreNumber(c[0]):
        outgoingBangaloreNumsCount+=1
        numCode = getAreaCodeOrPrefix(c[1])
        if isBangaloreNumber(numCode):
            calledBangaloreNumsCount+=1
        if numCode not in calledNums:
            calledNums.append(numCode)

calledNums.sort()

print('The numbers called by people in Bangalore have codes:')
for num in calledNums:
    print(num)

percentBangalore =  100.00 * calledBangaloreNumsCount / outgoingBangaloreNumsCount
formatPercent = "{:.2f}".format(percentBangalore)
print(f'{formatPercent} percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore.')


from django.contrib.auth import get_user_model
from django.db import transaction
from django.utils.translation import ugettext as _

from openslides.core.config import config
from openslides.utils.autoupdate import inform_changed_data
from openslides.utils.exceptions import OpenSlidesError
from openslides.utils.rest_api import (
    GenericViewSet,
    ListModelMixin,
    Response,
    RetrieveModelMixin,
    UpdateModelMixin,
    ValidationError,
    detail_route,
    list_route,
)

from .access_permissions import ItemAccessPermissions
from .models import Item, Speaker

# Viewsets for the REST API

class ItemViewSet(ListModelMixin, RetrieveModelMixin, UpdateModelMixin, GenericViewSet):
    """
    API endpoint for agenda items.

    There are the following views: metadata, list, retrieve, create,
    partial_update, update, destroy, manage_speaker, speak and tree.
    """
    access_permissions = ItemAccessPermissions()
    queryset = Item.objects.all()

    def check_view_permissions(self):
        """
        Returns True if the user has required permissions.
        """
        if self.action in ('list', 'retrieve'):
            result = self.get_access_permissions().check_permissions(self.request.user)
        elif self.action in ('metadata', 'manage_speaker', 'tree'):
            result = self.request.user.has_perm('agenda.can_see')
            # For manage_speaker and tree requests the rest of the check is
            # done in the specific method. See below.
        elif self.action in ('partial_update', 'update'):
            result = (self.request.user.has_perm('agenda.can_see') and
                      self.request.user.has_perm('agenda.can_see_hidden_items') and
                      self.request.user.has_perm('agenda.can_manage'))
        elif self.action in ('speak', 'sort_speakers', 'numbering'):
            result = (self.request.user.has_perm('agenda.can_see') and
                      self.request.user.has_perm('agenda.can_manage'))
        else:
            result = False
        return result

    @detail_route(methods=['POST', 'DELETE'])
    def manage_speaker(self, request, pk=None):
        """
        Special view endpoint to add users to the list of speakers or remove
        them. Send POST {'user': <user_id>} to add a new speaker. Omit
        data to add yourself. Send DELETE {'speaker': <speaker_id>} or
        DELETE {'speaker': [<speaker_id>, <speaker_id>, ...]} to remove one or
        more speakers from the list of speakers. Omit data to remove yourself.

        Checks also whether the requesting user can do this. He needs at
        least the permissions 'agenda.can_see' (see
        self.check_view_permissions()). In case of adding himself the
        permission 'agenda.can_be_speaker' is required. In case of adding
        someone else the permission 'agenda.can_manage' is required. In
        case of removing someone else 'agenda.can_manage' is required. In
        case of removing himself no other permission is required.
        """
        # Retrieve item.
        item = self.get_object()

        if request.method == 'POST':
            # Retrieve user_id
            user_id = request.data.get('user')

            # Check permissions and other conditions. Get user instance.
            if user_id is None:
                # Add oneself
                if not self.request.user.has_perm('agenda.can_be_speaker'):
                    self.permission_denied(request)
                if item.speaker_list_closed:
                    raise ValidationError({'detail': _('The list of speakers is closed.')})
                user = self.request.user
            else:
                # Add someone else.
                if not self.request.user.has_perm('agenda.can_manage'):
                    self.permission_denied(request)
                try:
                    user = get_user_model().objects.get(pk=int(user_id))
                except (ValueError, get_user_model().DoesNotExist):
                    raise ValidationError({'detail': _('User does not exist.')})

            # Try to add the user. This ensurse that a user is not twice in the
            # list of coming speakers.
            try:
                Speaker.objects.add(user, item)
            except OpenSlidesError as e:
                raise ValidationError({'detail': str(e)})
            message = _('User %s was successfully added to the list of speakers.') % user

        else:
            # request.method == 'DELETE'
            speaker_ids = request.data.get('speaker')

            # Check permissions and other conditions. Get speaker instance.
            if speaker_ids is None:
                # Remove oneself
                queryset = Speaker.objects.filter(
                    item=item, user=self.request.user).exclude(weight=None)
                try:
                    # We assume that there aren't multiple entries because this
                    # is forbidden by the Manager's add method. We assume that
                    # there is only one speaker instance or none.
                    speaker = queryset.get()
                except Speaker.DoesNotExist:
                    raise ValidationError({'detail': _('You are not on the list of speakers.')})
                else:
                    speaker.delete()
                    message = _('You are successfully removed from the list of speakers.')
            else:
                # Remove someone else.
                if not self.request.user.has_perm('agenda.can_manage'):
                    self.permission_denied(request)
                if type(speaker_ids) is int:
                    speaker_ids = [speaker_ids]
                for speaker_id in speaker_ids:
                    try:
                        speaker = Speaker.objects.get(pk=int(speaker_id))
                    except (ValueError, Speaker.DoesNotExist):
                        raise ValidationError({'detail': _('Speaker does not exist.')})
                    # Delete the speaker.
                    speaker.delete()
                    message = _('Speaker %s was successfully removed from the list of speakers.') % speaker

        # Initiate response.
        return Response({'detail': message})

    @detail_route(methods=['PUT', 'DELETE'])
    def speak(self, request, pk=None):
        """
        Special view endpoint to begin and end speech of speakers. Send PUT
        {'speaker': <speaker_id>} to begin speech. Omit data to begin speech of
        the next speaker. Send DELETE to end speech of current speaker.
        """
        # Retrieve item.
        item = self.get_object()

        if request.method == 'PUT':
            # Retrieve speaker_id
            speaker_id = request.data.get('speaker')
            if speaker_id is None:
                speaker = item.get_next_speaker()
                if speaker is None:
                    raise ValidationError({'detail': _('The list of speakers is empty.')})
            else:
                try:
                    speaker = Speaker.objects.get(pk=int(speaker_id))
                except (ValueError, Speaker.DoesNotExist):
                    raise ValidationError({'detail': _('Speaker does not exist.')})
            speaker.begin_speech()
            message = _('User is now speaking.')

        else:
            # request.method == 'DELETE'
            try:
                # We assume that there aren't multiple entries because this
                # is forbidden by the Model's begin_speech method. We assume that
                # there is only one speaker instance or none.
                current_speaker = Speaker.objects.filter(item=item, end_time=None).exclude(begin_time=None).get()
            except Speaker.DoesNotExist:
                raise ValidationError(
                    {'detail': _('There is no one speaking at the moment according to %(item)s.') % {'item': item}})
            current_speaker.end_speech()
            message = _('The speech is finished now.')

        # Initiate response.
        return Response({'detail': message})

    @detail_route(methods=['POST'])
    def sort_speakers(self, request, pk=None):
        """
        Special view endpoint to sort the list of speakers.

        Expects a list of IDs of the speakers.
        """
        # Retrieve item.
        item = self.get_object()

        # Check data
        speaker_ids = request.data.get('speakers')
        if not isinstance(speaker_ids, list):
            raise ValidationError(
                {'detail': _('Invalid data.')})

        # Get all speakers
        speakers = {}
        for speaker in item.speakers.filter(begin_time=None):
            speakers[speaker.pk] = speaker

        # Check and sort speakers
        valid_speakers = []
        for speaker_id in speaker_ids:
            if not isinstance(speaker_id, int) or speakers.get(speaker_id) is None:
                raise ValidationError(
                    {'detail': _('Invalid data.')})
            valid_speakers.append(speakers[speaker_id])
        weight = 0
        with transaction.atomic():
            for speaker in valid_speakers:
                speaker.weight = weight
                speaker.save(skip_autoupdate=True)
                weight += 1

        # send autoupdate
        inform_changed_data(item)

        # Initiate response.
        return Response({'detail': _('List of speakers successfully sorted.')})

    @list_route(methods=['post'])
    def numbering(self, request):
        """
        Auto numbering of the agenda according to the config. Manually added
        item numbers will be overwritten.
        """
        Item.objects.number_all(numeral_system=config['agenda_numeral_system'])
        return Response({'detail': _('The agenda has been numbered.')})


#program to print the largest and the smallest elements in array

arr = []
n = int(input("Enter the number of elements in numerical form :"));

for i in range(n):
    element=int(input("Enter the elements in numerical form :"))
    arr.append(element)

max = arr[0]
min = arr[0]
for i in range(n):
    if(arr[i]>max):
        max=arr[i]
    if(arr[i]<min):
        min=arr[i]

print("The largest element in array is : ", max)
print("The smallest element in array is :", min)


# -*- coding: utf-8 -*-
'''
Module for gathering and managing network information
'''

# Import python libs
from __future__ import absolute_import
import datetime
import hashlib
import logging
import re
import os
import socket

# Import salt libs
import salt.utils
import salt.utils.decorators as decorators
import salt.utils.network
from salt.exceptions import CommandExecutionError
import salt.utils.validate.net
from salt.ext.six.moves import range

log = logging.getLogger(__name__)

def __virtual__():
    '''
    Only work on POSIX-like systems
    '''
    # Disable on Windows, a specific file module exists:
    if salt.utils.is_windows():
        return False

    return True

def wol(mac, bcast='255.255.255.255', destport=9):
    '''
    Send Wake On Lan packet to a host

    CLI Example:

    .. code-block:: bash

        salt '*' network.wol 08-00-27-13-69-77
        salt '*' network.wol 080027136977 255.255.255.255 7
        salt '*' network.wol 08:00:27:13:69:77 255.255.255.255 7
    '''
    if len(mac) == 12:
        pass
    elif len(mac) == 17:
        sep = mac[2]
        mac = mac.replace(sep, '')
    else:
        raise ValueError('Invalid MAC address')
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    dest = ('\\x' + mac[0:2]).decode('string_escape') + \
           ('\\x' + mac[2:4]).decode('string_escape') + \
           ('\\x' + mac[4:6]).decode('string_escape') + \
           ('\\x' + mac[6:8]).decode('string_escape') + \
           ('\\x' + mac[8:10]).decode('string_escape') + \
           ('\\x' + mac[10:12]).decode('string_escape')
    sock.sendto('\xff' * 6 + dest * 16, (bcast, int(destport)))
    return True

def ping(host, timeout=False, return_boolean=False):
    '''
    Performs an ICMP ping to a host

    CLI Example:

    .. code-block:: bash

        salt '*' network.ping archlinux.org

    .. versionadded:: 2015.5.0

    Return a True or False instead of ping output.

    .. code-block:: bash

        salt '*' network.ping archlinux.org return_boolean=True

    Set the time to wait for a response in seconds.

    .. code-block:: bash

        salt '*' network.ping archlinux.org timeout=3
    '''
    if timeout:
        cmd = 'ping -W {0} -c 4 {1}'.format(timeout, salt.utils.network.sanitize_host(host))
    else:
        cmd = 'ping -c 4 {0}'.format(salt.utils.network.sanitize_host(host))
    if return_boolean:
        ret = __salt__['cmd.run_all'](cmd)
        if ret['retcode'] != 0:
            return False
        else:
            return True
    else:
        return __salt__['cmd.run'](cmd)

# FIXME: Does not work with: netstat 1.42 (2001-04-15) from net-tools
# 1.6.0 (Ubuntu 10.10)
def _netstat_linux():
    '''
    Return netstat information for Linux distros
    '''
    ret = []
    cmd = 'netstat -tulpnea'
    out = __salt__['cmd.run'](cmd)
    for line in out.splitlines():
        comps = line.split()
        if line.startswith('tcp'):
            ret.append({
                'proto': comps[0],
                'recv-q': comps[1],
                'send-q': comps[2],
                'local-address': comps[3],
                'remote-address': comps[4],
                'state': comps[5],
                'user': comps[6],
                'inode': comps[7],
                'program': comps[8]})
        if line.startswith('udp'):
            ret.append({
                'proto': comps[0],
                'recv-q': comps[1],
                'send-q': comps[2],
                'local-address': comps[3],
                'remote-address': comps[4],
                'user': comps[5],
                'inode': comps[6],
                'program': comps[7]})
    return ret

def _netinfo_openbsd():
    '''
    Get process information for network connections using fstat
    '''
    ret = {}
    _fstat_re = re.compile(
        r'internet(6)? (?:stream tcp 0x\S+ (\S+)|dgram udp (\S+))'
        r'(?: [<>=-]+ (\S+))?$'
    )
    out = __salt__['cmd.run']('fstat')
    for line in out.splitlines():
        try:
            user, cmd, pid, _, details = line.split(None, 4)
            ipv6, tcp, udp, remote_addr = _fstat_re.match(details).groups()
        except (ValueError, AttributeError):
            # Line either doesn't have the right number of columns, or the
            # regex which looks for address information did not match. Either
            # way, ignore this line and continue on to the next one.
            continue
        if tcp:
            local_addr = tcp
            proto = 'tcp{0}'.format('' if ipv6 is None else ipv6)
        else:
            local_addr = udp
            proto = 'udp{0}'.format('' if ipv6 is None else ipv6)
        if ipv6:
            # IPv6 addresses have the address part enclosed in brackets (if the
            # address part is not a wildcard) to distinguish the address from
            # the port number. Remove them.
            local_addr = ''.join(x for x in local_addr if x not in '[]')

        # Normalize to match netstat output
        local_addr = '.'.join(local_addr.rsplit(':', 1))
        if remote_addr is None:
            remote_addr = '*.*'
        else:
            remote_addr = '.'.join(remote_addr.rsplit(':', 1))

        ret.setdefault(
            local_addr, {}).setdefault(
                remote_addr, {}).setdefault(
                    proto, {}).setdefault(
                        pid, {})['user'] = user
        ret[local_addr][remote_addr][proto][pid]['cmd'] = cmd
    return ret

def _netinfo_freebsd_netbsd():
    '''
    Get process information for network connections using sockstat
    '''
    ret = {}
    # NetBSD requires '-n' to disable port-to-service resolution
    out = __salt__['cmd.run'](
        'sockstat -46 {0} | tail -n+2'.format(
            '-n' if __grains__['kernel'] == 'NetBSD' else ''
        ), python_shell=True
    )
    for line in out.splitlines():
        user, cmd, pid, _, proto, local_addr, remote_addr = line.split()
        local_addr = '.'.join(local_addr.rsplit(':', 1))
        remote_addr = '.'.join(remote_addr.rsplit(':', 1))
        ret.setdefault(
            local_addr, {}).setdefault(
                remote_addr, {}).setdefault(
                    proto, {}).setdefault(
                        pid, {})['user'] = user
        ret[local_addr][remote_addr][proto][pid]['cmd'] = cmd
    return ret

def _ppid():
    '''
    Return a dict of pid to ppid mappings
    '''
    ret = {}
    cmd = 'ps -ax -o pid,ppid | tail -n+2'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        pid, ppid = line.split()
        ret[pid] = ppid
    return ret

def _netstat_bsd():
    '''
    Return netstat information for BSD flavors
    '''
    ret = []
    if __grains__['kernel'] == 'NetBSD':
        for addr_family in ('inet', 'inet6'):
            cmd = 'netstat -f {0} -an | tail -n+3'.format(addr_family)
            out = __salt__['cmd.run'](cmd, python_shell=True)
            for line in out.splitlines():
                comps = line.split()
                entry = {
                    'proto': comps[0],
                    'recv-q': comps[1],
                    'send-q': comps[2],
                    'local-address': comps[3],
                    'remote-address': comps[4]
                }
                if entry['proto'].startswith('tcp'):
                    entry['state'] = comps[5]
                ret.append(entry)
    else:
        # Lookup TCP connections
        cmd = 'netstat -p tcp -an | tail -n+3'
        out = __salt__['cmd.run'](cmd, python_shell=True)
        for line in out.splitlines():
            comps = line.split()
            ret.append({
                'proto': comps[0],
                'recv-q': comps[1],
                'send-q': comps[2],
                'local-address': comps[3],
                'remote-address': comps[4],
                'state': comps[5]})
        # Lookup UDP connections
        cmd = 'netstat -p udp -an | tail -n+3'
        out = __salt__['cmd.run'](cmd, python_shell=True)
        for line in out.splitlines():
            comps = line.split()
            ret.append({
                'proto': comps[0],
                'recv-q': comps[1],
                'send-q': comps[2],
                'local-address': comps[3],
                'remote-address': comps[4]})

    # Add in user and program info
    ppid = _ppid()
    if __grains__['kernel'] == 'OpenBSD':
        netinfo = _netinfo_openbsd()
    elif __grains__['kernel'] in ('FreeBSD', 'NetBSD'):
        netinfo = _netinfo_freebsd_netbsd()
    for idx in range(len(ret)):
        local = ret[idx]['local-address']
        remote = ret[idx]['remote-address']
        proto = ret[idx]['proto']
        try:
            # Make a pointer to the info for this connection for easier
            # reference below
            ptr = netinfo[local][remote][proto]
        except KeyError:
            continue
        # Get the pid-to-ppid mappings for this connection
        conn_ppid = dict((x, y) for x, y in ppid.items() if x in ptr)
        try:
            # Master pid for this connection will be the pid whose ppid isn't
            # in the subset dict we created above
            master_pid = next(iter(
                x for x, y in conn_ppid.items() if y not in ptr
            ))
        except StopIteration:
            continue
        ret[idx]['user'] = ptr[master_pid]['user']
        ret[idx]['program'] = '/'.join((master_pid, ptr[master_pid]['cmd']))
    return ret

def _netstat_route_linux():
    '''
    Return netstat routing information for Linux distros
    '''
    ret = []
    cmd = 'netstat -A inet -rn | tail -n+3'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': comps[2],
            'flags': comps[3],
            'interface': comps[7]})
    cmd = 'netstat -A inet6 -rn | tail -n+3'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        if len(comps) == 6:
            ret.append({
                'addr_family': 'inet6',
                'destination': comps[0],
                'gateway': comps[1],
                'netmask': '',
                'flags': comps[3],
                'interface': comps[5]})
        elif len(comps) == 7:
            ret.append({
                'addr_family': 'inet6',
                'destination': comps[0],
                'gateway': comps[1],
                'netmask': '',
                'flags': comps[3],
                'interface': comps[6]})
        else:
            continue
    return ret

def _netstat_route_freebsd():
    '''
    Return netstat routing information for FreeBSD and OS X
    '''
    ret = []
    cmd = 'netstat -f inet -rn | tail -n+5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': comps[2],
            'flags': comps[3],
            'interface': comps[5]})
    cmd = 'netstat -f inet6 -rn | tail -n+5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet6',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[2],
            'interface': comps[3]})
    return ret

def _netstat_route_netbsd():
    '''
    Return netstat routing information for NetBSD
    '''
    ret = []
    cmd = 'netstat -f inet -rn | tail -n+5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[3],
            'interface': comps[6]})
    cmd = 'netstat -f inet6 -rn | tail -n+5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet6',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[3],
            'interface': comps[6]})
    return ret

def _netstat_route_openbsd():
    '''
    Return netstat routing information for OpenBSD
    '''
    ret = []
    cmd = 'netstat -f inet -rn | tail -n+5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[2],
            'interface': comps[7]})
    cmd = 'netstat -f inet6 -rn | tail -n+5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet6',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[2],
            'interface': comps[7]})
    return ret

def netstat():
    '''
    Return information on open ports and states

    .. note::
        On BSD minions, the output contains PID info (where available) for each
        netstat entry, fetched from sockstat/fstat output.

    .. versionchanged:: 2014.1.4
        Added support for OpenBSD, FreeBSD, and NetBSD

    CLI Example:

    .. code-block:: bash

        salt '*' network.netstat
    '''
    if __grains__['kernel'] == 'Linux':
        return _netstat_linux()
    elif __grains__['kernel'] in ('OpenBSD', 'FreeBSD', 'NetBSD'):
        return _netstat_bsd()
    raise CommandExecutionError('Not yet supported on this platform')

def active_tcp():
    '''
    Return a dict containing information on all of the running TCP connections

    CLI Example:

    .. code-block:: bash

        salt '*' network.active_tcp
    '''
    return salt.utils.network.active_tcp()

def traceroute(host):
    '''
    Performs a traceroute to a 3rd party host

    CLI Example:

    .. code-block:: bash

        salt '*' network.traceroute archlinux.org
    '''
    ret = []
    if not salt.utils.which('traceroute'):
        log.info('This minion does not have traceroute installed')
        return ret

    cmd = 'traceroute {0}'.format(salt.utils.network.sanitize_host(host))

    out = __salt__['cmd.run'](cmd)

    # Parse version of traceroute
    cmd2 = 'traceroute --version'
    out2 = __salt__['cmd.run'](cmd2)
    try:
        # Linux traceroute version looks like:
        #   Modern traceroute for Linux, version 2.0.19, Dec 10 2012
        # Darwin and FreeBSD traceroute version looks like: Version 1.4a12+[FreeBSD|Darwin]

        traceroute_version_raw = re.findall(r'.*[Vv]ersion (\d+)\.([\w\+]+)\.*(\w*)', out2)[0]
        log.debug('traceroute_version_raw: {0}'.format(traceroute_version_raw))
        traceroute_version = []
        for t in traceroute_version_raw:
            try:
                traceroute_version.append(int(t))
            except ValueError:
                traceroute_version.append(t)

        if len(traceroute_version) < 3:
            traceroute_version.append(0)

        log.debug('traceroute_version: {0}'.format(traceroute_version))

    except IndexError:
        traceroute_version = [0, 0, 0]

    for line in out.splitlines():
        if ' ' not in line:
            continue
        if line.startswith('traceroute'):
            continue

        if 'Darwin' in str(traceroute_version[1]) or 'FreeBSD' in str(traceroute_version[1]):
            try:
                traceline = re.findall(r'\s*(\d*)\s+(.*)\s+\((.*)\)\s+(.*)$', line)[0]
            except IndexError:
                traceline = re.findall(r'\s*(\d*)\s+(\*\s+\*\s+\*)', line)[0]

            log.debug('traceline: {0}'.format(traceline))
            delays = re.findall(r'(\d+\.\d+)\s*ms', str(traceline))

            try:
                if traceline[1] == '* * *':
                    result = {
                        'count': traceline[0],
                        'hostname': '*'
                    }
                else:
                    result = {
                        'count': traceline[0],
                        'hostname': traceline[1],
                        'ip': traceline[2],
                    }
                    for x in range(0, len(delays)):
                        result['ms{0}'.format(x + 1)] = delays[x]
            except IndexError:
                result = {}

        elif (traceroute_version[0] >= 2 and traceroute_version[2] >= 14
                or traceroute_version[0] >= 2 and traceroute_version[1] > 0):
            comps = line.split('  ')
            if comps[1] == '* * *':
                result = {
                    'count': int(comps[0]),
                    'hostname': '*'}
            else:
                result = {
                    'count': int(comps[0]),
                    'hostname': comps[1].split()[0],
                    'ip': comps[1].split()[1].strip('()'),
                    'ms1': float(comps[2].split()[0]),
                    'ms2': float(comps[3].split()[0]),
                    'ms3': float(comps[4].split()[0])}
        else:
            comps = line.split()
            result = {
                'count': comps[0],
                'hostname': comps[1],
                'ip': comps[2],
                'ms1': comps[4],
                'ms2': comps[6],
                'ms3': comps[8],
                'ping1': comps[3],
                'ping2': comps[5],
                'ping3': comps[7]}

        ret.append(result)

    return ret

def dig(host):
    '''
    Performs a DNS lookup with dig

    CLI Example:

    .. code-block:: bash

        salt '*' network.dig archlinux.org
    '''
    cmd = 'dig {0}'.format(salt.utils.network.sanitize_host(host))
    return __salt__['cmd.run'](cmd)

@decorators.which('arp')
def arp():
    '''
    Return the arp table from the minion

    CLI Example:

    .. code-block:: bash

        salt '*' network.arp
    '''
    ret = {}
    out = __salt__['cmd.run']('arp -an')
    for line in out.splitlines():
        comps = line.split()
        if len(comps) < 4:
            continue
        if not __grains__['kernel'] == 'OpenBSD':
            ret[comps[3]] = comps[1].strip('(').strip(')')
        else:
            if comps[0] == 'Host' or comps[1] == '(incomplete)':
                continue
            ret[comps[1]] = comps[0]
    return ret

def interfaces():
    '''
    Return a dictionary of information about all the interfaces on the minion

    CLI Example:

    .. code-block:: bash

        salt '*' network.interfaces
    '''
    return salt.utils.network.interfaces()

def hw_addr(iface):
    '''
    Return the hardware address (a.k.a. MAC address) for a given interface

    CLI Example:

    .. code-block:: bash

        salt '*' network.hw_addr eth0
    '''
    return salt.utils.network.hw_addr(iface)

# Alias hwaddr to preserve backward compat
hwaddr = hw_addr

def interface(iface):
    '''
    Return the inet address for a given interface

    .. versionadded:: 2014.7

    CLI Example:

    .. code-block:: bash

        salt '*' network.interface eth0
    '''
    return salt.utils.network.interface(iface)

def interface_ip(iface):
    '''
    Return the inet address for a given interface

    .. versionadded:: 2014.7

    CLI Example:

    .. code-block:: bash

        salt '*' network.interface_ip eth0
    '''
    return salt.utils.network.interface_ip(iface)

def subnets():
    '''
    Returns a list of subnets to which the host belongs

    CLI Example:

    .. code-block:: bash

        salt '*' network.subnets
    '''
    return salt.utils.network.subnets()

def in_subnet(cidr):
    '''
    Returns True if host is within specified subnet, otherwise False.

    CLI Example:

    .. code-block:: bash

        salt '*' network.in_subnet 10.0.0.0/16
    '''
    return salt.utils.network.in_subnet(cidr)

def ip_in_subnet(ip_addr, cidr):
    '''
    Returns True if given IP is within specified subnet, otherwise False.

    CLI Example:

    .. code-block:: bash

        salt '*' network.ip_in_subnet 172.17.0.4 172.16.0.0/12
    '''
    return salt.utils.network.ip_in_subnet(ip_addr, cidr)

def ip_addrs(interface=None, include_loopback=False, cidr=None):
    '''
    Returns a list of IPv4 addresses assigned to the host. 127.0.0.1 is
    ignored, unless 'include_loopback=True' is indicated. If 'interface' is
    provided, then only IP addresses from that interface will be returned.
    Providing a CIDR via 'cidr="10.0.0.0/8"' will return only the addresses
    which are within that subnet.

    CLI Example:

    .. code-block:: bash

        salt '*' network.ip_addrs
    '''
    addrs = salt.utils.network.ip_addrs(interface=interface,
                                        include_loopback=include_loopback)
    if cidr:
        return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])]
    else:
        return addrs

ipaddrs = ip_addrs

def ip_addrs6(interface=None, include_loopback=False):
    '''
    Returns a list of IPv6 addresses assigned to the host. ::1 is ignored,
    unless 'include_loopback=True' is indicated. If 'interface' is provided,
    then only IP addresses from that interface will be returned.

    CLI Example:

    .. code-block:: bash

        salt '*' network.ip_addrs6
    '''
    return salt.utils.network.ip_addrs6(interface=interface,
                                        include_loopback=include_loopback)

ipaddrs6 = ip_addrs6

def get_hostname():
    '''
    Get hostname

    CLI Example:

    .. code-block:: bash

        salt '*' network.get_hostname
    '''

    from socket import gethostname
    return gethostname()

def mod_hostname(hostname):
    '''
    Modify hostname

    CLI Example:

    .. code-block:: bash

        salt '*' network.mod_hostname   master.saltstack.com
    '''
    if hostname is None:
        return False

    hostname_cmd = salt.utils.which('hostname')
    # Grab the old hostname so we know which hostname to change and then
    # change the hostname using the hostname command
    o_hostname = __salt__['cmd.run']('{0} -f'.format(hostname_cmd))

    __salt__['cmd.run']('{0} {1}'.format(hostname_cmd, hostname))

    # Modify the /etc/hosts file to replace the old hostname with the
    # new hostname
    host_c = salt.utils.fopen('/etc/hosts', 'r').readlines()

    with salt.utils.fopen('/etc/hosts', 'w') as fh:
        for host in host_c:
            host = host.split()

            try:
                host[host.index(o_hostname)] = hostname
            except ValueError:
                pass

            fh.write('\t'.join(host) + '\n')

    # Modify the /etc/sysconfig/network configuration file to set the
    # new hostname
    if __grains__['os_family'] == 'RedHat':
        network_c = salt.utils.fopen('/etc/sysconfig/network', 'r').readlines()

        with salt.utils.fopen('/etc/sysconfig/network', 'w') as fh:
            for i in network_c:
                if i.startswith('HOSTNAME'):
                    fh.write('HOSTNAME={0}\n'.format(hostname))
                else:
                    fh.write(i)
    elif __grains__['os_family'] == 'Debian':
        with salt.utils.fopen('/etc/hostname', 'w') as fh:
            fh.write(hostname + '\n')
    elif __grains__['os_family'] == 'OpenBSD':
        with salt.utils.fopen('/etc/myname', 'w') as fh:
            fh.write(hostname + '\n')

    return True

def connect(host, port=None, **kwargs):
    '''
    Test connectivity to a host using a particular
    port from the minion.

    .. versionadded:: 2014.7

    CLI Example:

    .. code-block:: bash

        salt '*' network.connect archlinux.org 80

        salt '*' network.connect archlinux.org 80 timeout=3

        salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4

        salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3
    '''

    ret = {'result': None,
           'comment': ''}

    if not host:
        ret['result'] = False
        ret['comment'] = 'Required argument, host, is missing.'
        return ret

    if not port:
        ret['result'] = False
        ret['comment'] = 'Required argument, port, is missing.'
        return ret

    proto = kwargs.get('proto', 'tcp')
    timeout = kwargs.get('timeout', 5)
    family = kwargs.get('family', None)

    if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host):
        address = host
    else:
        address = '{0}'.format(salt.utils.network.sanitize_host(host))

    try:
        if proto == 'udp':
            __proto = socket.SOL_UDP
        else:
            __proto = socket.SOL_TCP
            proto = 'tcp'

        if family:
            if family == 'ipv4':
                __family = socket.AF_INET
            elif family == 'ipv6':
                __family = socket.AF_INET6
            else:
                __family = 0
        else:
            __family = 0

        (family,
         socktype,
         _proto,
         garbage,
         _address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0]

        s = socket.socket(family, socktype, _proto)
        s.settimeout(timeout)

        if proto == 'udp':
            # Generate a random string of a
            # decent size to test UDP connection
            h = hashlib.md5()
            h.update(datetime.datetime.now().strftime('%s'))
            msg = h.hexdigest()
            s.sendto(msg, _address)
            recv, svr = s.recvfrom(255)
            s.close()
        else:
            s.connect(_address)
            s.shutdown(2)
    except Exception as e:
        ret['result'] = False
        try:
            errno, errtxt = e
        except ValueError:
            ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'.format(host, _address[0], proto, port)
        else:
            ret['comment'] = '{0}'.format(errtxt)
        return ret

    ret['result'] = True
    ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'.format(host, _address[0], proto, port)
    return ret

def is_private(ip_addr):
    '''
    Check if the given IP address is a private address

    .. versionadded:: 2014.7.0

    CLI Example:

    .. code-block:: bash

        salt '*' network.is_private 10.0.0.3
    '''
    return salt.utils.network.IPv4Address(ip_addr).is_private

def is_loopback(ip_addr):
    '''
    Check if the given IP address is a loopback address

    .. versionadded:: 2014.7.0

    CLI Example:

    .. code-block:: bash

        salt '*' network.is_loopback 127.0.0.1
    '''
    return salt.utils.network.IPv4Address(ip_addr).is_loopback

def reverse_ip(ip_addr):
    '''
    Returns the reversed IP address

    CLI Example:

    .. code-block:: bash

        salt '*' network.reverse_ip 172.17.0.4
    '''
    return salt.utils.network.IPv4Address(ip_addr).reverse_pointer

def _get_bufsize_linux(iface):
    '''
    Return network interface buffer information using ethtool
    '''
    ret = {'result': False}

    cmd = '/sbin/ethtool -g {0}'.format(iface)
    out = __salt__['cmd.run'](cmd)
    pat = re.compile(r'^(.+):\s+(\d+)$')
    suffix = 'max-'
    for line in out.splitlines():
        res = pat.match(line)
        if res:
            ret[res.group(1).lower().replace(' ', '-') + suffix] = int(res.group(2))
            ret['result'] = True
        elif line.endswith('maximums:'):
            suffix = '-max'
        elif line.endswith('settings:'):
            suffix = ''
    if not ret['result']:
        parts = out.split()
        # remove shell cmd prefix from msg
        if parts[0].endswith('sh:'):
            out = ' '.join(parts[1:])
        ret['comment'] = out
    return ret

def get_bufsize(iface):
    '''
    Return network buffer sizes as a dict

    CLI Example:

    .. code-block:: bash

        salt '*' network.getbufsize
    '''
    if __grains__['kernel'] == 'Linux':
        if os.path.exists('/sbin/ethtool'):
            return _get_bufsize_linux(iface)

    return {}

def _mod_bufsize_linux(iface, *args, **kwargs):
    '''
    Modify network interface buffer sizes using ethtool
    '''
    ret = {'result': False,
           'comment': 'Requires rx=<val> tx==<val> rx-mini=<val> and/or rx-jumbo=<val>'}
    cmd = '/sbin/ethtool -G ' + iface
    if not kwargs:
        return ret
    if args:
        ret['comment'] = 'Unknown arguments: ' + ' '.join([str(item) for item in args])
        return ret
    eargs = ''
    for kw in ['rx', 'tx', 'rx-mini', 'rx-jumbo']:
        value = kwargs.get(kw)
        if value is not None:
            eargs += ' ' + kw + ' ' + str(value)
    if not eargs:
        return ret
    cmd += eargs
    out = __salt__['cmd.run'](cmd)
    if out:
        ret['comment'] = out
    else:
        ret['comment'] = eargs.strip()
        ret['result'] = True
    return ret

def mod_bufsize(iface, *args, **kwargs):
    '''
    Modify network interface buffers (currently linux only)

    CLI Example:

    .. code-block:: bash

        salt '*' network.getBuffers
    '''
    if __grains__['kernel'] == 'Linux':
        if os.path.exists('/sbin/ethtool'):
            return _mod_bufsize_linux(iface, *args, **kwargs)

    return False

def routes(family=None):
    '''
    Return currently configured routes from routing table

    CLI Example:

    .. code-block:: bash

        salt '*' network.routes
    '''
    if family != 'inet' and family != 'inet6' and family is not None:
        raise CommandExecutionError('Invalid address family {0}'.format(family))

    if __grains__['kernel'] == 'Linux':
        routes_ = _netstat_route_linux()
    elif __grains__['os'] in ['FreeBSD', 'MacOS', 'Darwin']:
        routes_ = _netstat_route_freebsd()
    elif __grains__['os'] in ['NetBSD']:
        routes_ = _netstat_route_netbsd()
    elif __grains__['os'] in ['OpenBSD']:
        routes_ = _netstat_route_openbsd()
    else:
        raise CommandExecutionError('Not yet supported on this platform')

    if not family:
        return routes_
    else:
        ret = [route for route in routes_ if route['addr_family'] == family]
        return ret

def default_route(family=None):
    '''
    Return default route(s) from routing table

    CLI Example:

    .. code-block:: bash

        salt '*' network.default_route
    '''

    if family != 'inet' and family != 'inet6' and family is not None:
        raise CommandExecutionError('Invalid address family {0}'.format(family))

    _routes = routes()
    default_route = {}
    if __grains__['kernel'] == 'Linux':
        default_route['inet'] = ['0.0.0.0', 'default']
        default_route['inet6'] = ['::/0', 'default']
    elif __grains__['os'] in ['FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS', 'Darwin']:
        default_route['inet'] = ['default']
        default_route['inet6'] = ['default']
    else:
        raise CommandExecutionError('Not yet supported on this platform')

    ret = []
    for route in _routes:
        if family:
            if route['destination'] in default_route[family]:
                ret.append(route)
        else:
            if route['destination'] in default_route['inet'] or \
               route['destination'] in default_route['inet6']:
                ret.append(route)

    return ret

def get_route(ip):
    '''
    Return routing information for given destination ip

    .. versionadded:: 2015.5.3

    CLI Example::

        salt '*' network.get_route 10.10.10.10
    '''

    if __grains__['kernel'] == 'Linux':
        cmd = 'ip route get {0}'.format(ip)
        out = __salt__['cmd.run'](cmd, python_shell=True)
        regexp = re.compile(r'(via\s+(?P<gateway>[\w\.:]+))?\s+dev\s+(?P<interface>[\w\.\:]+)\s+.*src\s+(?P<source>[\w\.:]+)')
        m = regexp.search(out.splitlines()[0])
        ret = {
            'destination': ip,
            'gateway': m.group('gateway'),
            'interface': m.group('interface'),
            'source': m.group('source')}

        return ret
    else:
        raise CommandExecutionError('Not yet supported on this platform')


'''
Author: 千仞无锋
Date: 2022-04-20 21:31:30
LastEditors: 千仞无锋
LastEditTime: 2022-04-20 22:36:20
FilePath: \20220411HTML_CSS\一个小插曲关于excel和py的\youtube_openpyxl_03.py
'''
import openpyxl
from openpyxl import Workbook, load_workbook
from openpyxl.utils import get_column_letter, column_index_from_string
from openpyxl.styles import Font ,PatternFill, Border, Side, Alignment, Protection
# data 是一个列表，每个元素是一个字典
data = [{
    'name': '赵日天',
    'tall': 180,
    'age': 18,
    'weight': 80,
}, {
    'name': '钱多多',
    'tall': 190,
    'age': 19,
    'weight': 100
}, {
    'name': '孙小小',
    'tall': 210,
    'age': 22,
    'weight': 120
}]
# 写入excel
wb = Workbook()
ws = wb.active

title = ['姓名', '身高', '年龄', '体重']
ws.append(title)

for person in data:
    # 字典变列表
    ws.append(list(person.values()))
wb.save(r'H:\study-notes\20220411HTML_CSS\一个小插曲关于excel和py的\text.xlsx')

# 基础计算
# 调用公式
for col in range(2, 5):
    char = get_column_letter(col)
    ws[char + '7'] = f'=AVERAGE({char+"2"}:{char+"6"})'
wb.save(r'H:\study-notes\20220411HTML_CSS\一个小插曲关于excel和py的\text.xlsx')

# 字体
for col in range(1, 5):
    char = get_column_letter(col)
    ws[char + '1'].font = Font(bold=True,color='FF0000') # 字体加粗,变红
wb.save(r'H:\study-notes\20220411HTML_CSS\一个小插曲关于excel和py的\text.xlsx')


import random
star = input('請決定隨機數字範圍開始值:')
end = input('請決定隨機數字範圍結束值:')
r = random.randint(int(star), int(end))

count = 0
while True:
	count += 1 # count = count + 1
	num = input('請輸入數字：')
	num = int(num)
	if num == r:
		print('恭喜你猜對了！')
		print('這是你猜的第', count, '次')
		break
	elif num > r:
		print('比答案大')
	elif num < r:
		print('比答案小')
	print('這是你猜的第', count, '次')