"""

Usage:
    trajectory.py <path> <start_time> <resolution> <x0> <y0> <z0> <t0> [<output_path>]
    trajectory.py (-h | --help)

Arguments:
    <path>
    <start_time>
    <resolution>

Options:
    -h --help
        Show this screen.
"""
import datetime
import warnings

import numpy as np

from twinotter.util.scripting import parse_docopt_arguments
from pylagranto import caltra
from pylagranto.datasets import MetUMStaggeredGrid

from moisture_tracers import grey_zone_forecast

trajectory_filename = "{start_time}_{resolution}_{x0}E_{y0}N_{z0}{units}_" \
                      "T+{lead_time:02d}.pkl"

# Inner-domain centre: x0=302.5, y0=13.5, t0=48
# HALO: x0=302.283, y0=13.3
# Ron Brown (2nd Feb): x0=305.5, y0=13.9
# 24th Jan Case study:
#   x0=302.5, y0=11.75, t0=T+24h
#   x0=310.0, y0=15.0,  t0=T+48h

def _command_line_interface(path, start_time, resolution, x0, y0, z0, t0, output_path="./"):
    forecast = grey_zone_forecast(
        path, start_time, resolution=resolution, grid=None, lead_times=range(1, 48 + 1)
    )

    traout = calculate_trajectory(
        forecast, float(x0), float(y0), float(z0), int(t0), "height_above_reference_ellipsoid"
    )

    traout.save(
        output_path + trajectory_filename.format(
            start_time=forecast.start_time.strftime("%Y%m%d"),
            resolution=resolution,
            x0=format_float_for_file(x0),
            y0=format_float_for_file(y0),
            z0=format_float_for_file(z0),
            t0=t0,
            units="m",
        )
    )

def calculate_trajectory(forecast, x0, y0, z0, t0, zcoord):
    levels = (zcoord, [z0])
    trainp = np.array([[x0, y0, z0]])

    times = list(forecast._loader.files)
    datasource = MetUMStaggeredGrid(forecast._loader.files, levels=levels)

    time_traj = forecast.start_time + datetime.timedelta(hours=t0)
    if time_traj == times[0]:
        traout = caltra.caltra(
            trainp, times, datasource, tracers=["x_wind", "y_wind"]
        )
    elif time_traj == times[-1]:
        traout = caltra.caltra(
            trainp, times, datasource, fbflag=-1, tracers=["x_wind", "y_wind"]
        )
    else:
        times_fwd = [time for time in times if time <= time_traj]
        traout_fwd = caltra.caltra(
            trainp, times_fwd, datasource, tracers=["x_wind", "y_wind"]
        )

        times_bck = [time for time in times if time >= time_traj]
        traout_bck = caltra.caltra(
            trainp, times_bck, datasource, fbflag=-1, tracers=["x_wind", "y_wind"]
        )
        traout = traout_bck + traout_fwd

    return traout

def format_float_for_file(x):
    # Replace decimal point with a p (copying what was done for the UM files)
    return str(x).replace(".", "p")

if __name__ == "__main__":
    warnings.filterwarnings("ignore")
    parse_docopt_arguments(_command_line_interface, __doc__)


def read_file(filename):
	file = open(filename)
	content = []
	for word in file.readlines():
		content.append(word.strip())
	return set(content)

WORDBANK = read_file("wordbank.txt")
PREV_ANSWERS = read_file("prev_answers.txt")
POSS_ANSWERS = read_file("poss_answers.txt")


#!/usr/bin/env python3
from ietf.sql.rfc import Rfc

def query_rfc_by_keyword(Session, search_terms):
    """Return a query that, if run, would return RFCs with the keywords in
    `keywords`.

    The matching on is case-insensitive.
    """
    # Assemble a query for each name
    queries = []  # Empty list to store queries
    for term in search_terms:
        term = term.lower()  # Convert to lowercase
        queries.append(Session.query(Rfc).filter(Rfc.keywords.any(word=term)))
    # Build a query of intersections
    query_to_run = queries[0]  # Assign first query
    for query in queries[1:]:  # Start at second element in list
        query_to_run = query_to_run.intersect(query)
    # Return the built query
    return query_to_run


"""
N×M 크기의 공간에 아기 상어 여러 마리가 있다. 공간은 1×1 크기의 정사각형 칸으로 나누어져 있다. 한 칸에는 아기 상어가 최대 1마리 존재한다.

어떤 칸의 안전 거리는 그 칸과 가장 거리가 가까운 아기 상어와의 거리이다. 두 칸의 거리는 하나의 칸에서 다른 칸으로 가기 위해서 지나야 하는 칸의 수이고, 이동은 인접한 8방향(대각선 포함)이 가능하다.

안전 거리가 가장 큰 칸을 구해보자.
"""

import sys
from collections import deque
N, M = list(map(int, sys.stdin.readline().strip().split()))
blocks = [[0] * M for _ in range(N)]  # blocks
dir = [(0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1)]

for i in range(N):
    blocks[i] = list(map(int, sys.stdin.readline().strip().split()))

def out_of_range(y,x):
    return y < 0 or x < 0 or y >= N or x >= M

def solve():
    max_val = float("-inf")
    for i in range(N):
        for j in range(M):
            if blocks[i][j] == 0:
                # bfs 시작
                q = deque()
                visited = set()
                q.append((i,j, 0))
                visited.add((i,j))
                dist = 0
                while q:
                    row, col, distance = q.popleft()
                    # print(row, col, distance)
                    if blocks[row][col] == 1:
                        dist = distance
                        break
                    for idx in range(8):
                        next_r, next_c = row + dir[idx][0], col + dir[idx][1]
                        if out_of_range(next_r, next_c) or (next_r, next_c) in visited:# or (next_r, next_c) in did_shark_test:
                            continue
                        q.append((next_r, next_c, distance + 1))
                        visited.add((next_r,next_c))
                max_val = max(max_val, dist)
    return max_val

def main():
    print(solve())

main()


#=======================================================
# lm35_slave.py : ADRS2040U PICO HAT Test Program
#       2022.09.14  V0.0    New Create
#       2022.10.26  V1.0    for ADRS2040U Ver 1.0
#=======================================================
import utime
import time
from machine import mem32,Pin
from i2cSlave import i2c_slave

unit = 0.005035477
# led pin config
led = Pin(25, Pin.OUT)  # GP25を出力モードに設定
# led off
led.value(0)
# ADC on
lm35 = machine.ADC(0)   # ADC0にLM35を接続

# i2c as slave
rp_i2c = i2c_slave(0, sda = 0, scl = 1, slaveAddress = 0x41)
rp_i2c.putWord(0)        # dummy write for bus lock
while True:
    cmd = 0
    val = 0
    temp = lm35.read_u16()  # read ADC
    if rp_i2c.any():
        cmd = rp_i2c.get()
        if cmd == 0x10 :
            while not rp_i2c.anyRead():
                pass
            rp_i2c.putWord(temp)
            #print('Temp:', temp * unit)
        elif cmd == 0x20 :
            val = rp_i2c.getWord()
            #print('val :', val)
            if val == 0 :
                led.value(0)
            elif val == 1 :
                led.value(1)


"""
    @Time    : 30/03/2023
    @Author  : qinghua
    @Software: PyCharm
    @File    : process_data.py

"""
import os.path
import pickle
import lgsvl
import pandas as pd
import json

from config import Config
from tqdm import tqdm

"""Processing deep scenario data"""

def get_ds_data(runner):
    """pair paths of scenarios and scenario attributes"""
    scene_attr_path_pairs = []
    for root, dirs, files in os.walk(Config.scenario_dir):
        depth = root.count(os.path.sep)
        if depth == 4:
            scenario_dirs = sorted([os.path.join(root, name) for name in os.listdir(root) if not name.endswith(".csv")])
            attribute_fnames = sorted([os.path.join(root, name) for name in os.listdir(root) if name.endswith(".csv")])
            scene_attr_path_pairs += list(zip(scenario_dirs, attribute_fnames))
    """
    pair contents of scenarios and scenario attributes by each run
    Output Example:
        [
            # run 0
            [
                # timestep 0
                (
                    # variables
                    [1.2,2.1,...]
                    # attribute
                    {"ttc":xxx,"tto":xxx}

                )
                # timestep 1
                ....
            ]
            # run 1
            ....
        ]
    """
    print(scene_attr_path_pairs)
    greedy_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                    "greedy-strategy" in scene_dir]
    random_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                    "random-strategy" in scene_dir]
    rl_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                "rl_based-strategy" in scene_dir]
    dto_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                 "reward-dto" in scene_dir]
    jerk_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                  "reward-jerk" in scene_dir]
    ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                 "reward-ttc" in scene_dir]
    greedy_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                        "greedy-strategy" in scene_dir and "reward-ttc" in scene_dir]
    random_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                        "random-strategy" in scene_dir and "reward-ttc" in scene_dir]
    rl_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                    "rl_based-strategy" in scene_dir and "reward-ttc" in scene_dir]
    r1_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                    "road1" in scene_dir and "reward-ttc" in scene_dir]
    r2_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                    "road2" in scene_dir and "reward-ttc" in scene_dir]
    r3_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                    "road3" in scene_dir and "reward-ttc" in scene_dir]
    r4_ttc_pairs = [(scene_dir, attr_path) for scene_dir, attr_path in scene_attr_path_pairs if
                    "road4" in scene_dir and "reward-ttc" in scene_dir]
    all_runs = get_all_runs(scene_attr_path_pairs)
    greedy_runs = get_all_runs(greedy_pairs)
    random_runs = get_all_runs(random_pairs)
    rl_runs = get_all_runs(rl_pairs)
    dto_runs = get_all_runs(dto_pairs)
    jerk_runs = get_all_runs(jerk_pairs)
    ttc_runs = get_all_runs(ttc_pairs)
    greedy_ttc_runs = get_all_runs(greedy_ttc_pairs)
    random_ttc_runs = get_all_runs(random_ttc_pairs)
    rl_ttc_runs = get_all_runs(rl_ttc_pairs)
    r1_ttc_runs = get_all_runs(r1_ttc_pairs)
    r2_ttc_runs = get_all_runs(r2_ttc_pairs)
    r3_ttc_runs = get_all_runs(r3_ttc_pairs)
    r4_ttc_runs = get_all_runs(r4_ttc_pairs)
    return all_runs, greedy_runs, random_runs, rl_runs, dto_runs, jerk_runs, ttc_runs, greedy_ttc_runs, random_ttc_runs, rl_ttc_runs, r1_ttc_runs, r2_ttc_runs, r3_ttc_runs, r4_ttc_runs

def get_all_runs(scene_attr_path_pairs):
    all_runs = []
    clean_key = lambda k: k.replace("Attribute[", "").replace("]", "")
    for scene_dir, attr_path in tqdm(scene_attr_path_pairs):
        runs = [[] for _ in range(20)]
        # get scenario attributes
        attr_pdf = pd.read_csv(attr_path)
        for row_id, row in attr_pdf.iterrows():
            run_id = int(row["Execution"])
            scene_fname = row["ScenarioID"] + ".deepscenario"
            attrs = row.to_dict()
            attrs = {clean_key(k): v for k, v in attrs.items()}
            runner.load_scenario_file(os.path.join(scene_dir, scene_fname))
            for i in range(1, 7):
                timeframe = runner.get_scene_by_timestep(timestep=i)
                timeframe = json.loads(timeframe)
                runs[run_id].append([timeframe, attrs])
        all_runs += runs
    return all_runs

class Vocab:
    def __init__(self):
        super(Vocab, self).__init__()
        self.id2str = []
        self.str2id = {}

    def add_if_not_exist(self, s):
        if s not in self.str2id:
            self.str2id[s] = len(self.id2str)
            self.id2str.append(s)

    def tokenize(self, s):
        return self.str2id[s]

    def size(self):
        return len(self.id2str)

def build_vocab(str_list):
    vocab = Vocab()
    for s in str_list:
        vocab.add_if_not_exist(s)
    return vocab

"""Process elevator data"""

