# BOJ_1260 DFS와 BFS

import sys
from collections import deque
sys.setrecursionlimit(10 ** 9)

def solution():
    n, m, v = map(int, sys.stdin.readline().rstrip().split())
    graph = [[0] * (n + 1) for _ in range(n + 1)]
    visited = [False] * (n+1)

    for _ in range(m):
        x, y = map(int, sys.stdin.readline().rstrip().split())
        graph[x][y] = 1
        graph[y][x] = 1

    print(graph)
    dfs(graph, v, visited)

    visited = [False] * (n+1)

    print()
    bfs(graph, v, visited)

def dfs(graph, v, visited):
    visited[v] = True
    print(v, end=' ')

    for i in range(1, len(graph)):
        if not visited[i] and graph[v][i] == 1:
            dfs(graph, i, visited)

def bfs(graph, v, visited):
    queue = deque([v])
    visited[v] = True

    while queue:
        v = queue.popleft()
        print(v, end = ' ')
        for i in range(1, len(graph)):
            if not visited[i] and graph[v][i] == 1:
                queue.append(i)
                visited[i] = True

solution()


#Make a die function that returns a random number
from random import randint #import python function random-you have to tell it to do this. 								Randint takes two variables and picks one randomly.
def die (): #defines function die
	roll=randint (1,6)
	print(roll)

#Make a function called custom_die that takes a range and prints a random #number in that range

def custom_die(num1, num2): #num1 and num2 are the buckets you hold your variables in
	roll=randint(num1, num2) #this tells computer to pick anything between

#determine if max or min

	if roll == num1: #num1 is min in range
		print(num1, "Critical fail!") #feeding print statement multiple arguments.
		#Can also be if roll == num1:
			#print("{r} Critical fail".format(r=roll))
# do the dot format like this, instead of commas or pluses "{name} is {age} and is from
#{place}".format(name=name, age=age, place=place)
	elif roll == num2:  #num2 is max in range
		print(num2, "Critical hit!")
	else: #if neither, print only the number.
		print(roll)

def main():
	print("Welcome to Die Roller. Enter q to exit.")

	entree = "" #empty string, must make it not equal q.

	while entree != "q":

		entree = input("How many dice do you want to roll?")
		if entree.lower() == "q": #this converts all input to lowercase. .upper also a thing
			#exit the program. can avoid repeat in line 34 with a function.
			exit()

		#Convert input string to integer. Called casting.
		#it's not q, it has to be total rolls, assign to total_rolls
		total_rolls= int(entree)

		#How big are the dice? Can nest int and input, to convert from string.
		entree = input("How many sides on the dice?")

		if entree == "q":
			#exit the program
			exit()
		#already checked to see entree wasn't q, now turn that entree into an int
		max_num= int(entree)

		#Roll that many dice. You'll need a FOR LOOP here.
		for something in range(0,total_rolls):
			custom_die(1, max_num) #this prints the number

main()


from sweetpea import *
import os
_dir = os.path.dirname(__file__)
### START
dfqk = Factor("dfqk", ["psdz", "flwj"])
ptzx = Factor("ptzx", ["xhsut", "zgap"])
jyg = Factor("jyg", ["psdz", "flwj"])
gqdbe = Factor("gqdbe", ["xhsut", "zgap"])
xgijm = Factor("xgijm", ["swu", "jdvb"])
zlvm = Factor("zlvm", ["fxydov", "qqc"])
def is_jczjok_hsh(xgijm, zlvm):
    return xgijm == zlvm
def is_jczjok_eik(xgijm, zlvm):
    return not is_jczjok_hsh(xgijm, zlvm)
jczjok= Factor("jczjok", [DerivedLevel("hsh", WithinTrial(is_jczjok_hsh, [xgijm, zlvm])), DerivedLevel("eik", WithinTrial(is_jczjok_eik, [xgijm, zlvm]))])
constraints = [MinimumTrials(52), ExactlyK(3, zlvm)]
crossing = [xgijm, dfqk]

design=[dfqk,ptzx,jyg,gqdbe,xgijm,zlvm]
block=CrossBlock(design,crossing,constraints)
### END
experiment=synthesize_trials(block,1)
save_experiments_csv(block, experiment, os.path.join(_dir, "out_code_2/6_1_2"))


'''
@author: Tsuyoshi Hombashi
'''

import os
import itertools

import pytest
from path import Path

import thutils.common as common
from thutils.gfile import *

TEST_DIR_PATH = os.path.dirname(os.path.realpath(__file__))

EMPTY_FILE_NAME = "empty_file"
TEMP_FILE_NAME = "tmp_file"
EMPTY_FILE_PATH = os.path.join(TEST_DIR_PATH, EMPTY_FILE_NAME + ".txt")
EMPTY_DIR_NAME = "empty_dir"
EMPTY_DIR_PATH = os.path.join(TEST_DIR_PATH, EMPTY_DIR_NAME)

class Test_FileManager_touch:

    @pytest.mark.parametrize(["value"], [
        ["aaa"],
        ["aaa/bbb"],
    ])
    def test_normal_file(self, tmpdir, value):
        FileManager.initialize(dry_run=False)
        target_dir = tmpdir.join("touch")
        target_path = os.path.join(str(target_dir), value)
        FileManager.touch(target_path)

    @pytest.mark.parametrize(["value"], [
        ["touch_time"],
    ])
    def test_normal_time(self, tmpdir, value):
        import time

        target_dir = tmpdir.join("touch")
        tmp_path = os.path.join(str(target_dir), value)

        FileManager.initialize(dry_run=False)

        touch_file = FileManager.touch(tmp_path)
        expected = Path(tmp_path)
        assert touch_file == expected
        before_atime = touch_file.atime
        time.sleep(0.5)
        touch_file = FileManager.touch(tmp_path)
        assert touch_file == expected
        assert touch_file.atime > before_atime

class Test_FileManager_make_directory:

    @pytest.mark.parametrize(["value"], [
        ["test_normal_1"],
    ])
    def test_normal_1(self, tmpdir, value):
        FileManager.initialize(dry_run=False)

        target_dir = tmpdir.join("make_directory")
        target_path = os.path.join(str(target_dir), value)

        assert not os.path.exists(target_path)
        assert FileManager.make_directory(target_path) == Path(target_path)
        assert os.path.isdir(target_path)

    @pytest.mark.parametrize(["value"], [
        ["test_normal_2"],
    ])
    def test_normal_2(self, tmpdir, value):
        FileManager.initialize(dry_run=False)

        target_dir = tmpdir.join("make_directory")
        target_path = os.path.join(str(target_dir), value)

        assert not os.path.exists(target_path)
        assert FileManager.make_directory(target_path) == Path(target_path)
        assert FileManager.make_directory(target_path) == Path(target_path)
        assert os.path.isdir(target_path)

    @pytest.mark.parametrize(["value", "expected"], [
        [None, ValueError],
    ])
    def test_exception(self, tmpdir, value, expected):
        with pytest.raises(expected):
            FileManager.make_directory(value)

class Test_check_file_existence:

    def test_normal_file(self, tmpdir):
        p = tmpdir.join(TEMP_FILE_NAME)
        p.write("test contents")
        assert check_file_existence(str(p)) == FileType.FILE

    def test_normal_empty_file(self, tmpdir):
        p = tmpdir.join(EMPTY_FILE_NAME)
        p.write("")

        check_file_existence(str(p))

    @pytest.mark.parametrize(["value", "expected"], [
        [EMPTY_DIR_NAME, FileType.DIRECTORY],
    ])
    def test_normal_dir(self, tmpdir, value, expected):
        tmpdir.mkdir(value)
        assert check_file_existence(str(tmpdir)) == expected

    @pytest.mark.parametrize(["value", "expected"], [
        [None, ValueError],
        [1.1, ValueError],
        [True, ValueError],
        ["", ValueError],
        ["/not/existing/file/__path__", FileNotFoundError],
    ])
    def test_exception(self, value, expected):
        with pytest.raises(expected):
            assert check_file_existence(value)

class Test_parsePermission3Char:

    @pytest.mark.parametrize(["value", "expected"], [
        ["---", 0],
        ["--x", 1],
        ["-w-", 2],
        ["r--", 4],
        ["-wx", 3],
        ["r-x", 5],
        ["rw-", 6],
        ["rwx", 7],
    ])
    def test_normal(self, value, expected):
        assert parsePermission3Char(value) == expected

    @pytest.mark.parametrize(["value", "expected"], [
        ["foo", 0],
    ])
    def test_abnormal(self, value, expected):
        assert parsePermission3Char(value) == expected

    @pytest.mark.parametrize(["value", "expected"], [
        [None, TypeError],
        [1, TypeError],
        [True, TypeError],
        ["hoge", ValueError],
    ])
    def test_exception(self, value, expected):
        with pytest.raises(expected):
            parsePermission3Char(value)

