# Given two integer arrays nums1 and nums2, return an array of their intersection.
# Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
from typing import List

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        arr = []
        for i in nums1:
            if nums2.__contains__(i):
                nums2.remove(i)
                arr.append(i)
        return arr


import pandas as pd
import plotly.express as px
from dash import Dash, html, dcc, Output, Input

# Load provided dataset
df = pd.read_csv("https://raw.githubusercontent.com/thom-appelman/pfb-dashboard/main/customer_segmentation.csv")

app = Dash(__name__)
app.title = "Customer Segmentation Dashboard"
server = app.server

app.layout = html.Div([
    html.Div(
        children=[
            html.H1("Customer Segmentation Dashboard", style={"color": "white", "textAlign": "center"}),
            html.H4("Created by Thom P.J. Appelman - S5502577", style={"color": "white", "textAlign": "center"}),
        ],
        style={
            "backgroundColor": "#1F559F",
            "padding": "5px",
            "marginBottom": "10px",
        }
    ),
    html.Div([
        html.H4("Select professions from the drop-down list"),
        dcc.Dropdown(
            id="xaxis-job",
            options=[dict(label=i, value=i) for i in df["job_title"].unique()],
            value=["Nurse"],
            multi=True
        )
    ]),
    html.Div([
        dcc.Graph(id="job-barchart"),
        html.H3(id="total-customers", style={"textAlign": "center"}),
    ]),
    html.Div([
        dcc.Graph(id="gender-piechart"),
        html.H4("Select a gender to see the breakdown of departments"),
        dcc.Dropdown(
            id="dropdown-gender",
            options=[dict(label=i, value=i) for i in df["gender"].unique()],
            value="Male"),
        dcc.Graph(id="department-piechart")
    ]),
    html.Div([
        html.H4("Show top 5 countries with:"),
        dcc.RadioItems(
            id="countries-toggle",
            options=[
                {"label": "Highest number of customers", "value": "highest"},
                {"label": "Lowest number of customers", "value": "lowest"}
            ],
            value="highest")
    ]),
    dcc.Graph(id="countries-barchart"),
    html.Div([
        html.H4("Top cities based on the number of customers in:"),
        dcc.Dropdown(
            id="xaxis-country",
            options=[dict(label=i, value=i) for i in df["country"].unique()],
            value="United Kingdom"
        )
    ]),
    dcc.Graph(id="city-barchart")
], style={'font-family': 'Arial'})

# Bar chart showing number of customers based on drop-down list of job titles
@app.callback(
    Output("job-barchart", "figure"),
    Input("xaxis-job", "value"))
def update_job_barchart(selected_jobs):
    filtered_df = df[df["job_title"].isin(selected_jobs)]
    fig = px.histogram(filtered_df, x="job_title", title="Customers by profession",
                       labels={"job_title": "Profession", "count": "Number of Customers"},
                       color="job_title", template="simple_white")
    return fig

# Showing the total number of customers based on job title selection
@app.callback(
    Output("total-customers", "children"),
    Input("xaxis-job", "value")
)
def update_total_customers(selected_jobs):
    filtered_df = df[df["job_title"].isin(selected_jobs)]
    total_customers = len(filtered_df)
    return f"Total number of customers based on Job selection: {total_customers}"

# Pie chart showing department breakdown for selected gender
@app.callback(
    Output("gender-piechart", "figure"),
    Input("xaxis-job", "value")
)
def update_gender_pie(selected_jobs):
    filtered_df = df[df["job_title"].isin(selected_jobs)]
    gender_count = filtered_df["gender"].value_counts()
    fig = px.pie(names=gender_count.index, values=gender_count.values,
                 title="gender breakdown of customers by selected professions")
    return fig

# Histogram showing the top 5 or bottom 5 countries based on number of customers
@app.callback(
    Output("countries-barchart", "figure"),
    Input("countries-toggle", "value")
)
def update_country_chart(order):
    countries_count = df["country"].value_counts()
    if order == "highest":
        top_five = countries_count.head(5)
    else:
        top_five = countries_count.tail(5)
    fig = px.histogram(x=top_five.index, y=top_five.values,
                       title=f"Top 5 countries with the {order} number of customers",
                       labels=dict(x="Countries", y="Number of Customers"),
                       color=top_five.index, template="simple_white")
    return fig

# Pie chart showing the breakdown of departments based on selected gender
@app.callback(
    Output("department-piechart", "figure"),
    Input("dropdown-gender", "value")
)
def update_department_pie(gender):
    filtered_df = df[df["gender"] == gender]
    department_count = filtered_df["department"].value_counts()
    fig = px.pie(names=department_count.index, values=department_count.values,
                 title=f"Breakdown of departments for {gender} customers")
    return fig

# Bar chart showing the 10 cities with the most customers from the selected countries
@app.callback(
    Output("city-barchart", "figure"),
    Input("xaxis-country", "value")
)
def update_city_chart(selected_country):
    filtered_df = df[df["country"] == selected_country]
    city_count = filtered_df["city"].value_counts()
    top_cities = city_count.head(10)
    fig = px.histogram(x=top_cities.index, y=top_cities.values,
                       title=f"Top Cities by number of customers in {selected_country}",
                       labels=dict(x="City", y="Number of customers"),
                       color=top_cities.index, template="simple_white")
    return fig

# Run Dashboard application
if __name__ == "__main__":
    app.run_server()


cases = 0
testcases = int(input())
while cases != testcases:
    variables = input().split()
    sessions=(int(variables[0]))
    additional=(int(variables[1]))
    minutesperses = input().split()
    minutespersesint=[]
    for i in range(len(minutesperses)):
        minutespersesint.append(int(minutesperses[i]))
    print(sessions)
    print(additional)
    print(minutespersesint)
    cases += 1


# name   : sai eshwar reddy kottapally
# rollno : 100519733022
# program to print no of occurances in the given string

s=input("enter a string:")

def count_char(text):
    for i in range(len(text)):
        if len(text) == 0:
            break
        ch = text[0]
        if ch == ' ' or ch == '\t':
            continue
        print(ch + " - ", text.count(ch))
        text = text.replace(ch, '').strip()

count_char(s)


import re
import json
from typing import List, Dict

import bs4
import requests
from bs4 import BeautifulSoup
from requests import Response

'''
最后获取的channel && programs的字典格式如下：

all_program_in_a_channel: Dict = {
    'channel_id': 12345,
    'all_programs_url': [
        {'program_id': 45678,'program_name': '音频标题'},
        {'program_id': 45679,'program_name': '音频标题'},
    ]
}

'''

class ChannelItemLoader(object):
    def __init__(self, channel_id:str):
        self.channel_fist_page_url: str = 'https://www.qtfm.cn/channels/' + str(channel_id)
        self.channel_id: str = channel_id
        self.page_number: int = self.get_channel_page_num()
        self.version: str = self.get_channel_version_field()

    # 每个页面获取一个soup，方便使用
    def get_page_soup(self, page_url) -> BeautifulSoup:
        response_text: str = requests.get(page_url).text
        soup: BeautifulSoup = BeautifulSoup(response_text, 'lxml')
        return soup

    # 获取一个channel中容纳所有节目的页码，就是最底下那个翻页组件
    def get_channel_page_num(self) -> int:
        soup: BeautifulSoup = self.get_page_soup(self.channel_fist_page_url)
        pagination_div: bs4.element.Tag = soup.find_all('ul', class_='pagination')[0]
        get_last_page_li: bs4.element.Tag = pagination_div.find_all("li")[-2]
        page_num: int = int(get_last_page_li.text)
        return page_num

    # 每个channel有一个version字段，根据这个字段可以拼出获取所有program json信息的URL
    def get_channel_version_field(self) -> str:
        version_url: str = f'https://i.qtfm.cn/capi/v3/channel/{self.channel_id}?user_id=null'
        version_response: Response = requests.get(version_url)
        json_version_response: str = version_response.text
        dict_version_response: dict = json.loads(json_version_response)
        version: str = dict_version_response['data']['v']
        return version

    # 获取一个单一页面中，比如第一页所包含的page的URL，但是是主要想获取program的ID
    def get_programs_json_in_onepage(self, page_num:int) -> List:
        program_info_json_url: str = f'https://i.qtfm.cn/capi/channel/{self.channel_id}/programs/{self.version}?curpage={page_num}&pagesize=30&order=asc'
        program_info_json_response: Response = requests.get(program_info_json_url)
        program_info_json_text: str = program_info_json_response.text
        program_info_json_dict: Dict = json.loads(program_info_json_text)
        # programs_json:List=program_info_json_dict['data']['programs']
        programs_json: List = program_info_json_dict.get('data', '没有data数据').get('programs', '没有programs数据')
        # return programs_json
        return programs_json

    # 获取一个channel中所有program的ID，并组成all_program_in_a_channel的字典
    def get_all_programs(self) -> Dict:
        all_program_in_a_channel: Dict = {}
        all_program_in_a_channel['channel_id'] = self.channel_id
        all_programs_url: List = []
        for page_num in range(self.page_number):
            programs_json = self.get_programs_json_in_onepage(page_num+1)
            all_programs_url.extend(programs_json)
        all_program_in_a_channel['all_programs_url'] = all_programs_url
        return all_program_in_a_channel

if __name__ == '__main__':
    # channel_url = 'https://www.qtfm.cn/channels/353596'#
    # channel_url='https://www.qtfm.cn/channels/353596/2'
    # get_all_audio_page_urls(channel_url)
    # get_channel_page_num(channel_url)

    chanel_item_loader = ChannelItemLoader(str(353596))
    # programs_json=chanel_item_loader.get_programs_json_in_onepage(1)
    # for i in programs_json:
    #     print(i)

    all_program_in_a_channel = chanel_item_loader.get_all_programs()
    for item in all_program_in_a_channel['all_programs_url']:
        print(item)


load(":image_diff_test.bzl", "image_diff_test")
load(":image_rpms_test.bzl", "image_test_rpm_integrity", "image_test_rpm_names")
load(":image_test.bzl", "image_cpp_test", "image_python_test", "image_rust_test", "image_sh_test")

antlir2_image_test = struct(
    unittest = struct(
        cpp = image_cpp_test,
        python = image_python_test,
        rust = image_rust_test,
        sh = image_sh_test,
    ),
    diff_test = image_diff_test,
    rpms = struct(
        names = image_test_rpm_names,
        integrity = image_test_rpm_integrity,
    ),
)


from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.home_page, name='home'),
    url(r'^study', views.study_page, name='study'),
    url(r'^test', views.test_page, name='test'),
    url(r'ajax/create_word_list/', views.create_user_word_list, name="new list"),
    url(r'ajax/test_score_update/', views.test_score_update, name="new score"),
]


import pytest

from advent.inverse_captcha import seq_sum, sum_half_seq

seq_sum_test_data = [
    (map(int, "1122"), 3),
    (map(int, "1111"), 4),
    (map(int, "1234"), 0),
    (map(int, "91212129"), 9),
]

sum_half_seq_test_data = [
    (map(int, "1212"), 6),
    (map(int, "1221"), 0),
    (map(int, "123425"), 4),
    (map(int, "123123"), 12),
    (map(int, "12131415"), 4),
]

@pytest.mark.parametrize("data,expected", seq_sum_test_data)
def test_seq_sum(data, expected):
    assert seq_sum(data) == expected

@pytest.mark.parametrize("data,expected", sum_half_seq_test_data)
def test_sum_half_seq(data, expected):
    assert sum_half_seq(data) == expected


""" Provides a range of functions used to create the overview page for blog
    posts.
"""
import os
from os import listdir
from os.path import isdir, join
from pathlib import Path

root_dir: str = f'{Path(__file__).parent.parent}'

class Post:
    """ Defines a post, consisting of a category, topic, headline,
        summary, link and thumbnail
    """

    def __init__(
        self,
        category: str,
        topic: str,
        headline: str,
        summary: str,
        link: str,
        thumbnail: str,
        date: str,
        series: str,
        series_section: int
    ):
        self.category: str = category
        self.topic: str = topic
        self.headline: str = headline
        self.summary: str = summary
        self.link: str = link
        self.thumbnail: str = thumbnail
        self.date: str = date
        self.series: str = series
        self.series_section: int = series_section