def get_ele_passenger_profiles(fname):
    """
    Arrival Time; Arrival Floor; Destination Floor; Mass; Capacity;Loading time; Unloading time;Placeholder

    :param fname:
    :return:
    """
    colnames = ["arrival_time", "arrival_floor", "destination_floor", "mass", "capacity", "loading_time",
                "unloading_time", "placeholder"]
    pdf = pd.read_csv(fname, header=None, names=colnames, index_col=False)
    pdf = pdf[colnames[:-1]]  # remove last column
    pdf["arrival_time"] = pdf["arrival_time"].astype("float")
    pdf["arrival_floor"] = pdf["arrival_floor"].astype("int")
    pdf["destination_floor"] = pdf["destination_floor"].astype("int")
    return pdf

def get_ele_simulator_result(fname):
    """
    Document;Passenger;Source;Destination;ArrivalTime;LiftArrivalTime;DestinationArrivalTime
    """
    colnames = ["document", "id", "arrival_floor", "destination_floor", "arrival_time", "lift_arrival_time",
                "lift_destination_time"]
    pdf = pd.read_csv(fname, names=colnames, delimiter=";", skiprows=1)
    pdf = pdf[colnames[2:-1]]
    pdf["arrival_time"] = pdf["arrival_time"].astype("float")
    pdf["arrival_floor"] = pdf["arrival_floor"].astype("int")
    pdf["destination_floor"] = pdf["destination_floor"].astype("int")
    return pdf

def get_ele_data(dispatcher, peak_type):
    """

    :param dispatcher: list of integers
    :param peak_type: ["lunchpeak","uppeak"]
    :return: joined data of profiles and results
    """
    print(dispatcher, peak_type)
    peak_type = "LunchPeak" if "lunch" in peak_type.lower() else "Uppeak"
    profile_dir = Config.lunchpeak_profile_dir if peak_type == "LunchPeak" else Config.uppeak_profile_dir
    dispatcher_name = "Dispatch_00" if dispatcher == 0 else "Dispatch_M{:2d}".format(dispatcher)
    result_dir = os.path.join(Config.result_dir, dispatcher_name)
    if not os.path.exists(result_dir):
        return False
    result_pdfs = []
    for i in range(10):
        n_variable = "4" if peak_type == "LunchPeak" else "Four"
        profile_fname = "{}_mass_capacity_loading_unloading(CIBSE-office-{}){}.txt".format(n_variable, peak_type, i)
        result_fname = "{}_mass_capacity_loading_unloading(CIBSE-office-{}){}.csv".format(n_variable, peak_type, i)
        profile_pdf = get_ele_passenger_profiles(os.path.join(profile_dir, profile_fname))
        result_pdf = get_ele_simulator_result(os.path.join(result_dir, result_fname))
        result_pdf = profile_pdf.merge(result_pdf, how="right",
                                       on=["arrival_time", "arrival_floor", "destination_floor"])
        result_pdfs.append(result_pdf)
    result_pdf = pd.concat(result_pdfs)
    result_fname = "Dispatcher_{:2d}_{}.pkl".format(dispatcher, peak_type)
    pickle.dump(result_pdf,
        open( os.path.join(Config.elevator_save_dir, result_fname),"wb")
    )
    return result_pdf

if __name__ == '__main__':
    """collect data by runs"""
    # runner = lgsvl.scenariotoolset.ScenarioRunner()
    # all_runs, greedy_runs, random_runs, rl_runs, dto_runs, jerk_runs, ttc_runs, greedy_ttc_runs, random_ttc_runs, rl_ttc_runs, r1_ttc_runs, r2_ttc_runs, r3_ttc_runs, r4_ttc_runs = get_ds_data(
    #     runner)
    # pickle.dump(all_runs, open(Config.all_runs_pkl_path, "wb"))
    # pickle.dump(greedy_runs, open(Config.greedy_runs_pkl_path, "wb"))
    # pickle.dump(random_runs, open(Config.random_runs_pkl_path, "wb"))
    # pickle.dump(rl_runs, open(Config.rl_runs_pkl_path, "wb"))
    # pickle.dump(dto_runs, open(Config.dto_runs_pkl_path, "wb"))
    # pickle.dump(jerk_runs, open(Config.jerk_runs_pkl_path, "wb"))
    # pickle.dump(rl_runs, open(Config.rl_runs_pkl_path, "wb"))
    # pickle.dump(random_ttc_runs, open(Config.random_ttc_runs_pkl_path, "wb"))
    # pickle.dump(greedy_ttc_runs, open(Config.greedy_ttc_runs_pkl_path, "wb"))
    # pickle.dump(rl_ttc_runs, open(Config.rl_ttc_runs_pkl_path, "wb"))
    # pickle.dump(r1_ttc_runs, open(Config.r1_ttc_runs_pkl_path, "wb"))
    # pickle.dump(r2_ttc_runs, open(Config.r2_ttc_runs_pkl_path, "wb"))
    # pickle.dump(r3_ttc_runs, open(Config.r3_ttc_runs_pkl_path, "wb"))
    # pickle.dump(r4_ttc_runs, open(Config.r4_ttc_runs_pkl_path, "wb"))
    # process elevator data

    ele_names = ["dispatch_00_lunchpeak", "dipatcher_00_uppeak"]
    ele_names += ["dispatcher_{:02d}_lunchpeak_variant".format(i) for i in range(1, 100)]
    ele_names += ["dispatcher_{:02d}_uppeak_variant".format(i) for i in range(1, 100)]
    peak_types = ["lunchpeak", "uppeak"]
    for i in range(100):
        for peak_type in peak_types:
            pdf = get_ele_data(i, peak_type)


from flask import Flask,render_template,flash,redirect,session,url_for,logging,request,Blueprint,json,session
from flask_json import FlaskJSON, JsonError, json_response, as_json
from smartiot.bin.config.db_config import mysql
from smartiot.routes.route_Permissions.userPermissions import getPermissions
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
import time

iot_ultraSonic_bp = Blueprint(
    'iot_ultra-sonic_bp',
    __name__
)

#define led oin
led_pin = 7

@iot_ultraSonic_bp.route("/ultra",methods=['POST'])
def ultraSonic():

    try:
        content = request.get_json()
        action = content['action']
        userid = content['userId']
        endpoint = content['endPoint']
    except:
        #response
        return json_response(
        message="Internal server error",
        status = 500
        )
    permissions = getPermissions(userid,endpoint)

    print(str(permissions))

    if permissions is "granted":
        print('granted')
        if action == "measure":
            #mysql
            #execute query
            sql ="INSERT INTO logs(info,value,dataType,deviceName,deviceId,userId) VALUES('',%s,%s,%s,'2',%s)"
            #print(str(sql))
            #get data from sensor
            distance = measure()
            d=round(distance ,2)
            distance_cm = format(d)
#            print( "Distance : {0} cm".distance_cm)

            #create a cursur
            cur = mysql.connection.cursor()
            result  = cur.execute(sql,(distance_cm,"proximity",endpoint,userid))
            #commit to Datebase
            mysql.connection.commit()

            return json_response(
                distance = distance,
                message = "Distance in cm",
                status  =200
                )

        if action == "":#other fuctions
            #mysql
            #execute query
            sql ="INSERT INTO logs(info,value,dataType,deviceName,deviceId,userId) VALUES('',%s,%s,%s,'1',%s)"
            print(str(sql))
            #create a cursur
            cur = mysql.connection.cursor()
            result  = cur.execute(sql,("on","state",endpoint,userid))
            #commit to Datebase
            mysql.connection.commit()

            #close connection
            cur.close()
            GPIO.cleanup()

            return
            print('granted')

    if permissions is "denied":

        #mysql
        #execute query
        sql ="INSERT INTO logs(info,value,dataType,deviceName,deviceId,userId) VALUES(%s,'','',%s,'1',%s)"
        print(str(sql))
        #create a cursur
        cur = mysql.connection.cursor()
        result  = cur.execute(sql,("Permission Denied",endpoint,userid))
        #commit to Datebase
        mysql.connection.commit()
        #close connection
        cur.close()

        #response
        return json_response(
        distance = "",
        message="Permission denied for this user",
        status = 403
        )
        print('denied')

# measure distance

def measure():
    GPIO.setmode(GPIO.BCM)

    TRIG = 4
    ECHO  = 18

    GPIO.setup(TRIG , GPIO.OUT)
    GPIO.setup(ECHO , GPIO.IN)

    GPIO.output(TRIG , True)
    time.sleep(0.0001)
    GPIO.output(TRIG , False)

    while GPIO.input(ECHO) == False:
        start = time.time();

    while GPIO.input(ECHO) == True:
        end = time.time();

    sig_time = end-start

#cm:
    dis = sig_time/0.000058

    print('Dist : {} cm'.format(dis))

    GPIO.cleanup()

    return dis

def measure_average():
    # This function takes 3 measurements and
    # returns the average.
    distance1=measure()
    time.sleep(0.1)
    distance2=measure()
    time.sleep(0.1)
    distance3=measure()
    distance = distance1 + distance2 + distance3
    distance_avg = distance / 3
    return distance_avg


from vector_class import Vectors
import math as m

def main():
    #ask user for components of the first vector
    component_1=input("The first component of the vector is:")
    component_2=input("The second component of the vector is:")
    component_3=input("The third component of the vector is:")

    vector_1=[component_1,component_2,component_3]
    print("the first vector is"+str(vector_1))

    #ask user for components of the second vector
    component2_1=input("The first component of the second vector is:")
    component2_2=input("The second component of the second vector is:")
    component2_3=input("The third component of the second vector is:")

    vector_2=[component2_1,component2_2,component2_3]
    print("the second vector is"+str(vector_2))

    #ask user for a scalar scalar multiple, c
    c=input("my scalar multiple is:")

    #initialise the first vector as an instance of the class Vectors
    instance_vector=Vectors(vector_1)

    #use mag property of vectors to compute the magnitude of the first vector
    magnitude=instance_vector.mag
    print("the magnitude of the first vector is:"+str(magnitude))

    #use mag2 property of vectors to compute the squared magnitude of the first vector
    magnitude2=instance_vector.mag2
    print("the squared magnitude of the first vector is:"+str(magnitude2))

    #use class method to compute dot product of the two vectors
    dot_product=instance_vector.dot_prod(vector_2)
    print("the dot product of the two vectors is:"+str(dot_product))

    #find scalar multiple of first vector
    multiple=instance_vector.scalar_multiple(c)
    print("the scalar multiple of the first vector is:"+str(multiple))

    #use class method "cross" to compute cross product of the two vectors
    print("the cross product of the two vectors is:"+str(instance_vector.cross(vector_2)))

    #use class method "sum" to add the two vectors
    print("the sum of the two vectors is:"+str(instance_vector.sum(vector_2)))

    #use class method "diff" the subtract the first vector from the second
    print("the second vector minus the first is:"+str(instance_vector.diff(vector_2)))

    #check whether the two vectors are the same
    print("are the two vectors the same?"+str(instance_vector.same(vector_2)))

main()


import time
import numpy as np

from librosa import load, stft, istft, resample
from librosa.output import write_wav
from sklearn.cluster import MiniBatchKMeans, FeatureAgglomeration
from sklearn import datasets
import warnings

# import matplotlib.pyplot as plt

import mir_eval

import corpus

from scipy.io import loadmat