def getTestValueList():
    perm_list = [
        ["---", 0],
        ["--x", 1],
        ["-w-", 2],
        ["r--", 4],
        ["-wx", 3],
        ["r-x", 5],
        ["rw-", 6],
        ["rwx", 7],
    ]

    return_value_list = []
    for pair_list in itertools.product(perm_list, perm_list, perm_list):
        value = "-"
        expected = ""
        for transposition_pair_list in zip(pair_list):
            for pair in transposition_pair_list:
                value += pair[0]
                expected += str(pair[1])

        return_value_list.append([value, int(expected, base=8)])

    return return_value_list

class Test_parseLsPermissionText:

    @pytest.mark.parametrize(["value", "expected"], getTestValueList())
    def test_normal(self, value, expected):
        assert parseLsPermissionText(value) == expected

    @pytest.mark.parametrize(["value", "expected"], [
        [None, TypeError],
        [1, TypeError],
        [True, TypeError],
        ["hoge", ValueError],
        ["aaaaaaaaaa", ValueError],
    ])
    def test_exception(self, value, expected):
        with pytest.raises(expected):
            parseLsPermissionText(value)


# -*- coding: utf-8 -*-
"""
Created on Fri Nov 17 03:34:30 2023

@author: anees
"""

import qrcode
import subprocess
import webbrowser
import socket

def get_local_ip():
    # Get the local IP address of the machine
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))  # Connect to a known external server
        local_ip = s.getsockname()[0]
        s.close()
        return local_ip
    except Exception as e:
        print(f"Error getting local IP: {e}")
        return None

if __name__ == "__main__":
    # Fetch the local IP address
    local_ip = get_local_ip()

    if local_ip:
        # Construct the URL using the local IP address
        port = 3000  # Replace with the actual port your server is running on
        url = f"http://{local_ip}:{port}"

        # Generate the QR code with the URL
        qr_code_data = url
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(qr_code_data)

        # Create an image from the QR code data
        img = qr.make_image(fill_color="black", back_color="white")

        # Save the image to a file or display it
        img.show()
    else:
        print("Unable to fetch local IP address.")


# Given an array of integers, where all elements but one occur twice, find the unique element.

# Example
# a = [1, 2, 3, 4, 3, 2, 1]
# The unique element is 4.

# Function Description
# Complete the lonelyinteger function in the editor below.
# lonelyinteger has the following parameter(s):
# int a[n]: an array of integers
# Returns
# int: the element that occurs only once
# Input Format

# The first line contains a single integer, n, the number of integers in the array.
# The second line contains  space-separated integers that describe the values in a.

# Constraints
# 1 <= n <= 100
# It is guaranteed that n is an odd number and that there is one unique element.
# 0 <= a[i] <= 100, where 0 <= i <= n.

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'lonelyinteger' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER_ARRAY a as parameter.
#

def lonelyinteger(a):
    if a is None or (len(a) == 0): return
    if len(a) == 1: return a[0]

    maxElement = max(a)
    frequencies = [0] * (maxElement+1)

    for i in range(len(a)):
        frequencies[a[i]] += 1

    for i in range(len(frequencies)):
        if frequencies[i] == 1:
            return i;

def lonelyInteger(a):
    if a is None or (len(a) == 0): return
    if len(a) == 1: return a[0]

    frequencies = {}

    for i in range(len(a)):
        key = a[i]
        if key in frequencies.keys(): frequencies[key] += 1
        else: frequencies[key] = 1

    # for k in frequencies.keys():
    #     if frequencies[k] == 1: return k
    # filteredDict = {(k,v) for (k, v) in frequencies.items() if v == 1}
    filteredDict = dict((k, v) for k, v in frequencies.items() if v == 1)

    # return (filteredDict.pop()[0])
    return list(filteredDict.keys())[0]

if __name__ == '__main__':
    # fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    a = list(map(int, input().rstrip().split()))

    result = lonelyInteger(a)
    print(result)

    # fptr.write(str(result) + '\n')

    # fptr.close()


import numpy as np
import pandas as pd

s_stats = ["average_AP_overshoot",
           "spike_rate",
           "average_AP_width",
           "average_AHP_depth",
           "latency_to_first_spike",
           "accommodation_index"]

headers = s_stats + ["epsilon", "n_sims"]

results = []

n_sims_lst = [100, 200]
for n_sims in n_sims_lst:
    stat_scales = [1., 2, 3, 4, 5, 6]
    epsilon = 0.5
    results.append([*stat_scales, epsilon, n_sims])

data = dict(zip(headers, np.stack(results, axis=-1)))
df = pd.DataFrame.from_dict(data)


from ksql import KSQLAPI
import socket
import json
import re
import pandas as pd
import time
from datetime import datetime

client = KSQLAPI('http://localhost:8088')
streamProperties = {
    "ksql.streams.auto.offset.reset": "earliest",
    "ksql.query.pull.table.scan.enabled": "true"
}

def parse_columns(columns_str):
    regex = r"(?<!\<)`(?P<name>[A-Z_]+)` (?P<type>[A-z]+)[\<, \"](?!\>)"
    result = []

    matches = re.finditer(regex, columns_str)
    for matchNum, match in enumerate(matches, start=1):
        result.append({"name": match.group("name"), "type": match.group("type")})

    return result

def process_row(row, column_names):
    row = row.replace(",\n", "").replace("]\n", "").rstrip("]")
    row_obj = json.loads(row)
    if "finalMessage" in row_obj:
        return None
    column_values = row_obj["row"]["columns"]
    index = 0
    result = {}
    for column in column_values:
        result[column_names[index]["name"]] = column
        index += 1

    return result

def process_query_result(results, return_objects=None):
    if return_objects is None:
        yield from results

    # parse rows into objects
    try:
        header = next(results)
    except StopIteration:
        return
    columns = parse_columns(header)

    for result in results:
        row_obj = process_row(result, columns)
        if row_obj is None:
            return
        yield row_obj

def return_query_df(ksql_string):
    query = client.query(ksql_string, stream_properties=streamProperties)
    tspm = list(process_query_result(query, return_objects=True))
    return pd.DataFrame(tspm)

def ts_unix_to_ts(time_unix):
    dt = datetime.fromtimestamp(time_unix/1000)
    return dt.strftime('%Y-%m-%dT%H:%M:%S.%f')

def ts_str_to_unix(time_str):
    dt = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S.%f')
    return int(time.mktime(dt.timetuple()) * 1000)

# FUNCTION TO RETURN MOST RECENT BIT MASK FOR ALL INTERSECTIONS
def return_recent_data_ts(look_back_time = 15):
    '''
    look_back_time: time in min
    '''
    current_time_ms= round(time.time()*1000)
    look_time = current_time_ms - look_back_time*60*1000
    TABLE_NAME = 'ATSPM_MASK_1500SEC' #THIS IS A TABLE
    ksql_string = f'SELECT *  from {TABLE_NAME} where WINDOWEND >=' + f'{look_time}'
    # print(ksql_string)
    df = return_query_df(ksql_string)
    return df

# FUNCTION TO RETURN COUNTS FOR A DETECTOR BETWEEN START AND END TIME. 5 sec aggregation
def return_det_counts_data(detector_id, time_start, time_end):
    '''
    detector_id: detector_id string (signalID + channel value)
    start_time: unix time in ms (INT)
    end_time: unix time in ms(INT)
    '''
    TABLE_NAME = 'COUNTS_RAW_STREAM_V1_AGG_5SEC' #Detector ID to counts  #THIS IS A TABLE
    ksql_string = f'SELECT * FROM {TABLE_NAME} where DETECTORID = ' +  "'" + detector_id + "'"   + f' AND WINDOWSTART>={time_start} AND WINDOWSTART < {time_end}'
    print(ksql_string)
    temp_df = return_query_df(ksql_string)

    temp_df.drop(columns = ['DETECTORID', 'WINDOWEND'], inplace = True)
    new_row = pd.Series(data={'WINDOWSTART':time_start,'COUNT':0}, name=0)
    temp_df = temp_df.append(new_row, ignore_index=False)
    new_row = pd.Series(data={'WINDOWSTART':time_end,'COUNT':0}, name=0)
    temp_df = temp_df.append(new_row, ignore_index=False)
    temp_df['timestamp']  = pd.to_datetime(temp_df['WINDOWSTART'], unit = 'ms').dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
    temp_df.set_index('timestamp', inplace = True)
    temp_df.drop(columns = ['WINDOWSTART'], inplace = True)
    temp_df.sort_index(inplace = True)

    final_df = temp_df.resample('5s').sum()

    return final_df

