'''
Name: Shivam Shah
UPI: ssha981
StudentID: 516637469
Research Project: Effective front-front Heuristic Bidirectional Search
Code_Name: B# Implementation with Manhattan distance and statistics
'''
#from networkx.classes.function import neighbors
from timeit import itertools
import itertools
from enum import unique
import heapq
import copy
from plotly.api.v2.users import current
from cmath import phase

# NODE CLASS
glim_bw = 0
glim_fw = 0
flim = 1
nodes = []
temp_nodes = [] #Just to get count of nodes for csv file
f_level_nodes = {}

class Node:
    def __init__(self, matrix, direction, gvalue,hvalue, state):
        self.matrix = matrix
        self.direction = direction
        self.gvalue = gvalue
        self.state = state
        self.next = None
        self.hvalue = hvalue

    def getmatrix(self):
        return self.matrix

    def setmatrix(self,new_matrix):
        self.matrix = new_matrix

    def getdirection(self):
        return self.direction

    def setdirection(self,new_direction):
        self.direction = new_direction

    def getvalue(self):
        return self.gvalue

    def setvalue(self,new_gvalue):
        self.gvalue = new_gvalue

    def sethvalue(self,new_hvalue):
        self.hvalue = new_hvalue

    def gethvalue(self):
        return self.hvalue

    def getstate(self):
        return self.state

    def setstate(self,new_state):
        self.state = new_state

    def getnext(self):
        return self.next

    def setnext(self,new_next):
        self.next = new_next

'''

b_hash returns optimal path solution
@param: array $nodes, array $initial_matrix, array $goal_matrix
@return: flim if puzzle is solvable else returns -1

'''

def b_hash(initial_matrix, goal_matrix):
    global glim_bw
    global glim_fw
    global flim
    global nodes
    global temp_nodes
    fw = 'fw' #forward direction
    bw = 'bw' #backward direction

    if(initial_matrix == goal_matrix): #trivial case that returns 0 if the input is solved
        return 0

    #adding initial nodes to Nodes list
    nodes.append(Node(initial_matrix, fw, 0 , 0, 'open'))
    nodes.append(Node(goal_matrix, bw, 0 ,0, 'open'))

    incremented_dir = bw #initially setting the direction to be incremented to backwards

    while(solvable(initial_matrix)):
        #switching directions and incrementing flim and glim for that direction
        if(incremented_dir == bw):
            incremented_dir = fw
            glim_fw += 1
            if(expandlevel(initial_matrix,incremented_dir) == True):
                #resetting glims for another test case
                glim_bw = 0
                glim_fw = 0
                for node in nodes:
                    if node.getstate() == 'closed':
                        temp_nodes.append(node)
                nodes[:] = []
                return flim,temp_nodes

        elif(incremented_dir == fw):
            incremented_dir = bw
            glim_bw += 1
            if(expandlevel(initial_matrix,incremented_dir) == True):
                #resetting glims for another test case
                glim_bw = 0
                glim_fw = 0
                for node in nodes:
                    if node.getstate() == 'closed':
                        temp_nodes.append(node)
                nodes[:] = []
                return flim,temp_nodes

        flim += 1
    return -1

'''
expandlevel returns true if we find optimal path at that level
@param array nodes, string incremented_dir, int glim, int flim:
@return: true if solution is found
'''

def expandlevel(initial_matrix,incremented_dir):
    global glim_bw
    global glim_fw
    global flim
    global nodes
    global f_level_nodes
    nodes_at_this_level = []
    count = 0
    expandable_list = []

    for node in nodes:
        if(isexpandable(initial_matrix,node,node.getstate()) == True ):
            expandable_list.append(node)

    while(len(expandable_list) != 0):
        node = expandable_list[0]
        if(isexpandable(initial_matrix,node,node.getstate()) == False ):
            expandable_list.remove(node)

        elif(flim >= h_abstraction(initial_matrix,node.getmatrix(),node.getdirection()) + node.getvalue()):
            expandable_list.remove(node)
            nodes_at_this_level.append(node)
            node.setstate('closed')
            node.sethvalue(h_abstraction(initial_matrix,node.getmatrix(),node.getdirection()))

            for neighbors_n in expand(node.getmatrix()):
                child = Node(neighbors_n, node.getdirection(), node.getvalue() + 1,0, 'open')
                temp_value, temp_node = checker_neighbor_node(neighbors_n) #checks if it already is inside nodes list
                if(temp_value == True):
                    if(node.getdirection() == temp_node.getdirection()):

            ########################### This is where I for reopening #############################

                        if(child.getvalue() < temp_node.getvalue()):
                            nodes.append(child)
                            nodes.remove(temp_node) #removing node with higher gvalue that was expanded before
                            if(isexpandable(initial_matrix,child, child.getstate())):
                                expandable_list.insert(0, child)
                        continue
                    else:
                        f_level_nodes[str(flim)] = len(nodes_at_this_level)
                        return True

                nodes.append(child)
                if(isexpandable(initial_matrix,child, child.getstate())):
                    #print("hi")
                    expandable_list.insert(0, child)

    f_level_nodes[str(flim)] = len(nodes_at_this_level)

        #print("jo")
    return False

'''
checker_neighbor_node checks if the neighbor we expanded already exist in Nodes list
@param array nodes, array neighbor:
@return: True and direction of node if found
'''

def checker_neighbor_node(neighbors_n):
    global nodes
    for node in nodes:
        if(node.getmatrix() == neighbors_n):
            return True,node
    return False, -1

'''
isexpandable checks if can expand the node and put it into our expandable_list
@param Node n, int glim, int flim, string incremented_dir:
@return: True if its expandable
'''

def isexpandable(initial_matrix,n,state):
    global glim_bw
    global glim_fw
    global flim
    global nodes

    if(n.getdirection() == 'bw'):
        hdir = h_abstraction(initial_matrix,n.getmatrix(),n.getdirection())
        fdir = n.getvalue() + hdir
        return(n.getvalue() < glim_bw and flim >= fdir and state == 'open')
    elif(n.getdirection() == 'fw'):
        hdir = h_abstraction(initial_matrix,n.getmatrix(),n.getdirection())
        fdir = n.getvalue() + hdir
        return(n.getvalue() < glim_fw and flim >= fdir and state == 'open')

'''
expand finds all possible neighbors of that node
@param array init_s
@return: array new_list(this contains all neighbors)
'''

def expand(init_s):
    flat_list = init_s
    i = init_s.index('0')
    new_board = []
    n_list = []
    if i in [3, 4, 5, 6, 7, 8]:
      new_board = init_s[:]
      new_board[i], new_board[i - 3] = new_board[i - 3], new_board[i]
      n_list.append(new_board)

    if i in [1, 2, 4, 5, 7, 8]:
      new_board = init_s[:]
      new_board[i], new_board[i - 1] = new_board[i - 1], new_board[i]
      n_list.append(new_board)

    if i in [0, 1, 3, 4, 6, 7]:
      new_board = init_s[:]
      new_board[i], new_board[i + 1] = new_board[i + 1], new_board[i]
      n_list.append(new_board)

    if i in [0, 1, 2, 3, 4, 5]:
      new_board = init_s[:]
      new_board[i], new_board[i + 3] = new_board[i + 3], new_board[i]
      n_list.append(new_board)

    return n_list

'''
Initially checks if the input is solvable or not
@param array s2:
@return: True if s2 is solvable
'''

def solvable(s2):
    s1 = s2[:]
    s1.remove('0')
    s = ''.join(str(r) for v in s1 for r in v)
    count = 0
    for i in range(len(s)-1):
        for j in range(i+1,len(s)):
            if s[i] > s[j]:
                count +=  1

    if count % 2 == 0:
        return True
    else:
        return False

def h_abstraction(initial_matrix, current_matrix,dir):
    global nodes
    unique_list_of_list = []
    unique_list_of_nodes = []
    opp_open_list = []
    sorted_opp_open_list = []
    if(True):
        for node in nodes:
            if node.getdirection() != dir and node.getstate() == 'open':
                node_temp_1 = copy.deepcopy(node)
                opp_open_list.append(node_temp_1)

        initial_matrix_temp = initial_matrix[:]
        current_matrix_temp = current_matrix[:]
        goal_matrix = ['1', '1', '1', '1', '5', '6', '7', '8', '0']

        #This is where I map my base space nodes to abstract space nodes (Here tiles 1,2,3,4 == 1)
        for n,i in enumerate(initial_matrix_temp):
            if i in ['1','2','3','4']:
                initial_matrix_temp[n]= '1'
        for n,i in enumerate(current_matrix_temp):
            if i in ['1','2','3','4']:
                current_matrix_temp[n]= '1'

        for node in opp_open_list:
            for n,i in enumerate(node.getmatrix()):
                if i in ['1','2','3','4']:
                    node.getmatrix()[n]= '1'

        sorted_opp_open_list = sorted(opp_open_list, key=lambda x: x.getvalue(), reverse=False)

        #This is where I check for duplicates in abstract space, ie nodes from base space mapped to same node in the abstract space

        for node in sorted_opp_open_list:
            if node.getmatrix() not in unique_list_of_list:
                unique_list_of_list.append(node.getmatrix())
                unique_list_of_nodes.append(node)

        phase_1_return = phase_1_abs(current_matrix_temp,unique_list_of_nodes,dir)
        return phase_1_return
    else:
        return 0

def abstract_isexpandable(node,dir,high_lim,state):
    return (node.getvalue() < high_lim and state == 'open')

def phase_1_abs(current_matrix,nodes_list, current_dir):
    high_lim = nodes_list[-1].getvalue()
    expandable_list = []
    for node in nodes_list:
        if abstract_isexpandable(node, node.getdirection(),high_lim, node.getstate()):
            heapq.heappush(expandable_list, (node.getvalue(),node))

    while(len(expandable_list)!= 0):
        node_temp = heapq.heappop(expandable_list)
        node = node_temp[1]
        n_value = node.getvalue()
        if abstract_isexpandable(node, node.getdirection(), high_lim, node.getstate()):
            node.setstate('closed')

            for neighbors_n in expand(node.getmatrix()):
                bool = False
                child = Node(neighbors_n, node.getdirection(), n_value + 1, 0, 'open')
                if neighbors_n == current_matrix:
                    return child.getvalue()

                for node in nodes_list:
                    if(node.getmatrix() == child.getmatrix() and child.getvalue() <= node.getvalue()):
                        bool = True
                        nodes_list.append(child)
                        nodes_list.remove(node)
                        if(abstract_isexpandable(child, dir, high_lim,child.getstate())):
                            heapq.heappush(expandable_list,(child.getvalue(),child))

                    elif(node.getmatrix() == child.getmatrix() and child.getvalue() > node.getvalue()):
                        bool = True

                if(bool != True):
                    nodes_list.append(child)
                    if(abstract_isexpandable(child, child.getdirection(), high_lim,child.getstate())):
                        heapq.heappush(expandable_list,(child.getvalue(),child))

    return phase_2_abs(current_matrix,nodes_list,high_lim,current_dir)