def compose_index_files() -> None:
    """ Iterates over all categories, finds all posts in their respective
        category, creates a list of blog posts based on the files found in a
        category's directory and writes the parsed objects to a json file.
    """
    categories: [bytes] = select_categories()
    for category in categories:
        post_dirs: [bytes] = select_post_dirs(category)
        posts: [Post] = parse_posts_in_category(post_dirs)
        if len(posts) > 0:
            write_posts_to_file(posts)

def parse_posts_in_category(post_dirs: [str]) -> [Post]:
    """ Takes a list of directories that may contain blog posts,
        checks whether the directory actually contains any posts and
        parses the content of the directory into a Post object.
    """
    posts: [Post] = []
    for post_dir in post_dirs:
        post_file: str = select_post(post_dir)
        posts.append(extract_post_from_file(post_file))
    return posts

def select_categories() -> [bytes]:
    """ Selects directories, containing categories of posts.
    """
    full_dir_name: str = f'{root_dir}/src/assets/posts'
    categories: [bytes] = []
    for directory in listdir(full_dir_name):
        categories.append(os.path.join(full_dir_name, directory))
    return list(filter(isdir, categories))

def select_post_dirs(category: str) -> [bytes]:
    """ Selects all posts contained in a category.
    """
    posts: [bytes] = []
    for directory in listdir(category):
        posts.append(join(category, directory))
    return list(filter(isdir, posts))

def select_post(post_dir: str) -> str:
    """ Selects the markdown file containing the actual post
    """
    for file in listdir(post_dir):
        # noinspection PyTypeChecker
        if file.endswith('.md'):
            return join(post_dir, file)

def extract_post_from_file(file_path: str) -> Post:
    """ Reads the content of a file, identified by its file path. A file path
        may look similar as the one depicted below:
        ./src/assets/posts/guides/001_angular_apps_on_github_pages/angular.md
    """
    topic = parse_topic(file_path)
    headline = parse_headline(file_path)
    summary = parse_summary(file_path)
    date = parse_date(file_path)
    series = parse_series(file_path)
    series_section = parse_series_section(file_path)
    category = file_path.split('/')[9]
    relative_path = '/'.join(file_path.split('/')[5:])
    link = compose_link(relative_path)
    thumbnail_path = compose_thumbnail_path(relative_path)

    return Post(
        category,
        topic,
        headline,
        summary,
        link,
        thumbnail_path,
        date,
        series,
        series_section
    )

def parse_headline(file_path: str) -> str:
    """Opens a file containing a blog posts, iterates over the file and returns
    the post's headline if existing.
    """
    with open(file_path) as reader:
        for line in reader:
            headline = line.split('# ')
            if len(headline) > 1:
                return clean_str(headline[1])

def parse_topic(file_path: str) -> str:
    """ Opens a file containing a blog posts, iterates over the file and returns
        the post's topic if existing.
    """
    with open(file_path) as reader:
        for line in reader:
            topic = line.split('topic=')
            if len(topic) > 1:
                return clean_str(topic[1])

def parse_date(file_path: str) -> str:
    """ Opens a file containing a blog posts, iterates over the file and returns
        the post's date if existing.
    """
    with open(file_path) as reader:
        for line in reader:
            date = line.split('date=')
            if len(date) > 1:
                return clean_str(date[1])

def parse_series(file_path: str) -> str:
    """ Opens a file containing a blog posts, iterates over the file and returns
        the series to which a post belongs to.
    """
    with open(file_path) as reader:
        for line in reader:
            series = line.split('series=')
            if len(series) > 1:
                return replace_underscores(series[1])

def parse_series_section(file_path: str) -> int:
    """ Opens a file containing a blog posts, iterates over the file and returns
        the series to which a post belongs to.
    """
    with open(file_path) as reader:
        for line in reader:
            series_section = line.split('series_section=')
            if len(series_section) > 1:
                return int(series_section[1])

def parse_summary(file_path: str) -> str:
    """ Opens a file containing a blog posts, iterates over the file and returns
        the series to which a post belongs to.
    """
    with open(file_path) as reader:
        for line in reader:
            summary = line.split('summary=')
            if len(summary) > 1:
                return clean_str(summary[1])

def clean_str(line: str) -> str:
    """ Removes whitespaces from a given str. """
    return line.replace('\n', ' ').replace('\r', ' ').replace("'", '')[:-1]

def replace_underscores(line: str) -> str:
    """ Replaces underscores with spaces. """
    return line.replace('_', ' ').replace('\n', '')

def write_posts_to_file(posts: [Post]) -> None:
    """ Writes a parsed Post object to a typescript file."""
    first_line = 'import { Post } from "src/app/modules/shared/models/post"; \n'
    path_elements: [str] = posts[0].link.split("/")[:-2]
    relative_path = "/".join(path_elements)
    file_name_elments = posts[0].category.split("-")
    file_name_elments = [string.title() for string in file_name_elments]
    file_name = "".join(file_name_elments)
    index_file = f'{root_dir}/src{relative_path}/{file_name}.ts'
    with open(index_file, 'w') as writer:
        writer.write(first_line)
        writer.write('\n')
        writer.write(f'export const {file_name}: Post[] = [\n')
        for post in posts:
            line = parse_post_to_line(post)
            writer.write(line)
        writer.write(']')

def compose_thumbnail_path(file_path: str) -> str:
    """ Computes the path to a post's thumbnail."""
    file_path = '/'.join(file_path.split("/")[2:-1])
    return f'{file_path}/thumbnail.svg'

def compose_link(file_path: str) -> str:
    """ Computes the path to a post's thumbnail."""
    print(file_path)
    file_name = file_path.split("/")[-1]
    link = '/'.join(file_path.split("/")[2:-1])
    return f'/{link}/{file_name}'

def parse_post_to_line(post: Post) -> str:
    """ Converts a Post object to a line, intended to be written to an index
        file.
    """
    line: str = ''
    line += "    new Post("
    line += f"'{post.category}', "
    line += f"'{post.topic}', "
    line += f"'{post.headline}', "
    line += f"'{post.summary}', "
    line += f"'{post.link}', "
    line += f"'{post.thumbnail}', "
    line += f"'{post.date}'"
    if post.series:
        line += f", '{post.series}'"
    if post.series_section:
        line += f", {post.series_section}"
    line += "), \n"
    print(post.headline)
    return line

if __name__ == '__main__':
    compose_index_files()


from django.shortcuts import render,redirect
from .models import Contact
from django.contrib import messages

# Create your views here.

def contact(request):
    if request.method == 'POST':
        listing_id = request.POST['listing_id']
        user_id = request.POST['user_id']
        listing = request.POST['listing']
        name = request.POST['name']
        email = request.POST['email']
        phone = request.POST['phone']
        message = request.POST['message']
        realtor_email = request.POST['realtor_email']

        if request.user.is_authenticated:
            user_id=request.user.id
            contacted=Contact.objects.all().filter(listing_id=listing_id,user_id=user_id)
            if contacted:
                messages.error(request,'You already make inquiry for this home')
                return redirect('/listing/'+listing_id)

        contact = Contact(user_id=user_id,listing_id=listing_id,listing=listing,name=name,email=email,phone=phone,message=message)
        contact.save()
        messages.success(request,'Thanks for inquiry.The realtor will touch you soon.')
        return redirect('dashboard')


import streamlit as st
import pandas as pd
import plotly.express as xp
import seaborn as sns
import matplotlib.pyplot as plt
plt.style.use('Solarize_Light2')
sns.set_style("darkgrid")
st.set_option('deprecation.showPyplotGlobalUse', False)

st.title('Uploader visualisation')
#fileuploader, Affichage du dataset aevc funct, affichage du describe, ajout des graphiques

st.sidebar.title('Visualisation de vos données')
Uploader = st.sidebar.file_uploader(label='Uploadez votre fichier',type=['csv','xlsx'])
#Df = pd.read_csv(Uploader)
if Uploader is not None:
    Df = pd.read_csv(Uploader)
else:
    st.warning("Vous devez d'abord importer votre fichier pour visualiser vos données")
Preview = st.sidebar.checkbox('Afficher votre dataset')
if Preview:
    st.write(Df)
    st.write(Df.shape)
    Describe = st.sidebar.checkbox('Les statistiques de votre dataset')
    if Describe:
        st.write(Df.describe())

#les types de données
def Data():
    Col_num = Df.select_dtypes(['int','float']).columns
    Col_str = Df.select_dtypes(['object']).columns
    return Col_num,Col_str

Num_cols = Df.select_dtypes(['float','int']).columns

#Add select widget and menu

Choice = ['Scatter','Histograme','Camenbert']
Menu = st.sidebar.selectbox(label='Choisissez votre graph',options=Choice)

if Menu == 'Scatter':
    Select_X = st.sidebar.selectbox(label='Votre variable X',options=Num_cols)
    Select_Y =st.sidebar.selectbox(label='Votre variable Y',options=Num_cols)
#create scatter plot
    st.sidebar.subheader('Scatter plot')
    sns.relplot(data=Df,x=Select_X, y=Select_Y)
    st.pyplot()
elif Menu == 'Histogramme':
    #create histogram
    st.sidebar.subheader('Histogramme')
    Select_three = st.sidebar.selectbox(label='Variables',options=Num_cols)
    Histogram_slider = st.sidebar.slider(label='Tranches',min_value=5,max_value=100,value=30)
    sns.distplot(Df[Select_three],bins=Histogram_slider)
    st.pyplot()
else:
    st.sidebar.subheader('Pie chart')
    Select_foor = list(Df.select_dtypes(['object']).columns)
    st.write(Select_foor)
    plt.pie(Select_foor,labels=Select_foor.index,shadow=True,autopct='%1.1f%%')


from timeit import default_timer as timer

from sklearn import tree
from sklearn.model_selection import train_test_split, learning_curve, validation_curve
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import GradientBoostingClassifier
from Utility import extractData, plotPerformance, getBestModel, plotLearningCurve, plotValidationCurve
import pandas as pd

class DecisionTree:

   def classify(self, data_file, encode, label):
        # data = pd.read_csv(data_file)
        X, Y = extractData(data_file)

        enc = LabelEncoder()

        if encode:
            rows,cols = X.shape
            for c in range(cols):
                if not str(X.iloc[1][c]).isnumeric() :
                    enc.fit(X.iloc[:,c])
                    X.iloc[:,c] = enc.transform(X.iloc[:,c])
            enc.fit(Y)
            Y = enc.transform(Y)

        #
        train_x, test_x, train_y,test_y = train_test_split(X,Y, test_size=0.2, random_state=123)

        #Find best model
        dct = tree.DecisionTreeClassifier()
        parameter_grid = {'criterion': ['gini', 'entropy'],
                          'splitter': ['best', 'random'],
                          'max_depth': range(1,10),
                          'max_features': range(1,5),
                          'min_samples_leaf': range(1,5)}
        start = timer()
        classifier, grid_search = getBestModel(dct, parameter_grid, train_x, train_y)
        classify_model =  classifier.fit(train_x, train_y)
        pred_y = classify_model.predict(test_x)
        end = timer()
        print('Elapsed time of train and test : '+ str(end - start))
        accuracy = grid_search.best_score_ * 100

        print('Accuracy of Decision Tree(depth={}) = {:.2f}%'.format(classify_model.get_depth(),accuracy))

        plotValidationCurve("Decision Tree", label, grid_search, train_x, train_y, parameter_grid)
        plotLearningCurve("Decision Tree", label, classifier, X, Y)
        plotPerformance(test_y, pred_y, label, 'Algorithm: Decision Tree')

   def classifyWithBoost(self, data_file, encode, label):
        X, Y = extractData(data_file)

        enc = LabelEncoder()

        if encode:
            rows, cols = X.shape
            for c in range(cols):
                if not str(X.iloc[1][c]).isnumeric():
                    enc.fit(X.iloc[:, c])
                    X.iloc[:, c] = enc.transform(X.iloc[:, c])
            enc.fit(Y)
            Y = enc.transform(Y)

        train_x, test_x, train_y, test_y = train_test_split(X, Y, test_size=0.3, random_state=123)
        dctb = GradientBoostingClassifier(random_state=123)
        parameter_grid = {'learning_rate': [0.2, 0.3, 0.5],
                          'max_depth': [2, 3, 4, 5]
                          }
        start = timer()
        classifier, grid_search = getBestModel(dctb, parameter_grid, train_x, train_y)
        plotValidationCurve("Decision Tree with Boost", label, grid_search, train_x, train_y, parameter_grid)
        plotLearningCurve("Decision Tree with Boost", label, classifier, X, Y)
        classify_model = classifier.fit(X, Y)
        pred_y = classify_model.predict(test_x)
        end = timer()
        print('Elapsed time of train and test : ' + str(end - start))
        accuracy = classify_model.score(test_x, test_y)*100

        print('Accuracy of GradientBoostingClassifier = {:.2f}%'.format(accuracy))

        plotPerformance(test_y, pred_y, label, 'Algorithm: Decision Tree with Boost')