def return_det_counts_data_v2(detector_id, time_start, time_end):
    '''
    detector_id: detector_id string (signalID + channel value)
    start_time: unix time in ms (INT)
    end_time: unix time in ms(INT)
    '''
    TABLE_NAME = 'COUNTS_RAW_STREAM_V1' #Detector ID to counts  #THIS IS A TABLE
    ksql_string = f'SELECT * FROM {TABLE_NAME} where DETECTORID = ' +  "'" + detector_id + "'"   + f' AND TS>={time_start} AND TS < {time_end}'
    print(ksql_string)
    temp_df = return_query_df(ksql_string)
    temp_df.drop(columns = ['DETECTORID', 'SIGNALID'], inplace = True)
    temp_df['EVENTCODE'].replace([82], 1, inplace  = True)
    temp_df.rename(columns={'EVENTCODE': 'COUNT'},inplace  = True)

    new_row = pd.Series(data={'TS':time_start,'COUNT':0}, name=0)
    temp_df = temp_df.append(new_row, ignore_index=False)
    new_row = pd.Series(data={'TS':time_end,'COUNT':0}, name=0)
    temp_df = temp_df.append(new_row, ignore_index=False)
    temp_df['timestamp']  = pd.to_datetime(temp_df['TS'], unit = 'ms').dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
    temp_df.set_index('timestamp', inplace = True)
    temp_df.drop(columns = ['TS'], inplace = True)
    temp_df.sort_index(inplace = True)

    final_df = temp_df.resample('5s').sum()

    return final_df


notasSim = []
while True:
    resposta = 0
    notaProva = float(input())
    if notaProva < 0 or notaProva > 10:
        print('nota invalida')
    else:
        notasSim.append(notaProva)
    if len(notasSim) == 2:
        media = (notasSim[0] + notasSim[1]) / 2
        print(f'media = {media:.2f}')
        notasSim.clear()
        while True:
            print('novo calculo (1-sim 2-nao)')
            resposta = float(input())
            if resposta == 1 or resposta == 2:
                break
        if resposta == 2:
            break


def getPossible(arr):
    finalArray = arr
    for i in range(len(arr)):
        for j in range(i+1,len(arr)):
            res = abs(arr[i] - arr[j])
            if(res not in finalArray):
                finalArray.append(res)

    return len(finalArray)

print(getPossible([6,2]))


import types
import typing
from collections.abc import Iterable, Mapping
from typing import Any

ALIAS_TYPES = [typing._SpecialGenericAlias, types.GenericAlias]  # type:ignore
UNION_TYPES = [typing._UnionGenericAlias, types.UnionType]  # type:ignore

def is_alias_type(t) -> bool:
    """
    Check if a type is an alias type (list[str], dict[str, int], etc...])
    """
    return type(t) in ALIAS_TYPES

def is_union_type(t) -> bool:
    """
    Check if a type is a union type (float | int, str | None, etc...)
    """
    return type(t) in UNION_TYPES

def is_iterable_type(t) -> bool:
    """
    Check if a type is an iterable type (list, tuple, etc...)
    """
    if is_alias_type(t):
        t = type_origin(t)
    return issubclass(t, Iterable)

def is_mapping_type(t) -> bool:
    """
    Check if a type is a mapping type (dict, defaultdict, etc...)
    """
    if is_alias_type(t):
        t = type_origin(t)
    return issubclass(t, Mapping)

def type_to_str(t) -> str:
    """
    Convert a Python type to its string representation.

    Args:
        t (type): A Python type.

    Returns:
        str: The string representation of the Python type.

    Examples:
        >>> type_to_str(union_parameter.UnionParameter)
        'UnionParameter'
        >>> type_to_str(int)
        'int'
    """
    type_str = repr(t)
    if "<class '" in type_str:
        type_str = type_str.split("'")[1]
    return type_str.split(".")[-1]

def type_origin(t: Any) -> Any:
    """
    typing.get_origin wrapper

    Example:
        >>> type_args(list[list[str]])
        <class 'list'>
        >>> type_origin(float | int)
        <class 'types.UnionType'>
    """
    return typing.get_origin(t)

def type_args(t: Any) -> tuple[Any, ...]:
    """
    typing.get_args wrapper

    Example:
        >>> type_args(list[str])
        (<class 'str'>,)
        >>> type_args(dict[str, int])
        (<class 'str'>, <class 'int'>)
        >>> type_args(list[list[str]])
        (list[str],)
    """
    return typing.get_args(t)

def type_simplify(t: Any) -> Any:
    """
    Examples:
    >>> type_simplify(list[str])
    <class 'list'>
    >>> type_simplify(float | list[str])
    (<class 'float'>, <class 'list'>)
    """
    origin = type_origin(t)
    if isinstance(type(origin), types.NoneType) or origin is None:
        return t

    if is_union_type(t):
        args = type_args(t)
        return tuple([type_simplify(i) for i in args])

    return origin

__all__ = [
    "is_alias_type",
    "is_union_type",
    "is_iterable_type",
    "is_mapping_type",
    "type_to_str",
    "type_origin",
    "type_args",
    "type_simplify",
]


import torch
import torch.nn as nn
import torch.nn.functional as F

class CoordConv2d(nn.Conv2d):

    def __init__(self, in_chan, out_chan, kernel_size=3, stride=1, padding=1, dilation=1, groups=1, bias=True):
        super(CoordConv2d, self).__init__(
            in_chan + 2, out_chan, kernel_size, stride=stride,
            padding=padding, dilation=dilation, groups=groups, bias=bias)

    def forward(self, x):
        batchsize, H, W = x.size(0), x.size(2), x.size(3)
        h_range = torch.linspace(-1, 1, H, device=x.device, dtype=x.dtype)
        w_range = torch.linspace(-1, 1, W, device=x.device, dtype=x.dtype)
        h_chan, w_chan = torch.meshgrid(h_range, w_range)
        h_chan = h_chan.expand([batchsize, 1, -1, -1])
        w_chan = w_chan.expand([batchsize, 1, -1, -1])

        feat = torch.cat([h_chan, w_chan, x], dim=1)
        return F.conv2d(feat, self.weight, self.bias,
                self.stride, self.padding, self.dilation, self.groups)


# -*- coding: utf-8 -*-
# © 2017 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import models, fields, api

class SaleConfirm(models.TransientModel):
    _name = 'sale.confirm'
    _description = 'Wizard to confirm a sale order'

    sale_id = fields.Many2one(
        'sale.order', string='Sale Order', readonly=True)
    client_order_ref = fields.Char(string='Customer PO Number')
    payment_term_id = fields.Many2one(
        'account.payment.term', string='Payment Terms')
    partner_invoice_id = fields.Many2one(
        'res.partner', 'Invoice Address', required=True)
    show_partner_invoice_id = fields.Many2one(
        related='partner_invoice_id', readonly=True,
        string='Detailed Invoice Address')
    partner_shipping_id = fields.Many2one(
        'res.partner', 'Delivery Address', required=True)
    show_partner_shipping_id = fields.Many2one(
        related='partner_shipping_id', readonly=True,
        string='Detailed Delivery Address')

    @api.model
    def _prepare_default_get(self, order):
        default = {
            'sale_id': order.id,
            'client_order_ref': order.client_order_ref,
            'payment_term_id': order.payment_term_id.id or False,
            'partner_invoice_id': order.partner_invoice_id.id,
            'partner_shipping_id': order.partner_shipping_id.id,
        }
        return default

    @api.model
    def default_get(self, fields):
        res = super(SaleConfirm, self).default_get(fields)
        assert self._context.get('active_model') == 'sale.order',\
            'active_model should be sale.order'
        order = self.env['sale.order'].browse(self._context.get('active_id'))
        default = self._prepare_default_get(order)
        res.update(default)
        return res

    @api.multi
    def _prepare_update_so(self):
        self.ensure_one()
        return {
            'client_order_ref': self.client_order_ref,
            'payment_term_id': self.payment_term_id.id or False,
            'partner_invoice_id': self.partner_invoice_id.id,
            'partner_shipping_id': self.partner_shipping_id.id,
            }

    @api.multi
    def confirm(self):
        self.ensure_one()
        vals = self._prepare_update_so()
        self.sale_id.write(vals)
        # confirm sale order
        self.sale_id.action_confirm()
        return True