def phase_2_abs(current_matrix,nodes_list,high_lim,current_dir):
    nodes_list_opp = []
    expandable_list_opp = []
    current_node = Node(current_matrix, current_dir, 0, 0, 'open')
    nodes_list_opp.append(current_node)
    if(abstract_isexpandable(current_node, current_node.getdirection(), high_lim, current_node.getstate())):
        heapq.heappush(expandable_list_opp, (current_node.getvalue(),current_node))
    while(len(expandable_list_opp) != 0):
        node_temp = heapq.heappop(expandable_list_opp)
        node = node_temp[1]
        n_value = node.getvalue()
        if abstract_isexpandable(node, node.getdirection(), high_lim, node.getstate()):
            node.setstate('closed')

            for neighbors_n in expand(node.getmatrix()):
                bool = False
                child = Node(neighbors_n, node.getdirection(), n_value + 1, 0, 'open')
                for node in nodes_list:
                    if(node.getmatrix() == child.getmatrix()):
                        return node.getvalue() + child.getvalue()

                for node in nodes_list_opp:
                    if(node.getmatrix() == child.getmatrix() and child.getvalue() <= node.getvalue()):
                        bool = True
                        nodes_list_opp.append(child)
                        nodes_list_opp.remove(node)

                        if(abstract_isexpandable(child, child.getdirection(), high_lim,child.getstate())):
                            heapq.heappush(expandable_list_opp,(child.getvalue(),child))

                    elif(node.getmatrix() == child.getmatrix() and child.getvalue() > node.getvalue()):
                        bool = True

                if(bool != True):
                    nodes_list_opp.append(child)
                    if(abstract_isexpandable(child, dir, high_lim,child.getstate())):
                            heapq.heappush(expandable_list_opp,(child.getvalue(),child))

    switcher = 0
    high_lim_front = high_lim
    high_lim_back = high_lim
    while(True):
        if switcher == 0:
            switcher = 1
            temp = phase_3_abs(nodes_list,nodes_list_opp,high_lim_back)
            high_lim_back += 1
            if(temp == True):
                return high_lim_back + high_lim_front

        elif switcher == 1:
            switcher = 0
            temp_1 = phase_3_abs(nodes_list_opp,nodes_list,high_lim_front)
            high_lim_front += 1
            if(temp_1 == True):
                return high_lim_back + high_lim_front

def phase_3_abs(nodes_list,nodes_list_opp, high_lim):
    expandable_list = []
    for node in nodes_list:
        if node.getvalue() == high_lim:
            expandable_list.append(node)

    while(len(expandable_list) != 0):
        node = expandable_list[0]
        expandable_list.remove(node)
        node.setstate('closed')
        n_value = node.getvalue()
        for neighbors_n in expand(node.getmatrix()):
            bool = False
            child = Node(neighbors_n, node.getdirection(), n_value + 1,0,'open')
            for node in nodes_list_opp:
                if(node.getmatrix() == child.getmatrix()):
                    return True
            for node in nodes_list:
                if(node.getmatrix() == child.getmatrix() and child.getvalue() <= node.getvalue()):
                    bool = True
                    nodes_list.append(child)
                    nodes_list.remove(node)

                elif(node.getmatrix() == child.getmatrix() and child.getvalue() > node.getvalue()):
                    bool = True

            if(bool != True):
                nodes_list.append(child)

def csv_format(initial_matrix):
    global nodes
    global temp_nodes
    new_list = []
    zero_list = []
    dir_values = ['fw','bw']
    g_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
    f_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32]

    for node in temp_nodes:
        if(node.getstate() == 'closed'):
            hdir = node.gethvalue()
            fdir = node.getvalue() + hdir
            new_list.append((node.getdirection(), node.getvalue(), fdir ))

    prod_list = list(itertools.product(dir_values,g_values,f_values))
    for i in prod_list:
        if i not in new_list:
            zero_list.append(i)

    return new_list,zero_list


#the following code connects to the remote server with the ip address "192.168.1.2"
#and prints out the documents of a collection in the database
from pymongo import MongoClient

#the ip address will need to change accordingly. 27017 is the main mongodb port
client = MongoClient('192.168.1.2',27017)
db = client['test']
#for my database, i had a collection called "coll"
#if the collection name you are looking for is different, change "coll" to the desired name
#coll = db['dataset']

cursor = db.coll.find()

for document in cursor:
	print(document)


# -*- coding: utf-8 -*-
"""
Created on Fri Sep 20 14:12:49 2019

@author: USER
"""
import turtle
import random

#Inputan angka 20-60 dgn default 40
length = int(turtle.numinput("length", "Please enter the side length of the first square [20-60]:", 40, minval=20, maxval=60))

turtle.speed(10000) #kecepatan turtle bergerak

#Memosisikan turtle di sebelah kiri
turtle.penup()
turtle.setpos(-200,0)
turtle.pendown()

#turtle menggambar persegi berputar sebanyak 72
j = 0
while j < 72:
    j += 1

    #menentukan warna persegi secara acak
    R = random.randint(0,255)
    G = random.randint(0,255)
    B = random.randint(0,255)
    turtle.colormode(255)
    turtle.color("black", (R, G, B))

    turtle.begin_fill()
    turtle.left(180)
    turtle.forward(length+j*2) #panjang persegi bertambah 2 secara berulang
    turtle.right(90)
    turtle.forward(length+j*2)
    turtle.right(90)
    turtle.forward(length+j*2)
    turtle.right(90)
    turtle.forward(length+j*2)
    turtle.left(85) #persegi berputar ke kanan 5 derajat dari persegi sebelumnya
    turtle.end_fill()

#Memosisikan turtle di sebelah kanan
turtle.penup()
turtle.setpos(200,0)
turtle.pendown()

#turtle menggambar lingkaran berputar sebanyak 36
for i in range (0,36):

    #menentukan warna persegi secara acak
    R = random.randint(0,255)
    G = random.randint(0,255)
    B = random.randint(0,255)
    turtle.colormode(255)
    turtle.color("black", (R, G, B))

    turtle.begin_fill()

    #jari-jari lingkaran pertama adalah setengah dari panjang persegi terakhir
    #jari-jari lingkaran berkurang 2 secara berulang
    turtle.circle(((length+(71)*2)/2)-i*2)

    turtle.left(10) #lingkaran berputar ke kiri 10 derajat dari persegi sebelumnya

    turtle.end_fill()

turtle.hideturtle()
turtle.mainloop()

Tugas Pemrograman/TP1_Ferdi Fadillah_1906351083_RR/TP1_Ferdi Fadillah_1906351083_RR.pyw


from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process import anonymous_traversal
from gremlin_python.process.graph_traversal import GraphTraversal
from gremlin_python.structure.graph import Vertex, Edge
import random

WEIGHT = 'weight'

class EmptyGraph(object):
    def __init__(self, server_url, traversal_source, vertex_count):
        self.output_graph = anonymous_traversal.traversal().withRemote(
            DriverRemoteConnection(server_url, traversal_source))
        self.output_graph.V().drop().toList()
        self.output_graph.E().drop().toList()
        for index in range(vertex_count):
            self.output_graph.addV().next()

    def add_random_edge(self, edge_count=1, weight=1):
        for index in range(edge_count):
            if weight is None:
                _weight = random.random()
            edge = self.output_graph.addE('random').from_(self.output_graph.V().sample(1)).to(self.output_graph.V().sample(1)).property(WEIGHT, _weight).next()

if __name__ == '__main__':
    genrator = EmptyGraph('ws://localhost:8182/gremlin', 'g', 5)


import configparser
import os
import numpy as np
import torch as th

class Config(object):
    def __init__(self, file_path, model, dataset, gpu):
        conf = configparser.ConfigParser()
        data_path = os.getcwd()
        if gpu == -1:
            self.device = th.device('cpu')
        elif gpu >= 0:
            if th.cuda.is_available():
                self.device = th.device('cuda', int(gpu))
            else:
                print("cuda is not available, please set 'gpu' -1")

        try:
            conf.read(file_path)
        except:
            print("failed!")
        # training dataset path
        self.model = model
        self.dataset = dataset
        self.path = {'output_modelfold': './output/models/',
                     'input_fold': './dataset/'+self.dataset+'/',
                     'temp_fold': './output/temp/'+self.model+'/'}

        if model == "NSHE":
            self.dim_size = {}
            self.dim_size['emd'] = conf.getint("NSHE", "emd_dim")
            self.dim_size['context'] = conf.getint("NSHE", "context_dim")
            self.dim_size['project'] = conf.getint("NSHE", "project_dim")

            self.lr = conf.getfloat("NSHE", "learning_rate")
            self.beta = conf.getfloat("NSHE", "beta")
            self.seed = conf.getint("NSHE", "seed")
            np.random.seed(self.seed)
            self.max_epoch = conf.getint("NSHE", "max_epoch")
            self.num_e_neg = conf.getint("NSHE", "num_e_neg")
            self.num_ns_neg = conf.getint("NSHE", "num_ns_neg")
            self.norm_emd_flag = conf.get("NSHE", "norm_emd_flag")
            self.task = 'unsupervised_train'
        elif model == "GTN":
            self.lr = conf.getfloat("GTN", "learning_rate")
            self.weight_decay = conf.getfloat("GTN", "weight_decay")
            self.seed = conf.getint("GTN", "seed")
            # np.random.seed(self.seed)

            self.emd_size = conf.getint("GTN", "emd_dim")
            self.num_channels = conf.getint("GTN", "num_channels")
            self.num_layers = conf.getint("GTN", "num_layers")
            self.max_epoch = conf.getint("GTN", "max_epoch")

            self.norm_emd_flag = conf.get("GTN", "norm_emd_flag")
            self.adaptive_lr = conf.get("GTN", "adaptive_lr_flag")
            self.sparse_flag = conf.get("GTN", "sparse")
        elif model == "RSHN":
            self.lr = conf.getfloat("RSHN", "learning_rate")
            self.weight_decay = conf.getfloat("RSHN", "weight_decay")
            self.dropout = conf.getfloat("RSHN", "dropout")

            self.seed = conf.getint("RSHN", "seed")
            self.dim = conf.getint("RSHN", "dim")
            self.max_epoch = conf.getint("RSHN", "max_epoch")
            self.rw_len = conf.getint("RSHN", "rw_len")
            self.batch_size = conf.getint("RSHN", "batch_size")
            self.num_node_layer = conf.getint("RSHN", "num_node_layer")
            self.num_edge_layer = conf.getint("RSHN", "num_edge_layer")
            self.patience = conf.getint("RSHN", "patience")
            self.validation = conf.getboolean("RSHN", "validation")
            self.mini_batch_flag = conf.getboolean("RSHN", "mini_batch_flag")
            self.task = 'entity_classification'
        elif model == 'RGCN':
            self.lr = conf.getfloat("RGCN", "learning_rate")
            self.dropout = conf.getfloat("RGCN", "dropout")

            self.hidden_dim = conf.getint("RGCN", "hidden_dim")
            self.out_dim = conf.getint("RGCN", "out_dim")

            self.n_bases = conf.getint("RGCN", "n_bases")
            self.n_layers = conf.getint("RGCN", "n_layers")
            self.max_epoch = conf.getint("RGCN", "max_epoch")
            self.weight_decay = conf.getint("RGCN", "weight_decay")
            self.seed = conf.getint("RGCN", "seed")
            self.fanout = conf.getint("RGCN", "fanout")
            self.patience = conf.getint("RGCN", "patience")
            self.batch_size = conf.getint("RGCN", "batch_size")
            self.validation = conf.getboolean("RGCN", "validation")
            self.mini_batch_flag = conf.getboolean("RGCN", "mini_batch_flag")
            self.use_self_loop = conf.getboolean("RGCN", "use_self_loop")

        elif model == 'CompGCN':
            self.lr = conf.getfloat("CompGCN", "learning_rate")

            self.weight_decay = conf.getfloat("CompGCN", "weight_decay")
            self.dropout = conf.getfloat("CompGCN", "dropout")

            self.h_dim = conf.getint("CompGCN", "h_dim")
            self.out_dim = conf.getint("CompGCN", "out_dim")
            self.n_layers = conf.getint("CompGCN", "n_layers")
            self.max_epoch = conf.getint("CompGCN", "max_epoch")
            self.seed = conf.getint("CompGCN", "seed")
            self.patience = conf.getint("CompGCN", "patience")

            self.comp_fn = conf.get("CompGCN", "comp_fn")
            self.task = 'entity_classification'
            self.mini_batch_flag = conf.getboolean("CompGCN", "mini_batch_flag")
            self.validation = conf.getboolean("CompGCN", "validation")
            pass
        elif model == 'HetGNN':
            self.lr = conf.getfloat("HetGNN", "learning_rate")

            self.weight_decay = conf.getfloat("HetGNN", "weight_decay")
            #self.dropout = conf.getfloat("CompGCN", "dropout")
            self.max_epoch = conf.getint("HetGNN", "max_epoch")
            self.dim = conf.getint("HetGNN", "dim")
            self.batch_size = conf.getint("HetGNN", "batch_size")
            self.window_size = conf.getint("HetGNN", "window_size")
            self.num_workers = conf.getint("HetGNN", "num_workers")
            self.batches_per_epoch = conf.getint("HetGNN", "batches_per_epoch")
            self.seed = conf.getint("HetGNN", "seed")
            self.patience = conf.getint("HetGNN", "patience")
            self.rw_length = conf.getint("HetGNN", "rw_length")
            self.rw_walks = conf.getint("HetGNN", "rw_walks")
            self.rwr_prob = conf.getfloat("HetGNN", "rwr_prob")
            self.mini_batch_flag = conf.getboolean("HetGNN", "mini_batch_flag")
            self.task = 'unsupervised_train'

            pass