class beta_NTF(object):
    def __init__(self, W, H, X, A, sigma_b, Q, V, K_partition,
                 epochs=20, debug=False, beta=0):
        super(beta_NTF, self).__init__()

        # np.seterr(all='warn')
        #
        # warnings.filterwarnings('error')
        self._epochs = epochs
        self._debug = debug
        self._V = V
        self._W = W
        self._H = H
        self._A = A
        self._Q = Q
        self._sigma_b = sigma_b
        self._Xb = X
        self._K_partition = K_partition
        self.I, self.F, self.T = X.shape
        self.K = W.shape[1]
        self.J = Q.shape[0]
        self.IJ = self.I*self.J
        self.O = np.ones((1,self.T))
        self.source_ind = []
        for j in range(self.J):
            self.source_ind.append(np.arange(0,self.K/self.J)+(j*(self.K/self.J)))

    def train(self):
        for epoch in range(self._epochs):
            # print(epoch)
            sigma_ss = np.zeros((self.I,self.J,self.F,self.T))
            for i in range(self.I):
                sigma_ss[i,:,:,:] = self._V[:,:,:]
            sigma_ss = sigma_ss.reshape((self.IJ, self.F, self.T))

            sigma_x = np.zeros((self.I,self.I,self.F,self.T), dtype=complex)
            inv_sigma_x = np.zeros((self.I,self.I,self.F,self.T), dtype=complex)

            Gs = np.zeros((self.I,self.IJ,self.F,self.T), dtype=complex)
            s_hat = np.zeros((self.IJ, self.F, self.T), dtype=complex)
            bar_Rxs = np.zeros((self.I, self.IJ, self.F, self.T), dtype=complex)
            bar_Rss_full = np.zeros((self.IJ, self.IJ, self.F, self.T), dtype=complex)
            bar_Rxx = np.zeros((self.I, self.I, self.F, self.T), dtype=complex)
            bar_P = np.zeros((self.J, self.F, self.T))
            bar_A = np.zeros((self.I, self.F, self.K))
            Vc = np.zeros((self.F, self.T, self.K))

            W_prev = self._W
            H_prev = self._H
            A_prev = self._A
            sig_b_prev = self._sigma_b

            sigma_x[0,0,:,:] = np.matmul(self._sigma_b, self.O)
            sigma_x[1,1,:,:] = np.matmul(self._sigma_b, self.O)
            for ij in range(self.IJ):
                sigma_x[0,0,:,:] = sigma_x[0,0,:,:] + np.multiply(np.matmul(np.power(np.abs(self._A[0,ij,:].reshape((self.F, 1))), 2), self.O), sigma_ss[ij,:,:])
                sigma_x[0,1,:,:] = sigma_x[0,1,:,:] + np.multiply(np.matmul(np.multiply(self._A[0,ij,:], np.conj(self._A[1,ij,:])).reshape((self.F, 1)), self.O), sigma_ss[ij,:,:])
                sigma_x[1,0,:,:] = np.conj(sigma_x[0,1,:,:])
                sigma_x[1,1,:,:] = sigma_x[1,1,:,:] + np.multiply(np.matmul(np.power(np.abs(self._A[1,ij,:].reshape((self.F, 1))), 2), self.O), sigma_ss[ij,:,:])

            try:
                det_sigma_x = np.multiply(sigma_x[0, 0, :, :], sigma_x[1,1,:,:]) - np.power(np.abs(sigma_x[0,1,:,:]),2)
                inv_sigma_x [0,0,:,:] = np.divide(sigma_x[1,1,:,:], det_sigma_x)
                inv_sigma_x [0,1,:,:] = np.negative(np.divide(sigma_x[0,1,:,:], det_sigma_x))
                inv_sigma_x [1,0,:,:] = np.conj(inv_sigma_x [0,1,:,:])
                inv_sigma_x [1,1,:,:] = np.divide(sigma_x[0,0,:,:], det_sigma_x)
            except Warning:
                scale = np.sum(self._W, axis=0)
                print(scale)

                # print(self._H)

                print(det_sigma_x)
            #correct till here
            for ij in range(self.IJ):
                Gs[0,ij,:,:] = np.multiply(np.multiply(np.matmul(np.conj(self._A[0,ij,:].reshape((self.F, 1))), self.O), inv_sigma_x [0,0,:,:]) + \
                                           np.multiply(np.matmul(np.conj(self._A[1,ij,:].reshape((self.F, 1))), self.O), inv_sigma_x [1,0,:,:]),
                                           sigma_ss[ij,:,:])
                Gs[1,ij,:,:] = np.multiply(np.multiply(np.matmul(np.conj(self._A[0,ij,:].reshape((self.F, 1))), self.O), inv_sigma_x [0,1,:,:]) + \
                                           np.multiply(np.matmul(np.conj(self._A[1,ij,:].reshape((self.F, 1))), self.O), inv_sigma_x [1,1,:,:]),
                                           sigma_ss[ij,:,:])
                s_hat[ij,:,:] = np.multiply(Gs[0,ij,:,:], self._Xb[0,:,:]) + np.multiply(Gs[1,ij,:,:], self._Xb[1,:,:])
                bar_Rxs[0, ij, :, :] = np.multiply(self._Xb[0,:,:], np.conj(s_hat[ij,:,:]))
                bar_Rxs[1, ij, :, :] = np.multiply(self._Xb[1,:,:], np.conj(s_hat[ij,:,:]))
            # correct till here

            for j1 in range(self.IJ):
                for j2 in range(self.IJ):
                    bar_Rss_full[j1, j2, :, :] = np.multiply(s_hat[j1, :, :], np.conj(s_hat[j2, :, :])) - \
                                                 np.multiply(np.multiply(Gs[0, j1, :, :], np.matmul(self._A[0,j2,:].reshape((self.F, 1)), self.O)) + \
                                                             np.multiply(Gs[1, j1, :, :], np.matmul(self._A[1,j2,:].reshape((self.F, 1)), self.O)),
                                                             sigma_ss[j2,:,:])
                bar_Rss_full[j1,j1,:,:] = bar_Rss_full[j1,j1,:,:] + sigma_ss[j1,:,:]
            # need to check bar_Rss_full calculation very carefully there is a tiny error
            for j in range(self.J):
                start_index = (j*self.I)
                end_index = (j+1) * self.I
                temp_P = np.zeros((self.I, self.F, self.T))
                P_i = 0
                for i in range(start_index, end_index):
                    temp_P[P_i, :, :] = np.real(bar_Rss_full[i,i,:,:])
                    P_i = P_i + 1
                bar_P[j, :, :] = np.mean(temp_P, axis=0)
            # correct till here
            bar_Rxx[0,0,:,:] = np.power(np.abs(self._Xb[0,:,:]),2)
            bar_Rxx[0,1,:,:] = np.multiply(self._Xb[0,:,:], np.conj(self._Xb[1,:,:]))
            bar_Rxx[1,0,:,:] = np.conj(bar_Rxx[0,1,:,:])
            bar_Rxx[1,1,:,:] = np.power(np.abs(self._Xb[1,:,:]),2)
            # outers are correct middle has a small error

            for f in range(self.F):
                self._A[:,:,f] = np.matmul(np.mean(bar_Rxs[:,:,f,:], axis=2),np.linalg.inv(np.mean(bar_Rss_full[:,:,f,:], axis=2)))

            for f in range(self.F):
                self._sigma_b[f] = 0.5 * np.real(np.trace(np.mean(bar_Rxx[:,:,f,:],axis=2) - \
                                   np.matmul(self._A[:,:,f], np.conj(np.transpose(np.mean(bar_Rxs[:,:,f,:],axis=2)))) - \
                                   np.matmul(np.mean(bar_Rxs[:,:,f,:],axis=2), np.conj(np.transpose(self._A[:,:,f]))) + \
                                   np.matmul(np.matmul(self._A[:,:,f], np.mean(bar_Rss_full[:,:,f,:],axis=2)),
                                             np.conj(np.transpose(self._A[:,:,f])))))

            # correct till here
            self.calculate_V()

            VP_neg = np.multiply(np.power(self._V, -2), bar_P)
            V_pos = np.power(self._V, -1)

            WoH = np.zeros((self.F, self.T, self.K))
            for k in range(self.K):
                W_k = self._W[:,k].reshape(-1,1)
                H_k = self._H[k,:].reshape(1,-1)
                WoH[:,:,k] = np.matmul(W_k, H_k)

            Q_num = np.matmul(VP_neg.reshape((self.J, self.F*self.T)), WoH.reshape((self.F*self.T, self.K)))
            Q_den = np.matmul(V_pos.reshape((self.J, self.F*self.T)), WoH.reshape((self.F*self.T, self.K)))
            self._Q = np.multiply(self._Q, np.divide(Q_num, Q_den))

            QoH = self.calculate_V()

            VP_neg = np.multiply(np.power(self._V, -2), bar_P)
            V_pos = np.power(self._V, -1)
            W_num = np.matmul(np.moveaxis(VP_neg, 1, 0).reshape((self.F, self.J*self.T)), QoH.reshape((self.J*self.T, self.K)))
            W_den = np.matmul(np.moveaxis(V_pos, 1, 0).reshape((self.F, self.J*self.T)), QoH.reshape((self.J*self.T, self.K)))
            self._W = np.multiply(self._W, np.divide(W_num, W_den))

            QoW = np.zeros((self.J, self.F, self.K))
            for k in range(self.K):
                Q_k = self._Q[:,k].reshape((-1, 1))
                W_k = self._W[:,k].reshape((1,-1))
                QoW[:,:,k] = np.matmul(Q_k, W_k)

            self.calculate_V()

            VP_neg = np.multiply(np.power(self._V, -2), bar_P)
            V_pos = np.power(self._V, -1)

            H_num = np.matmul(VP_neg.reshape((self.J*self.F,self.T)).transpose(), QoW.reshape((self.J*self.F, self.K)))
            H_den = np.matmul(V_pos.reshape((self.J*self.F,self.T)).transpose(), QoW.reshape((self.J*self.F, self.K)))
            self._H = np.multiply(self._H, np.divide(H_num, H_den).transpose())
            # small error in V and H

            for j in range(self.J):
                nonzero_f_ind = np.nonzero(self._A[0, j, :])
                self._A[1, j, nonzero_f_ind] = np.divide(self._A[1, j, nonzero_f_ind], self.sign(self._A[0,j,nonzero_f_ind]))
                self._A[0, j, nonzero_f_ind] = np.divide(self._A[0, j, nonzero_f_ind], self.sign(self._A[0,j,nonzero_f_ind]))

                A_scale = np.power(np.abs(self._A[0,j,:]),2) + np.power(np.abs(self._A[1,j,:]),2)
                self._A[:, j,:] = np.divide(self._A[:, j,:], np.tile(np.sqrt(A_scale).reshape(1,-1),(self.I,1)))
                self._W[:,self.source_ind[j]] = np.multiply(self._W[:,self.source_ind[j]], np.matmul(A_scale.reshape(-1,1),np.ones((1,len(self.source_ind[j])))))
            #
            # print(self._A[0,0,0])
            # print(self._A[0,1,1])
            # print(self._A[1,0,0])
            # print(self._A[1,1,1])

            scale = np.sum(self._Q, axis=0)
            self._Q = np.multiply(self._Q, np.tile(np.power(scale,-1),(self.J,1)))
            self._W = np.multiply(self._W, np.tile(scale,(self.F,1)))

            scale = np.sum(self._W, axis=0).reshape(1,-1)

            self._W = np.multiply(self._W, np.tile(np.power(scale,-1),(self.F,1)))
            self._H = np.multiply(self._H, np.tile(scale.transpose(),(1,self.T)))
            #
            self.calculate_V()
            # print(self._V[0,0,0])
            # print(self._V[0,1,1])
            # print(self._V[1,0,0])
            # print(self._V[1,1,1])

            criterion = np.sum(np.divide(bar_P, self._V) - np.log(np.divide(bar_P, self._V))) - self.J*self.F*self.T

    def sign(self, x):
        return np.divide(x,np.abs(x))

    def calculate_V(self):
        QoH = np.zeros((self.J, self.T, self.K))
        for k in range(self.K):
            Q_k = self._Q[:,k].reshape((-1, 1))
            H_k = self._H[k,:].reshape((1,-1))
            QoH[:,:,k] = np.matmul(Q_k, H_k)

        self._V = np.zeros((self.J, self.F, self.T))
        for j in range(self.J):
            self._V[j, :, :] = np.matmul(self._W, QoH[j,:,:].reshape((self.T, self.K)).transpose())

        return QoH

    def reconstruct(self):
        Y = np.zeros((self.I,self.J,self.F,self.T), dtype=complex)
        for t in range(self.T):
            for f in range(self.F):
                RV = np.zeros((self.I, self.I))
                for j in range(self.J):
                    start_index = (j*self.I)
                    end_index = (j+1) * self.I
                    RV = RV + (np.matmul(self._A[:,start_index:end_index,f],np.conj(np.transpose(self._A[:,start_index:end_index,f]))) * self._V[j,f,t])
                for j in range(self.J):
                    start_index = (j*self.I)
                    end_index = (j+1) * self.I
                    R = np.matmul(self._A[:,start_index:end_index,f],np.conj(np.transpose(self._A[:,start_index:end_index,f])))
                    Y[:,j,f,t] = np.matmul(np.matmul((R * self._V[j,f,t]), np.linalg.inv(RV)), self._Xb[:,f,t])

        return Y

    def getAV(self):
        return self._A, self._V