# 376. Wiggle Subsequence

'''
A wiggle sequence is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences.

For example, [1, 7, 4, 9, 2, 5] is a wiggle sequence because the differences (6, -3, 5, -7, 3) alternate between positive and negative.
In contrast, [1, 4, 7, 2, 5] and [1, 7, 4, 5, 5] are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero.
A subsequence is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.

Given an integer array nums, return the length of the longest wiggle subsequence of nums.

Example 1:

Input: nums = [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3).

Example 2:

Input: nums = [1,17,5,10,13,15,10,5,16,8]
Output: 7
Explanation: There are several subsequences that achieve this length.
One is [1, 17, 10, 13, 10, 16, 8] with differences (16, -7, 3, -3, 6, -8).

Example 3:

Input: nums = [1,2,3,4,5,6,7,8,9]
Output: 2
'''
class Solution:
    def wiggleMaxLength(self, nums: List[int]) -> int:
        return self.optimized(nums)

    def naive(self, nums: List[int]) -> int:
        idx = 0

        while idx < len(nums) - 1:
            if nums[idx] != nums[idx + 1]:
                if nums[idx] < nums[idx + 1]:
                    findLarge = True
                else:
                    findLarge = False

                break

            idx += 1

        if idx == len(nums) - 1:
            return 1

        prev_val = nums[idx]
        res = 0

        for n in nums[idx:]:
            if findLarge:
                if n > prev_val:
                    res += 1
                    prev_val = n
                    findLarge ^= True
                else:
                    prev_val = min(prev_val, n)
            else:
                if n < prev_val:
                    res += 1
                    prev_val = n
                    findLarge ^= True
                else:
                    prev_val = max(prev_val, n)

        return res + 1

    def optimized(self, nums: List[int]) -> int:
        if len(nums) < 2:
            return len(nums)

        diff = nums[1] - nums[0]
        count = 2 if diff != 0 else 1

        for i in range(2, len(nums)):
            next_diff = nums[i] - nums[i-1]

            if (diff <= 0 and next_diff > 0) or (diff >= 0 and next_diff < 0):
                count += 1
                diff = next_diff

        return count

1. Problems/c. Array/a. 1D 2 - Sequence - Wiggle Subsequence.py


import sys
import os
import os.path
import shutil
import re
import urllib
from datetime import date

from mako.template import Template
from gcache2ebook.tools import base_path

class ePub:
    def __init__(self, tmp_path):
        self.tmp_path       = tmp_path + "/ePub"
        self.pages_path     = self.tmp_path + "/pages"
        self.build_path     = self.tmp_path + "/build"
        os.mkdir(self.tmp_path)
        self.output_file    = ""
        self.author = "GeoCaching.com"
        self.title = "GeoCaches"

    def create(self, cache_data):
        """docstring for create"""
        os.mkdir(self.pages_path)
        cache_list = []
        for cache in cache_data:
            cache_list.append(self._create_page(cache))
        self.prep_dir()
        self.get_parts(cache_list)
        self.gen_toc(cache_list)
        self.create_book()

    def _create_page(self, cache):
        """docstring for _create_page"""
        html = Template(filename=base_path() + '/resources/templates/epub.html')
        output = html.render(**cache)
        # print 'Generating ' + os.path.basename(fileName)
        tmp_file = self.pages_path + '/' + cache['name'] + '.html'
        with open(tmp_file, 'w') as f:
            f.write('')
            f.write(output.encode('ascii', 'xmlcharrefreplace'))
        return cache['name']

    def prep_dir(self):
        """docstring for prepDir"""
        # setup all the file directories and default files
        os.mkdir(self.build_path)
        os.mkdir(self.build_path + '/META-INF')
        os.mkdir(self.build_path + '/OEBPS')
        os.mkdir(self.build_path + '/OEBPS/css')
        #os.mkdir(self.tmp_path + '/OEBPS/img')
        shutil.copytree(base_path() + '/resources/images', self.build_path + '/OEBPS/img')
        shutil.copyfile(base_path() + '/resources/templates/uitleg.html', self.build_path + '/OEBPS/uitleg.html')

        # Style sheet to use (todo allow people to pass in their own)
        myStyle = """@page {margin-top: 0.8em; margin-bottom: 0.8em;}\n.titleimg {text-align:center;}"""
        open(self.build_path + "/OEBPS/css/main.css", "w").write(myStyle)
        open(self.build_path + "/mimetype", "w").write("application/epub+zip")

        containerXml= (
        '<?xml version="1.0" ?>\n'
        '<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">\n'
        '<rootfiles>\n'
        '<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml" />\n'
        '</rootfiles>\n'
        '</container>\n' )
        open(self.build_path + "/META-INF/container.xml","w").write(containerXml)

    def get_parts(self, cache_list):
        """docstring for getParts"""
        for cache in cache_list:
            file_name = self.pages_path + '/' + cache + '.html'
            shutil.copyfile(file_name, self.build_path + '/OEBPS/' + cache + '.html')

    def gen_toc(self, sections):
        """docstring for genTOC"""
        count = 1
        opf1 = '<opf:item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>\n'
        opf1 = opf1 + '<opf:item id="TableOfContents" href="TableOfContents.html" media-type="application/xhtml+xml" />\n'
        opf2 = "<opf:itemref idref=\"TableOfContents\"/>\n"

        opf1 = opf1 + "<opf:item id=\"%s\" href=\"%s\" media-type=\"application/xhtml+xml\"/>\n" % ('uitleg', 'uitleg.html')
        opf2 = opf2 + "<opf:itemref idref=\"%s\"/>\n" % ('uitleg')
        toc1 = '