class Solution:
    def smallestpositive(self, array, n):
        # Your code goes here
        res = 1
        array.sort()
        x = 0
        while x < n and array[x] <= res:
            res += array[x]
            x += 1

        return res


import os
import wave
import time
import pyaudio
import tensorflow as tf
import matplotlib.pyplot as plt

def record(record_path, record_duration):
    """从麦克风录音声音道文件

    :param record_path: 声音文件保存路径
    :param record_duration: 录制时间，秒
    :return: 无
    """
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 1  # 声道数
    RATE = 16000  # 采样率
    RECORD_SECONDS = record_duration
    WAVE_OUTPUT_FILENAME = record_path
    p = pyaudio.PyAudio()

    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)
    frames = []
    print("开始录音：请在%d秒内输入语音:" % RECORD_SECONDS)
    for i in range(1, int(RATE / CHUNK * RECORD_SECONDS) + 1):
        data = stream.read(CHUNK)
        frames.append(data)
        if (i % (RATE / CHUNK)) == 0:
            print('\r%s%d%s' % ("剩余", int(RECORD_SECONDS - (i // (RATE / CHUNK))), "秒"), end="")
    print("\r录音结束\n")

    stream.stop_stream()
    stream.close()
    p.terminate()

    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()

def plot_history(history, valid_epoch_freq, history_img_path):
    """
    绘制各种指标数据
    :param history: 历史指标数据
    :param valid_epoch_freq: 验证频率
    :param history_img_path: 历史指标显示图片保存位置
    :return: 无返回值
    """
    plt.subplot(2, 1, 1)
    epoch1 = [i for i in range(1, 1 + len(history["loss"]))]
    epoch2 = [i * valid_epoch_freq for i in range(1, 1 + len(history["wers"]))]

    plt.xlabel("epoch")
    plt.ylabel("loss")
    plt.plot(epoch1, history["loss"], "--*b")
    plt.xticks(epoch1)

    # 绘制metric(valid_loss、wers、norm_lers)
    plt.subplot(2, 1, 2)
    plt.xlabel("epoch")
    plt.ylabel("metric")
    plt.plot(epoch2, history["wers"], "--*r", label="wers")
    plt.plot(epoch2, history["norm_lers"], "--*y", label="norm_lers")
    plt.xticks(epoch2)

    plt.legend()
    if not os.path.exists(history_img_path):
        os.makedirs(history_img_path, exist_ok=True)
    plt.savefig(history_img_path + time.strftime("%Y_%m_%d_%H_%M_%S_", time.localtime(time.time())))
    plt.show()

def wers(truths, preds):
    """
    多个文本WER计算
    :param truths: 以空格分隔的真实文本串list
    :param preds: 以空格分隔的预测文本串list
    :return: WER列表，WER平均值
    """
    count = len(truths)
    assert count > 0
    rates = []
    mean = 0.0
    assert count == len(preds)
    for i in range(count):
        rate = wer(truths[i], preds[i])
        mean = mean + rate
        rates.append(rate)

    return rates, mean / float(count)

def wer(truth, pred):
    """
    单个WER计算
    :param truth: 以空格分隔的真实文本串
    :param pred: 以空格分隔的预测文本串
    :return: WER
    """
    truth = truth.split()
    pred = pred.split()

    return _levenshtein(truth, pred) / float(len(truth))

def lers(truths, preds):
    """
    多个文本LER计算
    :param truths: 以空格分隔的真实文本串list
    :param preds: 以空格分隔的预测文本串list
    :return: 规范化ler指标组成的list; 规范化ler均值
    """
    count = len(truths)
    assert count > 0
    assert count == len(preds)

    norm_rates = []
    norm_mean = 0.0

    for i in range(count):
        rate = _levenshtein(truths[i], preds[i])
        normrate = (float(rate) / len(truths[i]))
        norm_mean = norm_mean + normrate
        norm_rates.append(round(normrate, 4))

    return norm_rates, (norm_mean / float(count))

def ler(truth, pred):
    """
    LER
    :param truth: 以空格分隔的真实文本串
    :param pred: 以空格分隔的预测文本串
    :return: LER
    """
    return _levenshtein(truth, pred) / float(len(truth))

def _levenshtein(a, b):
    """
    计算a和b之间的Levenshtein距离
    :param a: 原始文本
    :param b: 预测文本
    :return: a和b之间的Levenshtein距离
    """
    n, m = len(a), len(b)
    if n > m:
        # 确保n <= m, 使用O(min(n, m))
        a, b = b, a
        n, m = m, n

    current = list(range(n + 1))
    for i in range(1, m + 1):
        previous, current = current, [i] + [0] * n
        for j in range(1, n + 1):
            add, delete = previous[j] + 1, current[j - 1] + 1
            change = previous[j - 1]
            if a[j - 1] != b[i - 1]:
                change = change + 1
            current[j] = min(add, delete, change)

    return current[n]

def load_checkpoint(model: tf.keras.Model, checkpoint_dir: str,
                    execute_type: str, checkpoint_save_size: int):
    """
    恢复检查点
    :param model: 传入的模型
    :param checkpoint_dir: 检查点保存目录
    :param execute_type: 执行类型
    :param checkpoint_save_size: 检查点最大保存数量
    """
    # 如果检查点存在就恢复，如果不存在就重新创建一个
    checkpoint = tf.train.Checkpoint(model=model)
    ckpt_manager = tf.train.CheckpointManager(checkpoint, checkpoint_dir, max_to_keep=checkpoint_save_size)

    if os.path.exists(checkpoint_dir):
        if ckpt_manager.latest_checkpoint:
            checkpoint.restore(ckpt_manager.latest_checkpoint).expect_partial()
    else:
        os.makedirs(checkpoint_dir, exist_ok=True)
        if execute_type == "recognize":
            print("没有检查点，请先执行train模式")
            exit(0)

    return ckpt_manager

def compute_ctc_input_length(max_time_steps, ctc_time_steps, input_length):
    """
    计算ctc api中的参数input_length，基于https://github.com/tensorflow/models/blob/master/research/deep_speech
    将ctc相关的api函数(ctc_loss,ctc_decode)所需要的参数input_length进行一个按比例缩减
    这个比例是input_tensor的max_timestep:模型输出outputs的time_step
    :param max_time_steps: 最大时间维度大小
    :param ctc_time_steps: ctc计算的时间维度大小
    :param input_length: 音频特征实际时间维度大小
    :return: 计算的ctc长度
    """
    ctc_input_length = tf.cast(tf.multiply(input_length, ctc_time_steps), dtype=tf.float32)
    return tf.cast(tf.math.floordiv(ctc_input_length, tf.cast(max_time_steps,
                                                              dtype=tf.float32)), dtype=tf.int32)

def can_stop(numbers):
    last = numbers[-1]
    rest = numbers[:-1]
    # 最后一个错误率比所有的大则返回True
    if all(i <= last for i in rest):
        return True
    else:
        return False

if __name__ == "__main__":
    pred1 = "i like you"
    truth1 = "i like u"
    print(wer(truth1, pred1))
    print(ler(truth1, pred1))


import rclpy
from rclpy.node import Node

from sensor_msgs.msg import Image

import cv2
from cv_bridge import CvBridge

bridge = CvBridge()

class VideoWatcher(Node):
  def __init__(self, src=0):
    super().__init__('video_watcher')

    self.frame_subscriber_ = self.create_subscription(
      Image
      , '/camera/video'
      , self.display
      , 10)

  def display(self, msg):
    frame = bridge.imgmsg_to_cv2(msg)
    cv2.imshow('cat_laser', frame)
    cv2.waitKey(1)

def main(args=None):
  rclpy.init(args=args)

  video_watcher = VideoWatcher()

  rclpy.spin(video_watcher)

  # Destroy the node explicitly
  # (optional - otherwise it will be done automatically
  # when the garbage collector destroys the node object)
  video_watcher.destroy_node()
  rclpy.shutdown()

if __name__ == '__main__':
  main()


#!/usr/bin/env python
__author__ = 'marc santiago'
import re
import os
import argparse

def check_folder_exist(folder):
  if os.path.exists(folder):
    return True
  else:
    return False

parser = argparse.ArgumentParser(description='clean up select files')
parser.add_argument('-f',  '--file', help='cleans up one file')
parser.add_argument('-d',  '--directory', help='cleans up a directory of files')

args = vars(parser.parse_args())

if args['file']:
  new_file = []
  with open(args['file'], 'r') as indata:
    for line in indata.readlines():
      if line.startswith('>'):
        m = re.search(r'>[^ | \n]+(.*)', line)
        if m:
          #terminal_name = re.sub(m.group(1), '', line)
          terminal_name = line.replace(m.group(1), '')
        else:
          terminal_name = line
        new_file.append(terminal_name)
      else:
        new_file.append(line)
  with open(args['file'], 'w') as out:
     out.write(''.join(new_file))

if args['directory']:
  file_paths = []
  assert check_folder_exist(args['directory']),\
  '''The Folder Entered Was Not Found, check spelling or path, usage: python clean_fas_seq.py folder_name'''
  for files in os.listdir(args['directory']):
    path = args['directory'] + "/" + files
    file_paths.append(path)

  for file in file_paths:
    new_file = []
    with open(file, 'r') as indata:
      for line in indata.readlines():
        if line.startswith('>'):
          m = re.search(r'>[^ | \n]+(.*)', line)
          if m:
            #terminal_name = re.sub(m.group(1), '', line)
            terminal_name = line.replace(m.group(1), '')
          else:
            terminal_name = line
          new_file.append(terminal_name)
        else:
          new_file.append(line)
    with open(file, 'w') as out:
       out.write(''.join(new_file))


import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
from xgboost import XGBClassifier

def LetterSplitter(Letter, X, Y, per):
    LetterArray = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
                   'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    x = LetterArray.index(Letter)

    NewX = []
    NewY = []
    LX = []
    LY = []

    index = 0
    i = 1
    while (index < len(X)):
        if (Y[index] == x):
            if (i < per):
                LX.append(X[index])
                LY.append(Y[index])
                i += 1
            else:
                NewX.append(X[index])
                NewY.append(Y[index])
                i = 1
        else:
            NewX.append(X[index])
            NewY.append(Y[index])
        index += 1

    return NewX, LX, NewY, LY

def ModelDefine(identifier):
    model = None

    if (identifier == "xgb"):
        model = XGBClassifier(silent=False,
                              scale_pos_weight=1,
                              learning_rate=0.01,
                              colsample_bytree=0.4,
                              subsample=0.8,
                              #   objective='binary:logistic',
                              objective='multi:softprob',
                              n_estimators=1000,
                              reg_alpha=0.5,
                              max_depth=10,
                              gamma=3)
    elif (identifier == "rf"):
        model = RandomForestClassifier(n_estimators=100)
    else:
        model = None

    return model

def GetPreferences():
    Letter = None
    Model = None
    Per = 1

    Letter = input('Enter Letter: ')[0]
    Letter = Letter.upper()

    Model = input('Enter Model: (xgb, rf) ')
    Model = Model.lower()

    # print('For every x ', Letter, '\'s, keep 1 ',
    #       Letter, ' (x must be > 1): ', sep='', end='')
    # Per = int(input())
    Per = 2

    return Letter, Model, Per

LetterLabel, ModelLabel, Per = GetPreferences()

path = 'letter-recognition.csv'
data = pd.read_csv(path)

X = data.iloc[:, 1:]
Y = data.iloc[:, 0]

classes = len(np.unique(Y))

X = MinMaxScaler().fit_transform(X)
Y = LabelEncoder().fit_transform(Y)

train_x, test_x, train_y, test_y = LetterSplitter(LetterLabel, X, Y, Per)

# ttrain_x, ttest_x, ttrain_y, ttest_y = train_test_split(X, Y,
#                                                         random_state=42,
#                                                         train_size=0.8,
#                                                         test_size=0.2,
#                                                         shuffle=True)

# https://github.com/scikit-learn/scikit-learn/blob/f3f51f9b6/sklearn/model_selection/_split.py#L2349

model = ModelDefine(ModelLabel)

model.fit(train_x, train_y)

predictions = model.predict(test_x)

print(metrics.classification_report(test_y, predictions))
print(accuracy_score(test_y, predictions))


from django import forms

# QUANTITY_CHOICES = [(i, str(i) for i in range(1, 10))]
# color = [
#     ('red': '',
#      'blue': '',
#      'black': ,
#     )
# ]

class CartAddProductForm(forms.Form):

    quantity = forms.IntegerField(
        max_value= 1000,
        min_value= 1,
        label='Количество',
        widget=forms.NumberInput(attrs={'style': 'width:80px', 'id':'quantity', 'onchange':'sendCount(this)'}),
        initial=1
        )
    override = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)

    # quantity = forms.TypedChoiceField(choices=QUANTITY_CHOICES, coerce=int, label='Количество')
    # quantity = forms.IntegerField(max_value=1000, label='Количество')
    # override = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput )


from typing import List
from topsdk.client import BaseRequest
from topsdk.util import convert_struct_list,convert_basic_list,convert_struct,convert_basic
from datetime import datetime

class TaobaoRpRefundsAgreeRequest(BaseRequest):

    def __init__(
        self,
        code: str = None,
        refund_infos: str = None
    ):
        """
            短信验证码，如果退款金额达到一定的数量，后端会返回调用失败，并同时往卖家的手机发送一条短信验证码。接下来用收到的短信验证码再次发起API调用即可完成退款操作。
        """
        self._code = code
        """
            退款信息，格式：refund_id|amount|version|phase，其中refund_id为退款编号，amount为退款金额（以分为单位），version为退款最后更新时间（时间戳格式），phase为退款阶段（可选值为：onsale, aftersale，天猫退款必值，淘宝退款不需要传），多个退款以半角逗号分隔。
        """
        self._refund_infos = refund_infos

    @property
    def code(self):
        return self._code

    @code.setter
    def code(self, code):
        if isinstance(code, str):
            self._code = code
        else:
            raise TypeError("code must be str")

    @property
    def refund_infos(self):
        return self._refund_infos

    @refund_infos.setter
    def refund_infos(self, refund_infos):
        if isinstance(refund_infos, str):
            self._refund_infos = refund_infos
        else:
            raise TypeError("refund_infos must be str")

    def get_api_name(self):
        return "taobao.rp.refunds.agree"

    def to_dict(self):
        request_dict = {}
        if self._code is not None:
            request_dict["code"] = convert_basic(self._code)

        if self._refund_infos is not None:
            request_dict["refund_infos"] = convert_basic(self._refund_infos)

        return request_dict

    def get_file_param_dict(self):
        file_param_dict = {}
        return file_param_dict


def melon_count(day, file_path):
    """Function creates to list the type of melons, count them, and total amount"""
    print("Day", day)
    log = open(file_path)

    for line in log:   #Creates a for loop to iterate through the file
        line = line.rstrip()    #Strips the right side of white space
        words = line.split('|') #Splits line into separate strings
        melon = words[0]    #Selects type of melon
        count = words[1]    #Selects count of melon
        amount = words[2]   #Selects total amount of melons

    print("Delivered {} {}s for total of ${}".format(   #print statement to print off amounts
        count, melon, amount))

melon_count(1, "um-deliveries-20140519.txt")

melon_count(2, "um-deliveries-20140520.txt")

melon_count(3, "um-deliveries-20140521.txt")


# -*- coding: utf-8 -*-
from django.utils import simplejson
from django.http import HttpResponse

class JsonResponse(HttpResponse):
    def __init__(self, data, **kwargs):
        content = simplejson.dumps(
                    data,
                    indent=2,
                    ensure_ascii=False)
        super(JsonResponse, self).__init__(
                                    content=content,
                                    mimetype='application/json; charset=utf8',
                                    **kwargs)


import requests
import sqlite3
from secrets import API_KEY

# get api key from secrets.py
api_key = API_KEY

# connect to database
sql_conn = sqlite3.connect("calendarific.db")

cursor = sql_conn.cursor()

# create table
sql_query = """ CREATE TABLE IF NOT EXISTS calendarific (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT,
    description TEXT,
    type TEXT,
    country TEXT,
    year INTEGER,
    month INTEGER,
    day INTEGER
    )"""

cur = cursor.execute(sql_query)
cur.connection.commit()

# make request to calendarific
URL = "https://calendarific.com/api/v2/holidays?api_key={}".format(
    api_key)

country = 'BR'
year = '2022'

response = requests.get(
    f"{URL}&country={country}&year={year}")

# feriados = response.get('response').get('holidays')
feriados = response.json().get('response').get('holidays')

# insert into database
for feriado in feriados:
    name = feriado.get('name')
    description = feriado.get('description')
    type = feriado.get('type')
    type = ', '.join(type)
    country = feriado.get('country').get('name')
    year = feriado.get('date').get('datetime').get('year')
    month = feriado.get('date').get('datetime').get('month')
    day = feriado.get('date').get('datetime').get('day')

    cursor.execute(
        """INSERT INTO calendarific (name, description, type, country, year, month, day) VALUES (?, ?, ?, ?, ?, ?, ?)""",  # noqa
        (name, description, type, country, year, month, day))

    cursor.connection.commit()

    print("Added {};".format(name))
print("Done.")


from flask import Flask, request, render_template, g, flash, abort, url_for, redirect, make_response,session
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, timedelta
from sqlalchemy import text

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///ad.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'zxcv124'
db = SQLAlchemy(app)

class DBF(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), nullable=False)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    tm = db.Column(db.DateTime, default=datetime.utcnow())

    def __repr__(self):
        return 'DBF %r' % self.id

@app.route('/login', methods=['POST', 'GET'])
def login():  # put application's code here
    if not session:
        if request.method == 'POST':
            session['username'] = request.form['username']
            return redirect(url_for('get_ad'))
        else:
            return '''
        <form method="post">

<input type=text name=username>

<input type=submit value=Login>
        </form>
        '''
    else:
        return redirect(url_for('get_ad'))

@app.route('/')
def redirect_all():
    return redirect(url_for('login'))

@app.route('/all', methods=['POST', 'GET'])
def get_ad():  # put application's code here
    """Вызов объявления"""
    gad = DBF.query.order_by(DBF.tm.desc()).all()  # не удалять
    return render_template("all.html", gad=gad)  # е удалять

@app.route('/all/<int:id>')
def detail(id):  # put application's code here
    """подробный вывод объявления"""
    gad_detail = DBF.query.get(id)
    return render_template("ad_detail.html", gad_detail=gad_detail)

@app.route('/all/<int:id>/delete')
def del_ad(id):  # put application's code here
    """Удаление объявлений"""
    gad_detail = DBF.query.get_or_404(id)
    gad_detail.username = session['username']
    if gad_detail.username == session['username']:
        return "Возникла ошибка это не ваше объявление"
    else:
        try:
            db.session.delete(gad_detail)
            db.session.commit()
            return redirect('/all')
        except:
            return "Возникла ошибка"

@app.route('/all/<int:id>/update', methods=['POST', 'GET'])
def update_ad(id):  # put application's code here
    """Изменение объявления"""
    gad_detail = DBF.query.get(id)
    if request.method == "POST":
        gad_detail.username = session['username']
        gad_detail.title = request.form['title']
        gad_detail.content = request.form['content']
        try:
            db.session.commit()
            return redirect('/all')
        except:
            return "Возникла ошибка"
    else:
        if gad_detail.username != session['username']:
            return "Возникла ошибка это не ваше объявление"
        else:
            return render_template("update_ad.html", gad_detail=gad_detail)

@app.route('/create_ad', methods=['POST', 'GET'])
def create_ad():  # put application's code here
    """Создание объявления"""
    if request.method == "POST":
        username = session['username']
        title = request.form['title']
        content = request.form['content']

        ad = DBF(title=title, content=content, username=username)

        try:
            db.session.add(ad)
            db.session.commit()
            return redirect('/all')
        except:
            return "Возникла ошибка"
    else:
        return render_template("create_ad.html")

if __name__ == '__main__':
    app.run()


#%%
#%%
# -*- coding: utf-8 -*-
import torch
from torch.utils.data import Dataset
from torchvision import datasets
from torchvision.transforms import transforms
import matplotlib.pyplot as plt
from PIL import Image
import glob
import os
import cv2
import random
Tensor = torch.cuda.FloatTensor
#%%
class ImageDataset(Dataset):
    def __init__(self, root, transforms_=None, unaligned=False):
        self.transform = transforms.Compose(transforms_)
        self.unaligned = unaligned

        self.files_d = sorted(glob.glob(os.path.join(root+'/h') + '/*.*'))
        self.files_c = sorted(glob.glob(os.path.join(root+'/z') + '/*.*'))

    def __getitem__(self, index):
        item_d = self.transform(Image.open(self.files_d[index % len(self.files_d)]))

        if self.unaligned:
            item_c = self.transform(Image.open(self.files_c[random.randint(0, len(self.files_c) - 1)])) #隨機採一張
        else:
            item_c = self.transform(Image.open(self.files_c[index % len(self.files_c)])) #沒潤燈

        return {'d': item_d, 'c': item_c}

    def __len__(self):
        return max(len(self.files_d), len(self.files_c))

#%%
def save_img10(batch_img,type0,path,epoch):
    n=batch_img.shape[0]
    a=torch.chunk(batch_img, n, dim=0)
    for i in range(n):
        img = a[i].clone()
        img = img.cpu().numpy().squeeze(0).transpose((1, 2, 0))
        if i < 5:
            cv2.imwrite(path+str(epoch)+"-"+str(i)+"-"+type0+'.png',cv2.cvtColor(img*255, cv2.COLOR_RGB2BGR))
def show_img(batch_img):
    n=batch_img.shape[0]
    a=torch.chunk(batch_img, n, dim=0)
    for i in range(n):
        img = a[i].clone()
        img = img.cpu().numpy().squeeze(0).transpose((1, 2, 0))
        cv2.imshow('My Image', cv2.cvtColor(img*255, cv2.COLOR_RGB2BGR))
        # Discriminator Loss => BCELoss


# -*- coding: UTF-8 -*-

# author: luoboovo
# contact: fuyu16032001@gmail.com
# datetime: 2021/05/21
# software: PyCharm
#         =    =     =
#          =   =   =
#           =  =  =
#         ===========
#         =   萝    =
#         =   卜    =
#         =   神    =
#         =   保    =
#         =   佑    =
#         =   永    =
#         =   无    =
#         =   bug  =
#          =      =
#           =    =
#              =
import pytest
from selenium import webdriver

@pytest.fixture
def data(request):
    return request.param

@pytest.fixture
def driver():
    driver = webdriver.Chrome()
    driver.get('https://cn.bing.com')
    yield driver
    driver.quit()


#!/Users/jasonlu/.virtualenvs/pyven3_6/bin/python

import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt #导入图像库
plt.rcParams['font.sans-serif'] = ['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
plt.figure(figsize=(7, 5)) #创建图像区域，指定比例

import numpy as np
x = np.random.randn(1000) #1000个服从正态分布的随机数
plt.hist(x, 10)
plt.show()

3_7_二维条形直方图.py


import pytest

from piholeinflux import main

@pytest.mark.vcr()
def test_main(mocker, daemon_settings):
    """Test main function executed when running the daemon."""
    mock_write = mocker.patch("piholeinflux.write_api.WriteApi.write")

    main(settings=daemon_settings, single_run=True)

    assert mock_write.called
    assert mock_write.call_count == 1

@pytest.mark.vcr()
def test_main_exception(mocker):
    """Test main function, failing with exceptino inside of loop."""
    mock_influx = mocker.patch("piholeinflux.InfluxDBClient")
    mock_get_data = mocker.patch(
        "piholeinflux.Pihole.get_data", side_effect=ConnectionError
    )

    with pytest.raises(SystemExit) as ctx:
        main(single_run=True)

    assert ctx.value.code == 1
    mock_get_data.assert_called_with()
    assert mock_influx.called
    assert mock_influx.call_count == 1


def check(arr):
    mul, sum = 1, 0
    for i in arr:
        mul *= i
        sum += i
    if mul == sum:
        #print(arr, 'true')
        return 1
    else:
        #print(arr, 'false')
        return 0

def check1(arr):
    pass

def main():
    t = int(input())
    for _ in range(t):
        n = int(input())
        arr = list(map(int, input().split()))
        count = 0
        for i in range(n):
            for j in range(i, n):
                a = arr[i:j+1]
                count += check(a)
        print(count)

if __name__ == '__main__':
    main()


import time
import threading

class MyThread(threading.Thread):
    #def __init__(self, args):
    #   super(MyThread, self).__init__()
    #    self.args = args

    def run(self):
        time.sleep(2)
        print("Thread start at",time.ctime())
        #print("Args is {0}".format(self.args))

for i in range(5):
    t = MyThread()
    print(t.getName())
    t.start()
    t.join()

print("End.......")


import pandas as pd
import numpy as np
import os
import seaborn as sns
import datetime as dt

# modules relatifs à Tkinter
import tkinter as tk
from tkinter import IntVar, StringVar
from tkinter.scrolledtext import ScrolledText as ScrolledText
from tkcalendar import Calendar

# modules pour les images
from PIL import Image, ImageTk
from io import BytesIO
from urllib.request import urlopen

#import des données
path=os.getcwd()

calendar= pd.read_csv(path+"/calendar.csv", sep=",")
listings= pd.read_csv(path+"/listings.csv", sep=",")

#Nettoyage

def nettoyage1():
    listings["price_dollar"] = listings["price"].str.replace('$','')

    listings["price_dollar"][3122] = listings["price_dollar"][3122].replace(",","")

    listings["price_float"] = listings["price_dollar"].apply(float)

    calendar["date"] = pd.to_datetime(calendar["date"], format="%Y-%m-%d")
    year =calendar["date"].dt.year.astype(str)
    month = calendar["date"].dt.month.astype(str)

    calendar["month"] = month
    calendar["year"] = year

    calendar["price_dollar"] = calendar["price"].astype(str)
    calendar["price_dollar"] = calendar["price"].str.replace('$','')
    calendar["price_float"] = calendar["price_dollar"].str.replace(',','').astype(np.float64)

    def dispo(ligne):
        if ligne == "t" :
            return 1
        else :
            return 0

    calendar["dispo"] = calendar["available"].apply(dispo)

    return

def nettoyage2():
    global quartier, logement
    logement=listings['property_type'].drop_duplicates().dropna().tolist()
    a=[]
    for i in range (len (logement)):
        a=a+[logement[i].lower()]
    logement = list(a)

    quartier=listings['neighbourhood_cleansed'].drop_duplicates().dropna().tolist()
    a=[]
    for i in range (len(quartier)):
        a=a+[quartier[i].lower()]
    quartier = list(a)

nettoyage2()
nettoyage1()

################################################ Partie fonctions ########################################################

####### Deuxième page ########

def etape_2(): # en cliquant sur le 1er next, lance cette fonction

    global variable_logement2 # pour la réutiliser à l'extérieur de cette fonction

    frame1.destroy() # parce qu'on veut changer de page
    frame2.pack()

    a = variable_budget.get() # vaut 1 si "yes" a été coché
    b = variable_logement.get()
    c = variable_quartier.get()
    d = variable_install.get()
    e = variable_periode.get()

    tk.Label(frame2).pack()

    variable_logement2 = tk.StringVar() # récupère valeur du logement
    variable_quartier2 = tk.StringVar() # récupère valeur du quartier

    next2=tk.Button(frame2, text="Next", command=etape_3) # bouton "next" de la 2ème page pour pouvoir basculer sur la 3ème
    next2.pack(side=tk.BOTTOM)  # pour qu'il soit en bas

    if a == 1 : # si l'utilisateur veut sélectionner le budget

        frame20.pack(side=tk.LEFT) # affiche une sous-fenêtre

        ## 1ère sous-sous fenêtre

        def recup_var3(): # pour garder en mémoire le choix du budget minimal
            global variable_budget3
            for i in liste3.curselection() :
                variable_budget3 = liste3.get(i)

        frame213 = tk.Frame(frame20, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)
        frame213.pack() # 1ère sous-sous-fenêtre

        liste3 = tk.Listbox(frame213) #listbox pour le budget minimum
        index = liste3.curselection() #### je garde ??
        budgets3 = np.arange(20,1010,10) #intervalle par pas de 10

        for i in budgets3:
            liste3.insert(tk.END, i) #insert les valeurs dans la listbox
        liste3.pack()

        bouton_lb = tk.Button(frame213, text = 'Click here to confirm your min',command=recup_var3) # bouton pour valider le choix du budget minimum
        bouton_lb.pack(side=tk.BOTTOM)

        #2ème sous-sous fenêtre (même principe)

        def recup_var2():
            global variable_budget2
            for i in liste2.curselection() :
                variable_budget2 = liste2.get(i)

        frame211 = tk.Frame(frame20, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)
        frame211.pack(side=tk.BOTTOM)

        liste2 = tk.Listbox(frame211)
        index = liste2.curselection() #### je garde ??
        budgets2 = np.arange(20,1010,10)
        for i in budgets2:
            liste2.insert(tk.END, i)
        liste2.pack()

        bouton_lb = tk.Button(frame211, text = 'Click here to confirm your max',command=recup_var2)
        bouton_lb.pack(side=tk.BOTTOM)

    if b == 1 : # si l'utilisateur souhaite sélectionner son type de logement

        frame22 = tk.Frame(frame2, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)
        frame22.pack(side=tk.LEFT)

        label_logement2 = tk.Label(frame22, text="Housing") # titre de la sous-fenêtre
        label_logement2.pack()

        # tristatevalue = 0 : pour décocher toutes les cases au début
        label_logement2a = tk.Radiobutton(frame22, text = "Apartment", variable = variable_logement2, value = "Apartment", tristatevalue = 0)
        label_logement2b = tk.Radiobutton(frame22, text = "House", variable = variable_logement2, value = "House", tristatevalue = 0)
        label_logement2c = tk.Radiobutton(frame22, text = "Cabin", variable = variable_logement2, value = "Cabin", tristatevalue = 0)
        label_logement2d = tk.Radiobutton(frame22, text = "Condomium", variable = variable_logement2, value = "Condomium", tristatevalue = 0)
        label_logement2e = tk.Radiobutton(frame22, text = "Camper/RV", variable = variable_logement2, value = "Camper/RV", tristatevalue = 0)
        label_logement2f = tk.Radiobutton(frame22, text = "Bungalow", variable = variable_logement2, value = "Bungalow", tristatevalue = 0)
        label_logement2g = tk.Radiobutton(frame22, text = "Townhouse", variable = variable_logement2, value = "Townhouse", tristatevalue = 0)
        label_logement2h = tk.Radiobutton(frame22, text = "Loft", variable = variable_logement2, value = "Loft", tristatevalue = 0)
        label_logement2i = tk.Radiobutton(frame22, text = "Boat", variable = variable_logement2, value = "Boat", tristatevalue = 0)
        label_logement2j = tk.Radiobutton(frame22, text = "Bed & Breakfast", variable = variable_logement2, value = "Bed & Breakfast", tristatevalue = 0)
        label_logement2k = tk.Radiobutton(frame22, text = "Other", variable = variable_logement2, value = "Other", tristatevalue = 0)
        label_logement2l = tk.Radiobutton(frame22, text = "Dorm", variable = variable_logement2, value = "Dorm", tristatevalue = 0)
        label_logement2m = tk.Radiobutton(frame22, text = "Treehouse", variable = variable_logement2, value = "Treehouse", tristatevalue = 0)
        label_logement2n = tk.Radiobutton(frame22, text = "Yurt", variable = variable_logement2, value = "Yurt", tristatevalue = 0)
        label_logement2o = tk.Radiobutton(frame22, text = "Chalet", variable = variable_logement2, value = "Chalet", tristatevalue = 0)
        label_logement2p = tk.Radiobutton(frame22, text = "Tent", variable = variable_logement2, value = "Tent", tristatevalue = 0)
        # affiche tous les radiobuttons
        label_logement2a.pack()
        label_logement2b.pack()
        label_logement2c.pack()
        label_logement2d.pack()
        label_logement2e.pack()
        label_logement2f.pack()
        label_logement2g.pack()
        label_logement2h.pack()
        label_logement2i.pack()
        label_logement2j.pack()
        label_logement2k.pack()
        label_logement2l.pack()
        label_logement2m.pack()
        label_logement2n.pack()
        label_logement2o.pack()
        label_logement2p.pack()

    if c == 1 : # si l'utilisateur veut choisir le quartier

        def recup_var(): # garde en mémoire le choix du quartier
            global variable_quartier2
            for i in liste1.curselection() :
                variable_quartier2 = liste1.get(i)
                return variable_quartier2

        frame23 = tk.Frame(frame2, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)
        frame23.pack(side=tk.LEFT)

        label_quartier2 = tk.Label(frame23, text="Neighbourhood")
        label_quartier2.pack()

        quartier = listings['neighbourhood_cleansed'].drop_duplicates().dropna().tolist() # liste des quartiers
        liste = [] # on crée une liste de label_quartier20,label_quartier21,label_quartier22, etc...
        l = "label_quartier2"
        for i in range(len(quartier)): # on fait une boucle
            l = l[:len("label_quartier2")]+str(i) # pour ajouter uniquement à la fin
            liste.append(l)

        liste1 = tk.Listbox(frame23) # listbox
        index = liste1.curselection()

        quartiers = listings['neighbourhood_cleansed'].drop_duplicates().dropna().tolist()
        for i in quartiers:
            liste1.insert(tk.END, i)
        liste1.pack()

        bouton_lb = tk.Button(frame23, text = 'Click here to confirm your neighbourhood choice',command=recup_var, relief=tk.GROOVE)
        bouton_lb.pack(side=tk.BOTTOM) # bouton pour sauvegarder son choix car listbox faut bouton

    if d == 1 : # si l'utilisateur veut choisir ses installations

        global variable_install2a, variable_install2b, variable_install2c, variable_install2d, variable_install2e, variable_install2f

        frame24 = tk.Frame(frame2, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)
        frame24.pack(side=tk.LEFT)
        label_install2=tk.Label(frame24,text="What type of Installation do you need ? ")
        label_install2.pack()

        ### TV ###
        label_install2a = tk.Label(frame24, text="Do you need a TV ?")
        label_install2a.pack()
        variable_install2a = IntVar() # vaut 1 s'il veut la TV, sinon 0
        label_install2a_yes = tk.Radiobutton(frame24, text = "Yes", variable = variable_install2a, value = 1,tristatevalue=3)
        label_install2a_yes.pack()
        label_install2a_no = tk.Radiobutton(frame24, text = "I don't mind", variable = variable_install2a, value = 0,tristatevalue=3)
        label_install2a_no.pack()

        ### Wi-Fi ###
        label_install2b = tk.Label(frame24, text="Do you need Wifi ?")
        label_install2b.pack()
        variable_install2b = IntVar() # # vaut 1 s'il veut le Wi-Fi, sinon 0
        label_install2b_yes = tk.Radiobutton(frame24, text = "Yes", variable = variable_install2b, value = 1,tristatevalue=3)
        label_install2b_yes.pack()
        label_install2b_no = tk.Radiobutton(frame24, text = "I don't mind", variable = variable_install2b, value = 0,tristatevalue=3)
        label_install2b_no.pack()

        ### Climatisation ###
        label_install2c = tk.Label(frame24, text="Do you need Air Conditionning (A/C) ?")
        label_install2c.pack()
        variable_install2c = IntVar()  # vaut 1 s'il veut la climatisation, sinon 0
        label_install2c_yes = tk.Radiobutton(frame24, text = "Yes", variable = variable_install2c, value = 1,tristatevalue=3)
        label_install2c_yes.pack()
        label_install2c_no = tk.Radiobutton(frame24, text = "I don't mind", variable = variable_install2c, value = 0,tristatevalue=3)
        label_install2c_no.pack()

        ### Parking ###
        label_install2d = tk.Label(frame24, text="Do you need a Parking place ?")
        label_install2d.pack()
        variable_install2d = IntVar() # vaut 1 s'il veut un parking, sinon 0
        label_install2d_yes = tk.Radiobutton(frame24, text = "Yes", variable = variable_install2d, value = 1,tristatevalue=3)
        label_install2d_yes.pack()
        label_install2d_no = tk.Radiobutton(frame24, text = "I don't mind", variable = variable_install2d, value = 0,tristatevalue=3)
        label_install2d_no.pack()

        ### Elevator ###
        label_install2e = tk.Label(frame24, text="Do you need an Elevator ?")
        label_install2e.pack()
        variable_install2e = IntVar() # vaut 1 s'il veut un ascenseur, sinon 0
        label_install2e_yes = tk.Radiobutton(frame24, text = "Yes", variable = variable_install2e, value = 1,tristatevalue=3)
        label_install2e_yes.pack()
        label_install2e_no = tk.Radiobutton(frame24, text = "I don't mind", variable = variable_install2e, value = 0,tristatevalue=3)
        label_install2e_no.pack()

        ### Nothing ###
        label_install2f = tk.Label(frame24, text="Do you want No TV, no Wifi, no AC, no Parking, no Elevator?")
        label_install2f.pack()
        variable_install2f = IntVar() # vaut 1 s'il ne veut rien, sinon 0
        label_install2f_yes = tk.Radiobutton(frame24, text = "Yes, I'm crazy", variable = variable_install2f, value = 1,tristatevalue=3)
        label_install2f_yes.pack()
        label_install2f_no = tk.Radiobutton(frame24, text = "No", variable = variable_install2f, value = 0,tristatevalue=3)
        label_install2f_no.pack()

    if e==1: # si l'utilisateur veut choisir sa date de début et fin de séjour

        global cal1 # pour pouvoir rappeler à l'extérieur de la fonction
        frame25.pack(side=tk.LEFT)
        label_calendar = tk.Label(frame25, text="Date") # nom du calendrier
        label_calendar.pack()
        # Add Calendar

        frame251.pack() # affiche la sous-fenêtre

        cal1=Calendar(frame251,selectmode='day',year=2016,month=1,date_pattern="Y-mm-dd",background="black",selectbackground ="red", mindate=dt.date(2016,1,4), maxdate= dt.date(2017,1,2))
        cal1.pack() # affiche d'abord premier calendrier
        btn_251=tk.Button(frame251, text="Click to confirm your debut", command=calen2) # puis le 2ème calendrier seulement après avoir cliqué sur le bouton
        btn_251.pack()

def calen2():
    global cal1_min,cal2
    cal1_min = str(cal1.get_date()).split('-') # récupère la valeur du 1er calendrier et le split selon les tirets
    cal1_min[0] = int(cal1_min[0]) # prend la valeur entière de l'année
    cal1_min[1] = int(cal1_min[1]) # prend la valeur entière du mois car on ne veut pas que ça commence par 0
    cal1_min[2] = int(cal1_min[2]) # idem pour le jour
    frame252.pack()
    cal2=Calendar(frame252,selectmode='day',year=2016,month=1,date_pattern="Y-mm-dd",background="black",selectbackground ="red", mindate=dt.date(cal1_min[0], cal1_min[1], cal1_min[2]) + dt.timedelta(1), maxdate= dt.date(2017,1,2))
    cal2.pack() # affiche le 2ème calendrier
    btn_252=tk.Button(frame252, text="Click to confirm your end") # bouton optionnel, sert d'esthétique
    btn_252.pack()

######### Fin fonctions de la deuxième page ###########

######### Troisième page ############

def etape_3(): # fonction de la 3ème page qui affiche les résultats demandés

    global final, frame3 # dataframe final qui contient les résultats
    frame2.destroy() # détruit la 2ème frame
    frame3 = tk.Frame(window)
    frame3.pack() # pour la 3ème frame

    frame31 = tk.Frame(frame3, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)
    frame31.pack(side=tk.LEFT)

    frame32 = tk.Frame(frame3, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)

    def destroy_frame3(): # fonction pour relancer l'interface
        frame3.destroy()
        window.destroy()
        reset()

    # Bouton pour relancer l'interface
    frame33 = tk.Frame(frame3, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)
    frame33.pack(side=tk.TOP)
    bouton_reset = tk.Button(frame33, text = 'New search', command = destroy_frame3,relief=tk.GROOVE)
    bouton_reset.pack()

    # ScrolledText pour afficher les résultats dans une fenêtre Tkinter
    text_result= ScrolledText(frame31, width=120, height= 70) # configuration du ScrolledText
    text_result.pack()

    #stock=[prix,logement,quartier,installation,période]
    # récupère la valeur 1 ou 0 de chaque option
    stock=[variable_budget.get(),variable_logement.get(),variable_quartier.get(),variable_install.get(),variable_periode.get()]

    # dataframe de chacune des options
    a=pd.DataFrame(listings, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","TV","wifi","clim","parking","elevator","listing_url","picture_url"])
    b=pd.DataFrame(listings, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","TV","wifi","clim","parking","elevator","listing_url","picture_url"])
    c=pd.DataFrame(listings, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","TV","wifi","clim","parking","elevator","listing_url","picture_url"])
    d=pd.DataFrame(listings, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","TV","wifi","clim","parking","elevator","listing_url","picture_url"])
    e=pd.DataFrame(listings, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","TV","wifi","clim","parking","elevator","listing_url","picture_url"])

    if stock[0]==1:#si il veut séléctionner un budget alors on appelle la fonction budget() pour choisir budget et voir ce qui correspond
        a=budget()
    if stock[1]==1: # s'il veut choisir le type de logement
        b=proptype()
    if stock[2]==1: # type de quartier
        c=quartype()
    if stock[3]==1: # choix des installations
        d=instatype()
    if stock[4]==1: # choix de la date
        e=logement_dispo()

    # une fois les dataframe relatives à chaque option obtenues, on les merge 1 à 1 pour former le dataframe final
    final=pd.merge(a,b,how="inner")
    final=pd.merge(final,c,how="inner") # inner pour garder ce qui est en commun
    final=pd.merge(final,d,how="inner")
    final=pd.merge(final,e,how="inner") # ici le dataframe final
    final=final.sort_values(by=['price_float'])

    # on récupère les éléments de chaque colonne du dataframe dans une liste pour voir les afficher dans le ScrolledText
    id_txt = final['id'].tolist() # tous les ID dans une liste
    name_txt= final['name'].tolist()
    summary_txt = final['summary'].tolist()
    property_txt = final['property_type'].tolist()
    price_txt = final['price_float'].tolist()
    neighbourhood_txt = final['neighbourhood_cleansed'].tolist()
    bedrooms_txt = final['bedrooms'].tolist()
    hostname_txt = final['host_name'].tolist()
    tv_txt = final['TV'].tolist()
    wifi_txt = final['wifi'].tolist()
    clim_txt = final['clim'].tolist()
    parking_txt = final['parking'].tolist()
    elevator_txt = final['elevator'].tolist()
    url_txt = final['listing_url'].tolist()
    picture_txt = final['picture_url'].tolist()

    if final.shape[0]==0: # si aucun résultat ne correspond aux critères, c'est-à-dire si le dataframe final est vide
        text_result.insert(tk.END,"Sorry, there is no result.")

    else: # s'il y a au moins un résultat correspondant aux recherches
        for i in range(len(id_txt)): # toutes les listes font la même longueur donc on prend n'importe laquelle
            findelafin = " \n                                         ||| ID of the housing : " + str(id_txt[i]) + " |||" + "\n Name of the housing : " + str(name_txt[i])+ "\n Summary : " + str(summary_txt[i])+ "\n Type of property : "+ str(property_txt[i])+ "\n Price per night is : " + str(price_txt[i])+ "$"+"\n Neighbourhood :  " + str(neighbourhood_txt[i])+ "\n Number of bedrooms : "+ str(bedrooms_txt[i]) +" rooms" + "\n Host name is : " + str(hostname_txt[i])+ "\n TV : "+ str(tv_txt[i]==1)+ "\n Wi-Fi : "+ str(wifi_txt[i]==1)+"\n Air Conditionning (AC) : "+str(clim_txt[i]==1)+"\n Parking : "+ str(parking_txt[i]==1)+"\n Elevator : "+str(elevator_txt[i]==1)+"\n URL : " + str(url_txt[i])+"\n Picture's URL :"+ str(picture_txt[i])+"\n"+"\n"+"\n"+"\n"
            text_result.insert(tk.END,findelafin) # affiche dans le ScrolledText

        frame32.pack(side=tk.LEFT) # fenêtre de la listbox pour pouvoir choisir la photo à afficher

        def afficher(): #fonction qui permet d'afficher la photo
            for i in listbox_image.curselection() :
                a= tk.Toplevel() # dans une nouvelle fenêtre
                choix = listbox_image.get(i) # choix du logement
                URL = picture_txt[i] # URL du logement sélectionné
                u = urlopen(URL) # ouvre URL
                raw_data = u.read()
                u.close()

                im = Image.open(BytesIO(raw_data)) # met dans le bon format
                photo = ImageTk.PhotoImage(im)

                label_image = tk.Label(a,text='This is housing n°'+str(id_txt[i])) # titre de la photo
                label_image.pack()

                label_photo = tk.Label(a,image=photo) # photo
                label_photo.image = photo
                label_photo.pack(side=tk.BOTTOM)

        listbox_image = tk.Listbox(frame32) # listbox pour les photos

        for i in id_txt:
            listbox_image.insert(tk.END, i)
        listbox_image.pack()

        bouton_im = tk.Button(frame32, text = 'Click here to see the image',command=afficher, relief=tk.GROOVE) #bouton pour lancer la fonction qui affiche l'image
        bouton_im.pack(side=tk.BOTTOM) # bouton pour sauvegarder son choix

####### Fin fonction de la page 3 ######

###### Fonctions issues de la partie 2 (et adaptées) ######

def budget(): # fonction qui retourne les logements selon le budget
    mi=float(variable_budget3)
    ma=float(variable_budget2)
    if mi>ma:
        alt1=mi
        alt2=ma
        mi=alt2
        ma=alt1
    if mi<=ma:
        b=listings.sort_values(by=['price_float']) # trie par ordre croissant
        b=b.loc[(b["price_float"]<=ma)&(b["price_float"]>=mi)] # affiche les lignes qui correspondent au budget donné
    #changer b en nouveau df pour optimiser le code
        prix_mini = listings["price_float"].min() # prix minimal d'une nuit
        prix_maxi = listings["price_float"].max() # prix maximinal d'une nuit

        c=pd.DataFrame(b, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","listing_url","picture_url"])

        return c

def proptype(): # fonction qui retourne les types de logements selon le type
    b=listings
    z=variable_logement2.get()
    b1=b.loc[(b["property_type"]==z)]
    b=b1.sort_values(by=['price_float'])
    c=pd.DataFrame(b, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","listing_url","picture_url"])

    return c

def quartype(): # fonction qui retourne les logements selon les quartiers
    b=listings
    z=variable_quartier2 #.get()
    b1=b.loc[(b["neighbourhood_cleansed"]==z)]
    b=b1.sort_values(by=['price_float'])
    c=pd.DataFrame(b, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","listing_url","picture_url"])

    return c

def instatype(): # fonction pour retourner les logements ayant les installations souhaitées

    a=pd.DataFrame(listings, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","TV","wifi","clim","parking","elevator","listing_url","picture_url"])
    b=pd.DataFrame(listings, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","TV","wifi","clim","parking","elevator","listing_url","picture_url"])
    c=pd.DataFrame(listings, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","TV","wifi","clim","parking","elevator","listing_url","picture_url"])
    d=pd.DataFrame(listings, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","TV","wifi","clim","parking","elevator","listing_url","picture_url"])
    e=pd.DataFrame(listings, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","TV","wifi","clim","parking","elevator","listing_url","picture_url"])

    z=[variable_install2a.get(),variable_install2b.get(),variable_install2c.get(),variable_install2d.get(),variable_install2e.get(),variable_install2f.get()]

    if z[0]==1:
        a=a.loc[a["TV"]==1]#TV
    if z[1]==1:
        b=b.loc[b["wifi"]==1]#wifi
    if z[2]==1:
        c=c.loc[c["clim"]==1]#clim
    if z[3]==1:
        d=d.loc[d["parking"]==1]#parking
    if z[4]==1:
        e=e.loc[e["elevator"]==1]#Elevator
    if z[5]==1:#s'il sélectionne "rien"
        l=listings
        p=l.loc[(l["TV"]==0)&(l["wifi"]==0)&(l["clim"]==0)&(l["parking"]==0)&(l["elevator"]==0)]
        c=pd.DataFrame(p, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","TV","wifi","clim","parking","elevator","listing_url","picture_url"])
        return c
    ref1=pd.merge(a,b,how="inner")
    ref1=pd.merge(ref1,c,how="inner")
    ref1=pd.merge(ref1,d,how="inner")
    ref1=pd.merge(ref1,e,how="inner")
    ref=ref1.sort_values(by=['price_float'])
    c=pd.DataFrame(ref, columns=["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","TV","wifi","clim","parking","elevator","listing_url","picture_url"])
    return c

def demander_date(): # fonction pour avoir les id des logements disponibles entre début et fin du séjour

    debut = cal1.get_date()
    fin = cal2.get_date()

    calendar.sort_values(by='date')
    debut_time = dt.datetime.strptime(debut, "%Y-%m-%d").date()
    fin_time = dt.datetime.strptime(fin, "%Y-%m-%d").date()

    diff = fin_time - debut_time
    duree = str(diff)
    duree = duree.split(' ')

    if int(duree[0]) > 0:
        ligne_date = calendar.loc[(calendar["date"] <= fin) & (calendar["date"] >= debut) & (calendar["dispo"] == 1)]
        liste_id = ligne_date['listing_id'].drop_duplicates().dropna().tolist()

        liste_id_definitive = []
        for i in (liste_id):
            df = ligne_date.loc[ligne_date["listing_id"] == i]
            if df.shape[0] ==  int(duree[0]) :
                liste_id_definitive += [i]

        return liste_id_definitive

def logement_dispo(): # fonction pour avoir les logements disponibles
    liste = demander_date()
    annonce = listings.loc[listings["id"].isin(liste), ["id","name","summary","property_type","price_float","neighbourhood_cleansed","bedrooms","host_name","listing_url","picture_url"]]
    annonce=annonce.sort_values(by=['price_float'])
    return annonce

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

                        ############ Première fenêtre et définitions de frames ###########

def reset():# stocker dans une fonction pour pouvoir recommencer la procédure
    global frame1, frame2, frame20,frame25,frame251,frame252,framef1,window,variable_budget,variable_logement,variable_quartier,variable_install,variable_periode
    window=tk.Tk()
    window.title("Interface Airbnb")
    window.config(bg="#6b8496")
    label=tk.Label(window,text="Welcome")
    label.pack()

    frame1 = tk.Frame(window,borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)
    frame1.pack()

    frame2 = tk.Frame(window)
    frame20 = tk.Frame(frame2, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)

    frame25 = tk.Frame(frame2, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)
    frame251 = tk.Frame(frame25, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)
    frame252 = tk.Frame(frame25, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE)

    framef1 = tk.Frame(frame1, borderwidth=2, highlightthickness=3, highlightbackground="white", relief=tk.GROOVE) # tk.GROOVE : pour les bordures de la fenêtre
    framef1.pack(side=tk.TOP, padx=1, pady=1)

    label_budget = tk.Label(frame1, text="Do you want to select a budget ?") #dans frame1
    label_budget.pack()
    variable_budget = tk.IntVar() #récupère valeur
    label_budget_yes = tk.Radiobutton(frame1, text = "Yes", variable = variable_budget, value = 1) #radiobutton : cocher 1 case uniquement
    label_budget_yes.pack()
    label_budget_no = tk.Radiobutton(frame1, text = "No", variable = variable_budget, value = 0)
    label_budget_no.pack()

## demander type de logement particulier

    label_logement= tk.Label(frame1, text="Do you want to select a particular housing ?") #dans frame1
    label_logement.pack()
    variable_logement = tk.IntVar() #récupère valeur
    label_logement_yes = tk.Radiobutton(frame1, text = "Yes", variable = variable_logement, value = 1)
    label_logement_yes.pack()
    label_logement_no = tk.Radiobutton(frame1, text = "No", variable = variable_logement, value = 0)
    label_logement_no.pack()

## demander un quartier en particulier

    label_quartier = tk.Label(frame1, text="Do you want to select a particular neighbourhood ?") #dans frame1
    label_quartier.pack()
    variable_quartier = IntVar() #récupère valeur
    label_quartier_yes = tk.Radiobutton(frame1, text = "Yes", variable = variable_quartier, value = 1)
    label_quartier_yes.pack()
    label_quartier_no = tk.Radiobutton(frame1, text = "No", variable = variable_quartier, value = 0)
    label_quartier_no.pack()

## demander des installations en particulier

    label_install = tk.Label(frame1, text="Do you want to select specific amenities (Air Conditionner, Wi-Fi, Parking, etc.) ?") #dans frame1
    label_install.pack()
    variable_install = IntVar() #récupère valeur
    label_install_yes = tk.Radiobutton(frame1, text = "Yes", variable = variable_install, value = 1)
    label_install_yes.pack()
    label_install_no = tk.Radiobutton(frame1, text = "No", variable = variable_install, value = 0)
    label_install_no.pack()

## demander une période en particulier

    label_periode = tk.Label(frame1, text="Do you want to select a specific date ?") #dans frame1
    label_periode.pack()
    variable_periode = IntVar() #récupère valeur
    label_periode_yes = tk.Radiobutton(frame1, text = "Yes", variable = variable_periode, value = 1)
    label_periode_yes.pack()
    label_periode_no = tk.Radiobutton(frame1, text = "No", variable = variable_periode, value = 0)
    label_periode_no.pack()

# bouton "next step"

    next1=tk.Button(frame1, text="Next", command=etape_2) # cliquer sur "next" doit afficher autre chose)
    next1.pack()

    def ouitv(a):
        if "TV" in a:
            return 1
        else:
            return 0

    def ouifi(a):
        if ("Wireless Internet" in a) or("Internet" in a):
            return 1
        else:
            return 0

    def ouiclim(a):
        if "Air Conditioning" in a:
            return 1
        else:
            return 0

    def ouiparking(a):
        if "Free Parking on Premises" in a:
            return 1
        else:
            return 0

    def ouielevator(a):
        if "Elevator in Building" in a:
            return 1
        else:
            return 0

    def espace2(a) :
        b="" #stockage
        for i in range(len(a)):#on parcourt les éléments de la ligne en remplaçant les caractères spéciaux
            d=a[i].replace("{","")
            d=d.replace("}","")
            d=d.replace('"',"")
            b=b+d
        c=b.split(",")#on utilise la virgule (",")qui était le séparateur pour split la ligne et en faire une liste avec seulement les mots
        return c

    listings["instal"]=listings["amenities"].apply(list)#on transforme en liste la colonne amenities (qu'on appelle instal)
    listings["instal"]=listings["instal"].apply(espace2)
    #crée des colonnes qui valent 1 ou 0
    listings["TV"]=listings["instal"].apply(ouitv)
    listings["wifi"]=listings["instal"].apply(ouifi)
    listings["clim"]=listings["instal"].apply(ouiclim)
    listings["parking"]=listings["instal"].apply(ouiparking)
    listings["elevator"]=listings["instal"].apply(ouielevator)

    window.mainloop()

reset()


class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        index=-1
        if len(digits)==1 and digits[0] != 9:
            digits[0]=digits[0]+1
            return digits
        while digits[index]==9:
            digits[index]=0
            if abs(index)==len(digits):
                break
            index=index-1
        if len(digits)==abs(index) and digits[0]==0:
            digits.insert(0, 1)
            return digits
        digits[index]=digits[index]+1
        return digits


#!/usr/bin/env python3

import sys
from string import digits
from bs4 import BeautifulSoup
from fractions import Fraction

def main(argv):
    if len(argv) != 1:
        print('usage: ./dehtmlify.py "Spring 2022 CS 6290 Lecture A #21973202202"')
        return 1

    title_wanted = argv[0]

    response_rate = None

    soup = BeautifulSoup(sys.stdin, 'html.parser')

    for course in soup.find_all(class_=['MyEvalCenterToBeOpened', 'MyEvalCenterOpened']):
        title = course.select('.classTitle')[0].text
        if title == title_wanted:
            responded_numbers = course.select('.spanRespondedNumbers')
            n_responded = int(responded_numbers[0].text)
            n_total = int(responded_numbers[2].text)
            response_rate = (n_responded, n_total)
            break

    if response_rate is None:
        raise ValueError('i cant find that course!')

    print('{:.2f}%'.format(float(response_rate[0]) * 100.0 / float(response_rate[1])))
    print('{}/{}'.format(response_rate[0], response_rate[1]))

    return 0

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))


from ..Image import Exr

class ExrRender(Exr):
    """
    Abstracted crawler used to detect renders.
    """

    def __init__(self, *args, **kwargs):
        """
        Create a Render object.
        """
        super(ExrRender, self).__init__(*args, **kwargs)

        self.setVar('category', 'render')

        parts = self.var("name").split("_")
        self.setVar('renderType', parts[-1])


import os
def clear():
  os.system("clear")
while(True):
  try:
    angka = int(input("Masukkan angka : "))
  except:
    clear()
    print("Input tidak valid!")
  else:
    clear()
    if angka > 1:
      for i in range(2,angka):
        if angka % i == 0:
          clear()
          print(f"{angka} bukan bilangan prima")
        else:
          print(f"{angka} adalah bilangan prima")
          break
          break
    else:
      clear()
      print(f"{angka} bukan bilangan prima")
    if angka == 9999:
      break


from pyspark import  SparkContext
def main():
    sc = SparkContext(master="local",appName="UseCase3")
    sc.setLogLevel("ERROR")
    l = ["We", "Are" ,"Learning" , "Hadoop" , "From" , "Inceptez" , "We", "Are" ,"Learning" , "Spark" , "From" , "Inceptez.com" , "hadoop" , "HADOOP"]
    rdd = sc.parallelize(l)
    print(f"Count of Words {rdd.count()}")

    Non_Hadoop = rdd.filter(lambda x :  x.upper()!="HADOOP"  )

    print(f"Non Haddop Words Count: {Non_Hadoop.count()}")

main()


import numpy as np
from src.QubitClass import One_qubit

def Hamiltonian(lmb):
    # Pauli matrices
    sigma_x = np.array([[0, 1], [1, 0]])
    sigma_y = np.array([[0, -1j], [1j, 0]])
    sigma_z = np.array([[1, 0], [0, -1]])

    # Identity matrix
    I = np.eye(2)

    # Parameters
    E1 = 0
    E2 = 4
    V11 = 3
    V22 = -3
    V12 = 0.2
    V21 = 0.2

    # calculate variables
    eps = (E1 + E2) / 2
    omega = (E1 - E2) / 2
    c = (V11 + V22) / 2
    omega_z = (V11 - V22) / 2
    omega_x = V12

    H0 = eps * I + omega * sigma_z
    H1 = c * I + omega_z * sigma_z + omega_x * sigma_x

    return H0 + lmb * H1

def prepare_state(theta, phi, target = None):
    """
    Prepares a quantum state for given parameters.

    Parameters
    ----------
    theta, phi : float
        Parameters of the quantum state.
    target : numpy array, optional
        The target state, default is None.

    Returns
    -------
    numpy array
        The prepared quantum state.
    """

    I = np.eye(2)

    sigma_x = np.array([[0, 1], [1, 0]])
    sigma_y = np.array([[0, -1j], [1j, 0]])

    state = np.array([1, 0])

    Rx = np.cos(theta/2) * I - 1j * np.sin(theta/2) * sigma_x
    Ry = np.cos(phi/2) * I - 1j * np.sin(phi/2) * sigma_y

    state = Ry @ Rx @ state

    if target is not None:
        state = target

    return state

def get_energy(angles, lmb, number_shots, target = None):
    """
    Calculates the expected energy for given parameters.

    Parameters
    ----------
    angles : list
        A list of two angles.
    lmb : float
        Lambda parameter of the Hamiltonian.
    number_shots : int
        Number of measurements to be made for the energy calculation.
    target : numpy array, optional
        The target state, default is None.

    Returns
    -------
    float
        The expected energy.
    """

    theta, phi = angles[0], angles[1]

    E1 = 0; E2 = 4; V11 = 3; V22 = -3; V12 = 0.2; V21 = 0.2

    eps = (E1 + E2) / 2; omega = (E1 - E2) / 2; c = (V11 + V22) / 2; omega_z = (V11 - V22) / 2; omega_x = V12

    init_state = prepare_state(theta, phi, target)

    qubit = One_qubit()
    qubit.set_state(init_state)

    measure_z = qubit.measure(number_shots)

    qubit.set_state(init_state)
    qubit.apply_hadamard()

    measure_x = qubit.measure(number_shots)

    # expected value of Z = (number of 0 measurements - number of 1 measurements)/ number of shots
    # number of 1 measurements = sum(measure_z)
    exp_val_z = (omega + lmb*omega_z)*(number_shots - 2*np.sum(measure_z)) / number_shots
    exp_val_x = lmb*omega_x*(number_shots - 2*np.sum(measure_x)) / number_shots
    exp_val_i = (eps + c*lmb)

    exp_val = (exp_val_z + exp_val_x + exp_val_i)

    return exp_val

def minimize_energy(lmb, number_shots, angles_0, learning_rate, max_epochs):
    """
    Minimizes the expected energy of a quantum state.

    Parameters
    ----------
    lmb : float
        Lambda parameter of the Hamiltonian.
    number_shots : int
        Number of measurements to be made for the energy calculation.
    angles_0 : list
        A list of two initial angles.
    learning_rate : float
        Learning rate for the gradient descent optimization.
    max_epochs : int
        Maximum number of iterations for the optimization.

    Returns
    -------
    tuple
        A tuple containing final angles, number of epochs taken, a boolean indicating
        whether the optimization has converged, final energy, and energy change in the
        last iteration.
    """

    angles = angles_0 #lmb*np.array([np.pi, np.pi])
    epoch = 0
    delta_energy = 1

    energy = get_energy(angles, lmb, number_shots)

    while (epoch < max_epochs) and (delta_energy > 1e-4):
        grad = np.zeros_like(angles)

        for idx in range(angles.shape[0]):
            angles_temp = angles.copy()
            angles_temp[idx] += np.pi/2
            E_plus = get_energy(angles_temp, lmb, number_shots)
            angles_temp[idx] -= np.pi
            E_minus = get_energy(angles_temp, lmb, number_shots)
            grad[idx] = (E_plus - E_minus)/2

        angles -= learning_rate*grad
        new_energy = get_energy(angles, lmb, number_shots)
        delta_energy = np.abs(new_energy - energy)

        energy = new_energy

        epoch += 1

    return angles, epoch, (epoch < max_epochs), energy, delta_energy


from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from rest_framework.permissions import AllowAny
from rest_framework.viewsets import ModelViewSet

from kicksal.models import *
from kicksal.serializers import *

@method_decorator(csrf_exempt, name='dispatch')
class UnidadeViewSet(ModelViewSet):
    queryset = Unidade.objects.all()
    serializer_class = UnidadeSerializer
    permission_classes = (AllowAny,)

@method_decorator(csrf_exempt, name='dispatch')
class FuncionarioViewSet(ModelViewSet):
    queryset = Funcionario.objects.all()
    serializer_class = FuncionarioSerializer
    permission_classes = (AllowAny,)

@method_decorator(csrf_exempt, name='dispatch')
class QuadraViewSet(ModelViewSet):
    queryset = Quadra.objects.all()
    serializer_class = QuadraSerializer
    permission_classes = (AllowAny,)

@method_decorator(csrf_exempt, name='dispatch')
class CampeonatoViewSet(ModelViewSet):
    queryset = Campeonato.objects.all()
    serializer_class = CampeonatoSerializer
    permission_classes = (AllowAny,)

@method_decorator(csrf_exempt, name='dispatch')
class TimeViewSet(ModelViewSet):
    queryset = Time.objects.all()
    serializer_class = TimeSerializer
    permission_classes = (AllowAny,)

@method_decorator(csrf_exempt, name='dispatch')
class JogadorViewSet(ModelViewSet):
    queryset = Jogador.objects.all()
    serializer_class = JogadorSerializer
    permission_classes = (AllowAny,)

@method_decorator(csrf_exempt, name='dispatch')
class JogoViewSet(ModelViewSet):
    queryset = Jogo.objects.all()
    serializer_class = JogoSerializer
    permission_classes = (AllowAny,)


#coding:gb2312
from tkinter import *
import requests,re,time
from tkinter import ttk

def check():
    if v.get() == '':
        s.set('请输入合法的IP地址')
        return
    elif v.get() == 'i':
        Myip()
        return
    else:
        pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
        if re.match(pattern, v.get()):
            info()
            return
        else:
            s.set('请输入合法的IP地址')
            v.set('')
            return
def check_2(self):
    check()
def center_window(tl, width, height):
        screenwidth = tl.winfo_screenwidth()
        screenheight = tl.winfo_screenheight()
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        tl.geometry(size)
        return
def Myip():
    s.set('Loding...')
    p1["value"] = 20
    win.update()
    url = "http://myip.ipip.net/"
    try:
        p1["value"] = 30
        win.update()
        content = requests.get(url, verify=False, timeout=15, allow_redirects=False).content
        source = content.decode('utf8')
        p1["value"] = 50
        win.update()
        wepos = re.split(r'  来自于：', source)
        p1["value"] = 80
        win.update()
        weip = re.split(r'当前 IP：', wepos[0])
        pos = wepos[1]
        p1["value"] = 90
        win.update()
        iip = weip[1]
        s.set(pos)
        v.set('您的IP:' + iip)
        p1["value"] = 100
        win.update()
        time.sleep(0.3)
        p1["value"] = 0
        win.update()
        return
    except Exception as e:
        tl = Toplevel(window)
        center_window(tl, 300, 210)
        tl.maxsize(250, 100)
        tl.minsize(250, 100)
        tl.title('错误')
        tl.iconbitmap('c:\\sun.ico')
        Err = StringVar()
        Label(tl, text='连接超时\n请检查您的网络连接或联系开发者修复\nEmail：mingserverwarning@gmail.com',fg='red',wraplength=500,justify='center').pack()
        Err.set(e)
        p1["value"] = 0
        win.update()
        return
def WriteHosts():
    addr_list = [
        '192.168.0.202 google.com',
        '192.168.0.202 www.google.com',
    ]
    file = open('C:\\windows\\System32\\drivers\\etc\\hosts','a+')
    for i in addr_list:
        file.write(i +'\n')
    file.close()
def info():
    s.set('Loding...')
    p1["value"] = 20
    win.update()
    url = "https://www.ip.cn/index.php?ip=" +v.get()
    try:
        requests.packages.urllib3.disable_warnings()
        p1["value"] = 30
        win.update()
        content = requests.get(url, verify=False, timeout=15, allow_redirects=False).content
        p1["value"] = 50
        win.update()
        source = content.decode('utf-8')
        res_line = re.findall(r'

您查询的 IP：(.*)

', source)
        res = re.split(r'
', res_line[0])
        pos_exc = re.split(r'所在地理位置：', res[1])
        p1["value"] = 80
        win.update()
        pos = re.split(r'
', pos_exc[1])
        p1["value"] = 100
        win.update()
        local_net = re.split(r'', pos[0])
        s.set(local_net[0])
        time.sleep(0.5)
        p1["value"] = 0
        win.update()
        return
    except Exception as e:
        tl = Toplevel(window)
        center_window(tl, 300, 210)
        tl.maxsize(250,100)
        tl.minsize(250,100)
        tl.title('错误')
        tl.iconbitmap('c:\\sun.ico')
        Err = StringVar()
        Label(tl,text='连接超时\n请检查您的网络连接或联系开发者修复\nEmail：mingserverwarning@gmail.com',fg='red',wraplength=500,justify='center').pack()
        Err.set(e)
        p1["value"] = 0
        win.update()
        return
window = Tk()
window.title('IP归属地查询')
window.configure(background='#FFC')
center_window(window, 300, 240)
window.maxsize(250,130)
window.minsize(250,130)
#以上为主窗口参数，不解释
win = Frame(window,bg='#FFC')
#以下为进度条信息
p1 = ttk.Progressbar(win,length=140,mode="determinate",orient=HORIZONTAL)
p1.grid(row=2,column=2)
p1["maximum"] = 100
p1["value"] = 0
#以下为备注
rem = Label(win,text='By aminG',bg='#FFC')
rem.grid(row=3,column=0)
rem2 = Label(win,text='输入字母 i 查看本机IP',bg='#FFC')
rem2.grid(row=3,column=2)
v = StringVar() #输入组
s = StringVar() #输出组
lab1 = Label(win, text="输入IP:",bg='#FFC')
lab1.grid(row=0, column=0, padx=5, pady=5, sticky=W)
en = Entry(win,textvariable=v)  #输入框
en.bind('<Return>',check_2)
en.grid(row=0, column=1, sticky='ew', columnspan=2)
lab2 = Label(win, text="归属地:",bg='#FFC')
lab2.grid(row=1, column=0, padx=5, pady=5, sticky=W)
en2 = Entry(win,textvariable=s,state='readonly') #输出框
en2.grid(row=1, column=1, sticky='ew', columnspan=2)
bu = ttk.Button(win,text='查询',command=check)   #查询按钮
bu.grid(row=2, column=0)
win.pack(padx=8, pady=8, ipadx=4)
window.mainloop()
# WriteHosts()  #改Hosts文件