if __name__ == '__main__':
    # I = 2
    # F = 50
    # T = 200
    # J = 2
    # IJ = I * J
    # K_partition = np.asarray([20,20])
    # K = np.sum(K_partition)
    # X = np.random.randn(I,F,T)
    # V = np.random.rand(I,F,T)
    # mix_psd = 0.5 * (np.mean(np.power(np.abs(X[0,:,:]),2) + np.power(np.abs(X[1,:,:]),2),axis=1))
    # mix_psd = mix_psd.reshape((-1, 1))
    # A = 0.5 * np.multiply(1.9 * np.abs(np.random.randn(I,IJ,F)) + 0.1 * np.ones((I,IJ,F)),np.sign(np.random.randn(I,IJ,F) + 1j *np.random.randn(I,IJ,F)))
    # W = 0.5 * np.multiply(np.abs(np.random.randn(F,K)) + np.ones((F,K)), np.matmul(mix_psd, np.ones((1,K))))
    # H = 0.5 * np.abs(np.random.randn(K,T)) + np.ones((K,T))
    # Q = 0.5 * np.abs(np.random.randn(J,K)) + np.ones((J,K))
    # sigma_b = mix_psd / 100
    #
    # QoH = np.zeros((J, T, K))
    # for k in range(K):
    #     Q_k = Q[:,k].reshape((-1, 1))
    #     H_k = H[k,:].reshape((1,-1))
    #     QoH[:,:,k] = np.matmul(Q_k, H_k)
    #
    # V = np.zeros((J, F, T))
    # for j in range(J):
    #     V[j, :, :] = np.matmul(W, QoH[j,:,:].reshape((K, T)))
    K_partition = np.asarray([20,20,20])
    A = loadmat('mat_files/saveA.mat')['A']
    W = loadmat('mat_files/saveW.mat')['W']
    H = loadmat('mat_files/saveH.mat')['H']
    Q = loadmat('mat_files/saveQ.mat')['Q']
    V = loadmat('mat_files/saveV.mat')['V']
    X = loadmat('mat_files/saveX.mat')['x']
    sigma_b = loadmat('mat_files/saveSig_b.mat')['sig_b']
    bn = beta_NTF(W, H, X, A, sigma_b, Q, V, K_partition, epochs=22)
    bn.train()
    bn.reconstruct()


# Given the edges of a directed graph where edges[i] = [ai, bi] indicates there is an edge between nodes ai and bi, and two nodes source and destination of this graph, determine whether or not all paths starting from source eventually, end at destination, that is:

# At least one path exists from the source node to the destination node
# If a path exists from the source node to a node with no outgoing edges, then that node is equal to destination.
# The number of possible paths from source to destination is a finite number.
# Return true if and only if all roads from source lead to destination.

# Example 1:

# Input: n = 3, edges = [[0,1],[0,2]], source = 0, destination = 2
# Output: false
# Explanation: It is possible to reach and get stuck on both node 1 and node 2.
# Example 2:

# Input: n = 4, edges = [[0,1],[0,3],[1,2],[2,1]], source = 0, destination = 3
# Output: false
# Explanation: We have two possibilities: to end at node 3, or to loop over node 1 and node 2 indefinitely.
# Example 3:

# Input: n = 4, edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 3
# Output: true
# Example 4:

# Input: n = 3, edges = [[0,1],[1,1],[1,2]], source = 0, destination = 2
# Output: false
# Explanation: All paths from the source node end at the destination node, but there are an infinite number of paths, such as 0-1-2, 0-1-1-2, 0-1-1-1-2, 0-1-1-1-1-2, and so on.
# Example 5:

# Input: n = 2, edges = [[0,1],[1,1]], source = 0, destination = 1
# Output: false
# Explanation: There is infinite self-loop at destination node.

# Constraints:

# 1 <= n <= 104
# 0 <= edges.length <= 104
# edges.length == 2
# 0 <= ai, bi <= n - 1
# 0 <= source <= n - 1
# 0 <= destination <= n - 1
# The given graph may have self-loops and parallel edges.
class Solution:
    def leadsToDestination(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool:
        graph = {}
        for s, e in edges:
            graph.setdefault(s, []).append(e)

        non_destination = False
        found_path = False
        is_loop = False
        seen = {source}

        def bt(s):
            nonlocal is_loop, non_destination, found_path
            if is_loop or non_destination:
                return
            nexts = graph.get(s, [])
            if not nexts:
                if s != destination:
                    non_destination = True
                else:
                    found_path = True
                return
            for n in nexts:
                if n in seen:
                    is_loop = True
                    return
                else:
                    seen.add(n)
                    bt(n)
                    seen.remove(n)
        bt(source)
        return found_path and not is_loop and not non_destination

1059 All Paths from Souce Lead to Destination.py


import sqlite3
import urllib
from bs4 import BeautifulSoup
from datetime import datetime

conn = sqlite3.connect('pftcrawlerdb.sqlite')
cur = conn.cursor()

# Setup database
cur.executescript('''
DROP TABLE IF EXISTS Podcasts;
DROP TABLE IF EXISTS Appearances;

CREATE TABLE Podcasts (
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    name   TEXT UNIQUE
);

CREATE TABLE Appearances (
    id          INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    podcast_id  INTEGER,
    episode     INTEGER,
    title       STRING,
    date        DATETIME,
    link        TEXT UNIQUE)
''')

url = raw_input('Enter - ')
if len(url) == 0 : url = 'http://www.earwolf.com/person/paul-f-tompkins/'
html = urllib.urlopen(url).read()

soup = BeautifulSoup(html, 'lxml')

divTags = soup("div", {"class":"ep-description"})

# comment out when not debugging
# i = int(raw_input('Enter iterations to run: '))

for dtag in divTags:

    # comment out when not debugging
    # if i == 0: break
    # i -= 1

    # clear title and link list vars
    eptitle = ''
    eplink = ''
    podcast = ''
    epnum = ''
    epdatestr = ''
    epdate = datetime

    # get ep title
    eptitle = (dtag.parent.h1.text).replace(':', ' - ')

    # get ep link
    eplink = dtag.a.get('href', None)

    # parse text in span texts to a list & convert to ascii
    spanTags = dtag.find_all('span')
    tagTexts = []
    for tag in spanTags : tagTexts.append((tag.text).encode('ascii', 'ignore'))

    # get podcast name
    podcast = tagTexts[0].split('#')[0].strip()

    # get episode number
    epnum = tagTexts[0].split('#')[1].strip()

    # get episode date or assign earliest date if date string not parsable
    epdatestr = tagTexts[1].strip()
    try:
        epdate = datetime.strptime(epdatestr, '%B %d, %Y')
    except:
        epdate = datetime.min

    # write values to database
    cur.execute('''INSERT OR IGNORE INTO Podcasts (name)
        VALUES ( ? )''', ( podcast, ) )

    cur.execute('SELECT id FROM Podcasts WHERE name = ? ', (podcast, ))
    pod_id = cur.fetchone()[0]

    cur.execute('''INSERT OR REPLACE INTO Appearances
        (podcast_id, episode, title, date, link) VALUES ( ?, ?, ?, ?, ? )''',
        ( pod_id, epnum, eptitle, epdate, eplink ) )

conn.commit()

#     print alleps
#
#
# if len(titleerror) != 0: print 'There were title errors: ', titleerror
#
# if len(linkerror) != 0: print 'There were link errors: ', linkerror
#
#
# for key, value in alleps.items(): print value[0]


from mixer.auto import mixer
from rest_framework.test import APITestCase, APIClient

from stock_setup_info.factory import IndustryFactory
from stock_setup_info.models import Industry

# Create your tests here.

class BaseViewTest(APITestCase):
    client = APIClient()

    @staticmethod
    def create_industry(name="", exchange_code="", sync_flag="", logo=""):
        if name != "" and exchange_code != "":
            Industry.objects.create(
                name=name, exchange_code=exchange_code, sync_flag=sync_flag, logo=logo
            )

    def setUp(self):
        self.create_industry("Agriculture", "AG", "0", "0")
        self.create_industry("Finance", "AG", "0", "0")
        self.industry = IndustryFactory()

class AllModelCreatedTest(BaseViewTest):
    def test_model_can_create_list_of_industry(self):
        """
        This test ensures that all the industries added in the setup method exists
        """
        new_count = Industry.objects.count()
        self.assertNotEqual(0, new_count)

    def test_model_via_mixer(self):
        obj = mixer.blend("stock_setup_info.models.Industry")
        assert obj.pk > 1, "Should create an Industry Instance"


def dimensoes(matriz: list) -> str:
    return f"{len(matriz)}X{len(matriz[0])}"

def soma_matrizes(m1: list, m2: list) -> list:
    if dimensoes(m1) != dimensoes(m2):
        return False
    result = []
    for x in range(len(m1)):
        l = []
        for i_k, i_v in enumerate(m1[x]):
            for j_k, j_v in enumerate(m2[x]):
                if i_k == j_k:
                    l.append(i_v + j_v)
        result.append(l)
    return result


from scripts.hackerrank.isLeapYear import is_leap, is_leap2, is_leap3, is_leap4

class Test:

    test_cases = [
        [2004, True],
        [2008, True],
        [2012, True],
        [2016, True],
        [2005, False],
        [2009, False],
        [2013, False],
        [2017, False],
    ]
    testable_functions = [
        is_leap, is_leap2, is_leap3, is_leap4
    ]

    def test_is_leap(self):
        for f in self.testable_functions:
            for case, expected in self.test_cases:
                assert expected == f(case)


import emp,pickle
f=open("emp.dat","wb")
n=int(input("enter the number"))
for i in range(n):
    eid=int(input("enter"))
    name=input("enter teh name")
    sal=float(input("enter the sal"))
    e=emp.Emp_class(eid,name,sal)
    pickle.dump(e,f)#this will enter the data in emp.dat
    # print(type(e))
f.close()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
        self.result = 0
        oldPaths = defaultdict(int)
        oldPaths[0] = 1
        self.dfs(root, targetSum, 0, oldPaths)
        return self.result

    def dfs(self, root, targetSum, currPathSum, oldPaths):
        # exit condition
        if root == None:
            return

        currPathSum += root.val
        oldPathWanted = currPathSum - targetSum

        self.result += oldPaths[oldPathWanted]
        oldPaths[currPathSum] = oldPaths[currPathSum] + 1

        # dfs children
        self.dfs(root.left, targetSum, currPathSum, oldPaths)
        self.dfs(root.right, targetSum, currPathSum, oldPaths)

        oldPaths[currPathSum] -= 1


# This file is part of avahi.
#
# avahi is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# avahi is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
# License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with avahi; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA.

# Some definitions matching those in avahi-common/defs.h

import dbus

SERVER_INVALID, SERVER_REGISTERING, SERVER_RUNNING, SERVER_COLLISION, SERVER_FAILURE = range(0, 5)

ENTRY_GROUP_UNCOMMITED, ENTRY_GROUP_REGISTERING, ENTRY_GROUP_ESTABLISHED, ENTRY_GROUP_COLLISION, ENTRY_GROUP_FAILURE = range(0, 5)

DOMAIN_BROWSER_BROWSE, DOMAIN_BROWSER_BROWSE_DEFAULT, DOMAIN_BROWSER_REGISTER, DOMAIN_BROWSER_REGISTER_DEFAULT, DOMAIN_BROWSER_BROWSE_LEGACY = range(0, 5)

PROTO_UNSPEC, PROTO_INET, PROTO_INET6  = -1, 0, 1

IF_UNSPEC = -1

PUBLISH_UNIQUE = 1
PUBLISH_NO_PROBE = 2
PUBLISH_NO_ANNOUNCE = 4
PUBLISH_ALLOW_MULTIPLE = 8
PUBLISH_NO_REVERSE = 16
PUBLISH_NO_COOKIE = 32
PUBLISH_UPDATE = 64
PUBLISH_USE_WIDE_AREA = 128
PUBLISH_USE_MULTICAST = 256

LOOKUP_USE_WIDE_AREA = 1
LOOKUP_USE_MULTICAST = 2
LOOKUP_NO_TXT = 4
LOOKUP_NO_ADDRESS = 8

LOOKUP_RESULT_CACHED = 1
LOOKUP_RESULT_WIDE_AREA = 2
LOOKUP_RESULT_MULTICAST = 4
LOOKUP_RESULT_LOCAL = 8
LOOKUP_RESULT_OUR_OWN = 16
LOOKUP_RESULT_STATIC = 32

SERVICE_COOKIE = "org.freedesktop.Avahi.cookie"
SERVICE_COOKIE_INVALID = 0

DBUS_NAME = "org.freedesktop.Avahi"
DBUS_INTERFACE_SERVER = DBUS_NAME + ".Server"
DBUS_PATH_SERVER = "/"
DBUS_INTERFACE_ENTRY_GROUP = DBUS_NAME + ".EntryGroup"
DBUS_INTERFACE_DOMAIN_BROWSER = DBUS_NAME + ".DomainBrowser"
DBUS_INTERFACE_SERVICE_TYPE_BROWSER = DBUS_NAME + ".ServiceTypeBrowser"
DBUS_INTERFACE_SERVICE_BROWSER = DBUS_NAME + ".ServiceBrowser"
DBUS_INTERFACE_ADDRESS_RESOLVER = DBUS_NAME + ".AddressResolver"
DBUS_INTERFACE_HOST_NAME_RESOLVER = DBUS_NAME + ".HostNameResolver"
DBUS_INTERFACE_SERVICE_RESOLVER = DBUS_NAME + ".ServiceResolver"
DBUS_INTERFACE_RECORD_BROWSER = DBUS_NAME + ".RecordBrowser"

def byte_array_to_string(s):
    r = ""

    for c in s:

        if c >= 32 and c < 127:
            r += "%c" % c
        else:
            r += "."

    return r

def txt_array_to_string_array(t):
    l = []

    for s in t:
        l.append(byte_array_to_string(s))

    return l

def string_to_byte_array(s):
    r = []

    for c in s:
        r.append(dbus.Byte(ord(c)))

    return r

def string_array_to_txt_array(t):
    l = []

    for s in t:
        l.append(string_to_byte_array(s))

    return l

def dict_to_txt_array(txt_dict):
    l = []

    for k,v in txt_dict.items():
        l.append(string_to_byte_array("%s=%s" % (k,v)))

    return l


'''
https://www.codewars.com/kata/52efefcbcdf57161d4000091/

The main idea is to count all the occurring characters in a string. If you have a string like aba, then the result should be {'a': 2, 'b': 1}.

What if the string is empty? Then the result should be empty object literal, {}.
'''

# my solution
def count(str):
    dict = {}

    for i in str:
        if i in dict:
            dict[i] += 1
        else:
            dict[i] = 1

    return dict

#! alternative-solution
from collections import Counter

def count(string):
    return Counter(string)
# been seeing is Counter() all around lately. And I have the feeling this
# is more pythonic way to count a key-value

6 kyu/Count characters in your string.py


from matplotlib import pyplot as plt
from matplotlib import font_manager
# 设置中文
# !本字体路径为本机一款字体路径,运行时可任意替换为系统中的一款中文字体路径,必须为中文字体,系统不限:Windows/macOS/Linux
my_font = font_manager.FontProperties(
    fname='C:\Windows\Fonts\STFANGSO.TTF')
# 设置图片大小
plt.figure(figsize=(20, 8), dpi=80)

# 数据
x_3 = range(1, 32)
x_10 = range(51, 82)
y_1 = [11, 17, 16, 11, 12, 11, 12, 6, 6, 7, 8, 9, 12, 15, 14, 17, 18,
       21, 16, 17, 20, 14, 15, 15, 15, 19, 21, 22, 22, 22, 23]  # 3月份
y_2 = [26, 26, 28, 19, 21, 17, 16, 19, 18, 20, 20, 19, 22, 23, 17, 20,
       21, 20, 22, 15, 11, 15, 5, 13, 17, 10, 11, 13, 12, 13, 6]  # 10月份

# 设置坐标刻度
_x = list(x_3)+list(x_10)  # 将两个横坐标转化为列表相加,列表的值刚好中间缺少值,形成和坐标点的对应
_xticks_ = ['3月{}日'.format(i) for i in range(1, 32)]
_xticks_ += ['10月{}日'.format(i) for i in range(1, 32)]
plt.xticks(_x[::3], _xticks_[::3], fontproperties=my_font,
           rotation=45)  # _xticks_和_x一一对应 坐标刻度太密集可以将列表取步长

# 设置坐标轴描述
plt.xlabel("时间", fontproperties=my_font)
plt.ylabel("温度(℃)", fontproperties=my_font)
plt.title("3月和10月温度比较图", fontproperties=my_font)

# 绘图
plt.scatter(x_3, y_1, label="3月", color='r')
plt.scatter(x_10, y_2, label="10月")

# ?添加图例 添加图例必须在画图之后!!!!!!
plt.legend(prop=my_font, loc='upper left')
# 展示
plt.show()


import logging
import time

from aiogram import F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery, InlineKeyboardMarkup, Message
from sqlalchemy.orm import Session

from keyboards.keyboards import (
    back_keyboard,
    pagination_keyboard,
    yes_no_keyboard,
)
from keyboards.methodist_keyboards import (
    add_category_keyboard,
    category_keyboard_methodist,
    confirm_category_keyboard,
    edit_category_keyboard,
    methodist_profile_keyboard,
)
from lexicon.lexicon import BUTTONS, LEXICON
from utils.db_commands import (
    category_deleting,
    create_category,
    get_all_categories,
    select_user,
    set_category_param,
)
from utils.pagination import PAGE_SIZE
from utils.states_form import AddCategory, CategoryList, EditCategory
from utils.utils import generate_categories_list, get_category_info

logger = logging.getLogger(__name__)

methodist_category_router = Router()

# Обработчики добавления категории
@methodist_category_router.message(
    F.text.in_(
        [
            BUTTONS["RU"]["add_category"],
            BUTTONS["TT"]["add_category"],
            BUTTONS["EN"]["add_category"],
        ]
    )
)
async def add_category(message: Message, session: Session):
    """Обработчик кнопки Добавить категорию."""
    try:
        user = select_user(session, message.from_user.id)
        language = user.language
        lexicon = LEXICON[language]
        await message.answer(
            lexicon["add_category"],
            reply_markup=add_category_keyboard(language),
        )
    except KeyError as err:
        logger.error(f"Ошибка в ключе при добавлении категории в базу: {err}")
    except Exception as err:
        logger.error(f"Ошибка при добавлении категории в базу: {err}")

@methodist_category_router.callback_query(F.data == "ready_category")
async def start_add_category(
    query: CallbackQuery, state: FSMContext, session: Session
):
    """Начинает сценарий добавления категории в базу."""
    try:
        await query.answer()
        await state.clear()
        user = select_user(session, query.from_user.id)
        language = user.language
        lexicon = LEXICON[language]
        await state.update_data(language=language)
        await state.set_state(AddCategory.name)
        await query.message.answer(lexicon["send_category_name"])
        await query.message.delete()
    except KeyError as err:
        logger.error(f"Ошибка в ключе при запросе названия категории: {err}")
    except Exception as err:
        logger.error(f"Ошибка при запросе названия категории: {err}")

@methodist_category_router.message(AddCategory.name)
async def process_add_category_name(
    message: Message, state: FSMContext, session: Session
):
    """Обработчик принимает имя категории, сохраняет категорию в БД.

    Просит прислать сообщение.
    Отправляет собранные данные для подтверждения корректности
    или для перехода к редактированию.
    """
    try:
        data = await state.get_data()
        await state.clear()
        language = data["language"]
        lexicon = LEXICON[language]
        data["name"] = message.text
        category_created = create_category(session, data)
        if not category_created:
            await message.answer(
                lexicon["error_adding_category"],
                reply_markup=methodist_profile_keyboard(language),
            )
            return
        category_info = get_category_info(data["name"], lexicon, session)
        info = category_info["info"]
        category_id = category_info["id"]
        # Собираем пагинацию для списка категорий, если пользователь
        # перейдет к редактированию созданной категории
        categories = get_all_categories(session)
        page_info = generate_categories_list(
            categories=categories,
            lexicon=lexicon,
            current_page=0,
            page_size=PAGE_SIZE,
        )
        categories_ids = page_info["categories_ids"]
        new_current_page = page_info["current_page"]
        query_id = None
        for key in categories_ids.keys():
            if categories_ids[key] == categories_ids:
                query_id = key
        await state.set_state(EditCategory.confirm_task)
        await state.update_data(
            category_id=category_id,
            query_id=query_id,
            current_page=new_current_page,
            task_info=page_info,
            language=language,
        )
        # Сообщаем пользователю, что сейчас покажем, что получилось
        await message.answer(lexicon["confirm_adding_category"])
        time.sleep(2)
        # Показываем, что получилось
        await message.answer(
            info, reply_markup=confirm_category_keyboard(language)
        )
    except KeyError as err:
        logger.error(
            f"Ошибка в ключе при запросе подтверждения категории: {err}"
        )
    except Exception as err:
        logger.error(f"Ошибка при запросе подтверждения категории: {err}")

@methodist_category_router.callback_query(F.data == "edit_category")
async def process_edit_category(query: CallbackQuery, state: FSMContext):
    """Обарботчик инлайн кнопки Редактировать категорию.

    Начинает сценарий внесения изменений в базу.
    """
    try:
        await query.answer()
        data = await state.get_data()
        language = data["language"]
        query_id = data["query_id"]
        lexicon = LEXICON[language]
        await query.message.answer(
            lexicon["start_edit_category"],
            reply_markup=edit_category_keyboard(language, cd=query_id),
        )
        await query.message.delete()
    except KeyError as err:
        logger.error(
            f"Ошибка в ключе при начале редактирования категории: {err}"
        )
    except Exception as err:
        logger.error(f"Ошибка при начале редактирования категории: {err}")

@methodist_category_router.callback_query(F.data == "edit_category_name")
async def edit_category_name(query: CallbackQuery, state: FSMContext):
    """Обработчик создает состояние для смены названия категории.

    Просит прислать сообщение.
    """
    try:
        await query.answer()
        data = await state.get_data()
        await state.set_state(EditCategory.name)
        language = data["language"]
        lexicon = LEXICON[language]
        await query.message.answer(lexicon["edit_category_name"])
        await query.message.delete()
    except KeyError as err:
        logger.error(
            "Ошибка в ключевом слове при запросе нового "
            f"названия категории: {err}"
        )
    except Exception as err:
        logger.error(f"Ошибка при запросе нового названия категории: {err}")

@methodist_category_router.message(EditCategory.name)
async def process_edit_name(
    message: Message, state: FSMContext, session: Session
):
    """Обрабатывает сообщение для изменения названия категории."""
    try:
        data = await state.get_data()
        language = data["language"]
        query_id = data["query_id"]
        lexicon = LEXICON[language]
        category_saved = set_category_param(
            session, category_id=data["category_id"], name=message.text
        )
        if not category_saved:
            await message.answer(
                lexicon["error_adding_category"],
                reply_markup=methodist_profile_keyboard(language),
            )
            return
        await message.answer(
            lexicon["category_edited"],
            reply_markup=edit_category_keyboard(language, cd=query_id),
        )
    except KeyError as err:
        logger.error(
            f"Ошибка в ключевом слове при изменении названия категории: {err}"
        )
    except Exception as err:
        logger.error(f"Ошибка при изменении названия категории: {err}")

@methodist_category_router.callback_query(
    F.data.in_({"back_to_category_list", "category:next", "category:previous"})
)
async def show_category_list_callback(query: CallbackQuery, state: FSMContext):
    """Обарботчик кнопки Посмотреть/редактировать категории.

    Показывает все созданные категории с пагинацией.
    """
    try:
        await query.answer()
        data = await state.get_data()
        categories = data["task_info"]["categories"]
        current_page = data["current_page"]
        language = data["language"]
        lexicon = LEXICON[language]
        if query.data == "category:next":
            current_page += 1
        elif query.data == "category:previous":
            current_page -= 1
        page_info = generate_categories_list(
            categories=categories,
            lexicon=lexicon,
            current_page=current_page,
            page_size=PAGE_SIZE,
            methodist=True,
        )
        msg = page_info["msg"]
        first_item = page_info["first_item"]
        final_item = page_info["final_item"]
        new_current_page = page_info["current_page"]
        lk_button = {
            "text": BUTTONS[language]["lk"],
            "callback_data": "profile",
        }
        await state.set_state(CategoryList.categories)
        await state.update_data(
            categories=categories,
            current_page=new_current_page,
            task_info=page_info,
        )
        if query.data == "back_to_category_list":
            # Возвращаемся со страницы категории,
            # текст нельзя редактировать
            await query.message.answer(
                msg,
                reply_markup=pagination_keyboard(
                    buttons_count=len(categories),
                    start=first_item,
                    end=final_item,
                    cd="category",
                    page_size=PAGE_SIZE,
                    extra_button=lk_button,
                ),
            )
            await query.message.delete()
            return
        await query.message.edit_text(
            msg,
            reply_markup=pagination_keyboard(
                buttons_count=len(categories),
                start=first_item,
                end=final_item,
                cd="category",
                page_size=PAGE_SIZE,
                extra_button=lk_button,
            ),
        )
    except KeyError as err:
        logger.error(f"Ошибка в ключе при просмотре списка категорий: {err}")
    except Exception as err:
        logger.error(f"Ошибка при просмотре списка категорий: {err}")

@methodist_category_router.callback_query(
    F.data.startswith("back_to_category:") | F.data.startswith("category:")
)
@methodist_category_router.callback_query(F.data == "no:delete_category")
async def show_category(
    query: CallbackQuery, state: FSMContext, session: Session
):
    """Обработчик кнопок выбора отдельной категории.

    Получаем условный id категории из callback_data, достаем реальный id из
    состояние Data и получаем полную инфу о категории из базы данных.
    """
    try:
        await query.answer()
        data = await state.get_data()
        if not data:
            user = select_user(session, query.from_user.id)
            await query.message.answer(
                LEXICON[user.language]["error_getting_category"],
                reply_markup=InlineKeyboardMarkup(
                    inline_keyboard=category_keyboard_methodist(user.language)
                ),
            )
            return
        language = data["language"]
        lexicon = LEXICON[language]
        # Достаем id категории из состояния и делаем запрос к базе
        if "category_id" in data:
            category_id = data["category_id"]
        elif ("category_ids" in data) and query.data.startswith("category:"):
            category_ids = int(query.data.split(":")[-1])
            category_id = data["category_ids"][category_ids]
        elif ("categories_ids" in data) and query.data.startswith("category:"):
            category_ids = int(query.data.split(":")[-1])
            category_id = data["categories_ids"][category_ids]
        category_info = get_category_info(category_id, lexicon, session)
        info = category_info["info"]
        msg = f"{lexicon['category_chosen']}\n\n" f"{info}\n\n"
        await state.set_state(EditCategory.category_id)
        await state.update_data(category_id=category_id, query_id=category_id)
        await query.message.answer(
            msg, reply_markup=category_keyboard_methodist(language)
        )
        await query.message.delete()
    except KeyError as err:
        logger.error(f"Ошибка в ключевом слове при получении категории: {err}")
    except Exception as err:
        logger.error(f"Ошибка при получении категории: {err}")

@methodist_category_router.callback_query(
    EditCategory.confirm_task, F.data == "confirm"
)
async def process_saving_category_to_db(
    query: CallbackQuery, state: FSMContext
):
    """Обработчик кнопки Подтверждаю."""
    try:
        await query.answer()
        data = await state.get_data()
        await state.clear()
        language = data["language"]
        lexicon = LEXICON[language]
        await query.message.answer(
            lexicon["category_added"],
            reply_markup=methodist_profile_keyboard(language),
        )
        await query.message.delete()
    except KeyError as err:
        logger.error(f"Ошибка в ключе при добавлении категории: {err}")
    except Exception as err:
        logger.error(f"Ошибка при добавлении категории: {err}")

@methodist_category_router.message(
    F.text.in_(
        [
            BUTTONS["RU"]["category_list"],
            BUTTONS["TT"]["category_list"],
            BUTTONS["EN"]["category_list"],
        ]
    )
)
async def show_category_list(
    message: Message, state: FSMContext, session: Session
):
    """Обарботчик кнопки Посмотреть/редактировать категории.

    Показывает все созданные категории с пагинацией.
    """
    try:
        await state.clear()
        user = select_user(session, message.from_user.id)
        language = user.language
        lexicon = LEXICON[language]
        categories = get_all_categories(session)
        if not categories:
            await message.answer(
                lexicon["no_categories_yet"],
                reply_markup=add_category_keyboard(language),
            )
            return
        current_page = 1
        page_info = generate_categories_list(
            categories=categories,
            lexicon=lexicon,
            current_page=current_page,
            page_size=PAGE_SIZE,
            methodist=True,
        )
        msg = page_info["msg"]
        category_ids = page_info["categories_ids"]
        first_item = page_info["first_item"]
        final_item = page_info["final_item"]
        lk_button = {
            "text": BUTTONS[language]["lk"],
            "callback_data": "profile",
        }
        await state.set_state(CategoryList.categories)
        await state.update_data(
            categories=categories,
            category_ids=category_ids,
            current_page=current_page,
            task_info=page_info,
            language=language,
        )
        await message.answer(
            msg,
            reply_markup=pagination_keyboard(
                buttons_count=len(categories),
                start=first_item,
                end=final_item,
                cd="category",
                page_size=PAGE_SIZE,
                extra_button=lk_button,
            ),
        )
    except KeyError as err:
        logger.error(f"Ошибка в ключе при просмотре списка категорий: {err}")
    except Exception as err:
        logger.error(f"Ошибка при просмотре списка категорий: {err}")

@methodist_category_router.callback_query(F.data == "delete_category")
async def delete_category(
    query: CallbackQuery, state: FSMContext, session: Session
):
    """Кнопка "Удалить" в разделе редактирования категории."""
    try:
        await query.answer()
        data = await state.get_data()
        language = data["language"]
        lexicon = LEXICON[language]
        await query.message.edit_text(
            lexicon["delete_confirmation"],
            reply_markup=yes_no_keyboard(
                language, "delete_category", "delete_category"
            ),
        )

    except Exception as err:
        logger.error(f"Ошибка при получении категории: {err}")

@methodist_category_router.callback_query(F.data == "yes:delete_category")
async def category_deletion_confirmation(
    query: CallbackQuery, state: FSMContext, session: Session
):
    """Подтверждение удаления категории."""
    try:
        await query.answer()
        data = await state.get_data()
        language = data["language"]
        lexicon = LEXICON[language]
        category_id = data["category_id"]
        await category_deleting(session, category_id)
        categories = get_all_categories(session)
        if not categories:
            await query.message.edit_text(
                lexicon["no_categories_yet"],
                reply_markup=add_category_keyboard(language),
            )
            return
        page_info = generate_categories_list(
            categories=categories,
            lexicon=lexicon,
            page_size=PAGE_SIZE,
            methodist=True,
        )
        category_ids = page_info["categories_ids"]

        await state.set_data({})
        await state.update_data(
            categories=categories,
            category_ids=category_ids,
            task_info=page_info,
            language=language,
            current_page=1,
        )

        await query.message.edit_text(
            lexicon["category_deleting"],
            reply_markup=back_keyboard(
                language, "back_to_category_list", "back_to_category_list"
            ),
        )
    except Exception as err:
        logger.error(f"Ошибка при удалении категории: {err}")


from fastapi import APIRouter, Depends, Request
from sqlalchemy.orm import Session

from components.auth.logics import AuthLogic
from config.settings import get_db
from framework.api_response import ApiResponse
from framework.decorators import default_api_response, classview

from components.auth.schemas import (
    LoginRequestSchema, LoginResponseSchema
)

router = APIRouter(prefix="/auth")

@classview(router)
class LoginView:

    session: Session = Depends(get_db)

    @router.post("/login")
    @default_api_response
    async def login(self, request: Request,
                    login: LoginRequestSchema):
        return ApiResponse(
            request=request,
            request_schema=LoginRequestSchema,
            response_schema=LoginResponseSchema,
            method=AuthLogic(self.session).login,
            body=login
        )


from Crypto.Cipher import AES
from base64 import b64decode
import os

def main():
    key = 'YELLOW SUBMARINE'
    cipher = AES.new(key, AES.MODE_ECB)
    file_path = os.path.expanduser('~/Downloads/7.txt')
    with open(file_path, 'r') as f:
        data = f.read()

    data = b64decode(data)
    msg = cipher.decrypt(data).decode('utf-8')
    print(msg)

if __name__ == "__main__":
    main()


# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.addons.of_geolocalize.models.of_geo import GEO_PRECISION

class OFParcInstalle(models.Model):
    _name = 'of.parc.installe'
    _description = u"Parc installé"

    name = fields.Char(string=u"No de série", size=64, required=False, copy=False)
    date_service = fields.Date(string=u"Date vente", required=False)
    date_installation = fields.Date(string=u"Date d'installation", required=False)
    date_fin_garantie = fields.Date(string=u"Fin de garantie")
    type_garantie = fields.Selection(selection=[
        ('initial', u"Initiale"),
        ('extension', u"Extension"),
        ('expired', u"Expirée")], string=u"Type de garantie")
    product_id = fields.Many2one(comodel_name='product.product', string=u"Produit", required=True, ondelete='restrict')
    product_category_id = fields.Many2one(comodel_name='product.category', string=u"Catégorie")
    client_id = fields.Many2one(
        comodel_name='res.partner', string=u"Client", required=True, domain="[('parent_id','=',False)]",
        ondelete='restrict')
    client_name = fields.Char(related='client_id.name')  # for map view
    client_mobile = fields.Char(related='client_id.mobile')  # for map view
    site_adresse_id = fields.Many2one(
        comodel_name='res.partner', string=u"Site installation", required=False,
        domain="['|',('parent_id','=',client_id),('id','=',client_id)]", ondelete='restrict')
    revendeur_id = fields.Many2one(
        comodel_name='res.partner', string=u"Revendeur", required=False, ondelete='restrict')
    installateur_id = fields.Many2one(
        comodel_name='res.partner', string=u"Installateur", required=False, ondelete='restrict')
    installateur_adresse_id = fields.Many2one(
        comodel_name='res.partner', string=u"Adresse installateur", required=False,
        domain="['|',('parent_id','=',installateur_id),('id','=',installateur_id)]", ondelete='restrict')
    note = fields.Text(string="Note")
    tel_site_id = fields.Char(string=u"Téléphone site installation", related='site_adresse_id.phone', readonly=True)
    street_site_id = fields.Char(string=u"Adresse", related='site_adresse_id.street', readonly=True)
    street2_site_id = fields.Char(string=u"Complément adresse", related='site_adresse_id.street2', readonly=True)
    zip_site_id = fields.Char(string=u"Code postal", related='site_adresse_id.zip', readonly=True, store=True)
    city_site_id = fields.Char(string=u"Ville", related='site_adresse_id.city', readonly=True)
    country_site_id = fields.Many2one(
        comodel_name='res.country', string=u"Pays", related='site_adresse_id.country_id', readonly=True)
    no_piece = fields.Char(string=u"N° pièce", size=64, required=False)
    project_issue_ids = fields.One2many(
        comodel_name='project.issue', inverse_name='of_produit_installe_id', string=u"SAV")
    active = fields.Boolean(string=u"Actif", default=True)
    brand_id = fields.Many2one(comodel_name='of.product.brand', string=u"Marque")
    modele = fields.Char(string=u"Modèle")
    installation = fields.Char(string=u"Type d'installation")
    conforme = fields.Boolean(string=u"Conforme", default=True)
    state = fields.Selection(
        selection=[
            ('neuf', "Neuf"),
            ('bon', "Bon"),
            ('usage', u"Usagé"),
            ('remplacer', u"À remplacer"),
        ], string=u"État", default="neuf")
    sale_order_ids = fields.Many2many(comodel_name='sale.order', string=u"Commandes")
    sale_order_amount = fields.Float(compute='_compute_links')
    account_invoice_ids = fields.Many2many(comodel_name='account.invoice', string=u"Factures")
    account_invoice_amount = fields.Float(compute='_compute_links')

    # Champs ajoutés pour la vue map
    geo_lat = fields.Float(string="geo_lat", compute='_compute_geo', store=True)
    geo_lng = fields.Float(string="geo_lng", compute='_compute_geo', store=True)
    precision = fields.Selection(
        GEO_PRECISION, default='not_tried', string="precision", compute='_compute_geo', store=True,
        help=u"Niveau de précision de la géolocalisation.\n"
             u"bas: à la ville.\n"
             u"moyen: au village\n"
             u"haut: à la rue / au voisinage\n"
             u"très haut: au numéro de rue\n")
    lot_id = fields.Many2one(comodel_name='stock.production.lot', string="Lot d'origine")

    technician_id = fields.Many2one(comodel_name='hr.employee', string=u"Technicien")

    # @api.depends

    @api.depends('sale_order_ids', 'account_invoice_ids')
    def _compute_links(self):
        for parc in self:
            parc.sale_order_amount = len(parc.sale_order_ids)
            parc.account_invoice_amount = len(parc.account_invoice_ids)

    @api.multi
    @api.depends('client_id', 'client_id.geo_lat', 'client_id.geo_lng', 'client_id.precision',
                 'site_adresse_id', 'site_adresse_id.geo_lat', 'site_adresse_id.geo_lng', 'site_adresse_id.precision')
    def _compute_geo(self):
        for produit_installe in self:
            if produit_installe.site_adresse_id:
                produit_installe.geo_lat = produit_installe.site_adresse_id.geo_lat
                produit_installe.geo_lng = produit_installe.site_adresse_id.geo_lng
                produit_installe.precision = produit_installe.site_adresse_id.precision
            else:
                produit_installe.geo_lat = produit_installe.client_id.geo_lat
                produit_installe.geo_lng = produit_installe.client_id.geo_lng
                produit_installe.precision = produit_installe.client_id.precision

    # @api.onchange

    @api.onchange('date_fin_garantie')
    def onchange_date_fin_garantie(self):
        if self.date_fin_garantie and self.date_fin_garantie < fields.Date.today():
            self.type_garantie = 'expired'
        elif self.date_fin_garantie and self.date_fin_garantie >= fields.Date.today() and \
                self.type_garantie == 'expired':
            self.type_garantie = 'extension'

    @api.onchange('product_id')
    def onchange_product_id(self):
        if self.product_id:
            self.brand_id = self.product_id.brand_id
            self.product_category_id = self.product_id.categ_id

    @api.onchange('client_id')
    def _onchange_client_id(self):
        self.ensure_one()
        if self.client_id:
            self.site_adresse_id = self.client_id

    # Héritages

    @api.model
    def create(self, vals):
        parc = super(OFParcInstalle, self).create(vals)
        if parc.revendeur_id and not parc.revendeur_id.of_revendeur:
            parc.revendeur_id.of_revendeur = True
        if parc.installateur_id and not parc.installateur_id.of_installateur:
            parc.installateur_id.of_installateur = True
        return parc

    @api.multi
    def write(self, vals):
        res = super(OFParcInstalle, self).write(vals)
        if vals.get('revendeur_id'):
            non_revendeurs = self.mapped('revendeur_id').filtered(lambda p: not p.of_revendeur)
            non_revendeurs.write({'of_revendeur': True})
        if vals.get('installateur_id'):
            non_installateurs = self.mapped('installateur_id').filtered(lambda p: not p.of_installateur)
            non_installateurs.write({'of_installateur': True})
        return res

    @api.multi
    def name_get(self):
        """
        Permet dans un SAV lors de la saisie du no de série d'une machine installée de proposer les machines
        du contact précédées d'une puce.
        Permet dans une DI de proposer les appareils d'une adresse différente entre parenthèses.
        """
        if self._context.get('simple_display'):
            return super(OFParcInstalle, self).name_get()
        result = []
        client_id = self._context.get('partner_id_no_serie_puce')
        if client_id:
            for record in self:
                result.append((
                    record.id,
                    ("-> " if record.client_id.id == client_id else "")
                    + (record.name or u"(N° non renseigné)")
                    + " - " + record.client_id.display_name))
            return result

        for record in self:
            serial_number = '%s - ' % record.name if record.name else ''
            product_name = record.product_id.name
            partner_name = record.client_id.display_name
            record_name = '%s%s - %s' % (
                serial_number,
                product_name,
                partner_name,
            )
            result.append((record.id, record_name))
        return result

    @api.model
    def name_search(self, name='', args=None, operator='ilike', limit=100):
        """
        Permet dans un SAV lors de la saisie du no de série d'une machine installée de proposer les machines
        du contact en premier précédées d'une puce.
        Permet, dans une DI, de montrer en 1er les appareils de l'adresse, puis ceux du client et enfin les autres."""
        if self._context.get('partner_id_no_serie_puce'):
            client_id = self._context.get('partner_id_no_serie_puce')
            res = super(OFParcInstalle, self).name_search(name, [('client_id', '=', client_id)], operator, limit) or []
            limit = limit - len(res)
            res = [(parc[0], "-> " + parc[1]) for parc in res]
            res += super(OFParcInstalle, self).name_search(
                name, [('client_id', '!=', client_id)], operator, limit) or []
            return res
        if self._context.get('address_prio_id'):
            address_id = self._context.get('address_prio_id')
            args = args or []
            res = super(OFParcInstalle, self).name_search(
                name,
                args + [['site_adresse_id', '=', address_id]],
                operator,
                limit) or []
            limit = limit - len(res)
            res += super(OFParcInstalle, self).name_search(
                name,
                args + ['|', ['site_adresse_id', '=', False], ['site_adresse_id', '!=', address_id],
                        ['client_id', '=', address_id]],
                operator,
                limit) or []
            limit = limit - len(res)
            res += super(OFParcInstalle, self).name_search(
                name,
                args + ['|', ['site_adresse_id', '=', False], ['site_adresse_id', '!=', address_id],
                        ['client_id', '!=', address_id]],
                operator,
                limit) or []
            return res
        return super(OFParcInstalle, self).name_search(name, args, operator, limit)

    # Actions

    @api.multi
    def action_view_orders(self):
        action = self.env.ref('sale.action_quotations').read()[0]
        action['domain'] = [('id', 'in', self.sale_order_ids._ids)]
        action['context'] = {
            'default_of_parc_installe_ids': [(6, 0, self.ids)],
            'default_partner_id': len(self) == 1 and self.client_id.id or False,
        }
        return action

    @api.multi
    def action_view_invoices(self):
        action = self.env.ref('account.action_invoice_tree1').read()[0]
        action['domain'] = [('id', 'in', self.account_invoice_ids._ids)]
        return action

    @api.model
    def action_creer_sav(self):
        res = {
            'name': 'SAV',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'project.issue',
            'type': 'ir.actions.act_window',
            'target': 'current',
        }
        active_ids = self._context.get('active_ids')
        if active_ids:
            parc_installe = self.browse(active_ids[0])
            if parc_installe.client_id:
                res['context'] = {'default_partner_id': parc_installe.client_id.id,
                                  'default_of_produit_installe_id': parc_installe.id,
                                  'default_of_type': 'di'}
        return res

    # Autres

    @api.model
    def recompute_type_garantie_daily(self):
        today = fields.Date.today()
        all_parc_date_garantie = self.search([('date_fin_garantie', '!=', False)])
        # initialiser l'état de garantie pour les parcs qui ont une date de garantie future
        parc_garantie = all_parc_date_garantie.filtered(lambda p: p.date_fin_garantie >= today and not p.type_garantie)
        parc_garantie.write({'type_garantie': 'initial'})
        # Passer l'état de garantie à "Expirée" pour les parcs dont la date de garantie est future
        parc_expire = all_parc_date_garantie.filtered(
            lambda p: p.date_fin_garantie < today and p.type_garantie != 'expired')
        parc_expire.write({'type_garantie': 'expired'})


import torch.optim as optim

ADADELTA_LEARNING_RATE = 0.05
ADADELTA_MOMENTUM = 0.9
ADADELTA_WEIGHT_DECAY = 0.005

def get_adadelta_halnet(halnet,
                        momentum=ADADELTA_MOMENTUM,
                        weight_decay=ADADELTA_WEIGHT_DECAY,
                        learning_rate=ADADELTA_LEARNING_RATE):
    return optim.Adadelta(halnet.parameters(),
                               rho=momentum,
                               weight_decay=weight_decay,
                               lr=learning_rate)


from typing import Tuple

from pricer.pricer import Offer, Basket, Catalogue

def multibuy(item: str, buy: int, get: int) -> Offer:

    def offer(basket: Basket, catalogue: Catalogue) -> Tuple[float, Basket]:

        basket = basket.copy()

        if item not in basket or item not in catalogue:
            return 0, basket

        if basket[item] >= buy + get:
            basket[item] -= (buy + get)
            return buy * catalogue[item], basket
        else:
            return 0, basket

    return offer

def discount(item: str, percent: int) -> Offer:

    def offer(basket: Basket, catalogue: Catalogue) -> Tuple[float, Basket]:

        basket = basket.copy()

        if item not in basket or item not in catalogue:
            return 0, basket

        if basket[item] == 1:
            basket.pop(item)
        else:
            basket[item] -= 1

        return catalogue[item] * (100 - percent) / 100, basket

    return offer


"""A module defining functions for playing multiplayer games"""

import abc
import socket
import os
import os.path

from . import base

def mk_server(game_name, player_name):
    """Returns a serer for a game"""
    socket_name = ("/tmp/%s_%s_%s" % (game_name, player_name, os.getpid()))

    if os.path.exists(socket_name):
        os.remove(socket_name)

    server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    server.bind(socket_name)
    server.listen(1)

    conn, addr = server.accept()

    return conn

def mk_client(socket_name):
    """Returns a client for a game"""
    client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    client.connect("/tmp/%s" % socket_name)

    return client


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase, RequestFactory, Client
from app.tests.mixins import AuthRouteTestingWithKwargs
from app.tests.mixins import Pep8ViewsTests
import app.views as views

performance = views.user_performance_views

class PasswordResetPep8Tests(TestCase, Pep8ViewsTests):
    def setUp(self):
        self.path = 'app/views/users/performance/'

# /users/:user_id/performance(.:format) only accepts GET and POST
class UserPerformanceIndexRoutingTests(TestCase, AuthRouteTestingWithKwargs):
    def setUp(self):
        self.factory = RequestFactory()
        self.client = Client()
        self.route_name = 'app:user_performance_index'
        self.route = '/users/10/performance'
        self.view = performance.user_performance_index
        self.responses = {
            'exists': 200,
            'GET': 200,
            'POST': 200,
            'PUT': 405,
            'PATCH': 405,
            'DELETE': 405,
            'HEAD': 405,
            'OPTIONS': 405,
            'TRACE': 405
        }
        self.kwargs = {'user_id': 10}
        self.expected_response_content = 'Performance History Visualization'
        AuthRouteTestingWithKwargs.__init__(self)


from pages.courses.register_course_page import RegisterCoursePage
from utilities.test_status import TestStatus
from pages.home.login_page import LoginPage
import unittest
import pytest
from ddt import ddt, data, unpack
import time
from pages.home.navigation_page import NavigationPage

@pytest.mark.usefixtures("oneTimeSetUp", "setUp")
@ddt
class RegisterCourseTests(unittest.TestCase):

    @pytest.fixture(autouse=True)
    def objectSetup(self, oneTimeSetUp):
        self.courses = RegisterCoursePage(self.driver)
        self.ts = TestStatus(self.driver)
        self.lp = LoginPage(self.driver)
        self.nav = NavigationPage(self.driver)

    def set_up(self):
        self.nav.navigate_to_all_courses()

    @pytest.mark.run(order = 1)
    @data (("JavaScript for beginners", "10", "1220", "10"), ("Learn Python 3 from scratch", "20", "1220", "20"))
    @unpack
    def test_invalid_enrollment(self, courseName, ccNum, ccExp, ccCVV):
        self.lp.login("test@email.com", "abcabc")
        self.courses.enter_search_field(courseName)
        self.courses.click_search_button()
        self.courses.select_course()
        time.sleep(4)
        self.courses.enroll_course(num=ccNum, exp=ccExp, cvv=ccCVV)
        result = self.courses.verify_enroll_failed()
        self.ts.mark_final("test_invalid_enrollment", result,
                           "Enrollment Verification")
        self.courses.click_all_courses_link()


from default.liststc import length

__k = 3

def __get_ciphered_char(p: str):

    # cek apakah char merupakan sebuah alfabet
    if 97 <= ord(p) <= 122 or 65 <= ord(p) <= 90:

        # cek apakah char merupakan huruf kapital
        is_upper_case = p.isupper()

        # merubah char menjadi huruf kecil
        p = p.lower()

        # integer starting lowercase alphabet di format ascii
        starting = 97

        # lower = 97 122 upper = 65 90

        # proses cipher
        p_p = abs(ord(p) - ord('a'))
        num_p = (p_p + __k) % 26
        final_num = starting + num_p

        # return berdasarkan apakah huruf tersebut awalnya uppercase atau bukan
        return chr(final_num).upper() if is_upper_case else chr(final_num)

    # jika char bukan merupakan alfabet, return char yang sama
    else:
        return p

# loop through string menggunakan fungsi get_ciphered_char
def cipher_string(text: str):
    final_text = ""

    for i in range(length(text)):
        final_text += __get_ciphered_char(text[i])

    return final_text


# -*- coding: utf-8 -*-
"""
Created on Thu Apr  2 15:17:31 2020

@author: PARK
"""
import numpy as np
import pandas as pd

import warnings
warnings.filterwarnings('ignore')

def disease_load(val_rate = 0.25, seed = 42, target_split = True):

    # Load Data
    disease_data = pd.read_csv('./dataset/thyroid_disease/thyroid_disease.csv')
    disease_data = disease_data[['Age', 'TSH', 'T3', 'TT4', 'T4U', 'FTI', 'class']]
    disease_data['outlier'] = disease_data['class'].apply(lambda x: 0 if x == 3 else 1)
    disease_data.drop(columns = 'class', inplace = True)

    X = disease_data.drop(columns = 'outlier')
    y = disease_data['outlier']

    data_size = X.shape[0]
    idx = np.arange(data_size)

    split_size = int(val_rate * data_size)

    np.random.seed(seed)
    np.random.shuffle(idx)

    tr_idx, val_idx = idx[split_size:], idx[:split_size]

    X_train = X.iloc[tr_idx]
    y_train = y.iloc[tr_idx]

    X_val = X.iloc[val_idx]
    y_val = y.iloc[val_idx]

    if target_split == True:
        return X_train, y_train, X_val, y_val

    elif target_split == False:
        X_train['label'] = y_train
        X_val['label'] = y_val

        return X_train, X_val

def tree_load(val_rate = 0.25, seed = 42, target_split = True):
    # Load Data
    tree_data = pd.read_csv('./dataset/forest_cover_type/covtype.csv')
    label = tree_data['Cover_Type']
    tree_data = tree_data.iloc[:, :10]
    tree_data['Cover_Type'] = label
    tree_data['outlier'] = tree_data['Cover_Type'].apply(lambda x: 1 if (x == 3) | (x == 4) | (x == 6) else 0)
    tree_data.drop(columns = 'Cover_Type', inplace = True)

    X = tree_data.drop(columns = 'outlier')
    y = tree_data['outlier']

    data_size = X.shape[0]
    idx = np.arange(data_size)

    split_size = int(val_rate * data_size)
    np.random.seed(seed)
    np.random.shuffle(idx)

    tr_idx, val_idx = idx[split_size:], idx[:split_size]

    X_train = X.iloc[tr_idx]
    y_train = y.iloc[tr_idx]

    X_val = X.iloc[val_idx]
    y_val = y.iloc[val_idx]

    if target_split == True:
        return X_train, y_train, X_val, y_val

    elif target_split == False:
        X_train['label'] = y_train
        X_val['label'] = y_val

        return X_train, X_val


from clases import *

personas = persona()
personas.setNombre("Rene")
personas.setApellidos("Franco")
personas.setAltura(178)
personas.setEdad(200)

print(f"La persona es {personas.getNombre()} {personas.getApellidos()} ")

informatica = informatico()
informatica.setNombre("Paquito")
informatica.setApellidos("Cabezon")
informatica.setAltura(160)
informatica.setEdad(30)

print(f"La persona es : {informatica.getNombre()} {informatica.getApellidos()} ")


# Create the grid
import numpy as np
import pygame

grid_size = 20

# The abstract representation of the grid.

# A nxn grid
grid = np.zeros((grid_size, grid_size))

pygame.init()

screen_width, screen_height = 600, 600
screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()

class ClickableTile(pygame.sprite.Sprite):

    def __init__(self, pos, size, state, position):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((size, size))
        self.state = state
        self.position = position
        if self.state == 0:
            self.image.fill('darkgrey')
        else:
            self.image.fill('white')
        self.rect = self.image.get_rect(topleft=pos)

    def on_click(self):
        if self.state == 0:
            self.image.fill('white')
            self.state = 1
        elif self.state == 1:
            self.image.fill('darkgrey')
            self.state = 0

class GridGenerator:

    def __init__(self):
        self.grid = np.zeros((grid_size, grid_size))
        self.grid[-10:, :] = 1
        self.setup_grid()

    def setup_grid(self):
        self.palette_group = pygame.sprite.Group()
        p_tile = screen_width // grid_size

        for i in range(grid_size):
            for j in range(grid_size):
                state = self.grid[i][j]
                tile = ClickableTile(((j * p_tile), (i * p_tile)), p_tile - 1, state, position=(i, j))
                self.palette_group.add(tile)

    def update_grid(self):
        for sprite in self.palette_group.sprites():
            self.grid[sprite.position[0]][sprite.position[1]] = sprite.state

    def print_grid(self):
        print(self.grid)

    def save_grid(self):
        np.save('grid.npy', self.grid)

gridgenerator = GridGenerator()

# Define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                pos = pygame.mouse.get_pos()
                for sprite in gridgenerator.palette_group.sprites():
                    if sprite.rect.collidepoint(pos):
                        sprite.on_click()
                        gridgenerator.update_grid()
                        # print(gridgenerator.print_grid())

        keys = pygame.key.get_pressed()
        if keys[pygame.K_SPACE]:
            print("saved")
            gridgenerator.save_grid()

    gridgenerator.palette_group.draw(screen)
    # Update the display
    pygame.display.update()
    clock.tick(30)
    pygame.display.flip()

# Quit the game
pygame.quit()


import urllib.request
import urllib.parse

kw = '日本'
data = {
	'wd': kw
}

data = urllib.parse.urlencode(data)

url = 'https://www.baidu.com/s?' + data

headers = {
	'User-Agent': 'Mozilla/5.0(Macintosh;IntelMacOSX10.6;rv:2.0.1)Gecko/20100101Firefox/4.0.1'
}
request = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(request)

#with open('haha.html', 'wb') as fp:
#	fp.write(response.read())

with open('haha.html', 'w', encoding='utf-8') as fp:
	fp.write(response.read().decode('utf-8'))


import timeit

def t1():
    li = []
    for i in range(10000):
        li.append(i)

def t2():
    li = []
    for i in range(10000):
        li = li +[i]

def t3():
    li = [i for i in range(10000)]

def t4():
    li = list(range(10000))

def t5():
    li = []
    for i in range(10000):
        li.insert(0, i)

time1 = timeit.Timer('t1()', 'from __main__ import t1')
time2 = timeit.Timer('t2()', 'from __main__ import t2')
time3 = timeit.Timer('t3()', 'from __main__ import t3')
time4 = timeit.Timer('t4()', 'from __main__ import t4')
time5 = timeit.Timer('t5()', 'from __main__ import t5')

print('append:%s' % time1.timeit(number=100))   # 0.127835
print('[]+[]:%s' % time2.timeit(number=100))         # 19.7184115
print('列表推导式:%s' % time3.timeit(number=100))      # 0.04835290000000114
print('list():%s' % time4.timeit(number=100))         # 0.026356299999999777
print('insert:%s' % time5.timeit(number=100))        # 2.6034982000000007

基础语法/列表类型性能测试.py


# https://www.acmicpc.net/problem/14500

# solution
# 1) 초기 좌표 (i,j)를 정한다
# 2) 인접한 좌표에 대해 dfs 하며 4개 블럭으로 가능한 합의 최대값을 갱신한다
# 3) dfs 불가능한 'ㅗ' 모양 블럭으로 가능한 값을 계산해 최대값을 갱신한다
# 4) 1)로 돌아가 새로운 초기 좌표(i, j) 정한다. brute-forcely 순회한다
# 5) 순회를 마치고 최대값을 출력한다

# TIL
# O(N)인 초기화 함수(reset_visited)를 brute-force에 이용하는 것은 가볍지 않은 코드이다. 결과적으로 O(N^2)가 된다

# 테트로미노의 길이인 4 level 동안 현재 노드에서 가능한 방향을 모두 탐색하는 dfs 함수
def dfs(i,j,cnt,this_sum):
    global nums, visited, max_sum
    di = [1,0,-1,0] # row 방향 움직임
    dj = [0,1,0,-1] # col 방향 움직임

    if cnt == 4: # 4번째 블럭까지 계산했을때
        max_sum = max(this_sum, max_sum) # global max_sum보다 크면 갱신
        return

    for d_idx in range(4):
        next_i = i+di[d_idx]
        next_j = j+dj[d_idx]

        if ( (next_i < N) and (next_i >= 0) and (next_j < M) and (next_j >= 0) and visited[next_i][next_j] == False ):
            visited[next_i][next_j] = True
            dfs(next_i, next_j, cnt+1, this_sum+nums[next_i][next_j])
            visited[next_i][next_j] = False

# 'ㅗ' 모양 블럭의 경우 dfs 탐색이 불가(revisit 필요)하기에 따로 계산 해주자
def sum_directly(locations:list): # 4블럭의 좌표롤 모두 받아 값을 계산하는 함수
    global nums
    sum_d = 0
    for loc in locations:
        sum_d += nums[loc[0]][loc[1]]

    return sum_d

def fucking_block(i,j): # 'ㅗ' 모양 블럭으로 가능한 결과 계산하는 함수
    global nums, max_sum

    # 'ㅗ' 블럭으로 가능한 4가지 경우를 brute-forcely 계산하자
    four_ways = {
                'ㅗ':[(i,j-1),(i,j),(i-1,j),(i,j+1)],
                'ㅓ':[(i,j-1),(i,j),(i-1,j),(i+1,j)],
                'ㅜ':[(i,j-1),(i,j),(i+1,j),(i,j+1)],
                'ㅏ':[(i-1,j),(i,j),(i,j+1),(i+1,j)]
                }

    for locs in four_ways.values():
        calc_valid = True
        for loc in locs:
            if not ( (loc[0] >= 0) and (loc[0] < N) and (loc[1] >= 0) and (loc[1] < M) ):
                calc_valid = False
                break # 불가능한 좌표있으면 중단

        if calc_valid == True: # 계산 가능할 때만 계산
            max_sum = max(max_sum, sum_directly(locs))

# nums의 방문 여부를 표시한 리스트 visited를 reset하는 함수
## -> 사용하지 말자(시간초과)
# def reset_visited():
#     visited =[]
#     for _ in range(N):
#         visited.append([False for _ in range(M)])
#     return visited

if __name__ == "__main__":
    N,M = tuple(map(int, input().split()))

    nums = [] # N by M 인 정수의 리스트
    for _ in range(N):
        nums.append(list(map(int, input().split())))

    visited =[]
    for _ in range(N):
        visited.append([False for _ in range(M)])

    max_sum = 0
    for i in range(N):
        for j in range(M):
            # visited = reset_visited() # -> 사용하지 말자

            visited[i][j] = True # (i,j)를 방문한 상태
            dfs(i,j,1,nums[i][j]) # (i,j)에서부터 dfs 탐색
            fucking_block(i,j) # 'ㅗ' 모양 블럭으로 가능한 결과 계산
            visited[i][j] = False

    print(max_sum)