%s
\n' % ('uitleg.html', 'Wat is GeoCaching?')

        tocOut = ( '<?xml version="1.0" encoding="UTF-8"?>\n'
        '<!DOCTYPE ncx PUBLIC "-//NISO//DTD ncx 2005-1//EN" "http://www.daisy.org/z3986/2005/ncx-2005-1.dtd">\n'
        '<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" xml:lang="en" version="2005-1">\n\n'
        '\n'
        '<meta name="dtb:uid" content="b0f76506-7763-11dd-83b7-001cc05a7670"/>\n'
        '<meta name="dtb:depth" content="1"/>\n'
        '<meta name="dtb:totalPageCount" content="0"/>\n'
        '<meta name="dtb:maxPageNumber" content="0"/>\n'
        '\n\n'
        '<docTitle>\n'
        '<text>%s</text>\n'
        '</docTitle>\n'
        '<navMap>\n' ) % self.title

        tocOut = tocOut + (
        '<navPoint id="part%d" playOrder="%d">\n'
        '<navLabel>\n'
        '<text>%s</text>\n'
        '</navLabel>\n'
        '<content src="%s"/>\n'
        '</navPoint>\n' ) % (count, count, 'Wat is GeoCaching?' , 'uitleg.html')

        contentHeader = ( '<?xml version="1.0" encoding="UTF-8" ?>\n'
        '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\n'
        '\n\n'
        '\n'
        '<title>%s</title>\n'
        '<link rel="stylesheet" href="css/main.css" type="text/css" />\n'
        '<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />\n'
        '\n\n'
        '\n'
        '

\n'
        '
List of Caches
\n'
        '
From www.geocaching.com
\n'
        '
' ) % self.title

        # for each section create an entry in the TOC for it, and then write it to disk
        for section in sections:
            tocOut = tocOut + (
            '<navPoint id="part%d" playOrder="%d">\n'
            '<navLabel>\n'
            '<text>%s</text>\n'
            '</navLabel>\n'
            '<content src="%s"/>\n'
            '</navPoint>\n' ) % (count, count, section , section + '.html')

            # create some xml indexing
            opf1 = opf1 + "<opf:item id=\"%s\" href=\"%s\" media-type=\"application/xhtml+xml\"/>\n" % (section, section + '.html')
            opf2 = opf2 + "<opf:itemref idref=\"%s\"/>\n" % (section)
            toc1 = toc1 + '
%s
\n' % (section + '.html', section)
            count = count + 1

        tocOut = tocOut + "</navMap></ncx>"

        contentOpf = ( '<?xml version="1.0" encoding="UTF-8"?>\n'
        '<opf:package version="2.0" unique-identifier="dcid" xmlns:opf="http://www.idpf.org/2007/opf" xmlns:dc="http://purl.org/dc/elements/1.1/">\n'
        '<opf:metadata>\n'
        '<dc:identifier id="dcid" opf:scheme="UUID">urn:uuid:3675ff2a-3059-4102-a2f4-30ab059267ed</dc:identifier>\n'
        '<dc:title>%s</dc:title>\n'
        '<dc:creator>%s</dc:creator>\n'
        '<dc:language>English</dc:language>\n'
        '<dc:subject>A Book of Caches from Geocaching.com</dc:subject>\n'
        '<dc:description>This book has been generated from GPX files downloaded from Geocaching.com, in an effort to go paperless</dc:description>\n'
        '<dc:date opf:event="modification">%s</dc:date>\n'
        '</opf:metadata>\n'
        '<opf:manifest>\n'
        '%s'
        '</opf:manifest>\n'
        '<opf:spine toc="ncx">\n'
        '%s'
        '</opf:spine>\n'
        '</opf:package>') % (self.title, self.author, date.today(), opf1, opf2)

        open(str(self.build_path) + "/OEBPS/toc.ncx", "w").write(tocOut)
        open(str(self.build_path) + "/OEBPS/content.opf","w").write(contentOpf)
        open(str(self.build_path) + "/OEBPS/TableOfContents.html", "w").write(contentHeader + toc1 + '
')

    def create_book(self):
        """docstring for createBook"""
        # now package everything up
        os.system("cd %s ; zip -q -X %s.zip -n mimetype mimetype  ; zip %s.zip -q -r META-INF/ OEBPS/ ; mv %s.zip %s.epub; mv %s.epub %s/" % (self.build_path, self.title, self.title, self.title, self.title, self.title, self.output_file) )

# end of genepub


import streamlit as st
from torch import nn

@st.cache(hash_funcs={nn.parameter.Parameter: lambda _: None})
def load_model():
    from transformers import PegasusTokenizer, PegasusForConditionalGeneration

    # Let's load the model and the tokenizer
    model_name = "human-centered-summarization/financial-summarization-pegasus"
    tokenizer = PegasusTokenizer.from_pretrained(model_name)
    model = PegasusForConditionalGeneration.from_pretrained(model_name)
    return model, tokenizer

@st.cache
def summarize(articles):
    model = load_model()[0]
    tokenizer = load_model()[1]
    summaries = []
    for article in articles:
        input_ids = tokenizer.encode(article, return_tensors="pt")
        output = model.generate(input_ids, max_length=55, num_beams=5, early_stopping=True)
        summary = tokenizer.decode(output[0], skip_special_tokens=True)
        summaries.append(summary)

    return summaries

@st.cache(allow_output_mutation=True)
def load_transformers():
    from transformers import pipeline
    sentiment = pipeline("sentiment-analysis")
    return sentiment


import discord
from discord import colour
from discord import embeds
from discord.abc import GuildChannel
from discord.ext import commands
import datetime
import asyncio
import random

client = commands.Bot(command_prefix = "&")
intents = discord.Intents(messages=True, guilds = True, reactions = True)

client.remove_command("help")

@client.event
async def on_ready():
	print("Bot is ready")

#gaw start cmd
@client.command()
@commands.has_permissions(manage_messages = True)
async def gstart(ctx, mins : int, member : discord.Member, * , prize:str ):
	await discord.TextChannel.trigger_typing()

	#def convert(time):

		#pos = ["s", "m", "h", "d", "y"]

		#time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : f"{3600*24}", "y" : f"{3600*24*365}"}

		#unit = time[-1]

		#if unit not in pos:
			#return -1
		#try:
		#	val = int(time[:-1])
		#except:
		#	return -2

		#return val * time_dict[unit]

	embed = discord.Embed(title = f"ðŸŽ‰{prize}ðŸŽ‰", description = f"Donated by : {member.mention}", color = discord.Colour.random())
	ends = datetime.datetime.utcnow() + datetime.timedelta(seconds = mins * 60)
	embed.add_field(name = "Ends At:", value = f"{ends} UTC")
	embed.set_footer(text = f"Ends in {mins} min(s) from now!")
	my_msg = await ctx.send("<a:giveaway:862239615241945108> Crown Dank Memers gaw <a:giveaway:862239615241945108>", embed = embed)
	await my_msg.add_reaction("<a:giveaway:862239615241945108>")
	await ctx.message.delete()
	await asyncio.sleep(mins*60)
	await ctx.trigger_typing()
	new_msg = await ctx.channel.fetch_message(my_msg.id)

	users = await new_msg.reactions[0].users().flatten()
	users.pop(users.index(client.user))

	winner = random.choice(users)

	await my_msg.reply(f"Congratulations! {winner.mention}, you won {prize}!")

#gaw end cmd
@client.command()
@commands.has_permissions(manage_messages = True)
async def gend(ctx, msg_id : int):
	await ctx.trigger_typing()

	new_msg_1 = await ctx.channel.fetch_message(msg_id)

	users = await new_msg_1.reactions[0].users().flatten()
	users.pop(users.index(client.user))

	winner = random.choice(users)

	link = discord.Message.jump_url(msg_id)
	await asyncio.sleep(5)
	await ctx.send(f"Congratulations! {winner.mention}, you won the gaw, {link} !")

#reply on members
@client.event
async def on_message(msg):
	if 'members' in msg.content:
		await msg.trigger_typing()
		link = await msg.channel.create_invite(max_age = 0)
		true_members = msg.guild.member_count
		embed = discord.Embed(title = "Member count" , colour = discord.Colour.random())
		embed.add_field(name = "What we want?" , value = f"We have {true_members} members help us reach 500 members.")
		embed.add_field(name = "Note:", value = f"Invite Friends when??! {link} " )
		await msg.reply(embed = embed)
	elif 'Members' in msg.content:
		await msg.trigger_typing()
		link = await msg.channel.create_invite(max_age = 0)
		true_members = msg.guild.member_count
		embed = discord.Embed(title = "Member count" , colour = discord.Colour.random())
		embed.add_field(name = "What we want?" , value = f"We have {true_members} members help us reach 500 members.")
		embed.add_field(name = "Note:", value = f"Invite Friends when??! {link} " )
		await msg.reply(embed = embed)

#reroll cmd
@client.command(aliases = ['r'])
@commands.has_permissions(manage_messages = True)
async def reroll(ctx, msg_id : int):
	await ctx.trigger_typing()
	await asyncio.sleep(5)

	new_msg_1 = await ctx.channel.fetch_message(msg_id)

	users = await new_msg_1.reactions[0].users().flatten()
	users.pop(users.index(client.user))

	winner = random.choice(users)
	await asyncio.sleep(5)

	await ctx.send(f"Congratulations! {winner.mention}, you won the reroll for the gaw with the id of {msg_id}!")

#splitorsteal
@client.command(aliases = ['sos'])
@commands.has_permissions(manage_messages = True)
async def splitorsteal(ctx, donor : discord.Member,dm : discord.Member, mins = 5, *, prize : str):
	await ctx.trigger_typing()
	await ctx.message.delete()
	embed = discord.Embed(title = f"<a:giveaway:862239615241945108> {prize} <a:giveaway:862239615241945108>", description = f"Donated by: {donor}", colour = discord.Colour.random())
	ends = datetime.datetime.utcnow() + datetime.timedelta(mins*60)
	embed.add_field(name = "DM:", value = dm)
	embed.add_field(name = "Ends At:", value = f"{ends} UTC")
	embed.set_footer(text = f"Ends in {mins} min(s) from now!")
	my_msg = await ctx.send("<a:giveaway:862239615241945108> Crown Dank Memers split or steal <a:giveaway:862239615241945108>", embed = embed)
	await my_msg.add_reaction("<a:giveaway:862239615241945108>")

	link = my_msg.jump_url
	try:
		await donor.send(f"Your split or steal in Crown Dank Memers, hosted by {ctx.author} has been started and the link to it is : {link}")
	except:
		f = 1 + 1
	await asyncio.sleep(mins*60)

	await ctx.trigger_typing()
	await asyncio.sleep(5)

	new_msg = await ctx.channel.fetch_message(my_msg.id)
	users = await new_msg.reactions[0].users().flatten()
	users.pop(users.index(client.user))

	winner1 = random.choice(users)
	winner2 = random.choice(users)

	await ctx.send(f"{winner1} , {winner2}")

	try:
		await winner1.send(f"Congratualtions! You are one of the winners of the split or steal, {link} , hosted in Crown Dank Memers, dm your response to {dm} in 30 seconds or you will be rerolled")
		await winner2.send(f"Congratualtions! You are one of the winners of the split or steal, {link} , hosted in Crown Dank Memers, dm your response to {dm} in 30 seconds or you will be rerolled")
		await dm.send(f"The winners of Your steal or split events, {link}, are {winner1.mention} and {winner2.mention}. Make sure that your DMs are open!")
	except:
		await ctx.send("R.I.P There was an error delievering some dms, as one of them had their dms off")

	await my_msg.reply(f"Congratulations! {winner2.mention} and {winner1.mention} are the two winners of the split or steal.")

#sos end

@client.command(aliases = ['sosend', 'sose'])
@commands.has_permissions(manage_messages = True)
async def splitorstealend(ctx, my_msg : discord.Message):
	await ctx.trigger_typing()
	new_msg = await ctx.channel.fetch_message(my_msg.id)
	users = await new_msg.reactions[0].users().flatten()
	users.pop(users.index(client.user))

	winner1 = random.choice(users)
	winner2 = random.choice(users)
	link = my_msg.jump_url
	dm = ctx.author

	try:
		await winner1.send(f"Congratualtions! You are one of the winners of the split or steal, {link} , hosted in Crown Dank Memers, dm your response to {dm.mention} in 30 seconds or you will be rerolled")
		await winner2.send(f"Congratualtions! You are one of the winners of the split or steal, {link} , hosted in Crown Dank Memers, dm your response to {dm.mention} in 30 seconds or you will be rerolled")
		await dm.send(f"The winners of Your steal or split events, {link}, are {winner1.mention} and {winner2.mention}. Make sure that your DMs are open!")
	except:
		await my_msg.reply(f"Congratulations! {winner2.mention} and {winner1.mention} are the two winners of the split or steal.")

#sos reroll

@client.command(aliases = ['sosr', 'sosreroll'])
@commands.has_permissions(manage_messages = True)
async def splitorstealreroll(ctx, my_msg : discord.Message , win = 2):
	await ctx.trigger_typing()
	new_msg = await ctx.channel.fetch_message(my_msg.id)
	users = await new_msg.reactions[0].users().flatten()
	users.pop(users.index(client.user))
	link = my_msg.jump_url
	if win == 1:
		winner1 = random.choice(users)
		try:
			await winner1.send((f"Congratualtions! You are the winner of the reroll of the split or steal, {link} , hosted in Crown Dank Memers, dm your response to the one to be dmed in 30 seconds or you will be rerolled"))
		except:
			await my_msg.reply(f"Congratulations! {winner1.mention} , you  are the new winner of the split or steal.")
	elif win == 2:

		winner1 = random.choice(users)
		winner2 = random.choice(users)

		try:
			await winner1.send(f"Congratualtions! You are one of the winners of the split or steal, {link} , hosted in Crown Dank Memers, dm your response to the one to be dmed in 30 seconds or you will be rerolled")
			await winner2.send(f"Congratualtions! You are one of the winners of the split or steal, {link} , hosted in Crown Dank Memers, dm your response to the one to be dmed in 30 seconds or you will be rerolled")
		except:
			await my_msg.reply(f"Congratulations! {winner2.mention} and {winner1.mention} are the two winners of the reroll of split or steal.")

	else:
		await ctx.reply("My man, u need to gimme the no. of wins after the message id and the win should be 1 or 2 or I break. ``` *sosr <sos> <winners>```")

#kick cmd

@client.command(aliases = ['k'])
@commands.has_permissions(kick_members = True)
async def kick(ctx, member : discord.Member,*, reason = "none"):
	await ctx.trigger_typing()
    #check = False
   # for i in member.roles:
       # if i in ctx.author.roles[1:]:
          #  check = True

    		#if(check):
        		#await ctx.send('Cant kick Moderators/Admins')
    		#else:
	await member.send(f"You have been kicked from Crown Dank Memers by {ctx.author} and the reason provided was {reason}")
	await member.kick(reason = reason)
	await ctx.send(f"{ctx.author.mention} has kicked {member.mention} from Crown Dank Memers and the reason provided was {reason}")

#false ban cmd
@client.command(aliases = ['bann'])
@commands.has_permissions(manage_messages = True)
async def bon(ctx, member : discord.Member):
	await ctx.trigger_typing()
	msg = await ctx.send(f"{ctx.author.mention} has banned {member.mention} using my long ppppppppp")
	await msg.add_reaction("<a:abanhammer:851715377255677972>")
	await member.send(f"Sry to say but you have been banned <a:abanhammer:851715377255677972> from Crown Dank Memers by {ctx.author.mention}")

#purge cmd
@client.command(aliases = ['c'])
@commands.has_permissions(manage_messages = True)
async def clear(ctx, amount = 1):
	await ctx.channel.purge(limit = amount + 1)

#mute members
@client.command(aliases = ['m'])
@commands.has_permissions(kick_members = True)
async def mute(ctx,member : discord.Member, time = 60, * , reason = "N/A" ):
	await ctx.trigger_typing()
	muted_role = ctx.guild.get_role(868397565249470464)
	time = int(time)
	await member.add_roles(muted_role)
	await ctx.send(f"{ctx.author.mention} has muted {member.mention} successfully for {time}.")
	await member.send(f"You have been muted in Crown Dank Memers for {time} by {ctx.author}.")

	await asyncio.sleep(time*60)
	unmute = await member.remove_role(muted_role)

#unmute members

@client.command(aliases=['um'])
@commands.has_permissions(kick_members=True)
async def unmute(ctx, member : discord.Member):
	await ctx.trigger_typing()
	muted_role = ctx.guild.get_role(868397565249470464)
	await member.remove_role(muted_role)

#unban users
@client.command(aliases = ['ub'])
@commands.has_permissions(ban_members = True)
async def unban(ctx,*, member):
	await ctx.trigger_typing()
	banned_users = await ctx.guild.bans()
	member_name, member_disc = member.split("#")

	for banned_entry in banned_users:
		user = banned_entry.user
		if(user.name, user.discriminator) == (member_name,member_disc):

			await ctx.guild.unban(user)
			await ctx.send(member_name + f" has been unbanned successfully by {ctx.author.mention}")
			await member.send(f"You have been unbanned from Crown Dank Memers by {ctx.author}")
			return
	await ctx.send(f"{member} was not found.")

#Ban command
@client.command(aliases = ['b'])
@commands.has_permissions(ban_members=True)
async def ban(ctx, member : discord.Member, *, reason=None):

    check = False
    for i in member.roles:
        if i in ctx.author.roles[1:]:
            check = True

    if(check):
        ctx.send('Cant ban Moderators/Admins')
    else:
        await member.ban(reason=reason)
        my_msg = await ctx.send(f'{member.mention} has been banned!')
        await my_msg.add_reaction("<a:abanhammer:851715377255677972>")
        await member.send(f"You have been banned from Crown Dank Memers by {ctx.author} and the reason provided was {reason}")

#USER INFO
@client.command(aliases=['user', 'info'])
@commands.has_permissions(administrator = True)
async def whois(ctx, member:discord.Member):
	await ctx.trigger_typing()
	embed = discord.Embed(title = member.name, description = member.mention , color = discord.Colour.random())

	Role = discord.Member.roles
	top_role = discord.Member.top_role
	created = discord.Member.created_at
	#created = int(created)
	#created = datetime.datetime(created)
	roles = Role
	Top_role = top_role

	embed.add_field(name = "ID", value = member.id, inline = True)
	embed.add_field(name = "Roles", value = ", ".join(role.mention for role in reversed(member.roles) if role.name != "@everyone"), inline = True)
	embed.add_field(name = "Top Role", value = f"{member.top_role.mention}", inline = True)
	embed.add_field(name = "Account was created on:", value = f"{member.created_at}")
	embed.set_thumbnail(url = member.avatar_url)
	embed.set_footer(icon_url = ctx.author.avatar_url, text = f"Requested by {ctx.author.name}")
	await ctx.send(embed = embed)

#role info
@client.command(aliases = ['rinfo'])
@commands.has_permissions(administrator = True)
async def roleinfo(ctx, role : discord.Role ):
	await ctx.trigger_typing()

	#colours = ["red", "purple", "blue", "green"]
	#colour = random.choice(colours)
	embed = discord.Embed(title = role.name, color = discord.Colour.random())
	embed.add_field(name = "ID", value = role.id , inline = True)
	embed.add_field(name = "Mentionable by users :", value = role.mentionable, inline = True)
	embed.add_field(name = "Created at:", value = role.created_at, inline = True)
	#embed.add_field(name = "Can add reactions:", value = role.Permissions.add_reaction(), inline = True)
	#embed.add_field(name = "Admin:", value = role.permissions.administrator, inline = True)
	#embed.add_field(name = "Can attach files:", value = role.permissions.attach_files, inline = True)
	#embed.add_field(name = "Can ban members:", value = role.permissions.ban_members, inline = True)
	#embed.add_field(name = "Can change nickname:", value = role.permissions.change_nickname, inline = True)
	#embed.add_field(name = "Can connect:", value = role.permissions.connect, inline = True)
	#embed.add_field(name = "Can create instant invite:", value = role.permissions.creat_instant_invite, inline = True)
	#embed.add_field(name = "Can deafen members:", value = role.permissions.deafen_members, inline = True)
	#embed.add_field(name = "Can embed links:", value = role.permissions.embed_links, inline = True)
	#embed.add_field(name = "Can kick members:", value = role.permissions.kick_members, inline = True)
	#embed.add_field(name = "Can manage chanels:", value = role.permissions.manage_channels, inline = True)
	#embed.add_field(name = "Can manage emojis:", value = role.permissions.manage_emojis, inline = True)
	#embed.add_field(name = "Can manage server:", value = role.permissions.manage_guild, inline = True)
	#embed.add_field(name = "Can manage messages:", value = role.permissions.manage_messages, inline = True)
	#embed.add_field(name = "Can manage nicknames:", value = role.permissions.manage_nicknames, inline = True)
	#embed.add_field(name = "Can manage permissions:", value = role.permissions.manage_permissions, inline = True)
	#embed.add_field(name = "Can manage roles:", value = role.permissions.manage_roles, inline = True)
	#embed.add_field(name = "Can manage webhooks:", value = role.permissions.manage_webhooks, inline = True)
	#embed.add_field(name = "Can mention everyone/here:", value = role.permissions.mention_everyone, inline = True)
	#embed.add_field(name = "Can move members:", value = role.permissions.move_members, inline = True)
	#embed.add_field(name = "Can mute members:", value = role.permissions.mute_members, inline = True)
	#embed.add_field(name = "Is priority speaker:", value = role.permissions.priority_speaker, inline = True)
	#embed.add_field(name = "Can read message history:", value = role.permissions.read_message_history, inline = True)
	#embed.add_field(name = "Can read messages:", value = role.permissions.read_messages, inline = True)
	#embed.add_field(name = "Can request to speak:", value = role.permissions.request_to_speak, inline = True)
	#embed.add_field(name = "Can send messages:", value = role.permissions.send_messages, inline = True)
	#embed.add_field(name = "Can send tts messages:", value = role.permissions.send_tts_messages, inline = True)
	#embed.add_field(name = "Can speak:", value = role.permissions.speak, inline = True)
	#embed.add_field(name = "Can stream:", value = role.permissions.stream, inline = True)
	#embed.add_field(name = "Can use external emojis:", value = role.permissions.use_external_emojis, inline = True)
	#embed.add_field(name = "Can use slash commands:", value = role.permissions.use_slash_commands, inline = True)
	#embed.add_field(name = "Can use voice activation:", value = role.permissions.use_voice_activation, inline = True)
	#embed.add_field(name = "Can view audit log:", value = role.permissions.view_audit_log, inline = True)
	#embed.add_field(name = "Can view channel:", value = role.permissions.view_channel, inline = True)
	#embed.add_field(name = "Can view guild insights:", value = role.permissions.view_guild_insights, inline = True)
	embed.add_field(name = "Position in Hierarchy:", value = role.position, inline = True)
	embed.add_field(name = "Managed by an integration:", value = role.managed)
	embed.set_footer(icon_url = ctx.author.avatar_url, text = f"Requested by {ctx.author.name}")

	await ctx.send(embed = embed)

#info on text channel
@client.command(aliases = ['t'])
async def textchannel(ctx, text : discord.TextChannel):
	await ctx.trigger_typing()
	embed = discord.Embed(title = f"{text.name}", color = discord.Colour.random())
	embed.add_field(name = "ID", value = text.id , inline = True)
	embed.add_field(name = "Category that they fall under:", value = text.category, inline = True)
	embed.add_field(name = "Category ID", value = text.category_id)
	embed.add_field(name = "Created at:", value = text.created_at)
	#l_m = text.last_message
	#l_m1 = l_m.jump_url
	#embed.add_field(name = "Last Message", value = l_m1)
	embed.add_field(name = "Slowmode:", value = text.slowmode_delay)
	embed.set_footer(icon_url = ctx.author.avatar_url, text = f"Requested by {ctx.author.name}")

	await ctx.send(embed = embed)

#ping pong
@client.command(aliases = ['pong' , 'latency'])
async def ping(ctx):
	await ctx.trigger_typing()
	pong = format(round(client.latency, 1)*1000)
	embed = discord.Embed(title = "My pong is:", color = discord.Colour.random())
	embed.add_field(name = "pong!", value =  f"{pong} ms" )

	await ctx.send(embed = embed)

#serverinfo
@client.command(aliases = ['sinfo', 'guildinfo'])
@commands.has_permissions(kick_members = True)
async def serverinfo(ctx):
	await ctx.trigger_typing()
	s_name = ctx.guild.name
	s_id = s_name.id
	owner = s_name.owner
	owner_id = owner.id
	embed = discord.Embed(title = f"{s_name} info", description = f"{owner.mention}", colour = discord.Colour.random())
	embed.add_field(name = "Server ID:", value = s_id , inline = False)
	embed.add_field(name = "Owner ID:", value = owner_id)
	embed.add_field(name = "Total number of channels:", value = ctx.guild.channel_count)

@client.command
async def test(ctx):
	await ctx.send("bruh")

#help
@client.command(aliases = ['h', 'help me'])
async def help(ctx , f = 0):
	await discord.TextChannel.trigger_typing()
	embed = discord.Embed(title = "I am here to help u", description = "y u reading this just read from below", colour = discord.Colour.random())
	embed.add_field(name = "gstart" , value = "This command starts a gaw. The cmd includes: ```*gstart <time in mins> <donor> <prize> ```")
	embed.add_field(name = "gend", value = "This command ends a gaw. The cmd needs: ```*gend <gaw_id>```")
	embed.add_field(name = "greroll" , value = "This command rerolls the winner of a gaw. This cmd needs: ```*greroll <gaw_id>")
	embed.add_field(name = "splitorsteal / sos", value = "This command starts a split or steal. This cmd requires: ```*sos <donor> <the one who needs to be dmed> <time(default is 5m) in minutes> <prize> ```")
	embed.add_field(name = "splitorstealend / sose", value = "This command ends a split or steal. It requires: ```*sos <sos_id>```")
	embed.add_field(name = "splitorstealreroll / sosreroll", value = "This command rerolls a split or steal. It needs: ```*sosr <sos_id> ```")
	embed.add_field(name = "bann / bon", value = "This command is just for fun and requires : ```*bon <member> <reason (this is optional)>```")
	embed.add_field(name = "kick / k", value = "This command kicks a member and requires: ```*k <member> <reason (this is optional) > ```")
	embed.add_field(name = "ban / b", value  = "This command, as u might have guessed, **bans** a member. It requires: ```*b <member>``` ")
	embed.add_field(name = "purge / clear / c", value = "This command clears the specified number of msgs and needs: ```*c <no. of msgs>```")
	embed.add_field(name = "mute / m", value = "This command mutes a member. It needs: ```*mute <member> <time(optional)> <reason(optional)>```")
	embed.add_field(name = "unmute / um" , value = "This command unmutes a member. It needs: ```*um <member>```")
	embed.add_field(name="unba	n / ub" , value = "This command unbans a member. It requires: ```*ub <member>```")
	embed.add_field(name = "whois / user / info" , value = "This command gives a detailed info on the member and requires: ```*user <member> ```")
	embed.add_field(name="roleinfo / rinfo", value = "This command gives info of a role and needs: ```*rinfo <role (if the role is ping role, pls refrain from pinging it)> ")
	embed.add_field(name = "serverinfo / sinfo / guildinfo" , value = "This command returns the major characteristics of the server and it requires just the cmd.")
	embed.add_field(name = "textchannl / t ", value = "This returns the characteristics of a text channel. It requires: ```*t <textchannel> ```")
	embed.add_field(name = "ping / pong / latency", value = "This returns the bot's latency and requires just the cmd.")
	embed.add_field(name = "freeloader / fl" , value = "This command tempbans the user that has been recorded as a freeloader for 7 dyas and needs: ```*fl <user>```")
	await ctx.send(embed = embed)

#error-handling
@client.event
async def on_command_error(ctx,error):
	if isinstance(error,commands.MissingPermissions):
		await ctx.reply("Bruh, you dont have the required perms")
	elif isinstance(error,commands.MissingRequiredArgument):
		await ctx.reply("Bruh, you didnt tell me everything.")
	elif isinstance(error, commands.CommandNotFound):
		await ctx.reply("Bruh, wat ya sayin'?")
	else:
		raise error

@client.command(aliases = ['fl'])
@commands.has_permissions(ban_members = True)
async def freeloader(ctx, member : discord.Member):
	await ctx.trigger_typing()
	await member.ban(reason = "freeloading")
	await ctx.send(f"Banned {member}")
	try:
		member.send(f"U were freeloading and have been banned from {ctx.guild.name} for 7 days. **So don't freeload**")
	except:
		f = 1+1
	await asyncio.sleep(604800)
	await ctx.guild.unban(member)

client.run("ODY4NzQ3MDkyNDE4NTIzMTQ3.YP0Jxw.hDbH-VEBKgz2w4435AlftH-GkcI")


# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

__author__ = "d01"
__email__ = "jungflor@gmail.com"
__copyright__ = "Copyright (C) 2017, Florian JUNG"
__license__ = "MIT"
__version__ = "0.1.0"
__date__ = "2017-07-21"
# Created: 2017-07-21 13:38

import threading
import sys

import kombu.serialization
from kombu import Exchange, Connection, Queue, producers
from kombu.mixins import ConsumerMixin
from nameko.exceptions import (
    ContainerBeingKilled, MalformedRequest, MethodNotFound,
UnknownService, UnserializableValueError, deserialize, serialize)
from flotils import Loadable, StartStopable

class RPCListener(ConsumerMixin, Loadable, StartStopable):

    def __init__(self, settings=None):
        if settings is None:
            settings = {}
        ConsumerMixin.__init__(self)
        Loadable.__init__(self, settings)
        StartStopable.__init__(self, settings)

        self._broker_url = settings['AMQP_URI']
        self._heartbeat = settings.get('heartbeat', None)
        self._serializer = settings.get('serializer', "json")
        """ Which formats for serialization to support
            :type : list[unicode] """
        self._connection_timeout = settings.get('connection_timeout', 2.0)
        """ Timeout of timeout
            :type : float """
        self.service = settings.get('service')
        """ Service to call
            :type : object """
        self.allowed_functions = settings.get('allowed_functions')
        """ Which functions on the service are callable (None means all)
            :type : None | list[unicode] """
        self.connection = None
        """ Connection to broker
            :type : None | kombu.Connection """
        self._nameko_exchange_rpc_name = settings.get(
            'rpc_exchange', "nameko-rpc"
        )
        """ Name of exchange
            :type : unicode """
        self._nameko_exchange_rpc = None
        """ :type : None | kombu.Exchange """
        self._nameko_queue_rpc = None
        """ :type : None | kombu.Queue """
        self._service_name = settings['service_name']

    def _thread_wrapper(self, func, *args, **kwargs):
        """
        Wrap function for exception handling with threaded calls

        :param func: Function to call
        :type func: callable
        :param args: Tuple arguments
        :type args: ()
        :param kwargs: Dict arguments
        :type kwargs: dict
        :rtype: None
        """
        try:
            func(*args, **kwargs)
        except:
            self.exception("Threaded execution failed")

    def _register_service(self, service_name):
        if self._nameko_exchange_rpc is None:
            self._nameko_exchange_rpc = Exchange(
                self._nameko_exchange_rpc_name, type="topic",
                auto_delete=False, durable=True
            )
        self._nameko_queue_rpc = Queue(
            "rpc-{}".format(service_name),
            self._nameko_exchange_rpc,
            routing_key="{}.*".format(service_name),
            durable=True
        )

    def get_consumers(self, Consumer, channel):
        return [Consumer(
            queues=[self._nameko_queue_rpc],
            accept=[self._serializer],
            callbacks=[self._process_message]
        )]

    def _process_message(self, body, message):
        """
        Called whenever a message is received

        :param body: Decoded message body
        :type body: object
        :param message: Message instance
        :type message: kombu.message.Message
        :rtype: None
        """
        correlation_id = message.properties.get('correlation_id')
        routing_key = message.properties['reply_to']
        called = message.delivery_info.get('routing_key', "")
        exec_info = None
        error = None
        result = None
        args = kwargs = None

        if called:
            parts = called.split(".")
            if len(parts) == 2:
                called = parts[1]
            else:
                called = None
        if not called:
            self.error("No method called: '{}'".format(
                message.delivery_info.get('routing_key')
            ))
            error = serialize(MethodNotFound("No method given"))

        if self.service and called:
            message.ack()
            try:
                try:
                    args = body['args']
                    kwargs = body['kwargs']
                except KeyError:
                    raise MalformedRequest("Message missing `args` or `kwargs`")
                fn = None
                # Only allowed methods
                if self.allowed_functions is None \
                        or called in self.allowed_functions:
                    # Attempt to call
                    fn = getattr(self.service, called, None)
                    if callable(fn):
                        result = fn(*args, **kwargs)
                    else:
                        error = serialize(MethodNotFound(
                            "No such Method on service"
                        ))
                else:
                    error = serialize(MethodNotFound("Method not allowed"))
            except:
                self.exception("Failed to call process method")
                exec_info = sys.exc_info()
                result = None
        else:
            self.warning("No service found")
            message.ack()
            if not error:
                error = serialize(MethodNotFound("No service found"))

        if exec_info is not None:
            # TODO: Serialize
            try:
                error = kombu.serialization.dumps(exec_info, self._serializer)
            except:
                self.exception("Failed to serialize exec_info")
                error = "{}".format(exec_info)
        elif error is None:
            # Check that kombu is able to serialize data
            try:
                kombu.serialization.dumps(result, self._serializer)
            except:
                error = serialize(UnserializableValueError(result))
                result = None

        msg = {
            'result': result,
            'error': error
        }
        with producers[self.connection].acquire(
                block=True, timeout=self._connection_timeout
        ) as producer:
            producer.publish(
                msg,
                compression="bzip2",
                exchange=self._nameko_exchange_rpc_name,
                retry=True,
                routing_key=routing_key,
                serializer=self._serializer,
                correlation_id=correlation_id
            )

    def _run_worker(self):
        """
        Connect and run worker

        :rtype: None
        """
        self._register_service(self._service_name)
        with Connection(self._broker_url, heartbeat=self._heartbeat) as conn:
            self.connection = conn
            self.run()

    def start(self, blocking=False):
        super(RPCListener, self).start(False)
        if not blocking:
            try:
                a_thread = threading.Thread(
                    target=self._thread_wrapper,
                    args=(self._run_worker,)
                )
                a_thread.daemon = True
                a_thread.start()
            except:
                self.exception("Failed to run receive loop")
                self.stop()
                return
        else:
            self._run_worker()

    def stop(self):
        self.should_stop = True
        super(RPCListener, self).stop()
        self._nameko_queue_rpc = None
        self._nameko_queue_rpc = None


### if / elif /  else ###

animal = input('Dime un animal: ')
if animal == 'perro':
    print('-guau')
elif animal == 'gato':
    print('-Miau')
elif animal == 'vaca':
    print('-Muu')
else:
    print('No conozco su sonido.')

print('Conozco pocos animales')

# nota: se usa pass cuando queremos que un bloque de codigo no haga nada

num = int(input('Ingrese un entero: '))
if num < 0:
    num = -num
print('Su valor absoluto es', num)

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

### while ###

print('Impares menores a 10')

x = 1

while x <= 10:
    print(x)
    x+=2

# Nota: aquí se impreme el resultado hasta antes del 10 ya que previo a ello el while era FALSE.

factorial = 5

contador = factorial -1

while contador > 0:

    factorial *= contador
    contador -= 1

# Nota: revisar ejemplo con print!

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

### FOR ###

for i in 1,2,3:
    print(i)

for i in range(5): # Nota; dentro del parentesis se pone el rango, que es la catidad de veces que se ejecutará el codigo).
    print(i) # En este ejemplo, a recordar que en Python el 0 se cuenta como 1 para conteo.

for i in ['Ale', 'Ivan', 'Monse', 'Luis', 'Rafa', 'Luca']: # Esta es una lista con el sigo [].
    print(i)

for i in 'Hola Mundo':

    if i == 'M':
        pass # ejemplo del pass donde el FOR no considera esta parte.

    else:
        print(i, end='')

Módulo 2 - Estructuras de control y colecciones/ConsideracionesPrevias.py