def main():
       treeClassify = DecisionTree()
       print('------- DecisionTree - Classification for : WineQuality-Red -------')
       treeClassify.classify("winequality-red.csv", encode=False, label='Wine Quality')
       print('------- DecisionTree with Boost - Classification for : WineQuality-Red -------')
       treeClassify.classifyWithBoost("winequality-red.csv", encode=False, label='Wine Quality')
       print('------- DecisionTree - Classification for : CC Default -------')
       treeClassify.classify("default_of_credit_card_clients.csv", encode=False, label='Creditcard Default')
       print('------- DecisionTree with Boost - Classification for : CC Default -------')
       treeClassify.classifyWithBoost("default_of_credit_card_clients.csv", encode=False, label='Creditcard Default')

if __name__ == "__main__":
    main()


ebozor = {}
print('e bozor uchun mahsulotlar va ularning narxini kiritamiz')

while True:

    mahsulot = input('mahsulot nomini kiriting : ')
    narx = input(f'{mahsulot}ning narxini kiriting : ')

    ebozor[mahsulot] = int(narx)

    savol = input('yana mahsulot qo\'shasizmi ? (ha/yo\'q) : ')

    if savol == 'yo\'q' :
        break

for mahsulot, narx in ebozor.items():
    info = f'{mahsulot}ning narxi : {narx}'
    print(info)


#!/usr/bin/python3
# -*- coding: utf-8 -*-

# This creates an hexahedral mesh of uniform grids
# The inputs of this script are:
#     x_length x_n x_offset y_length y_n y_offset z_length z_n z_offset fileout
# This 3 files created are:
#     Topology.T
#        n dim
#        node1 node2 ...
#        .
#        .
#
#     Node.X
#        n dim
#        x1 x2 x3 ...
#        .
#        .
#
#     Boundary.B
#        n
#        elem node1 node2 ... patch#
#        .
#        .
#

import os, sys, fileinput
import numpy as np

# This is gives the order of the nodes in an elent given a starting indice
vorder = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]]

# These function compares two values and see if they are numerically equal given some numerical error from summing n floats
def same_dbl(A, B, n):
  trial = abs(A - np.full(n, A/n).sum())
  diff = abs(A - B)
  test = max(abs(A), abs(B))
  if (diff <= test * trial):
    return True
  return False

class make_grid:
    tp   = []
    tpi  = []
    surf = []
    edge = []
    def __init__(self, arg):
        # extract the arguments first
        self.xsize = float(arg[1])
        self.xn    = int(arg[2])
        self.dx    = float(arg[1])/float(arg[2])
        self.xoff  = float(arg[3])
        self.ysize = float(arg[4])
        self.yn    = int(arg[5])
        self.dy    = float(arg[4])/float(arg[5])
        self.yoff  = float(arg[6])
        self.zsize = float(arg[7])
        self.zn    = int(arg[8])
        self.dz    = float(arg[7])/float(arg[8])
        self.zoff  = float(arg[9])
        #
        self.nnode = (int(arg[2]) + 1) * (int(arg[5]) + 1) * (int(arg[8]) + 1)
        self.nelem = int(arg[2]) * int(arg[5]) * int(arg[8])
        # create empty index array
        self.ind = np.zeros((self.xn + 1, self.yn + 1, self.zn +1), dtype=int)
        # fill array
        g = 0
        for i in range(self.zn + 1):
            for j in range(self.yn + 1):
                for k in range(self.xn + 1):
                    self.ind[k, j, i] = g
                    g = g + 1
        size = (self.xn + 1) * (self.yn + 1) * (self.zn + 1)
        # create empty space array
        self.space = np.zeros((size, 3))
        # fill array
        for i in range(self.zn + 1):
            for j in range(self.yn + 1):
                for k in range(self.xn + 1):
                    self.space[self.ind[k, j, i]] = [k*self.dx + self.xoff, j*self.dy + self.yoff, i*self.dz + self.zoff]
    def __getitem__(self, key):
        # if key is of invalid type or value, the list values will raise the error
        return self.space[self.ind[key]]

def compute_topology(g):
    g.tp = np.zeros((g.nelem, 8), dtype=int)
    for i in range(g.zn):
        for j in range(g.yn):
            for k in range(g.xn):
                for m in range(8):
                    g.tp[i * g.yn * g.xn + j * g.xn + k, m] = g.ind[k + vorder[m][0], j + vorder[m][1], i + vorder[m][2]]
    g.tpi = np.zeros((g.xn, g.yn, g.zn), dtype=int)
    l = 0
    for i in range(g.zn):
        for j in range(g.yn):
            for k in range(g.xn):
                g.tpi[k, j, i] = l
                l = l + 1
    return

def compute_surface(g):
    # for the -x surface
    surface = np.zeros((g.yn * g.zn, 6), dtype=int)
    for i in range(g.zn):
        for j in range(g.yn):
            surface[i*g.yn + j, 0] = g.tpi[0, j,     i]
            surface[i*g.yn + j, 1] = g.ind[0, j,     i]
            surface[i*g.yn + j, 2] = g.ind[0, j + 1, i]
            surface[i*g.yn + j, 3] = g.ind[0, j,     i + 1]
            surface[i*g.yn + j, 4] = g.ind[0, j + 1, i + 1]
            surface[i*g.yn + j, 5] = 0
    g.surf.append(surface)
    # for the +x surface
    surface = np.zeros((g.yn * g.zn, 6), dtype=int)
    for i in range(g.zn):
        for j in range(g.yn):
            surface[i*g.yn + j, 0] = g.tpi[g.xn - 1, j,     i]
            surface[i*g.yn + j, 1] = g.ind[g.xn, j,     i]
            surface[i*g.yn + j, 2] = g.ind[g.xn, j + 1, i]
            surface[i*g.yn + j, 3] = g.ind[g.xn, j,     i + 1]
            surface[i*g.yn + j, 4] = g.ind[g.xn, j + 1, i + 1]
            surface[i*g.yn + j, 5] = 1
    g.surf.append(surface)
    # for the -y surface
    surface = np.zeros((g.xn * g.zn, 6), dtype=int)
    for i in range(g.zn):
        for k in range(g.xn):
            surface[i*g.xn + k, 0] = g.tpi[k,     0, i]
            surface[i*g.xn + k, 1] = g.ind[k,     0, i]
            surface[i*g.xn + k, 2] = g.ind[k + 1, 0, i]
            surface[i*g.xn + k, 3] = g.ind[k,     0, i + 1]
            surface[i*g.xn + k, 4] = g.ind[k + 1, 0, i + 1]
            surface[i*g.xn + k, 5] = 2
    g.surf.append(surface)
    # for the +y surface
    surface = np.zeros((g.xn * g.zn, 6), dtype=int)
    for i in range(g.zn):
        for k in range(g.xn):
            surface[i*g.xn + k, 0] = g.tpi[k,     g.yn - 1 , i]
            surface[i*g.xn + k, 1] = g.ind[k,     g.yn, i]
            surface[i*g.xn + k, 2] = g.ind[k + 1, g.yn, i]
            surface[i*g.xn + k, 3] = g.ind[k,     g.yn, i + 1]
            surface[i*g.xn + k, 4] = g.ind[k + 1, g.yn, i + 1]
            surface[i*g.xn + k, 5] = 3
    g.surf.append(surface)
    # for the -z surface
    surface = np.zeros((g.xn * g.yn, 6), dtype=int)
    for j in range(g.yn):
        for k in range(g.xn):
            surface[j*g.xn + k, 0] = g.tpi[k,     j,     0]
            surface[j*g.xn + k, 1] = g.ind[k,     j,     0]
            surface[j*g.xn + k, 2] = g.ind[k + 1, j,     0]
            surface[j*g.xn + k, 3] = g.ind[k,     j + 1, 0]
            surface[j*g.xn + k, 4] = g.ind[k + 1, j + 1, 0]
            surface[j*g.xn + k, 5] = 4
    g.surf.append(surface)
    # for the +z surface
    surface = np.zeros((g.xn * g.yn, 6), dtype=int)
    for j in range(g.yn):
        for k in range(g.xn):
            surface[j*g.xn + k, 0] = g.tpi[k,     j,     g.zn - 1]
            surface[j*g.xn + k, 1] = g.ind[k,     j,     g.zn]
            surface[j*g.xn + k, 2] = g.ind[k + 1, j,     g.zn]
            surface[j*g.xn + k, 3] = g.ind[k,     j + 1, g.zn]
            surface[j*g.xn + k, 4] = g.ind[k + 1, j + 1, g.zn]
            surface[j*g.xn + k, 5] = 5
    g.surf.append(surface)
    return

def compute_edge(g):
    g.tp = np.zeros((g.zn * g.yn * g.xn, 8), dtype=int)
    for i in range(g.zn):
        for j in range(g.yn):
            for k in range(g.xn):
                for m in range(8):
                    g.tp[i * g.yn * g.xn + j * g.xn + k, m] = g.ind[i + vorder[m][0], j + vorder[m][1], k + vorder[m][2]]
    return

# g.ind[[i + order[m, 0], j + order[m, 1], k + order[m, 2]]]

# ----  Here beging the main program  ---------------------------------------
# Get the command line arguments
arg = sys.argv

# Check the number of arguments to see if they are correct
#    The number of arguments must be exactly 6
if len(arg) != 11:
  print('{} arguments supplied'.format(len(arg)))
  print('usage: \n\tThere must be exactly 10 arguments:')
  print('\tx_length x_n x_offset y_length y_n y_offset z_length z_n z_offset fileout')
  exit()

# Create the filenames for export
fileX = arg[-1] + '_FE.X'
fileT = arg[-1] + '_FE.T'
fileB = arg[-1] + '_FE.B'

g = make_grid(arg)
print('Made a grid with {} nodes'.format(g.nnode))
compute_topology(g)
print('Created a topology for the grid with {} elements'.format(g.nelem))
compute_surface(g)
print('Generated a the 6 surfaces facing each side')

print(g.space)
print(g.tp)

with open(fileX, 'w') as f:
    f.write('{:>12d}{:>12d}'.format(g.nnode, 3))
    for [x, y, z] in g.space:
        print(x, y, z)
        f.write('\n{:>20.16}{:>20.16f}{:>20.16f}'.format(x, y, z))
print('The X file is saved as {}'.format(fileX))

with open(fileT, 'w') as f:
    f.write('{:>12d}{:>12d}'.format(g.nelem, g.nnode))
    for elem in g.tp:
        f.write('\n')
        for node in elem:
            f.write(' {:>11d}'.format(node + 1))
print('The T file is saved as {}'.format(fileT))

with open(fileB, 'w') as f:
    f.write('{:>12d}'.format(2*(g.yn * g.zn + g.xn * g.zn + g.xn * g.yn)))
    for surf in g.surf:
        for patch in surf:
            f.write('\n')
            for item in patch:
                f.write(' {:>11d}'.format(item + 1))
print('The B file is saved as {}'.format(fileB))

print('                !!!JOB COMPLETE!!!')


from vpython import button, sphere
from console import *
from files import *
from rate import *
from phys import *

#Import and Export buttons
def console_import():
    global get_running
    if get_running():
        pause()
    make_planets(from_console())
    if not get_running():
        pause()
button(bind = console_import, text = 'Console Import')

def console_export():
    global planets_list
    to_console(compile_planets(planets_list))
button(bind = console_export, text = 'Console Export')

def file_import():
    global get_running
    if get_running():
        pause()
    new_planets = []
    new_planets.extend(from_file(input('Enter file Name: ')))
    make_planets(new_planets)
    if not get_running():
        pause()
button(bind = file_import, text = 'File Import')

def file_export():
    global planets_list
    to_file(input('Enter file Name: '), compile_planets(planets_list))
button(bind = file_export, text = 'File Export')

# Rate buttons
button(bind = inc_rate, text = 'Increase Rate')
button(bind = dec_rate, text = 'Decrease Rate')

# Planet buttons
def clear_planets():
    global planets_list, default_planets_button, get_running, default_planets_button_exist
    if get_running():
        pause()
    for i in range(len(planets_list)):
        planets_list[i].visible = False
    planets_list.clear()

    # Recreate the 'Add Sun & Earth' button if it doesn't exist
    if not default_planets_button_exist:
       default_planets_button = button(bind = default_planets, text = 'Add Sun & Earth')
       default_planets_button_exist = True
button(bind = clear_planets, text = 'Clear Planets')

# Earth and Sun button
def default_planets():
    global planets_list, default_planets_button, default_planets_button_exist
    sun = sphere(id = 'sun', pos=vector(0,0,0), radius = 0.8, mass = 1500 , p = vector(0,0,0), temp = 5000, texture= 'Assets\\Sun.jpg')
    earth = sphere(id = 'earth', pos = vector(2,0,0), radius = 0.2, mass=1, p = vector(0,30,0), temp = 40, texture = 'Assets\\Earth.jpg')

    planets_list.append(sun)
    planets_list.append(earth)

    # Delete itself once used
    default_planets_button.delete()
    default_planets_button_exist = False
default_planets_button = button(bind = default_planets, text = 'Add Sun & Earth')
default_planets_button_exist = True

#Physics buttons
button(bind = lambda: calc_rad(input('Enter planet ID: ')), text = 'Plank Distribution')
button(bind = lambda: calc_luminosity(input('Enter planet ID: ')), text = 'Luminosity')
button(bind = lambda: calc_COM(input('Enter planet 1 ID: '), input('Enter planet 2 ID: ')), text = 'Get Center of Mass')


# lab 7
from math import sqrt, pi

class MathFunctions(object):
    def __init__(self):
        pass

    def quadratic_formula(self):
        try:
            A = float(input("Please enter in Value for 'A': "))
            B = float(input("Please enter in Value for 'B': "))
            C = float(input("Please enter in Value for 'C': "))

            root1 = (- B + (sqrt(B*B) - sqrt(4*A*C)))/2*A
            root2 = (- B - (sqrt(B*B) - sqrt(4*A*C)))/2*A

            # if the roots are negative zeros, return zeros
            if root1 == -0.0:
                root1 = 0

            if root2 == -0.0:
                root2 = 0

            # if the roots are the same, return one of them
            if root1 == root2:
                print(f'Root is {root1}')

            else:
                print(f'Root 1: {root1}')
                print(f'Root 2: {root2}')

        except ValueError as e:
            print("Invalid number. Please enter in a valid number.")
            print(str(e) + '\n')
            con = input("Would you like to continue? [Y]es or [N]o - ")
            if str(con.lower()) == "y" or str(con.lower()) == "yes":
                self.quadratic_formula()
            else:
                return

        except:
            print("No roots!")

    def area(self, r):
        area = pi * (r * r)

        if area <= 0:
            raise ValueError('Cannot compute area!', False)

        return area

maf = MathFunctions()
# maf.quadratic_formula()

radius = float(input("Please enter in the radius: "))
try:
    print(maf.area(radius))

except ValueError:
    print("Error, incorrect value entered. Please enter in a new number.")
    maf.area(radius)


def numberOfArithmeticSlices(nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    #dp[i][d] represents the number of arithmetic subsequences ending with nums[i] and its common difference is d.
    #dp[i][d] += dp[j][d] + 1, where j < i and nums[i] - nums[j] == d.
    #Time: O(n^2)
    #Space: O(n^2)
    dp = [dict() for _ in range(len(nums))]
    res = 0
    for i in range(1, len(nums)):
        for j in range(i):
            d = nums[i] - nums[j]
            dp[i][d] = dp[i].get(d, 0) + dp[j].get(d, 0) + 1
            res += dp[j].get(d, 0)
    return res

if __name__ == '__main__':
    numberOfArithmeticSlices()


def setDifference(arr1, arr2):
    diff_arr = []
    for i in range(len(arr1)):

        for j in range(len(arr2)):
            if arr1[i] == arr2[j]:
                break
            elif arr2[j] == arr2[len(arr2)-1]:
                diff_arr.append(arr1[i])

    return diff_arr

a =[]
b = []

len_a = int(input("Enter the number of element in array a:"))
print("Enter the elements ")
for i in range(len_a):
    a.append(int(input()))

len_b = int(input("Enter the number of element in array b:"))
print("Enter the eloements ")
for i in range(len_b):
    b.append(int(input()))

print(a)
print(b)
result = setDifference(a,b)
print("The set difference is :",result)


import os
import jsonpickle
from dataclasses import dataclass
from datetime import datetime
import functools
import enum

from better_profanity import profanity
profanity.load_censor_words()
import discord

from common import run_bot
from abstract_bot import Bot

# A note on levels:
# A user's level is the highest level

class DbLocked(Exception):
    def __init__(self, file_name):
        message = f'XP database {file_name} is locked. ' + \
            'If you are sure that another process is not running, ' + \
            'Manually delete the file and start the program again'
        super().__init__(message)

@dataclass
class XpSettings:
    base_char_score = 1
    message_length_exponent = 1/3
    message_length_break_even_point = 100 # The point at which base_char_score * len(message) == (base_char_score * len(message)) ^ message_length_exponent
    capital_multiplier = 2
    profanity_multiplier = 3
    multiplier_char_exponent = 1/2
    multiplier_char_break_even_point = 4
    attachment_score_per_byte = 100 / 1_000_000
    image_multiplier = 2
    image_multiplier_duration = 60
    base_level_size = 1000
    level_size_exponent = 1.232
    xp_gain_exponent = 1.184
    score_square_words = ['square', 'squared', 'quadratic', 'parabola'] # score is squared if you say this word

# Info about what boosts were applied during the scoring of a message
class XpGainFlags(enum.Flag):
    NONE = 0
    PROFANITY = enum.auto()
    CAPITALS = enum.auto()
    IMAGE_BOOST = enum.auto()
    SQUARED = enum.auto()

@dataclass
class UserXp:
    xp: int
    image_send_timestamps: list[float]
    squared_message_count = 0

    def clear_old_image_timestamps(self, current_time: float, settings: XpSettings):
        self.image_send_timestamps = [t for t in self.image_send_timestamps if
            t + settings.image_multiplier_duration >= current_time]

    def calc_level(self, settings: XpSettings):
        target = self.xp / settings.base_level_size
        multiplier = 1
        level = 0
        last_delta = 1
        while multiplier < target:
            level += 1
            multiplier += last_delta
            last_delta *= settings.level_size_exponent
        return level

def apply_exponent_with_break_even_point(value: float, exponent: float, break_even_point: float) -> float:
    return value ** exponent * (break_even_point / break_even_point ** exponent)

def apply_char_based_multiplier(existing_value: float, multiplier: float, num_matching_chars: int, message_length: int) -> float:
    if message_length == 0:
        return existing_value
    return existing_value + existing_value * (num_matching_chars / message_length * (multiplier - 1))

def calculate_xp_gain(message: str, attachment_bytes: int, xp: UserXp, current_time: float, s: XpSettings) -> (int, XpGainFlags):
    flags = XpGainFlags.NONE

    length = len(message)

    if any([x in message for x in s.score_square_words]):
        length *= length
        flags |= XpGainFlags.SQUARED

    value = length * s.base_char_score
    value = apply_exponent_with_break_even_point(value, s.message_length_exponent, s.message_length_break_even_point)

    profanity_count = calculate_str_delta(message, profanity.censor(message))
    profanity_count = apply_exponent_with_break_even_point(profanity_count, s.multiplier_char_exponent, s.multiplier_char_break_even_point)
    if profanity_count:
        flags |= XpGainFlags.PROFANITY
    value = apply_char_based_multiplier(value, s.profanity_multiplier * s.base_char_score, profanity_count, length)

    capital_count = [c.isupper() for c in message].count(True)
    capital_count = apply_exponent_with_break_even_point(capital_count, s.multiplier_char_exponent, s.multiplier_char_break_even_point)
    if profanity_count:
        flags |= XpGainFlags.CAPITALS
    value = apply_char_based_multiplier(value, s.capital_multiplier * s.base_char_score, capital_count, length)

    value += attachment_bytes * s.attachment_score_per_byte

    value *= s.xp_gain_exponent ** xp.calc_level(s)
    value *= s.image_multiplier ** len(xp.image_send_timestamps)
    if len(xp.image_send_timestamps):
        flags |= XpGainFlags.IMAGE_BOOST

    return (int(value), flags)

def calculate_level_size(level: int, settings: XpSettings) -> float:
    multiplier = 1
    last_delta = 1
    for i in range(level):
        multiplier += last_delta
        last_delta *= settings.level_size_exponent
    return settings.base_level_size * multiplier

def calculate_str_delta(a: str, b: str) -> int:
    return [i != j for i, j in zip(a, b)].count(True)

def get_user_tag(user: discord.User):
    return str(user.id)

class XpManager:
    def __init__(self, leaderboard_file_name: str, xp_settings: XpSettings):
        self.leaderboard_file_name = leaderboard_file_name
        self.lock_file_name = leaderboard_file_name + '.lck'
        self.xp_settings = xp_settings

        self.check_lock_file()

        self.load_leaderboard()

    def check_lock_file(self):
        if os.path.exists(self.lock_file_name):
            raise DbLocked(self.lock_file_name)

        with open(self.lock_file_name, 'w+') as lock_file:
            lock_file.write('locked')

    def load_leaderboard(self):
        self.leaderboard = {}
        try:
            with open(self.leaderboard_file_name, 'r') as f:
                self.leaderboard = jsonpickle.decode(f.read())
        except:
            pass

    def save_leaderboard(self):
        with open(self.leaderboard_file_name, 'w+') as f:
            f.write(jsonpickle.encode(self.leaderboard))

    def get_user(self, username: str) -> UserXp:
        try:
            return self.leaderboard[username]
        except KeyError:
            user = UserXp(0, [])
            self.leaderboard[username] = user
            return user

    def apply_xp_from_message(self, message: str, attachment_bytes: int, image_count: int, username: str):
        user = self.get_user(username)
        user.clear_old_image_timestamps(datetime.utcnow().timestamp(), self.xp_settings)
        user.image_send_timestamps += [datetime.utcnow().timestamp()] * image_count
        score, flags = calculate_xp_gain(message, attachment_bytes, user, datetime.utcnow().timestamp(), self.xp_settings)
        user.xp = int(user.xp) + score
        if XpGainFlags.SQUARED in flags:
            user.squared_message_count += 1

    def cleanup(self):
        if os.path.exists(self.lock_file_name):
            os.remove(self.lock_file_name)

class DumbXp(Bot):
    '''Intentionally stupid XP bot'''
    START_PREFIX = '/xpstart'
    RANK_PREFIX = '/xprank'
    LEADERBOARD_PREFIX = '/xpleaderboard'
    LEADERBOARD_AMOUNT = 10
    SAVE_INTERVAL = 10
    SQUARED_BOOST_OVERUSE_AMOUNT = 3

    def __init__(self, token: str, xp_settings: XpSettings = None):
        super().__init__(token)
        xp_settings = xp_settings or XpSettings()

        self.enabled_servers = []
        self.message_counter = 0

        self.xp_manager = XpManager('leaderboard.json', xp_settings)

    async def on_message(self, message: discord.Message):
        if message.content.startswith(self.START_PREFIX):
            self.enabled_servers.append(message.guild.id)
            await message.reply('Started!')
            return

        if message.guild.id not in self.enabled_servers:
            return

        # Don't reply to self
        if message.author == self.user:
            return
        if message.content.startswith(self.RANK_PREFIX):
            await self.send_rank_message(message)
            return
        if message.content.startswith(self.LEADERBOARD_PREFIX):
            await self.send_leaderboard_message(message)
            return

        attachment_bytes = sum([a.size for a in message.attachments])
        image_count = [t.content_type.startswith('image/') for t in message.attachments].count(True)

        user = self.xp_manager.get_user(get_user_tag(message.author))
        old_level = user.calc_level(self.xp_manager.xp_settings)
        self.xp_manager.apply_xp_from_message(message.content, attachment_bytes, image_count, get_user_tag(message.author))
        if user.squared_message_count >= self.SQUARED_BOOST_OVERUSE_AMOUNT:
            await self.send_stop_squaring_message(message)
            user.squared_message_count = 0
        if user.calc_level(self.xp_manager.xp_settings) != old_level:
            await self.send_level_up_message(message)

        self.message_counter += 1
        if self.message_counter % self.SAVE_INTERVAL == 0:
            self.message_counter = 0
            self.xp_manager.save_leaderboard()

    async def send_rank_message(self, message: discord.Message):
        if len(message.mentions) == 0:
            await message.reply(f'Please specify a user to rank by mentioning them, eg {self.RANK_PREFIX} @ThatCoolCoder')
            return

        discord_user = message.mentions[0]
        user = self.xp_manager.get_user(get_user_tag(discord_user))
        level = user.calc_level(self.xp_manager.xp_settings)
        level_size = calculate_level_size(level + 1, self.xp_manager.xp_settings)
        await message.channel.send(f'Ranking info for {message.mentions[0].mention}: {round(user.xp)} xp / {round(level_size)} [level {level}]')

    async def send_leaderboard_message(self, message: discord.Message):
        users = [(k, v) for k, v in self.xp_manager.leaderboard.items()]
        users.sort(reverse=True, key=lambda u: u[1].xp)
        if len(users) > self.LEADERBOARD_AMOUNT:
            users = users[:self.LEADERBOARD_AMOUNT]

        leaderboard_lines = []
        for idx, user_info in enumerate(users):
            user_name, user_xp = user_info
            leaderboard_lines.append(f'{idx + 1}) <@{user_name}> {round(user_xp.xp)} xp [level {user_xp.calc_level(self.xp_manager.xp_settings)}]')

        await message.channel.send(f'Leaderboard:\n' + '\n'.join(leaderboard_lines))

    async def send_level_up_message(self, message: discord.Message):
        user = self.xp_manager.get_user(get_user_tag(message.author))
        await message.channel.send(f'Congrats to {message.author.mention} for reaching level {user.calc_level(self.xp_manager.xp_settings)}!')

    async def send_stop_squaring_message(self, message: discord.Message):
        await message.reply('Stop trying to game the system')

    def cleanup(self):
        self.xp_manager.cleanup()
        self.xp_manager.save_leaderboard()

if __name__ == '__main__':
    run_bot(DumbXp)


# -*- coding: utf-8 -*-
"""
@Date  : 2021/6/25
@Desc  :
"""

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# 读取数据
df = pd.read_csv("PhoneOldAndNew.csv")
print(df)

plt.subplot(121)
sns.stripplot(x="species", y="area", data=df)
plt.subplot(122)
sns.stripplot(x="species", y="perimeter", data=df)

sns.relplot(x="perimeter", y="area", hue="species", style="species", data=df, size="species")
plt.show()


DOCUMENTATION = '''
---
module: oa_license
short_description: installs OAP license
description: Installs OAP license from local file on target host to OA management node.
version_added: "2.3.2"
author: Andrey Kartashov (gorilych@gmail.com)
options:
    license_file:
        description: path to license file (local)
        required: true
        type: path
requirements:
    ansible: 2.3
notes: uses library oaapi, embedded into module_utils
'''

ANSIBLE_METADATA = {'metadata_version': '1.0',
    'status': ['preview'],
    'supported_by': 'community'}

from ansible.module_utils.basic import AnsibleModule

def main():
    module = AnsibleModule(
            argument_spec = dict(
                license_file = dict(required=True, type='path'),
                )
            )
    try:
        from ansible.module_utils.oaapi import OaError, OaApi, OaLicense
    except ImportError as e:
        module.fail_json(msg="Failed to import OA API library: %s" % e)
    license_file = module.params['license_file']
    try:
        a = OaApi()
        if a.has_active_license():
            module.exit_json(changed=False)
        else:
            l = OaLicense(license_file)
            a.upload_license(l)
            module.exit_json(changed=True)
    except OaError as e:
        module.fail_json(msg="Failed with %s" % e)

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
"""
Created on Fri Aug 19 13:33:28 2016

@author: consT_000
"""

def isVowel2(char):
    '''
    char: a single letter of any case

    returns: True if char is a vowel and False otherwise.
    '''
    if char in "aeiouAEIOU":
        return True
    else:
        return False


import cv2

#Affichage des nombres sur l'image finale
def affichagenombres(image, grille):
    #the step is a will help to find a location
    step_x = image.shape[1] // 9
    step_y = image.shape[0] // 9

    font = cv2.FONT_HERSHEY_SIMPLEX

    for x in range(0, 9):
        for y in range(0, 9):
            cv2.putText(image, str(grille[y][x]), (x*step_x+18, y*step_y+53), font, 2, (0, 0, 255), 3, cv2.LINE_AA)
    return image


from keras.models import Model
from keras.layers import BatchNormalization, Conv1D, Dense, Input,  TimeDistributed, Activation, Bidirectional, GRU

def rnn_automatic_speech_recognition(
        input_dim=13,
        filters=200,
        kernel_size=11,
        conv_stride=2,
        dilation=1,
        units=200,
        activation="relu",
        dropout=.1,
        recur_layers=3,
        output_dim=29):

    input_data = Input(name='the_input', shape=(None, input_dim))

    conv_1d = Conv1D(
        filters,
        kernel_size,
        strides=conv_stride,
        padding="valid",
        activation=activation)(input_data)

    layer = BatchNormalization()(conv_1d)

    for _ in range(recur_layers):
        layer = Bidirectional(GRU(
            units,
            dropout=dropout,
            activation=activation,
            return_sequences=True,
            implementation=2, ))(layer)

        layer = BatchNormalization()(layer)

    time_dense = TimeDistributed(Dense(output_dim))(layer)

    y_pred = Activation('softmax', name='softmax')(time_dense)

    model = Model(inputs=input_data, outputs=y_pred)

    def cnn_output_length(input_length, ):
        if input_length is None:
            return None
        dilated_filter_size = kernel_size + (kernel_size - 1) * (dilation - 1)
        output_length = input_length - dilated_filter_size + 1
        return (output_length + conv_stride - 1) // conv_stride

    model.output_length = cnn_output_length

    return model


###Wizards' Duel###
#info from HP API: call by character name for:
    #name (str)
    #house (str)
    #patronus (str)
    #wand {dict of wand wood, core and length}

#Class 1 - Wizards (Characters for Vs)
#user will be able to add 2 characters to compete against each other: player and opponent
    #attributes: (see above)
    #methods: select spell, cast spell, cast patronus(if char does not have one, action fails)
#Class 2 - Spells
#info added by me from HP Wiki (5-7 spells)
    #attributes: name, description, type
    #methods:
        #power_spell - points given in relation to type of spell and wizard house
        #wand_power - points given in relation to wizard wand core
#Class 3 - Main
#driver code for beginning play
    #give instructions for game
    #-select characters to duel, first player then opponent
    #-select which char to play as
        #then user can select and cast spell
        #cast spell starts funct for wand_power and spell_power, totals added
    #other character's spell is randomly selected and auto cast
    #winner is determined by highest points from spell cast
    #play again y/n?

import requests as r

import random

request = r.get('http://hp-api.herokuapp.com/api/characters')
if request.status_code == 200:
    request = request.json()

#for i in range(23):
   #print(request[i]['name'])

wiz_opt = ['Harry Potter','Hermione Granger','Ron Weasley','Draco Malfoy','Minerva McGonagall','Cedric Diggory',
'Cho Chang','Severus Snape','Rubeus Hagrid','Neville Longbottom','Luna Lovegood','Ginny Weasley','Sirius Black',
'Remus Lupin','Arthur Weasley','Bellatrix Lestrange','Lord Voldemort','Horace Slughorn','Kingsley Shacklebolt',
'Dolores Umbridge','Lucius Malfoy','Vincent Crabbe','Gregory Goyle']

wd1 = {}
wd2 = {}

class Wizards:
    def __init__(self, d):
        self.name = d['name']
        self.house = d['house']
        self.patronus = d['patronus']
        self.wand = d['wand']

def select_wiz():
    print(wiz_opt)
    name = input('\nPlease select a wizard from the provided list to be your player. ')
    if name.title() not in wiz_opt:
        print('Your selection is not valid. ')
        select_wiz()
    else:
        w = wiz_opt.index(name.title())
        getWiz1(w)
        return Wizards(wd1)

def getWiz1(x):
    data = r.get(f'http://hp-api.herokuapp.com/api/characters')
    if data.status_code == 200:
        data = data.json()
        my_wiz = data[x]
        wd1.update({'name': [my_wiz['name']],'house': [my_wiz['house']],'patronus': [my_wiz['patronus']],'wand': [my_wiz['wand']]})
        print(f"{data[x]['name']} was added to your wizard selections!\n")
        getWiz2()
        return Wizards(wd2)

def getWiz2():
    choice2 = input('Please select another wizard from the list to be your opponent. ')
    if choice2.title() not in wiz_opt:
        print('Your selection is not valid. ')
        getWiz2()
    else:
        data = r.get(f'http://hp-api.herokuapp.com/api/characters')
        if data.status_code == 200:
            data = data.json()
            x = wiz_opt.index(choice2.title())
            my_wiz = data[x]
            wd2.update({'name': [my_wiz['name']],'house': [my_wiz['house']],'patronus': [my_wiz['patronus']],'wand': [my_wiz['wand']]})
            print(f"{data[x]['name']} was added to your wizard selections! ")
            print('Thank you. Your selection is complete.')
            prep_duel()

player = Wizards(wd1)
opponent = Wizards(wd2)

class Spells:
    def __init__(self, name, desc, category):
        self.name = name
        self.desc = desc
        self.category = category

    def power_spell(self, wz):

        if wz.house == ['Gryffindor']:
            if self.category == 'jinx':
                pow_points = random.randint(25, 100)
            elif self.category == 'transfiguration':
                pow_points = random.randint(20, 95)
            elif self.category == 'hex':
                pow_points = random.randint(15, 90)
            elif self.category == 'curse':
                pow_points = random.randint(10, 85)
            else:
                pow_points = random.randint(5, 80)
            return pow_points

        elif wz.house == ['Slytherin']:
            if self.category == 'curse':
                pow_points = random.randint(25, 100)
            elif self.category == 'hex':
                pow_points = random.randint(20, 95)
            elif self.category == 'charm':
                pow_points = random.randint(15, 90)
            elif self.category == 'jinx':
                pow_points = random.randint(10, 85)
            else:
                pow_points = random.randint(5, 80)
            return pow_points

        elif wz.house == ['Hufflepuff']:
            if self.category == 'charm':
                pow_points = random.randint(25, 100)
            elif self.category == 'jinx':
                pow_points = random.randint(20, 95)
            elif self.category == 'transfiguration':
                pow_points = random.randint(15, 90)
            elif self.category == 'hex':
                pow_points = random.randint(10, 85)
            else:
                pow_points = random.randint(5, 80)
            return pow_points

        elif wz.house == ['Ravenclaw']:
            if self.category == 'transfiguration':
                pow_points = random.randint(25, 100)
            elif self.category == 'charm':
                pow_points = random.randint(20, 95)
            elif self.category == 'jinx':
                pow_points = random.randint(15, 90)
            elif self.category == 'curse':
                pow_points = random.randint(10, 85)
            else:
                pow_points = random.randint(5, 80)
            return pow_points

aa = Spells('alarte ascendare', 'shoots the target high into the air', 'charm')
imd = Spells('impedimenta', 'slows movement of the target', 'hex')
flp = Spells('flipendo', 'knock opponent over', 'jinx')
inc = Spells('incarcerous', 'conjures ropes or chains around opponent', 'transfiguration')
ptr = Spells('petrificus totalus', 'instantly paralyze opponent', 'curse')
con = Spells('confundo', 'causes target to be confused', 'charm')

spell_list = [aa, imd, flp, inc, ptr, con]

def cast_spell(s):
    print("Wands at the ready! Here we go! ")
    wp1 = (wand_power(player))
    ps1 = (s.power_spell(player))
    wp2 = (wand_power(opponent))
    x = random.choice(spell_list)
    ps2 = (x.power_spell(opponent))
    duel()

def wand_power(wz):
    if (wz.wand[0]['core']) == 'phoenix feather':
        w_pow = random.randint(30, 100)
    elif (wz.wand[0]['core']) == 'dragon heartstring':
        w_pow = random.randint(25, 95)
    elif (wz.wand[0]['core']) == 'unicorn tail-hair':
        w_pow = random.randint(20, 90)
    else:
        w_pow = random.randint(15, 85)
    return w_pow

def duel():
    player_pow = ps1 + wp1
    opponent_pow = ps2 + wp2
    if player_pow == opponent_pow:
        print("It's a draw! Prepare another spell. ")
    elif player_pow > opponent_pow:
        print(f"{player.name} won the duel! You are the winner!\n")
        reply = input("Would you like to play again? (y/n) ")
        if reply.lower() == 'y':
            new = input("Would you like to duel with the same player and opponent? (y/n) ")
            if new.lower() == 'y':
                prep_duel()
            else:
                select_wiz()
        else:
            print("Thank you for playing Wizards' Duel! Cheers!")
    else:
        print(f"Oh no! {opponent.name} bested {player.name}. You lost the duel.\n")
        again = input("Would you like to play again? (y/n) ")
        if again.lower() == 'y':
            same = input("Would you like to duel with the same player and opponent? (y/n) ")
            if same.lower() == 'y':
                prep_duel()
            else:
                select_wiz()
        else:
            print("Thank you for playing Wizards' Duel! Cheers!")

def prep_duel():
    print(f"Wizards' Duel: {player.name} vs. {opponent.name} is about to begin!\n")
    print('Prepare for your duel by selecting a spell from the following list: \n')
    print("[a] Alarte Ascendare: (charm) Shoots the target high into the air.\
    [b] Impedimenta: (hex) Slows movement of the target. \
    [c] Flipendo: (jinx) Knock opponent over. \
    [d] Incarcerous: (transfiguration) Conjures ropes or chains around opponent. \
    [e] Petrificus Totalus: (curse) Instantly paralyze opponent. \
    [f] Confundo: (charm) Causes target to be confused. \n")
    choice = input("Which spell would you like to cast? a, b, c, d, e, or f? ")
    if choice.lower() == 'a':
        spell = spell_list[0]
        cast_spell(spell)
    elif choice.lower() == 'b':
        spell = spell_list[1]
        cast_spell(spell)
    elif choice.lower() == 'c':
        spell = spell_list[2]
        cast_spell(spell)
    elif choice.lower() == 'd':
        spell = spell_list[3]
        cast_spell(spell)
    elif choice.lower() == 'e':
        spell = spell_list[4]
        cast_spell(spell)
    elif choice.lower() == 'f':
        spell = spell_list[5]
        cast_spell(spell)
    else:
        print('Invalid selection.')
        prep_duel()

def start_game():
    print("Welcome to the Wizards' Duel game!\
    You will be asked to select two wizards from the list below.\
    Your first choice will be the wizard you control. \
    Your second choice will be the wizard you duel.\
    After making your selections, you will be able to choose a spell to cast. \
    When you cast your spell, your opponent will cast theirs as well. \
    The spell cast with the most power wins!\n")
    ready = input("Ready to play? (y/n) ")
    if ready.lower() == 'y':
        select_wiz()
    else:
        print("No worries! Goodbye!")

start_game()


import argparse
import glob
import os
import os.path as osp

import moviepy.editor as mp
import tqdm

from bigdata_itmo.config import system_config

def create_parser():
    parser = argparse.ArgumentParser("Convert video to audio")

    parser.add_argument(
        "--input_path",
        default=osp.join(system_config.data_dir, "raw", "pytube_data", "BBC_News"),
        help="File or folder with video files to extract audio",
    )
    parser.add_argument(
        "--output_folder",
        default=osp.join(system_config.data_dir, "raw", "mp3_data", "BBC_News"),
        help="Folder to store audio files",
    )
    parser.add_argument("--audio_format", default="mp3", help="Format of output audio file (wav, mp3)")
    parser.add_argument("--rewrite", action="store_true", help="Whether to rewrite existing audio tracks")

    args = parser.parse_args()
    return args

def extract_one_file(fpath, output_folder, format="wav", rewrite=False):
    os.makedirs(output_folder, exist_ok=True)

    out_fpath = osp.join(output_folder, f"{osp.splitext(osp.basename(fpath))[0]}.{format}")
    if not osp.exists(out_fpath) or rewrite:
        my_clip = mp.VideoFileClip(fpath)
        my_clip.audio.write_audiofile(out_fpath)

if __name__ == "__main__":
    args = create_parser()

    if osp.isfile(args.input_path):
        extract_one_file(args.input_path, args.output_folder)

    else:
        file_list = glob.glob(osp.join(args.input_path, "*"))
        for fpath in tqdm.tqdm(file_list, desc="Extracting audios"):
            extract_one_file(fpath, args.output_folder, format=args.audio_format, rewrite=args.rewrite)


"""Add organisation_id to unit model

Revision ID: 65b9741ff2b3
Revises: abd92aeb5e33
Create Date: 2019-10-31 23:10:29.541301

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '65b9741ff2b3'
down_revision = 'abd92aeb5e33'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('Unit', sa.Column('organisation_id', sa.String(length=21), nullable=True))
    op.drop_constraint('unit_name_and_greeksymbolnum_unique_constraint', 'Unit', type_='unique')
    op.create_unique_constraint('unit_name_and_greeksymbolnum_unique_constraint', 'Unit', ['name', 'greek_symbol_num', 'organisation_id'])
    op.drop_constraint('unit_name_and_letter_symbol_unique_constraint', 'Unit', type_='unique')
    op.create_unique_constraint('unit_name_and_letter_symbol_unique_constraint', 'Unit', ['name', 'letter_symbol', 'organisation_id'])
    op.create_foreign_key(None, 'Unit', 'Organisation', ['organisation_id'], ['id'], ondelete='CASCADE')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    # op.drop_constraint(None, 'Unit', type_='foreignkey')
    op.drop_constraint('unit_name_and_letter_symbol_unique_constraint', 'Unit', type_='unique')
    op.create_unique_constraint('unit_name_and_letter_symbol_unique_constraint', 'Unit', ['name', 'letter_symbol'])
    op.drop_constraint('unit_name_and_greeksymbolnum_unique_constraint', 'Unit', type_='unique')
    op.create_unique_constraint('unit_name_and_greeksymbolnum_unique_constraint', 'Unit', ['name', 'greek_symbol_num'])
    op.drop_column('Unit', 'organisation_id')
    # ### end Alembic commands ###


import math
from simTest import rtest, distance

def aero_test(theta):
    r=1

    prop_mass = 1
    prop_length = .762
    I_prop = prop_mass * prop_length ** 2 / 12

    # rotating part of the motor casing (mainly magnets)
    casing_mass = 1
    casing_outer_r = .2
    casing_inner_r = .1
    I_casing = (casing_inner_r + casing_outer_r)**2 / 2

    I = I_prop + I_casing

    k = 1

    max_iter = 50000
    dt = .00005
    avel = 30

    all_theta = [theta]
    all_avel = [avel]
    all_dv = [0]

    # aero drag
    air_density = 1.225
    v = 26.8
    A = 6.4 * 100**-2
    Cd_front = .01
    Cd_back = .34

    for i in range(1,max_iter):
        #Friction

        # we need a new method for friction - this way increases the amount of friction when time step is decreased
        #avel = avel * .997
        # quick adjustment so time scaling is less with decreased time scale
        avel = avel - avel * (1-.997) * (dt/.001)

        #Ratchet Force

        #Aero Torque = force_back * half length of prop - force_front * half length of prop
        # Cd is adjusted for angle with the cos
        aero_torque = (air_density * v**2 * A / 2) * (Cd_back - Cd_front) * math.fabs(math.cos(theta)) * prop_length /4

        # net torque
        torque = aero_torque

        # just to work with rtest
        all_dv.append(1)

        #Add Changes
        dv = torque * dt / I
        avel = avel + dv
        theta = theta + avel * dt

        #reset theta to within 2pi range
        if (theta >= 2 * math.pi):
            theta = theta - (2 * math.pi)
        if (theta < 0):
            theta += 2 * math.pi

        all_theta.append(theta)
        all_avel.append(avel)

    all_t = [i * dt for i in range(max_iter)]
    all_distance = [distance(i,r) for i in all_theta]
    return {"time" : all_t, "theta" : all_theta, "avel" : all_avel,
            "distance" : all_distance, "dv" : all_dv}

rtest(aero_test)


from bs4 import BeautifulSoup
import urllib.request

class dotabuffParser():
    def __init__(self, hero):
        self.url = "http://dotabuff.com/heroes/" + str(hero) + "/matchups"
        self.hero1 = hero
        self.content = ''
        self.setContent()
        self.content_of_heroes = ''
        self.AllHeroListForDict = []
        self.HeroList = []
        self.setHeroList()
        self.dictinary_heroes = {}

    def setContent(self):
        opener = urllib.request.build_opener()
        opener.addheaders = [('User-agent',
                              'Mozilla/5.0')]
        # 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:45.0) Gecko/20100101 Firefox/45.0'
        response = opener.open(self.url)
        page = response.read()
        soup = BeautifulSoup(page, "lxml")
        self.content = soup.encode("utf-8")

    def setHeroList(self):
        # getData
        from lxml import html
        tree = html.fromstring(self.content)
        movie_link = tree.xpath('//table[@class="sortable"]')[0]  # table class="sortable"
        movie_link1 = movie_link[1].xpath('string()')

        self.content_of_heroes = movie_link1
        # Parsing
        listOfHeroes = movie_link1.split(',')
        listOfHeroes[0] = listOfHeroes[0][:listOfHeroes[0].find('%')]
        for i in range(1, len(listOfHeroes)):
            listOfHeroes[i] = listOfHeroes[i][3:listOfHeroes[i].find('%')]
        self.HeroList = listOfHeroes

    def getDictinary(self):
        print(self.HeroList[0])
        import re
        regSymb = re.compile('[^a-zA-Z ]')
        regNum = re.compile('[^0-9.-]')
        for i in range(0, len(self.HeroList)):
            self.dictinary_heroes[regSymb.sub('', self.HeroList[i])] = regNum.sub('', self.HeroList[i])
        try:
            self.dictinary_heroes.pop('')
        except:
            print('')
        return self.dictinary_heroes

class starter_of_parser():
    def __init__(self):
        self.DictinaryDictinary_heroes = {}
        self.hero_list = []

    def save_to_json(self):
        with open("HeroList.txt") as file_list:
            self.hero_list = file_list.readlines()

        for i in range(0, len(self.hero_list)):
            hero = self.hero_list[i].lower().replace(" ", "-").rstrip()
            print(hero.lower().replace(" ", "-").rstrip())
            parser = dotabuffParser(hero)
            self.DictinaryDictinary_heroes[hero] = parser.getDictinary()
        import json
        with open('HeroList.json', 'w') as file:
            json.dump(self.DictinaryDictinary_heroes, file, indent=2, ensure_ascii=False)

if __name__ == '__main__':
    textStarter = starter_of_parser()
    textStarter.save_to_json()


from collections import deque

def getinput():  # input 받기, shark의 위치만 따로 저장
    n = int(input())
    mymap = [list(map(int, input().split())) for _ in range(n)]

    for i in range(n):
        for j in range(n):
            if mymap[i][j] == 9:
                mymap[i][j] = 0
                shark = (i, j)

    return n, mymap, shark

def bfs(n, mymap, shark, size):  # 가장 가까운 먹이 탐색
    visit = [[False for _ in range(n)] for _ in range(n)]

    queue = deque()
    time = 0
    queue.append([shark, time])
    visit[shark[0]][shark[1]] = True
    result = []
    resulttime = 0
    while len(queue) > 0 :
        front = queue.popleft()
        q = front[0]
        time = front[1]
        candidates = [(q[0] - 1, q[1]), (q[0], q[1] - 1), (q[0], q[1] + 1), (q[0] + 1, q[1])]
        for c in candidates:  # 4방향에 대해 탐색
            if 0 <= c[0] < n and 0 <= c[1] < n:  # 범위 안에 있는 좌표만 탐색
                if mymap[c[0]][c[1]] <= size and not visit[c[0]][c[1]]:  # 갈 수 있는 범위만 탐색
                    if mymap[c[0]][c[1]] in [0, size]:  # 먹지 못하는 곳 탐색 시, queue에 추가
                        queue.append([c, time + 1])
                        visit[c[0]][c[1]] = True
                    else:  # 먹이가 있으면 result 에 추가
                        if len(result) == 0:  # result 가 비어있으면 최소 time 정해줌
                            resulttime = time
                        if resulttime < time:  # 기준 시간 초과 시, 결과 리턴
                            result.sort(key=lambda x: x[0][0] * 100 + x[0][1])  # 위, 왼쪽 기준 우선순위
                            r = result[0]  # 가장 우선순위 높은 것 출력
                            c, time = r[0], r[1]
                            mymap[c[0]][c[1]] = 0
                            shark = c
                            return True, time + 1, shark
                        else:  # 기준 시간과 같을 경우 결과 값에 포함
                            result.append([c, time])

    if len(result) == 0:  # 결과 값이 없으면 False 반환
        return False, 0, shark
    else:  # 결과 값이 있으면 sorting 후, 우선순위 값 리턴
        result.sort(key=lambda x: x[0][0] * 100 + x[0][1])
        r = result[0]
        c, time = r[0], r[1]
        mymap[c[0]][c[1]] = 0
        shark = c
        return True, time + 1, shark

def debug(n, mymap, shark, size, time):  # 디버그용 상어 위치 및 먹이 현황 그래프
    print("=======",size,"======")
    for i in range(n):
        for j in range(n):
            if (i, j) == shark:
                print("9", end=" ")
            else:
                print(mymap[i][j], end=" ")
        print()
    print("========",time,"=======")

def gettime(n, mymap, shark):  # 최소 시간 계산
    size = 2  # 상어 크기
    cnt = 0  # 먹은 수
    totaltime = 0  # 총 걸린 시간
    for i in range(n*n):  # 최대 n*n 번의 시행
        result, time, shark = bfs(n, mymap, shark, size)  # 1회 bfs 순환
        # debug(n, mymap, shark, size, time)
        totaltime += time
        if not result:  # 먹이를 못찾았으면 return
            return totaltime
        else:  # 먹이를 찾았으면
            if cnt+1 == size:  # 몸집이 커지는 조건에서는 몸집 증가
                size += 1
                cnt = 0  # 초기화
            else:  # 먹은 수 증가
                cnt += 1
    return totaltime

if __name__ == "__main__":
    n, mymap, shark = getinput()
    print(gettime(n, mymap, shark))


import unittest
import os
import json
from subprocess import call
import cairis.core.BorgFactory
from cairis.core.Borg import Borg
from cairis.core.EnvironmentParameters import EnvironmentParameters
from cairis.core.AssetParameters import AssetParameters
from cairis.core.AssetEnvironmentProperties import AssetEnvironmentProperties
from cairis.core.GoalParameters import GoalParameters
from cairis.core.GoalAssociationParameters import GoalAssociationParameters
from cairis.core.GoalEnvironmentProperties import GoalEnvironmentProperties
from cairis.core.PolicyStatement import PolicyStatement
from cairis.core.ARM import DatabaseProxyException

__author__ = 'Shamal Faily'

class PolicyStatementTest(unittest.TestCase):

  def setUp(self):
    call([os.environ['CAIRIS_CFG_DIR'] + "/initdb.sh"])
    cairis.core.BorgFactory.initialise()
    f = open(os.environ['CAIRIS_SRC'] + '/test/policy_statements.json')
    d = json.load(f)
    f.close()
    ienvs = d['environments']
    iep1 = EnvironmentParameters(ienvs[0]["theName"],ienvs[0]["theShortCode"],ienvs[0]["theDescription"])
    b = Borg()
    b.dbProxy.addEnvironment(iep1)
    iassets = d['assets']
    iaeps1 = AssetEnvironmentProperties(iassets[0]["theEnvironmentProperties"][0][0],iassets[0]["theEnvironmentProperties"][0][1],iassets[0]["theEnvironmentProperties"][0][2])
    iap1 = AssetParameters(iassets[0]["theName"],iassets[0]["theShortCode"],iassets[0]["theDescription"],iassets[0]["theSignificance"],iassets[0]["theType"],"0","N/A",[],[],[iaeps1])
    b.dbProxy.addAsset(iap1)
    iaeps1 = AssetEnvironmentProperties(iassets[1]["theEnvironmentProperties"][0][0],iassets[1]["theEnvironmentProperties"][0][1],iassets[1]["theEnvironmentProperties"][0][2])
    iap2 = AssetParameters(iassets[1]["theName"],iassets[1]["theShortCode"],iassets[1]["theDescription"],iassets[1]["theSignificance"],iassets[1]["theType"],"0","N/A",[],[],[iaeps1])
    b.dbProxy.addAsset(iap2)
    self.iGoals = d['goals']

    igep1d = GoalEnvironmentProperties(self.iGoals[0]["theEnvironmentProperties"][0]["theName"],self.iGoals[0]["theEnvironmentProperties"][0]["theLabel"],self.iGoals[0]["theEnvironmentProperties"][0]["theDefinition"],self.iGoals[0]["theEnvironmentProperties"][0]["theCategory"],self.iGoals[0]["theEnvironmentProperties"][0]["thePriority"],self.iGoals[0]["theEnvironmentProperties"][0]["theFitCriterion"],self.iGoals[0]["theEnvironmentProperties"][0]["theIssue"],[],[],self.iGoals[0]["theEnvironmentProperties"][0]["theConcerns"],[])
    igp1 = GoalParameters(self.iGoals[0]["theName"],self.iGoals[0]["theOriginator"],[],[igep1d])
    b.dbProxy.addGoal(igp1)
    self.iPs = d['policy_statements']

  def testPolicyStatement(self):
    b = Borg()

    ip = PolicyStatement(-1,self.iPs[0]['theGoalName'],self.iPs[0]['theEnvironmentName'],self.iPs[0]['theSubject'],self.iPs[0]['theAccessType'],self.iPs[0]['theResource'],self.iPs[0]['thePermission'])
    b.dbProxy.addPolicyStatement(ip)

    ops = b.dbProxy.getPolicyStatements()
    op = ops[0]
    self.assertEqual(ip.goal(), op.goal())
    self.assertEqual(ip.environment(), op.environment())
    self.assertEqual(ip.subject(), op.subject())
    self.assertEqual(ip.accessType(), op.accessType())
    self.assertEqual(ip.resource(), op.resource())
    self.assertEqual(ip.permission(), op.permission())

    ip.theId = op.id()
    ip.thePermission = 'deny'
    b.dbProxy.updatePolicyStatement(ip)

    ops = b.dbProxy.getPolicyStatements()
    op = ops[0]
    self.assertEqual(ip.goal(), op.goal())
    self.assertEqual(ip.environment(), op.environment())
    self.assertEqual(ip.subject(), op.subject())
    self.assertEqual(ip.accessType(), op.accessType())
    self.assertEqual(ip.resource(), op.resource())
    self.assertEqual(ip.permission(), op.permission())

    b.dbProxy.deletePolicyStatement(op.id())

  def tearDown(self):
    pass

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


from math import remainder
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render
from AppGimnasios.models import *
from AppGimnasios.forms import *

def sucursales(request):
    return render(request,'appGimnasios/sucursales.html')

def clases(request):
    return render(request,'appGimnasios/clases.html')

def profesores(request):
    return render(request,'appGimnasios/profesores.html')

def horarios(request):
    return render(request,'appGimnasios/horarios.html')

def inicio(request):
    return render(request,'appGimnasios/inicio.html')

def sucursalesFormulario(request):
    if request.method == 'POST':
        formularioSucursal = SucursalesFormulario(request.POST)
        if formularioSucursal.is_valid():
            informacionSucursal = formularioSucursal.cleaned_data
        nombreSucursal=informacionSucursal['nombreSucursal']
        direccionSucursal=informacionSucursal['direccionSucursal']
        fechaDeInauguracionSucursal=informacionSucursal['fechaDeInauguracionSucursal']
        sucursal = Sucursales(nombreSucursal=nombreSucursal,direccionSucursal=direccionSucursal,fechaDeInauguracionSucursal=fechaDeInauguracionSucursal)
        sucursal.save()
        return render(request,'AppGimnasios/inicio.html')

    else:
        formularioSucursal = SucursalesFormulario()
    return render(request,'AppGimnasios/sucursalesFormulario.html', {'formularioSucursal':formularioSucursal})

def profesoresFormulario(request):
    if request.method == 'POST':
        formularioProfesor = ProfesoresFormulario(request.POST)
        if formularioProfesor.is_valid():
            informacionProfesor = formularioProfesor.cleaned_data
        nombreProfesor=informacionProfesor['nombreProfesor']
        apellidoProfesor=informacionProfesor['apellidoProfesor']
        nombreClaseProfesor=informacionProfesor['nombreClaseProfesor']
        fechaDeNacimientoProfesor=informacionProfesor['fechaDeNacimientoProfesor']
        profesor = Profesores(nombreProfesor=nombreProfesor,apellidoProfesor=apellidoProfesor,nombreClaseProfesor=nombreClaseProfesor,fechaDeNacimientoProfesor=fechaDeNacimientoProfesor)
        profesor.save()
        return render(request,'AppGimnasios/inicio.html')

    else:
        formularioProfesor = ProfesoresFormulario()
    return render(request,'AppGimnasios/profesoresFormulario.html', {'formularioProfesor':formularioProfesor})

def clasesFormulario(request):
    if request.method == 'POST':
        formularioClase = ClasesFormulario(request.POST)
        if formularioClase.is_valid():
            informacionClase = formularioClase.cleaned_data
        nombreClase=informacionClase['nombreClase']
        clases = Clases(nombreClase=nombreClase)
        clases.save()
        return render(request,'AppGimnasios/inicio.html')

    else:
        formularioClase = ClasesFormulario()
    return render(request,'AppGimnasios/clasesFormulario.html', {'formularioClase':formularioClase})

def horariosFormulario(request):
    if request.method == 'POST':
        formularioHorario = HorariosFormulario(request.POST)
        if formularioHorario.is_valid():
            informacionHorario = formularioHorario.cleaned_data
        nombreClaseH=informacionHorario['nombreClaseH']
        horarioClase=informacionHorario['horarioClase']
        horarios = Horarios(nombreClaseH=nombreClaseH,horarioClase=horarioClase)
        horarios.save()
        return render(request,'AppGimnasios/inicio.html')

    else:
        formularioHorario = HorariosFormulario()
    return render(request,'AppGimnasios/horariosFormulario.html', {'formularioHorario':formularioHorario})

def busquedaSucursal(request):
    return render(request,'AppGimnasios/busquedaSucursal.html')

def buscarSucursal(request):
    if request.GET['nombreSucursal']:
        nombreSucursal = request.GET['nombreSucursal']
        sucursales = Sucursales.objects.filter(nombreSucursal=nombreSucursal)
        return render(request,'AppGimnasios/resultadosBusquedaSucursal.html', {'sucursales':sucursales, 'nombreSucursal':nombreSucursal})
    else:
        respuesta = "No se ha ingresado sucursal válida"
    return render(request,'AppGimnasios/resultadosBusquedaSucursal.html', {"respuesta":respuesta})


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: bp.py

import numpy as np
from src.activation import sigmoid, sigmoid_prime

def backprop(x, y, biases, weights, cost, num_layers):
    """ function of backpropagation
        Return a tuple ``(nabla_b, nabla_w)`` representing the
        gradient of all biases and weights.

        Args:
            x, y: input image x and label y
            biases, weights (list): list of biases and weights of entire network
            cost (CrossEntropyCost): object of cost computation
            num_layers (int): number of layers of the network

        Returns:
            (nabla_b, nabla_w): tuple containing the gradient for all the biases
                and weights. nabla_b and nabla_w should be the same shape as
                input biases and weights
    """
    # initial zero list for store gradient of biases and weights
    nabla_b = [np.zeros(b.shape) for b in biases]
    nabla_w = [np.zeros(w.shape) for w in weights]

    ### Implement here
    # feedforward
    # Here you need to store all the activations of all the units
    # by feedforward pass

    activations = [x]   # List to store the activation values
    zs = []   # List to store the matrix multiplications
    val = x
    for i in range(num_layers-1):
        val =  np.dot(weights[i] , val ) + biases[i]
        zs.append(val)
        val = sigmoid(val)
        activations.append(val)
    ###

    # compute the gradient of error respect to output
    # activations[-1] is the list of activations of the output layer
    delta = (cost).delta(activations[-1], y)

    ### Implement here
    # backward pass
    # Here you need to implement the backward pass to compute the
    # gradient for each weight and bias

    # backward pass

    nabla_b[-1] = delta
    nabla_w[-1] = np.dot(delta, activations[-2].transpose())

    for l in range(2, num_layers):
        z = zs[-l]
        delta = np.dot(weights[-l+1].transpose(), delta) * sigmoid_prime(z)
        nabla_b[-l] = delta
        nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())

    return (nabla_b, nabla_w)


# Importing the packages

import json
import pandas as pd
import requests
import psycopg2

# Getting the json Beer API

beer_api_url = 'https://api.punkapi.com/v2/beers'

r = requests.get(beer_api_url)

beer_data = json.loads(r.text)

beer_str = json.dumps(beer_data, indent=2, sort_keys=True)

print(beer_data)
print(len(beer_data))

# Making an empty list

beer_list= []

# for loop

for beer in beer_data:
    id= beer['id']
    name = beer['name']
    tagline=beer['tagline']
    first_brewed = beer['first_brewed']
    description= beer['description']
    abv= beer['abv']
    food_pairing= beer['food_pairing']
    volume_value = beer['volume']['value']
    volume_unit = beer['volume']['unit']
    malt_name = beer['ingredients']['malt'][-1]['name']
    malt_value_kg = beer['ingredients']['malt'][-1]['amount']['value']
    hops_name = beer['ingredients']['hops'][-1]['name']
    hops_value_g = beer['ingredients']['hops'][-1]['amount']['value']
    yeast = beer['ingredients']['yeast']
    brewers_tips= beer['brewers_tips']

    beer_item = {
        'id': id,
        'name': name,
        'tagline': tagline,
        'first_brewed': first_brewed,
        'description': description,
        'abv': abv,
        'food_pairing': food_pairing,
        'volume_value' : volume_value,
        'volume_unit' : volume_unit,
        'malt_name' : malt_name,
        'malt_value_kg' : malt_value_kg,
        'hops_name' : hops_name,
        'hops_value_g' : hops_value_g,
        'yeast' : yeast,
        'brewers_tips' : brewers_tips
    }
    beer_list.append(beer_item)

#list into tuple

def convert(list):
    return tuple(list)

convert(beer_list)

print(beer_list)

#tuple into dataframe

beer_df = pd.DataFrame(beer_list)
print(beer_df[['abv','name']].to_string())
print(type(beer_df['abv']))
print(beer_df[['id', 'name', 'tagline', 'first_brewed', 'description', 'abv', 'food_pairing', 'volume_value', 'volume_unit', 'malt_name',
'malt_value_kg', 'hops_name', 'hops_value_g', 'yeast', 'brewers_tips']].to_string())

# Connecting PostgreSQL to Python

#Establishing connection
pgconn = psycopg2.connect(
    database="beer_api_database",
    user='postgres',
    password='*******',
    host='localhost',
    port=5433
)
#Creating a cursor object using the cursor() method

pgcursor = pgconn.cursor()

#Checking if database is right

pgcursor.execute('SELECT current_database()')

print(pgcursor.fetchone())

#Creating the beer table

pgcursor.execute(''' CREATE TABLE IF NOT EXISTS beer_api (
                            id  SERIAL PRIMARY KEY,
                            name TEXT,
                            tagline TEXT,
                            first_brewed TEXT,
                            description TEXT,
                            abv FLOAT,
                            food_pairing TEXT,
                            volume_value FLOAT,
                            volume_unit TEXT,
                            malt_name TEXT,
                            malt_value_kg FLOAT,
                            hops_name TEXT,
                            hops_value_g FLOAT,
                            yeast TEXT,
                            brewers_tips TEXT);
                            ''')

pgconn.commit()

#Inserting the data

from psycopg2.extras import execute_values

execute_values(pgcursor,
'INSERT INTO beer_api (id, name, tagline, first_brewed, description, abv, food_pairing, volume_value, volume_unit, malt_name, malt_value_kg, hops_name, hops_value_g, yeast, brewers_tips) VALUES %s',
beer_df.values)

pgconn.commit()

#Closing cursor

pgcursor.close()

#Closing connection

pgconn.close()


import json
import random
from time import sleep

from bs4 import BeautifulSoup #import beautiful soup
import requests
from mongoengine import *
import os
from dotenv import load_dotenv
from deep_translator import GoogleTranslator
from datetime import datetime
import openai

load_dotenv()

class Headline(EmbeddedDocument):
  en = StringField(required=True)
  id = StringField(required=True)

class Content(EmbeddedDocument):
  en = StringField(required=True)
  id = StringField(required=True)

class Summary(EmbeddedDocument):
  en = StringField(required=True)
  id = StringField(required=True)

class Article(Document):
  headline = EmbeddedDocumentField(Headline)
  author = StringField(required=True)
  date_published = DateTimeField()
  content = EmbeddedDocumentField(Content)
  location = StringField()
  link_to_origin = StringField(required=True)
  category = StringField(required=True)
  summary = EmbeddedDocumentField(Summary)
  timezone = StringField(required=True)

translator = GoogleTranslator(source='id', target='en')
openai.api_key = os.environ.get("OPEN_API_KEY")

# scrapper for detik.com/bali/hukum-kriminal Done
def detik_scraper(index):
  if index == 0:
    return 0

  html_content = requests.get('https://www.detik.com/bali/hukum-kriminal/indeks/{index}'.format(index=index))
  soup = BeautifulSoup(html_content.content, 'lxml')
  article_list = soup.find_all('article', class_='list-content__item')

  for article in article_list:
    identical_article_amount = Article.objects(link_to_origin=article.a["href"]).count()
    if identical_article_amount > 0:
      break

    html_content = requests.get(article.a["href"])

    print("get link {}".format(article.a["href"]))

    soup = BeautifulSoup(html_content.content, 'lxml')

    print("parse html")

    # pre process cleansing
    for i in range(len(soup.find_all('p', class_='para_caption'))):
      soup.find('p', class_='para_caption').decompose()

    headline = {
      "id": (soup.find('h1', class_='detail__title')).text.strip().replace("\n", ""),
      "en": ''
    }

    content = {
      "id": (' '.join([p.text for p in soup.find_all('p')])).strip(),
      "en": ''
    }

    formatted_prompt = "{prompt}\ntitle : {title}\ncontent : {content}"
    gpt_executed = False

    while not gpt_executed:
      try:
        response = openai.ChatCompletion.create(
          model="gpt-3.5-turbo",
          messages=[
            {
              "role": "system",
              "content": formatted_prompt.format(
                prompt=os.environ.get("PROMPT"),
                title=headline["id"],
                content=content["id"]
              )
            }
          ]
        )

        data_obj = json.loads(response.choices[0].message.content)
        gpt_executed = True
        print("gpt processed")
      except Exception as e:
        print(f"failed : {e}")
        sleep(1)

    summary = {
      "id": data_obj["summary"],
      "en": ''
    }

    category = data_obj["category"]

    date_string, timezone = (soup.find('div', class_='detail__date')).string.rsplit(' ', 1)

    translation_executed = False

    while not translation_executed:
      try:
        headline["en"] = translator.translate(headline["id"])
        content["en"]  = (' '.join([translator.translate(p.text) for p in soup.find_all('p')])).strip()
        summary["en"]  = translator.translate(data_obj["summary"])
        date_string = translator.translate(date_string)
        translation_executed = True
        print("translation processed")
      except Exception as e:
        print(f"failed : {e}")
        sleep(1)

    date_formats = ["%d %b %Y %H:%M", "%b %d %Y %H:%M", "%b %d, %Y %H:%M"]
    date_string = (date_string.split(" "))
    del date_string[0]
    date_string = " ".join(date_string)
    date_formating = False
    format_index = len(date_formats) - 1

    while not date_formating:
      try:
        date = datetime.strptime(date_string, date_formats[format_index])
        date_formating = True
      except Exception as e:
        print(f"failed : {e}")
        format_index = format_index - 1

    article = {
      "headline": Headline(**headline),
      "author": (soup.find('div', class_='detail__author')).text,
      "date_published": date,
      "content": Content(**content),
      "location": data_obj["location"],
      "link_to_origin": article.a["href"],
      "category": category,
      "summary": Summary(**summary),
      "timezone": timezone
    }

    after_process_article = Article(**article)
    after_process_article.save()

    print("data saved")
  return detik_scraper(index - 1)

def main():
  connect(db=os.environ.get("DB_NAME"),host=os.environ.get("DB_URI"))
  detik_scraper(100)

if __name__ == "__main__":
  main()


"""Home page shown when the user enters the application"""
import holidays
import streamlit as st
from src.utils import cache
from streamlit import caching
from fbprophet import Prophet
import pandas as pd

session_state = cache()

@st.cache
def get_model(data):
    m = Prophet()
    m.add_country_holidays(country_name=session_state["hol_val"])
    m.fit(data)
    return m

def write():
    hist = session_state["mrkt"].history(start=session_state["begin"], end=session_state["end"],)
    hist = hist.reset_index()

    data = pd.DataFrame(data={'ds': hist['Date'], 'y': hist['Open']})

    m = get_model(data)

    future = m.make_future_dataframe(periods=session_state["days"])

    forecast = m.predict(future)

    st.title("Results")
    st.write(
        """
        Welcome to the results! you can click the graphs to expand them.
        """
    )

    st.pyplot(m.plot(forecast))
    st.write(
        """
        In the graph above you can find the expected forecast. All the black dots are data points that have been used to
        calculate the prediction. The darker blue line is the models prediction. This is also calculated for previous
        days to show the accuracy of the model. The lighter blue "bands" around the prediction line is the expected
        upper and lower bound.
        """
    )

    st.pyplot(m.plot_components(forecast))
    st.write(
        """
        This model can also give you some intuition on how the stock fluctuates within a year (fig 2.3) or even within a
        week (fig 2.2). The first graph shows the trend line. This is the same as the in the first graph.
        """
    )

    # st.write(
    #     """
    #     want to know what the model predicts on a specific date? Select the date below and find out!
    #     """
    # )
    # date = st.date_input("select date")
    # forecast = m.predict(future)
    # st.write(f"The predicted value of stock {session_state['mrkt_val']} on {date} is: {forecast}")

    st.write(
        """
        Are you satisfied with the results? \n
        If you want to change some answers on a specific topic you can just go to the topic, hit save and return to the Results page to see the new results. \n
        Or if you want to retry from the start, hit the \"Try again\" button below!
        """
    )
    if st.button("Try again"):
        caching.clear_cache()