#!/usr/bin/env python3

import os
import json
import fnmatch

SOURCE_DIR = 'content_src'
OUTPUT = 'src/assets/articles.json'

def load():
    articles = []
    files = os.listdir(SOURCE_DIR)
    markdown_files = [f for f in files if fnmatch.fnmatch(f, '*.md')]
    markdown_files.sort()

    for article in markdown_files:
        with open(os.path.join(SOURCE_DIR, article)) as f:
            content = f.read()
            title = content.splitlines()[0]
            slug = article[3:-3].lower()
            img_name = article.replace('.md', '.jpg')
            img = os.path.join('images', 'titles', img_name)

            articles.append({
                "title": title,
                "slug": slug,
                "img": img,
                "content": content,
            })

    return articles

def overview(articles):
    print()
    print('IMPORTIERTE INHALTE')
    print('###################')
    print()
    for a in articles:
        print('- %s' % a['slug'])
    print()

def export(articles):
    with open(OUTPUT, 'w') as output:
        json.dump(articles, output, indent=4, ensure_ascii=False)

if __name__ == '__main__':
    articles = load()
    overview(articles)
    export(articles)


from . import osmnx_customized as oxc
from . import graph_utils, space_allocation, _errors
from .constants import *
import geopandas as gpd
import networkx as nx
import pyproj
import copy
import shapely
import numpy as np

def get_subgraph_with_invalid_geometries(G):
    filtered_edges = filter(
        lambda e: e[3].get('geometry') is not None and e[3].get('geometry').is_valid > 2,
        G.edges(keys=True, data=True)
    )
    return nx.Graph(filtered_edges)

def get_subgraph_with_empty_geometries(G):
    filtered_edges = filter(
        lambda e: e[3].get('geometry') is None or e[3].get('geometry').is_empty > 2,
        G.edges(keys=True, data=True)
    )
    return nx.Graph(filtered_edges)

def prepare_graph(G):
    """
    A set of operations needed to make the street graph created by osmnx ready for snman operations

    Parameters
    ----------
    G : nx.MultiDiGraph
        OSM Graph

    Returns
    -------
    None
    """

    for uvk, data in G.edges.items():

        # ensure consistent data types: maxspeed
        maxspeed = data.get('maxspeed', '')
        data['maxspeed'] = int(maxspeed) if maxspeed.isdigit() else -1

        # ensure consistent data types: layer
        layer = data.get('layer', '')
        # isdigit only supports positive numbers, so we need to remove any '-' first
        data['layer'] = int(layer) if layer.lstrip('-').isdigit() else 0

    for i, data in G.nodes.items():
        # prepare traffic_signals attribute
        data['traffic_signals'] = 1 * (data.get('highway') == 'traffic_signals')

    surrogate_missing_edge_geometries(G)

def organize_edge_directions(G, method='lower_to_higher_node_id', key_lanes_description=KEY_LANES_DESCRIPTION):
    """
    Ensure that all edges in a street graph have the direction from the lower to the higher node id.
    Edges with a different direction will be reversed, including the lanes and their geometry.

    Parameters
    ----------
    G : nx.MultiDiGraph
        OSM graph
    method : str
        - lower_to_higher_node_id: each edge will be digitized from the lower to the higher node id
        - by_osm_convention: one-way nodes will be digitized according to their lane direction
        - heaviest_forward:

    Returns
    -------
    None
    """

    edges = list(G.edges(data=True, keys=True))
    for edge in edges:

        if method == 'lower_to_higher_node_id':
            if edge[0] > edge[1]:
                reverse_edge(G, *edge[0:3])

        elif method == 'by_osm_convention':
            if space_allocation.is_backward_oneway_street(edge[3].get(key_lanes_description)):
                reverse_edge(G, *edge[0:3])

        elif method == 'by_top_order_lanes':
            if space_allocation.is_backward_by_top_order_lanes(edge[3].get(key_lanes_description)):
                reverse_edge(G, *edge[0:3])

        else:
            raise _errors.OptionNotImplemented('Method ' + str(method) + ' is not valid')

def surrogate_missing_edge_geometries(G):
    for uvk, data in G.edges.items():
        if 'geometry' not in data:
            data['geometry'] = shapely.LineString([
                shapely.Point(get_node_point(G, uvk[0])),
                shapely.Point(get_node_point(G, uvk[1]))
            ])

def get_node_point(G, node):
    data = G.nodes[node]
    return shapely.Point(data['x'], data['y'])

def add_connected_component_ids(G):
    """
    For directed graphs: Adds IDs of weakly ('_weakly_connected_component')
    and strongly ('_strongly_connected_component') connected components to all edges
    For undirected graphs: Adds IDs of connected components ('_connected_component') to all edges

    Parameters
    ----------
    G : nx.MultiGraph
    Returns
    -------
    None
    """

    if G.is_directed():

        wccs = nx.weakly_connected_components(G)
        for wcc, nodes in enumerate(wccs):
            subgraph = nx.subgraph(G, nodes)
            nx.set_edge_attributes(subgraph, wcc, '_weakly_connected_component')

        sccs = nx.strongly_connected_components(G)
        for scc, nodes in enumerate(sccs):
            subgraph = nx.subgraph(G, nodes)
            nx.set_edge_attributes(subgraph, wcc, '_strongly_connected_component')

    else:

        ccs = nx.connected_components(G)
        for wcc, nodes in enumerate(ccs):
            subgraph = nx.subgraph(G, nodes)
            nx.set_edge_attributes(subgraph, wcc, '_connected_component')

def update_precalculated_attributes(G):
    """
    Update edge attributes in a street graph that have been pre-calculated by osmnx
    when the graph was created

    Parameters
    ----------
    G : nx.MultiGraph or nx.MultiDiGraph
        street graph

    Returns
    -------
    None
    """
    street_count = oxc.stats.count_streets_per_node(G)
    nx.set_node_attributes(G, street_count, name="street_count")

def convert_crs(G, to_crs):
    """
    Convert the coordinate reference system of the geometries in a graph.
    The graph must follow the convention of networkx:
        * edges have a 'geometry' attribute with a shapely geometry
        * nodes have 'x' and 'y' attributes holding the coordinates as floats
        * the graph has a 'crs' attribute

    Parameters
    ----------
    G : nx.MultiGraph
        centerline graph
    to_crs : int
        target crs

    Returns
    -------
    None
    """

    # Initialize the CRS transformer
    from_crs = pyproj.CRS(G.graph['crs'])
    to_crs = pyproj.CRS(to_crs)
    project = pyproj.Transformer.from_crs(from_crs, to_crs, always_xy=True).transform

    # Update the street_graph's metadata
    G.graph["crs"] = to_crs

    # Transform the geometry of all edges
    for edge in G.edges(data=True, keys=True):
        if "geometry" in edge[3]:
            edge[3]["geometry"] = shapely.ops.transform(project, edge[3]["geometry"])

    # Transform the geometry of all nodes
    for id, data in G.nodes.items():
        geom = shapely.geometry.Point(data.get('x'), data.get('y'))
        geom = shapely.ops.transform(project, geom)
        data['x'] = geom.x
        data['y'] = geom.y

def _remove_edge_from_list(edges, edge_to_remove, dead_ends=True):
    """
    Remove edge from a list using its unique string id

    Parameters
    ----------
    edges : list
    edge_to_remove : list
    dead_ends : bool
        include dead ends in the resulting list

    Returns
    -------
    list
    """

    edges_cleaned = []
    for idx, candidate in enumerate(edges):
        if (candidate[0:3] != edge_to_remove[0:3]
                and not (not dead_ends and candidate[3].get('dead_end'))):
            edges_cleaned.append(candidate)
    return edges_cleaned

def _get_neighbors(G, edge, dead_ends=True):
    """
    Return the neighbor edges of a given edge. The result is a list of three lists:
        * neighbors at the side of u node
        * neighbors at the side of v node
        * neighbors from both sides

    Parameters
    ----------
    G : nx.MultiGraph
        street graph
    edge : tuple
        the complete tuple of an edge
    dead_ends : bool
        include dead ends int the results

    Returns
    -------
    list
        a list of edges
    """

    adjacent_nodes = edge[0:2]
    u_neighbors = list(G.edges(nbunch=adjacent_nodes[0], data=True, keys=True))
    v_neighbors = list(G.edges(nbunch=adjacent_nodes[1], data=True, keys=True))
    # Remove this edge from the neighbors
    u_neighbors = _remove_edge_from_list(u_neighbors, edge, dead_ends=dead_ends)
    v_neighbors = _remove_edge_from_list(v_neighbors, edge, dead_ends=dead_ends)
    return [
        _unique_edges(u_neighbors),
        _unique_edges(v_neighbors),
        _unique_edges(u_neighbors + v_neighbors)
    ]

def _unique_edges(edges):
    """
    Remove duplicates from a list of edges

    Parameters
    ----------
    edges : list

    Returns
    -------
    list
    """

    unique_edges = []
    ids = set()
    for edge in edges:
        this_id = edge[0:3]
        this_id in ids or unique_edges.append(edge)
        ids.add(this_id)
    return unique_edges

def split_edge(G, u, v, key, split_points):

    if not G.has_edge(u, v, key):
        return

    edge_data = G.get_edge_data(u, v, key)
    edge_linestring = edge_data.get('geometry', False)

    if edge_linestring is False:
        return

    # snap split points to the edge linestring
    split_points = shapely.ops.nearest_points(edge_linestring, split_points)[0]
    # make a small buffer around the points to deal with numeric errors
    split_circles = shapely.MultiPoint(split_points).buffer(0.5)
    # split the edge linestring using the buffer circles
    segments = shapely.ops.split(edge_linestring, split_circles)

    # generate a list of new node points (where the linestring has been split)
    node_points = list(map(lambda segment: segment.centroid, list(segments.geoms)[1::2]))
    # add first and last node of the linestring to the new node points
    node_points = [shapely.Point(edge_linestring.coords[0])] + node_points + [shapely.Point(edge_linestring.coords[-1])]

    # generate a list of new node ids
    start_node_id = max(G.nodes) + 1
    node_ids = list(range(start_node_id, start_node_id + len(node_points)-2))
    node_ids = [u] + node_ids + [v]

    # generate a list of edge linestrings
    edge_linestrings = list(segments.geoms)[0::2]

    # zip
    nodes = list(zip(node_ids, node_points))

    if not len(nodes) == len(split_points) + 2 == len(edge_linestrings) + 1:
        print('not len(nodes) == len(split_points) + 2 == len(edge_linestrings) + 1')
        print(u, v, key)
        print(edge_data.get('geometry', shapely.Point()).wkt)
        print(shapely.MultiPoint(split_points).wkt)
        return

    new_edges = []

    for i, node in enumerate(nodes):
        # add node into the graph
        if i != 0 and i != len(node_points)-1:
            G.add_node(node[0], x=node[1].x, y=node[1].y, _split_node=True)
        # add edge into the graph
        if i != 0:
            previous_node = nodes[i-1]
            new_u = previous_node[0]
            new_v = node[0]
            new_edge_data = copy.deepcopy(edge_data)
            # extend the geometry to the exact node points
            new_edge_data['geometry'] = shapely.LineString(
                [previous_node[1]] +
                list(edge_linestrings[i-1].coords) +
                [node[1]]
            )
            new_key = G.add_edge(new_u, new_v, **new_edge_data)
            new_edges.append((new_u, new_v, new_key, new_edge_data))

            # in undirected graphs, the edge topology might have reversed implicitly
            # in such cases, we need to reverse everything else in the edge as well
            if not nx.is_directed(G) and new_u > new_v:
                reverse_edge(G, new_u, new_v, new_key, reverse_topology=False)

    # remove the original edge
    G.remove_edge(u, v, key)

    return new_edges

def reverse_edge(
        G, u, v, key,
        reverse_topology=True,
        lane_description_keys={KEY_LANES_DESCRIPTION, KEY_LANES_DESCRIPTION_AFTER, KEY_GIVEN_LANES_DESCRIPTION}
):
    """
    Flip the edge direction, including lanes and geometry

    Parameters
    ----------
    G : nx.MultiDiGraph
        street graph
    edge : tuple
        the edge to be reversed
    reverse_topology : boolean
        flip the start and end node, automatically false if the G is undirected, be careful when using this
        as is may corrupt the graph by creating inconsistencies between the topological direction and the geometry
    lane_description_keys : set
        which lane description keys should be reversed
    """

    if not G.has_edge(u, v, key):
        return

    data = G.get_edge_data(u, v, key)

    # don't reverse topology if the graph is not directed
    reverse_topology = reverse_topology and nx.is_directed(G)

    # remove the old edge
    if reverse_topology:
        G.remove_edge(u, v, key)

    # reverse lanes
    for lane_description_key in lane_description_keys:
        if data.get(lane_description_key) is not None:
            data[lane_description_key] = space_allocation.reverse_lanes(data[lane_description_key])

    # reverse sensors
    sensors_forward = data.get('sensors_forward', [])
    sensors_backward = data.get('sensors_backward', [])
    data['sensors_forward'] = sensors_backward
    data['sensors_backward'] = sensors_forward

    # reverse geometry
    if data.get('geometry') and data.get('geometry') != shapely.ops.LineString():
        try:
            data['geometry'] = shapely.ops.substring(data['geometry'], 1, 0, normalized=True)
        except AttributeError:
            pass

    # flip the reversed flag
    data[KEY_REVERSED] = not data.get(KEY_REVERSED, False)

    # add the new edge
    if reverse_topology:
        key = G.add_edge(v, u, **data)
    else:
        nx.set_edge_attributes(G, {(u, v, key): data})

    # return the resulting edge
    if reverse_topology:
        return v, u, key, data
    else:
        return u, v, key, data

def delete_edges_without_lanes(G, lane_description_key=KEY_LANES_DESCRIPTION):
    edges_without_lanes = dict(filter(lambda x: x[1] == [], nx.get_edge_attributes(G, lane_description_key).items()))
    G.remove_edges_from(edges_without_lanes)

def filter_lanes_by_modes(G, modes, lane_description_key=KEY_LANES_DESCRIPTION):
    H = copy.deepcopy(G)

    for uvk, data in H.edges.items():
        lanes = data.get(lane_description_key, [])
        data[lane_description_key] = space_allocation.filter_lanes_by_modes(lanes, modes)

    delete_edges_without_lanes(H, lane_description_key=lane_description_key)

    return H

def filter_by_hierarchy(G, hierarchy_levels):
    edges = dict(filter(lambda x: x[1] in hierarchy_levels, nx.get_edge_attributes(G, 'hierarchy').items()))
    return G.edge_subgraph(edges).copy()

def calculate_edge_cost(G, u, v, k, direction, mode, lanes_description=KEY_LANES_DESCRIPTION):

    cost_list = []
    uvk = (u, v, k)
    data = G.edges[uvk]
    for lane in data[lanes_description]:
        lp = space_allocation._lane_properties(lane)
        length = data['length']
        cost = space_allocation._calculate_lane_cost(lane, length, mode, direction)
        cost_list.append(cost)

    return min(cost_list)

def add_edge_costs(G, lanes_description=KEY_LANES_DESCRIPTION):

    for uvk, data in G.edges.items():
        for mode in MODES:
            for direction in ['<', '>']:
                cost = calculate_edge_cost(G, *uvk, direction, mode, lanes_description=lanes_description)
                key = '_'.join(['cost', lanes_description, mode, direction])
                data[key] = cost

def add_pseudo_cycling_lanes(G, lanes_description=KEY_LANES_DESCRIPTION):

    for uvk, data in G.edges.items():
        lanes = data[lanes_description]
        lane_types = [space_allocation._lane_properties(lane).lanetype for lane in lanes]
        has_m_lanes = LANETYPE_MOTORIZED in lane_types

        # ignore if there are no lanes for private cars
        if not has_m_lanes:
            continue

        for direction in [DIRECTION_FORWARD, DIRECTION_BACKWARD]:
            cycling_cost = calculate_edge_cost(G, *uvk, direction, MODE_CYCLING, lanes_description=lanes_description)

            if cycling_cost == np.Inf:
                lanes.append(LANETYPE_CYCLING_PSEUDO + direction)

def clone(G, edges=True):

    H = nx.MultiDiGraph()
    H.graph = G.graph
    H.nodes = G.nodes

    if edges:
        for uvk, data in G.edges.items():
            H.add_edge(*uvk, **data)

    return H

def separate_edges_for_lane_directions(G):

    H = clone(G, edges=False)

    for uvk, data in G.edges.items():

        u, v, k = uvk
        lanes = data[KEY_LANES_DESCRIPTION]
        lanes_forward = []
        lanes_backward = []

        for lane in lanes:
            lp = space_allocation._lane_properties(lane)
            if lp.direction == DIRECTION_FORWARD:
                lanes_forward.append(lane)
            if lp.direction == DIRECTION_BACKWARD:
                lanes_backward.append(lane)
            # convert bidirectional lanes into two separate oneway lanes
            if lp.direction == DIRECTION_BOTH:
                lp_forward = space_allocation._lane_properties(lane)
                lp_forward.direction = DIRECTION_FORWARD
                lanes_forward.append(str(lp_forward))
                lp_backward = space_allocation._lane_properties(lane)
                lp_backward.direction = DIRECTION_BACKWARD
                lanes_backward.append(str(lp_backward))

        new_data = copy.deepcopy(data)
        del new_data[KEY_LANES_DESCRIPTION]
        del new_data['sensors_forward'], new_data['sensors_backward']

        if len(lanes_forward) > 0:
            H.add_edge(
                u, v, **new_data,
                **{KEY_LANES_DESCRIPTION: lanes_forward},
                sensors_forward=data['sensors_forward'],
                sensors_backward=[]
            )

        if len(lanes_backward) > 0:
            H.add_edge(
                u, v, **new_data,
                **{KEY_LANES_DESCRIPTION: lanes_backward},
                sensors_forward=[],
                sensors_backward=data['sensors_backward']
            )

    space_allocation.update_osm_tags(G, lanes_description_key=KEY_LANES_DESCRIPTION)
    organize_edge_directions(G)

    return H


#!/usr/bin/python3

import sys
sys.path.append("/course/common/utils")
from inginious_container_api import input, feedback, rst
from answer import expected_answers
from feedback_functions import *
from validation_functions import *
from parsing_functions import *
from correction_functions import *

correct_answers = 0
student_answer_q1 = input.get_input("tr_td_tags")
student_answer_q2 = input.get_input("th_tag")
student_answer_q3 = input.get_input("span")

input.parse_template("template_q1.html")
input.parse_template("template_q2.html")
input.parse_template("template_q3.html")

raw_student_answers = {"tr_td_tags": [student_answer_q1, False], "th_tag": [student_answer_q2, False], "span": [student_answer_q3, False]}

validation_errors_q1 = nu_checker_validation("template_q1.html", task="tr_td_tags", offset=7)
validation_errors_q2 = nu_checker_validation("template_q2.html", task="th_tag", offset=7)
validation_errors_q3 = nu_checker_validation("template_q3.html", task="span", offset=7)

validation_errors = {"tr_td_tags": validation_errors_q1, "th_tag": validation_errors_q2, "span": validation_errors_q3}
for task in validation_errors:
    if validation_errors[task]:
        raw_student_answers.pop(task)
        feedback.set_problem_feedback("Il y a des erreurs de syntaxe:\n\n", task, True)
        for error in validation_errors[task]:
            feedback.set_problem_feedback(f"- Ligne {error.get('line_number')} : {error.get('message')}\n", task, True)
    else:
        tag_errors = html_tags_validation(input.get_input(task))
        if tag_errors:
            raw_student_answers.pop(task)
            feedback.set_problem_feedback("Il y a des erreurs de syntaxe:\n\n", task, True)
            for error in tag_errors:
                feedback.set_problem_feedback(f"- Ligne {error.get('line_number')} : l'élément ``{error.get('element')}`` en position n°{error.get('element_number')} dans la hiérarchie ne semble pas être accompagné de sa balise fermante.\n", task, True)

parsed_answers = parse_html_as_dict(raw_student_answers)

task_result = check_html_correctness(parsed_answers, expected_answers)

for task in task_result:
    if task_result.get(task):
        correct_answers += 1

if correct_answers == 3:
    feedback.set_global_result("success")
else:
    feedback.set_global_result("failed")

compute_score(3, correct_answers)


import numpy as np
import pandas as pd
np.set_printoptions(suppress=True, threshold=np.nan)
import json

def demo1():
    A = np.array([[3, -1], [-1, 3]])
    print('打印A：\n{}'.format(A))
    a, b = np.linalg.eig(A)
    print('打印特征值a：\n{}'.format(a))
    print('打印特征向量b：\n{}'.format(b))

    A = np.array([[-1, 1, 0], [-4, 3, 0], [1, 0, 2]])
    print('打印A：\n{}'.format(A))
    a, b = np.linalg.eig(A)
    print('打印特征值a：\n{}'.format(a))
    print('打印特征向量b：\n{}'.format(b))

    A = np.array([[0.1, 0.2, 0.4, 0.6], [0.2, 0.3, 0.4, 0.2]])
    H = np.dot(A.T, A)
    print("打印H: \n{}".format(H))
    a, b = np.linalg.eig(H)

    print("打印特征值a: \n{}".format(a))
    print("打印特征值b: \n{}".format(b))
    print(b.T)

class WeightCalculation():
    def __init__(self, filePath):
        self.filePath = filePath

    # 评价指标Xj是以同等地位参与评价过程这个条件为前提的, 而事实上Xj之间的相对重要性程度是不同的
    def compute_weights(self):
        p = pd.read_csv(self.filePath)
        print(p)
        #p = p[["demDiff", "perDiff", "AveDia", "diaDiff", "pipeLen", "DiaLen", "Degree"]]
        p = p[["perDiff", "AveDia", "pipeLen", "DiaLen", "Degree"]]

        npl = p.values
        phalanx = np.dot(npl.T, npl)
        a, b = np.linalg.eig(phalanx)  # 计算矩阵的特征值, 特征向量
        b2 = b.T
        # print(b2)   # 查看b2首行是否全为正 或者全为负
        # print(np.dot(b.T, b))
        l = []
        # 得到最大特征值对应的特征向量并进行归一化
        for i in b2[0]:
            o = i / sum(b2[0])
            l.append(o)
        return l

    def compute_result(self):
        weights_list = self.compute_weights()
        print(weights_list)
        p = pd.read_csv(self.filePath)
        new_p = p[["perDiff", "AveDia", "pipeLen", "DiaLen", "Degree"]]
        evaluation_result = new_p["perDiff"]*weights_list[0]+\
                            new_p["AveDia"]*weights_list[1]+\
                            new_p["pipeLen"]*weights_list[2]+\
                            new_p["DiaLen"]*weights_list[3]+\
                            new_p["Degree"]*weights_list[4]
        #print(type(evaluation_result))
        print(sum(evaluation_result))
        # p["evaluation_result"] = evaluation_result
        # p.to_csv("F:\\AWorkSpace\\Python-Learning-Data\\datamining__weight_result2.csv")

    # 将权重拿出来, 放进单独的文件里
    def add_weight(self):
        p = pd.read_csv("F:\\AWorkSpace\\Python-Learning-Data\\datamining__weight_result.csv")
        node_name = p[["nodeName", "evaluation_result"]]
        node_json = node_name.to_json()
        path = "F:\\AWorkSpace\\Python-Learning-Data\\json_node_weight.json"

        with open(path, "r") as f:
            data = json.load(f)
        m = list(data["nodeName"].values())
        n = list(data["evaluation_result"].values())
        node_dirt = {}
        for i in range(len(m)):
            node_dirt[m[i]] = n[i]
        print(node_dirt)
        with open(path, "w") as f:
            json.dump(node_dirt, f)
        return node_dirt

if __name__=="__main__":
    filePath = "F:\\AWorkSpace\\Python-Learning-Data\\datamining2.csv"
    filePath2 = "F:\\AWorkSpace\\Python-Learning-Data\\datatest.csv"

    # print(WeightCalculation(filePath).compute_result())


sr=lambda: input()
ir=lambda: int(sr())
lr=lambda: list(map(int, sr().split()))

# dr=lambda: float(sr())
# dlr=lambda: list(map(float, sr().split()))

inf=10**18
# mod = 10**9+7
mod=998244353

def main():
    n,k,x=lr()
    a=lr()
    a.sort(reverse=True)
    # 0 ijou
    for i in range(n):
        now = a[i]
        tmp = now//x
        if k >= tmp:
            k-=tmp
            a[i]=now-tmp*x
        else:
            a[i]=now-k*x
            k=0
            break
    a.sort(reverse=True)
    for i in range(n):
        if k==0:
            break
        a[i]=0
        k-=1
    print(sum(a))

if __name__ == '__main__':
    main()


from tkinter import *
from tkinter import ttk

ventana= Tk()
ventana.title("Películas")
ventana.configure(bg="#F3C7AA")
ventana.configure(cursor="pencil")
ventana.geometry('420x220')
style =ttk.Style()
style.configure("Transparent.TLabel", background=ventana["bg"])

def añadir_pelicula():
    pelicula = nombre.get()
    if pelicula:
        listpelis.insert(END, pelicula)
        nombre.delete(0, END)

def borrar_todo():
    listpelis.delete(0, END)

titulo=ttk.Label(ventana, text="Ingresa el nombre de una película", style="Transparent.TLabel", font=("Arial", 9, "bold"))
titulo.grid(row=2, column=1, padx=20, pady=20)
nombre=ttk.Entry(ventana, width=25)
nombre.grid(row=3, column=1)

añadir=Button(ventana, text="Añadir", bg="#9E3700", fg="white", command=añadir_pelicula). grid(row=4, column=1, padx=20, pady=20)
añadir=Button(ventana, text="Borrar todo",  bg="#9E3700",  fg="white", command=borrar_todo). grid(row=5, column=1, padx=20, pady=8)

peliculas=ttk.Label(ventana, text="Películas", style="Transparent.TLabel", font=("Arial", 9, "bold"))
peliculas.grid(row=2, column=2, padx=20, pady=20)
listpelis = Listbox(ventana, width=25, height=9)
listpelis.grid(row=3, column=2, rowspan=3, padx=10)

ventana.mainloop()


import json
import base64
from io import BytesIO
from urllib import parse
from PIL import Image, ImageDraw, ImageFont

FONT_PATH = "./assets/GenEiLateMin_subset.ttf"
IMG_PATH = "./assets/plain.png"

# magic numbers
# result of try&error confirming output image.
TEXT_MAX_WORDS = 25
FONT_RELATIVE_HEIGHT = 0.05
TEXT_ONE_Y = 0.798
TEXT_TWO_Y = 0.876
TEXT_X = 0.0708

def insert_text(img, text, relative_xy, fontname, fill="#FFF"):
    """insert text (one line) to Pillow image object
    Parameters
    ----------
    img: PIL.Image, required
    text: string, required
    relative_xy: tuple[float, float], required
    fontname: string, required

    Returns
    ----------
    img: PIL.Image
    """

    if len(text) > TEXT_MAX_WORDS:
        text = text[:TEXT_MAX_WORDS] + ".."

    draw = ImageDraw.Draw(img)

    (w, h) = img.size
    (rel_x, rel_y) = relative_xy
    absolute_pos = (round(w*rel_x), round(h*rel_y)) # need calculation

    fontSize = round(h * FONT_RELATIVE_HEIGHT)
    font = ImageFont.truetype(fontname, fontSize)
    draw.text(absolute_pos, text, font=font, fill=fill)
    return img

def pil_to_base64(img):
    """convert PIL.Image to base64 encoded string
    Parameters
    ----------
    img: PIL.Image, required

    Returns
    ----------
    img_base64: string
    """
    buf = BytesIO()
    img.save(buf, format="png")
    img_base64 = base64.b64encode(buf.getvalue()).decode("ascii")
    return img_base64

def lambda_handler(event, context):
    """
    Parameters
    ----------
    event: dict, required
        API Gateway Lambda Proxy Input Format

        Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format

    context: object, required
        Lambda Context runtime methods and attributes

        Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html

    Returns
    ------
    API Gateway Lambda Proxy Output Format: dict

        Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html
    """

    try:
        req = json.loads(event["body"])
    except TypeError:
        print("null request body.")
        return {
            "statusCode": 400,
            "body": "null request body."
        }

    try:
        claim = parse.unquote(req["claim"])
        who = parse.unquote(req["who"])
    except KeyError:
        print("unexpected request format")
        return {
            "statusCode": 400,
            "body": "unexpected request format."
        }

    try:
        img = Image.open(IMG_PATH)
    except:
        return {
            "statusCode": 502,
            "body": "could not open plain image."
        }

    try:
        img = insert_text(img, f"{claim}よぅ、", (TEXT_X, TEXT_ONE_Y), FONT_PATH)
        img = insert_text(img, f"そういうところだぞ{who}ーーーー！", (TEXT_X, TEXT_TWO_Y), FONT_PATH)
        # img.save("out.png", "PNG", quality=100, optimize=True)
    except:
        return {
            "statusCode": 502,
            "body": "could not insert texts."
        }

    try:
        img_base64 = pil_to_base64(img)
    except:
        return {
            "statusCode": 502,
            "body": "could not encode img by base64"
        }

    return {
        "isBase64Encoded": True,
        "statusCode": 200,
        "headers": {
            "Content-Type": "image/png",
            "Access-Control-Allow-Headers": "Content-Type",
            "Access-Control-Allow-Origin": "https://tenkoh.github.io",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        },
        "body": json.dumps({
            "image": img_base64,
        }),
    }


from .gcp import Model as GCPModel
from .lp import LinConstr, Bounds, CvxConstr, ConeConstr, ExpConstr, KLConstr, LMIConstr
from .lp import Vars, VarSub, Affine, Convex
from .lp import DecRule
from .lp import RoAffine, RoConstr
from .lp import PiecewiseConvex, PWConstr
from .lp import Solution, def_sol
import numpy as np
from numbers import Real
from collections.abc import Iterable
# from .subroutines import *

class Model:
    """
    The Model class creates an object of robust optimization models
    """

    def __init__(self, name=None):

        self.rc_model = GCPModel(mtype='R', top=self)
        self.sup_model = GCPModel(nobj=True, mtype='S', top=self)

        self.all_constr = []

        self.obj = None
        self.obj_support = None
        self.sign = 1

        self.primal = None
        self.dual = None
        self.solution = None
        self.pupdate = True
        self.dupdate = True

        self.solution = None

        self.name = name

    def reset(self):

        self.all_constr = []
        self.pupdate = True
        self.dupdate = True
        self.primal = None
        self.dual = None
        self.rc_model.reset()

    def dvar(self, shape=(), vtype='C', name=None, aux=False):
        """
        Returns an array of decision variables with the given shape
        and variable type.

        Parameters
        ----------
        shape : int or tuple
            Shape of the variable array. The variable is a scalar if
            the shape is unspecified.
        vtype : {'C', 'B', 'I'}
            Type of the decision variables. 'C' means continuous; 'B'
            means binary, and 'I" means integer.
        name : str
            Name of the variable array
        aux : leave it unspecified.

        Returns
        -------
        new_var : rsome.lp.Vars
            An array of new decision variables
        """

        new_var = self.rc_model.dvar(shape, vtype, name, aux)
        return new_var

    def rvar(self, shape=(), name=None):

        """
        Returns an array of random variables with the given shape.

        Parameters
        ----------
        shape : int or tuple
            Shape of the variable array.
        name : str
            Name of the variable array

        Returns
        -------
        new_var : rsome.lp.Vars
            An array of new random variables
        """

        new_var = self.sup_model.dvar(shape, 'C', name)
        return new_var

    def ldr(self, shape=(), name=None):

        """
        Returns an array with the given shape of linear decision rule
        variables.

        Parameters
        ----------
        shape : int or tuple
            Shape of the variable array.
        name : str
            Name of the variable array

        Returns
        -------
        new_var : rsome.ro.DecRule
            An array of new linear decision rule variables
        """

        new_ldr = DecRule(self, shape, name)
        return new_ldr

    def min(self, obj):
        """
        Minimize the given objective function.

        Parameters
        ----------
        obj : RSOME expression, numeric constant
            An objective function

        Notes
        -----
        The objective function given as an array must have the size
        to be one.
        """

        if self.obj is not None:
            raise SyntaxError('Redefinition of the objective is not allowed.')

        if not isinstance(obj, (Real, PiecewiseConvex)):
            if isinstance(obj, VarSub):
                if obj.indices.size > 1:
                    raise ValueError('Incorrect function dimension.')
            else:
                if obj.size > 1:
                    raise ValueError('Incorrect function dimension.')

        self.obj = obj
        self.sign = 1
        self.pupdate = True
        self.dupdate = True

    def max(self, obj):
        """
        Maximize the given objective function.

        Parameters
        ----------
        obj : RSOME expression, numeric constant
            The objective function

        Notes
        -----
        The objective function given as an array must have the size
        to be one.
        """

        if self.obj is not None:
            raise SyntaxError('Redefinition of the objective is not allowed.')

        if not isinstance(obj, (Real, PiecewiseConvex)):
            if isinstance(obj, VarSub):
                if obj.indices.size > 1:
                    raise ValueError('Incorrect function dimension.')
            else:
                if obj.size > 1:
                    raise ValueError('Incorrect function dimension.')

        self.obj = obj
        self.sign = - 1
        self.pupdate = True
        self.dupdate = True

    def minmax(self, obj, *args):

        """
        Minimize the maximum objective value over the given uncertainty set.

        Parameters
        ----------
        obj : RSOME expression, numeric constant
            Objective function involving random variables
        *args
            Constraints or collections of constraints of random variables
            used for defining the uncertainty set

        Notes
        -----
        The uncertainty set defined for the objective function is considered
        the default uncertainty set for the robust model.
        """

        if self.obj is not None:
            raise SyntaxError('Redefinition of the objective is not allowed.')

        if not isinstance(obj, (Real, PiecewiseConvex)):
            if obj.size > 1:
                raise ValueError('Incorrect function dimension.')

        constraints = []
        for items in args:
            if isinstance(items, Iterable):
                constraints.extend(list(items))
            else:
                constraints.append(items)

        sup_model = self.sup_model
        sup_model.reset()
        for item in constraints:
            if item.model is not sup_model:
                raise ValueError('Models mismatch.')
            sup_model.st(item)

        self.obj = obj
        self.obj_support = sup_model.do_math(primal=False, obj=False)
        self.sign = 1
        self.pupdate = True
        self.dupdate = True

    def maxmin(self, obj, *args):

        """
        Maximize the minimum objective value over the given uncertainty set.

        Parameters
        ----------
        obj : RSOME expression, numeric constant
            Objective function involving random variables
        *args
            Constraints or collections of constraints of random variables
            used for defining the uncertainty set

        Notes
        -----
        The uncertainty set defined for the objective function is considered
        the default uncertainty set for the robust model.
        """

        if self.obj is not None:
            raise SyntaxError('Redefinition of the objective is not allowed.')

        if not isinstance(obj, (Real, PiecewiseConvex)):
            if obj.size > 1:
                raise ValueError('Incorrect function dimension.')

        constraints = []
        for items in args:
            if isinstance(items, Iterable):
                constraints.extend(list(items))
            else:
                constraints.append(items)

        sup_model = self.sup_model
        sup_model.reset()
        for item in constraints:
            if item.model is not sup_model:
                raise ValueError('Models mismatch.')
            sup_model.st(item)

        self.obj = obj
        self.obj_support = sup_model.do_math(primal=False, obj=False)
        self.sign = - 1
        self.pupdate = True
        self.dupdate = True

    def st(self, *arg):
        """
        Define constraints that an optimization model subject to.

        Parameters
        ----------
        *args : RSOME constraints, iterables
            Constraints or collections of constraints that the model
            subject to.

        Notes
        -----
        Multiple constraints can be defined altogether as the argument
        of the st method.
        """

        for constr in arg:
            if isinstance(constr, Iterable):
                for item in constr:
                    self.st(item)
            elif isinstance(constr, PWConstr):
                for piece in constr.pieces:
                    self.st(piece)
            elif isinstance(constr, (LinConstr, Bounds, CvxConstr,
                                     ConeConstr, ExpConstr, KLConstr, LMIConstr)):
                if (constr.model is not self.rc_model) or \
                        (constr.model.mtype != 'R'):
                    raise ValueError('Models mismatch.')
                self.all_constr.append(constr)
            elif isinstance(constr, RoConstr):
                if (constr.dec_model is not self.rc_model) or \
                        (constr.rand_model is not self.sup_model):
                    raise ValueError('Models mismatch.')
                sense = (constr.sense[0] if isinstance(constr.sense,
                                                       np.ndarray)
                         else constr.sense)
                if sense == 0:
                    self.all_constr.append(constr)
                else:
                    left = RoAffine(constr.raffine, constr.affine,
                                    constr.rand_model)
                    right = RoAffine(-constr.raffine, -constr.affine,
                                     constr.rand_model)
                    left_constr = RoConstr(left, sense=0)
                    left_constr.support = constr.support
                    right_constr = RoConstr(right, sense=0)
                    right_constr.support = constr.support
                    self.all_constr.append(left_constr)
                    self.all_constr.append(right_constr)
            else:
                raise TypeError('Unknown type of constraints')

        self.pupdate = True
        self.dupdate = True

        if len(arg) == 1:
            return arg[0]
        else:
            return arg

    def do_math(self, primal=True):
        """
        Return the linear, or conic programming problem as the standard
        formula or deterministic counterpart of the model.

        Parameters
        ----------
        primal : bool, default True
            Specify whether return the primal formula of the model.
            If primal=False, the method returns the dual formula.

        Returns
        -------
        prog : GCProg
            A conic programming problem.
        """

        if primal:
            if self.primal is not None and not self.pupdate:
                return self.primal
        else:
            if self.dual is not None and not self.dupdate:
                return self.dual
            else:
                self.do_math(primal=True)
                return self.rc_model.do_math(False, obj=True)

        self.rc_model.reset()
        if isinstance(self.obj, (Vars, VarSub, Affine, Convex, Real)):
            self.rc_model.obj = self.obj
            self.rc_model.sign = self.sign
            more_roc = []
        elif isinstance(self.obj, RoAffine):
            obj_constr = (self.rc_model.vars[0] >= self.sign * self.obj)
            obj_constr.support = self.obj_support
            more_roc = [obj_constr]
        elif isinstance(self.obj, PiecewiseConvex):
            more_roc = []
            pw_constr = self.rc_model.vars[0] >= self.sign * self.obj
            more_roc = pw_constr.pieces
        else:
            raise TypeError('Incorrect type for the objective function.')

        for constr in self.all_constr + more_roc:
            if isinstance(constr, (LinConstr, Bounds, CvxConstr, ConeConstr,
                                   ExpConstr, KLConstr, LMIConstr)):
                self.rc_model.st(constr)
            if isinstance(constr, RoConstr):
                if constr.support:
                    rc_constrs = constr.le_to_rc()
                else:
                    rc_constrs = constr.le_to_rc(self.obj_support)
                for rc_constr in rc_constrs:
                    self.rc_model.st(rc_constr)

        formula = self.rc_model.do_math(primal, obj=True)

        if primal:
            self.primal = formula
            self.pupdate = False
        else:
            self.dual = formula
            self.dupdate = False

        return formula

    def solve(self, solver=None, display=True, log=False, params={}):
        """
        Solve the model with the selected solver interface.

        Parameters
        ----------
        solver : {None, lpg_solver, clp_solver, ort_solver, eco_solver
                  cpx_solver, grb_solver, msk_solver, cpt_solver}
            Solver interface used for model solution. Use the default
            solver if solver=None.
        display : bool
            True for displaying the solution information. False for hiding
            the solution information.
        log : bool
            True for printing the log information. False for hiding the log
            information. So far the argument only applies to Gurobi, CPLEX,
            and Mosek.
        params : dict
            A dictionary that specifies parameters of the selected solver.
            So far the argument only applies to Gurobi, CPLEX, and Mosek.
        """

        if solver is None:
            solution = def_sol(self.do_math(), display, log, params)
        else:
            solution = solver.solve(self.do_math(), display, log, params)

        if isinstance(solution, Solution):
            self.rc_model.solution = solution
        else:
            self.rc_model.solution = None

        self.solution = self.rc_model.solution

    def soc_solve(self, solver=None, degree=4, cuts=(-30, 60),
                  display=True, log=False, params={}):
        """
        Solve the approximated SOC model with the selected solver interface.

        Parameters
        ----------
            solver : {None, lpg_solver, clp_solver, ort_solver, eco_solver
                      cpx_solver, grb_solver, msk_solver}
                Solver interface used for model solution. Use default solver
                if solver=None.
            degree : int
                The L-degree value for approximating exponential cone
                constraints.
            cuts : tuple of two integers
                The lower and upper cut-off values for the SOC approximation
                of exponential constraints.
            display : bool
                Display option of the solver interface.
            params : dict
                A dictionary that specifies parameters of the selected solver.
                So far the argument only applies to Gurobi, CPLEX, and Mosek.
        """

        formula = self.do_math().to_socp(degree, cuts)
        if solver is None:
            solution = def_sol(formula, display, log, params)
        else:
            solution = solver.solve(formula, display, log, params)

        if isinstance(solution, Solution):
            self.rc_model.solution = solution
        else:
            self.rc_model.solution = None

        self.solution = self.rc_model.solution

    def get(self):
        """
        Return the optimal objective value of the solved model.

        Notes
        -----
        An error message is given if the model is unsolved or no solution
        is obtained.
        """

        if self.rc_model.solution is None:
            raise RuntimeError('The model is unsolved.')

        solution = self.rc_model.solution
        if np.isnan(solution.objval):
            msg = 'No solution available. '
            msg += f'{solution.solver} solution status: {solution.status}'
            raise RuntimeError(msg)

        return self.sign * self.rc_model.solution.objval

    def optimal(self):

        if self.solution is None:
            return False
        else:
            return not np.isnan(self.solution.objval)


from bs4 import BeautifulSoup
import requests
import pandas as pd

pages=[]
titles=[]
locations=[]
companys=[]
links=[]
dates=[]

page_to_scape=1

search = "student"
location = 3500

for i in range(1,page_to_scape+1):
  url = ("https://be.indeed.com/jobs?q={}&l={}&sort=date&start={}0").format(search,location,i)
  pages.append(url)

for url in pages:
    page = requests.get(url)
    soup = BeautifulSoup(page.text,'html.parser')

    for title in soup.find_all('h2'):
        titles.append(title.getText()[2:-6])
        temp = title.findChild("a" , recursive=False).get('href')
        link = "https://be.indeed.com{}".format(temp)
        links.append(link)

    for location in soup.find_all('div',class_='recJobLoc'):
        locations.append(location.get('data-rc-loc'))

    for date in soup.find_all('span',class_="date"):
        dates.append(date.getText())

    for company in soup.find_all('span',{'class':"company"}):
        companys.append(company.text[1:])

data = {'Title':titles, 'Locations':locations,'Company':companys, 'Link': links,'Date':dates}
df = pd.DataFrame(data = data)
df.index+=1
df.to_excel('Jobs.xlsx')


'''
    This is the main driver file resposible for user input and user return displays
'''

import pygame as p
from ChessEngine import GameState, Move

p.init()
p.font.init()

WIDTH = HEIGHT = 512
DIMENSION = 8
SQ_SIZE = HEIGHT // DIMENSION
MAX_FPS = 15 # for animation purposes
IMAGES = {} # an empty image dictionary
WHITE = p.Color("white")
SALMON = p.Color("salmon")

# function in pygame that loads the elements images onto the board once
def loadImages():
    pieces = ['bB', 'bK', 'bN', 'bp', 'bQ', 'bR', 'wB', 'wK', 'wN', 'wp', 'wQ', 'wR']
    for piece in pieces:
        IMAGES[piece] = p.transform.scale(p.image.load('images/' + piece + '.png'), (SQ_SIZE, SQ_SIZE))

# the main driver handling user input and graphics update
def main():
    screen =  p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color(WHITE))
    gs = GameState()    # gs is the game state
    validMoves = gs.getValidMoves()
    moveMade = False
    loadImages()    # we are only loading the images once in pygame
    running = True
    sqSelected = () # keeps track of the last user mouse clicks
    playerClicks = [] # keeps track of the last player clicks
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            # mouse key handlers
            elif e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos() # location of x and y
                col = location[0]//SQ_SIZE
                row = location[1]//SQ_SIZE
                if sqSelected == (row, col):
                    sqSelected = ()
                    playerClicks = []
                # if the player clicks on a chess piece
                else:
                    sqSelected = (row, col)
                    playerClicks.append(sqSelected) # this appends both the 1st and the 2nd clicks
                if len(playerClicks) == 2: # if the user made 2 mouse clicks
                    move = Move(playerClicks[0], playerClicks[1], gs.board)
                    print(str(move.getChessNotation()) + ' id: ' + str(move.moveID))

                    for i in range(len(validMoves)):
                        if move == validMoves[i]:
                            gs.makeMove(validMoves[i])
                            moveMade = True
                            sqSelected = ()
                            playerClicks = [] # resets user clicks
                    if not moveMade:
                        playerClicks = [sqSelected]

            # keyboard handlers
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z: # the undo key
                    gs.undoMove()
                    moveMade = True

        if moveMade:
            validMoves = gs.getValidMoves()
            moveMade = False

        drawGameState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()

# The drawGameState is responsible for all user graphics
def drawGameState(screen, gs):
    drawBoard(screen) # draws the board squares
    drawPieces(screen, gs.board)

# random color placements
def drawBoard(screen):
    colors = [p.Color(WHITE), p.Color(SALMON)]
    for r in range(DIMENSION):
        for c in range(DIMENSION):
            color = colors[((r+c) % 2)]
            p.draw.rect(screen, color, p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))

# drawPieces responsible for the chess pieces
def drawPieces(screen, board):
    for r in range(DIMENSION):
        for c in range(DIMENSION):
            piece = board[r][c]
            if piece != "--": # not empty
                screen.blit(IMAGES[piece], p.Rect(c*SQ_SIZE, r*SQ_SIZE, SQ_SIZE, SQ_SIZE))


from mido import *
from mido import open_input
from mido import open_output
from mido import Message

midi_in = open_input('Midi Fighter Twister')
midi_out = open_output('Midi Fighter Twister')

# Use knobs as input to learn how outputs are mapped on one knob

control = 0
value = 0
channel = 0

print(dir(midi_in))

for msg in midi_in:

    if msg.control == 32:
        control = msg.value
    elif msg.control == 33:
        value = msg.value
    elif msg.control == 34:
        channel = msg.value % 16

    m = Message('control_change', control=control, value=value, channel=channel)
    print(m)
    midi_out.send(m)

print("Done")


"""
    Autor: Dan Nastasa

        Changlog
    Version 1.0
    - first implementation
"""

import string

# IMPORTANT: If you add more endings, make sure they are lowercase
basicEndings = ["bye","goodbye", "ciao", "cya", "later", "adio", "sayonara", "servus", "farewell", "adios",
                "peace out", "so long", "have a good one", "see you later", "talk to you later", "bye bye",
                "take care", "have a good day", "see you later", "see you next time", "im out"]

def isEndOfConversation(prop):
    eliminatePunctuation = str.maketrans({key: None for key in string.punctuation})

    parsedProp = prop.translate(eliminatePunctuation)
    parsedProp = parsedProp.replace(" ", "")

    for phrase in basicEndings:
        checkString = phrase.replace(" ", "")

        if checkString == parsedProp.lower():
            return True
        if parsedProp.startswith(checkString):
            return True
        if parsedProp.endswith(checkString):
            return True

    return False

# print (isEndOfConversation("Goodbye! Im gonna go now. See you later!!"))


import threading

from .types import is_icypaw_type_annotation, BooleanWithMetadata
from .exceptions import IcypawException
from .descriptor import get_object, iter_objects, iter_objects_from_type
from . import tahu_interface as ti

class Metric:
    """A class following the Python descriptor protocol that provides easy
    access to a metric. It allows the user to set up hooks to
    customize the external API while automatically providing a simple,
    property-like API internally.

    """

    def __init__(self, type_, name=None, read_only=False, initial=None, properties=None):
        """Create a new Metric in the body of a Node or Device.

        type_ -- The IcypawType for this metric.

        name -- The name this metric will be published as externally. If not
        given, use the same name as the variable this is stored under.

        read_only -- Whether this variable is read-only for clients on the
        network. The metric is always writable within the Node or Device. This
        value is also used to set the ``Writable`` property of this metric,
        which may be overridden by ``properties``

        initial -- An initial value to make all instances of this metric.

        properties -- A dict of properties to associate with this metric.

        """

        if not is_icypaw_type_annotation(type_):
            raise TypeError(f'type {type_} is not an IcypawType')

        self._type = type_
        self._name = str(name) if name is not None else None
        self._owner_name = None
        self._read_only = bool(read_only)
        self._initial = initial

        # Merge default metric properties with arguments
        self._properties = {
            'Writable': not self._read_only
        }
        if properties:
            self._properties.update(properties)

        self._net_hook = None

    ##
    # Public methods
    #

    @property
    def name(self):
        """The full path this metric is known under on the network."""
        return self._name or self._owner_name

    @property
    def owner_name(self):
        """The name this metric is known by internally."""
        return self._owner_name

    @property
    def type(self):
        """The IcypawType subclass representing the type of this metric."""
        return self._type

    @property
    def properties(self):
        """Return a dict of the properties of this metric mapping strings
        to Python types."""
        return dict(self._properties)

    def assign_to_current_thread(self, instance):
        """Make it an error to read or write this metric from any thread other
        than this one."""
        stored_metric = self._get_stored_metric(instance)
        stored_metric.assign_to_current_thread()

    def get(self, instance):
        """Return the IcypawType object stored."""
        return self._get_value(instance)

    def is_historical(self, instance):
        """Return whether the value as currently stored is considered
        historical."""

        return self._get_stored_metric(instance).is_historical

    def is_transient(self, instance):
        """Return whether the value as currently stored is considered
        transient."""

        return self._get_stored_metric(instance).is_transient

    def is_null(self, instance):
        """Return whether the value as currently stored is null."""

        return self._get_value(instance) is None

    def get_network(self, instance):
        """Return the value according to the user's customizations. If a
        get_hook has been provided, use it. Otherwise return the value
        itself. Unlike __get__, this returns the wrapped Icypaw
        object.

        """

        # Note: We eventually will want to add some sort of hook here,
        # but prematurely adding features here was causing problems so
        # it's not implemented.

        icypaw_value = self._get_value(instance)
        return icypaw_value

    def set_network(self, instance, value):
        """Set the value according to the user's customizations. If a net_hook
        has been provided, use it. Otherwise set the value
        directly. This accepts a wrapped IcypawType value but unwraps
        it when being sent to the set hook.

        Additionally, if this Metric has Template type, this will
        merge the value in, unlike the direct setter which will
        overwrite all previous values.

        """

        if self._read_only:
            raise IcypawException(f"Attempting to set read-only metric {self._name}")

        if not isinstance(value, self._type):
            raise IcypawException(f"Metric set with wrong type, expected {self._type} got {type(value)}")

        is_historical = False
        is_transient = False

        if self._net_hook:
            pyvalue = self._net_hook(instance, value.to_pseudopython())
            if pyvalue is None:
                raise IcypawException("net_hook did not return a value")
            icypaw_value = self._type(pyvalue)
            self._set_value(instance, icypaw_value, is_historical, is_transient)
        else:
            self._set_value(instance, value, is_historical, is_transient)

    def tahu_metric(self, instance, with_properties=False):
        """Construct a Tahu Metric representation of this metric."""
        tahu_metric = ti.new_metric()
        tahu_metric.name = str(self.name).encode()

        if not self.is_null(instance):
            self.get(instance).set_in_metric(tahu_metric)
        else:
            tahu_metric.is_null = True

        if self.is_historical(instance):
            tahu_metric.is_historical = True

        if self.is_transient(instance):
            tahu_metric.is_transient = True

        if with_properties:
            self._set_properties(tahu_metric, self._properties)

        return tahu_metric

    def delete_metric(self, instance):
        """Delete this metric and its stored data from the given instance."""
        delattr(type(instance), self._owner_name)
        delattr(instance, self._store_name)

    ##
    # Decorators
    #

    def net_hook(self, func):
        """Define the given function as the network set hook for this metric. If
        not provided, the value is set directly.

        net_hook is expected to be a method in the endpoint class. It must
        return the value it wants set. In this way it differs from Python
        property setters which expect the user to store the value themselves.

        """

        if self._read_only:
            raise IcypawException("net_hook cannot be used for a read-only metric")

        self._net_hook = func
        return self

    ##
    # Descriptor protocol methods
    #

    def __get__(self, instance, owner):
        """Return the value of this metric. This is used locally on the Node
        or Device. Return a value that acts like a native Python
        value.

        """

        if not self.is_null(instance):
            return self._get_value(instance).to_pseudopython()
        else:
            return None

    def __set__(self, instance, value):
        """Set the value of this metric, performing type checking and possible
        conversion. This is used locally on the Node or Device.

        """

        value, is_historical, is_transient, is_null = self._unwrap_user_value(value)

        if is_null:
            icypaw_value = None
        else:
            icypaw_value = self._type(value)
        self._set_value(instance, icypaw_value, is_historical, is_transient)

    def __set_name__(self, owner, name):
        """Set the network name if one has not already been given."""
        self._owner_name = name

        # If the hook has a different name from what this descriptor
        # is registered with, also register the hook as its own method
        # so that it may be used directly.

        if self._net_hook and self._net_hook.__name__ != name:
            setattr(owner, self._net_hook.__name__, self._net_hook)

    ##
    # Private methods
    #

    def _get_value(self, instance):
        """Retrieve the value stored in the instance."""
        stored_metric = self._get_stored_metric(instance)
        return stored_metric.stored_value

    def _set_value(self, instance, value, is_historical, is_transient):
        """Store the given Icypaw value in the instance."""
        stored_metric = self._get_stored_metric(instance)
        stored_metric.stored_value = value
        stored_metric.is_historical = is_historical
        stored_metric.is_transient = is_transient

    def _get_stored_metric(self, instance):
        stored_metric = getattr(instance, self._store_name, None)
        if stored_metric is None:
            stored_metric = StoredMetric(self._type(self._initial))
            setattr(instance, self._store_name, stored_metric)
        return stored_metric

    @property
    def _store_name(self):
        """Return the name we use to store the actual value in the instance."""
        return f'__icypaw_{self._owner_name}__'

    @classmethod
    def _set_properties(cls, tahu_metric, property_dict):
        """Apply properties from a python dict to a tahu metric.

        Certain metric properties may have ICPW semantics which require special
        handling.
        """
        props = ti.PropertyDict(tahu_metric.properties)
        property_dict = property_dict.copy()

        #'Low' and 'High' limits must be of the same type as the metric itself
        for limit_key in ('Low', 'High'):
            value = property_dict.pop(limit_key, None)
            if value is not None:
                props[limit_key] = ti.property_value(value, tahu_metric.datatype)

        # Add all the rest of the metrics
        props.update(property_dict)

    def _unwrap_user_value(self, value):
        """Given a value that may have optional metadata wrapped around it,
        return the value and the value for any metadata.

        return (value, is_historical, is_transient, is_null)

        """

        # Note that we allow null values to be historical or
        # transient, even if I don't have a good use case for this.

        if isinstance(value, BooleanWithMetadata):
            is_historical = value.is_historical
            is_transient = value.is_transient
            value = value.value
        else:
            is_historical = False
            is_transient = False

        is_null = (value is None)

        return value, is_historical, is_transient, is_null

def get_metric_object(inst, name):
    """Extract a metric object from an instance, bypassing the normal
    descriptor protocol."""

    return get_object(inst, name, Metric)

def iter_metric_objects(inst):
    """Iterate over all Metric objects accessible in an instance."""

    return iter_objects(inst, Metric)

def iter_metric_objects_from_type(cls):
    """Iterate over all Metric objects accessible from the give class."""
    return iter_objects_from_type(cls, Metric)

class StoredMetric:
    """A metric along with some metadata stored in the Node object."""

    def __init__(self, value):
        self._value = value
        self._thread_id = None
        self.is_historical = False
        self.is_transient = False
        self.is_null = False

    @property
    def stored_value(self):
        self._check_thread()
        return self._value

    @stored_value.setter
    def stored_value(self, value):
        self._check_thread()
        self._value = value

    def assign_to_current_thread(self):
        """Assign this metric to the current thread. This will ensure that
        future access only occurs from this thread."""
        self._thread_id = threading.get_ident()

    def _check_thread(self):
        """Validate that this thread is being called from the assigned thread
        if one was assigned."""
        if self._thread_id is not None and self._thread_id != threading.get_ident():
            raise IcypawException('Metric called from the wrong thread')


from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions

def test_show_all_pets(driver):
    assert driver.find_element(By.TAG_NAME, 'h1').text == "PetFriends"

def test_all_pets_are_exist(driver): # Присутствуют все питомцы
    WebDriverWait(driver, 5).until(expected_conditions.element_to_be_clickable((By.XPATH, '//a[contains(text(), "Мои питомцы")]'))).click()
    count_pets = driver.find_element(By.XPATH, '//div[@class=".col-sm-4 left"]') # Общее количество питомцев
    pets = driver.find_element(By.XPATH, '//tbody') # Питомца на доске
    count_pet = count_pets.text.split()
    pet = pets.text.split('×')
    assert (len(pet)-1) == int(count_pet[2])

def test_pets_have_name_species_age(driver): # У всех питомцев есть имя, возраст и порода
    driver.find_element(By.XPATH, '//a[contains(text(), "Мои питомцы")]').click()
    driver.implicitly_wait(5)
    all_pets = driver.find_element(By.XPATH, '//tbody')
    info_of_all_pets = all_pets.text.split('\n')
    x = [] # кнопка удаления питомца (×)
    info_list = []
    names = []
    species = []
    age = []
    for i in info_of_all_pets:
        if i != '×':
            info_list.append(i)
        else:
            x.append(i)
    info_list = [j.split() for j in info_list]
    for i in info_list:
        names.append(i[0])
        species.append(i[1])
        age.append(i[2])

    for i in names:
        assert i != '' and i != int # проверяем, что строка "имя" не пустая
    for i in species:
        assert i != '' and i != int # проверяем, что строка "порода" не пустая
    for i in age:
        assert i != '' # проверяем, что строка "возраст" не пустая

    """В случае, если количество имен, пород, возрастов меньше кнопок удаления питомца - у питомца отсутствует имя, порода или возраст"""
    assert len(names) < len(x)
    assert len(species) < len(x)
    assert len(age) < len(x)

def test_pets_images(driver): # Хотя бы у половины питомцев есть фото
    driver.find_element(By.XPATH, '//a[contains(text(), "Мои питомцы")]').click()
    count_pets = driver.find_element(By.XPATH, '//div[@class=".col-sm-4 left"]')
    count_pet = count_pets.text.split() # Количество питомцев
    count = 1 # Счетчик тегов tr
    images = []
    for i in range(int(count_pet[2])):
        all_my_pets = driver.find_elements(By.XPATH, f'//*[@id="all_my_pets"]/table[1]/tbody/tr[{count}]/th/img')
        count += 1
        for i in range(len(all_my_pets)):
            if all_my_pets[i].get_attribute('src') != '':
                images.append(all_my_pets[i].get_attribute('src'))

    assert len(images) >= round(int(count_pet[2])/2)

def test_same_names(driver): # Проверка на одинаковые иммена
    WebDriverWait(driver, 5).until(expected_conditions.element_to_be_clickable((By.XPATH, '//a[contains(text(), "Мои питомцы")]'))).click()
    pets = driver.find_element(By.XPATH, '//tbody')
    pets_list = pets.text.split('\n')
    list_info_of_pets = [i for i in pets_list if i != '×']
    list_of_list_info_of_pets = [i.split() for i in list_info_of_pets]
    names = [] # Список всех имен
    uniq_names = [] # Список уникальных имен
    same_names = [] # Список совпадающих имен
    for i in list_of_list_info_of_pets:
        names.append(i[0]) # Создаем список всех имен
    for i in names:
        if i not in uniq_names:
            uniq_names.append(i) # Создаем список уникальных имен
        else:
            same_names.append(i) # Создем список совпадающих имен, шобы было

    assert len(names) != len(uniq_names) # Проверяем, равно ли количество всех имен списку уникальных имен, если не равно - есть одинаковые имена


from infraxys.logger import Logger
from infraxys.communicator import Communicator

class JsonInstances(object):

    def __init__(self, instances, parent_instance_id, packet_guid):
        self.instances = instances
        self.parent_instance_id = parent_instance_id
        self.packet_guid = packet_guid
        self.logger = Logger.get_logger(self.__class__.__name__)

    def import_instances(self, remove_existing_children):
        json_request = {
            "requestType": "IMPORT INSTANCES",
            "parentInstanceId": self.parent_instance_id,
            "packetGuid": self.packet_guid,
            "removeExistingChildren": remove_existing_children,
            "instances": []
        }

        instances_attribute = json_request["instances"]
        for instance in self.instances:
            instances_attribute.append({ "fields": instance.to_json_fields()})

        answer = Communicator.get_instance().send_synchronous(json=json_request)
        print("Json answer: {}.".format(answer), flush=True)
        return answer


# https://leetcode.com/problems/happy-number/
# Write an algorithm to determine if a number n is "happy".
# A happy number is a number defined by the following process:
# Starting with any positive integer, replace the number by the sum
# of the squares of its digits, and repeat the process until the number
# equals 1 (where it will stay), or it loops endlessly in a cycle which
# does not include 1. Those numbers for which this process ends in 1
# are happy numbers.
# Return True if n is a happy number, and False if not.

class Solution:
    def isHappy(self, n: int) -> bool:
        results = set()
        while True:
            powers = 0
            while n != 0:
                powers += (n % 10) ** 2
                n //= 10
            if powers == 1:
                return True
            else:
                if powers in results:
                    return False
                else:
                    results.add(powers)
                    n = powers

solution = Solution()
for n in range(1, 100):
    print(n, "is happy:", solution.isHappy(n))


from pylons import g, c, request
from pylons.i18n import _

from r2.controllers.reddit_base import RedditController, abort_with_error
from r2.lib.base import abort
from r2.lib.validator import (
    validate,
    VOneOf,
    VPrintable,
    VRatelimit,
    VValidatedJSON,
)

class WebLogController(RedditController):
    on_validation_error = staticmethod(abort_with_error)

    @validate(
        VRatelimit(rate_user=False, rate_ip=True, prefix='rate_weblog_'),
        level=VOneOf('level', ('error',)),
        logs=VValidatedJSON('logs',
            VValidatedJSON.ArrayOf(VValidatedJSON.Object({
                'msg': VPrintable('msg', max_length=256),
                'url': VPrintable('url', max_length=256),
            }))
        ),
    )
    def POST_message(self, level, logs):
        # prevent simple CSRF by requiring a custom header
        if not request.headers.get('X-Loggit'):
            abort(403)

        uid = c.user._id if c.user_is_loggedin else '-'

        # only accept a maximum of 3 entries per request
        for log in logs[:3]:
            g.log.warning('[web frontend] %s: %s | U: %s FP: %s UA: %s',
                          level, log['msg'], uid, log['url'],
                          request.user_agent)

        VRatelimit.ratelimit(rate_user=False, rate_ip=True,
                             prefix="rate_weblog_", seconds=10)


from django.http import JsonResponse, HttpRequest
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework import status

# from drf_yasg.utils import swagger_auto_schema

from account.models import User
from .models import Habit, RoundRecord, DailyRecord
from .serializers import HabitSerializer, RoundRecordSerializer, DailyRecordSerializer
from .views_aux import authenticate, authenticate_and_authorize

# Create your views here.
@csrf_exempt
@api_view(["GET", "POST"])
@authenticate
def index(request: HttpRequest):
    if request.method == "GET":
        user: User = request.user
        habit_list = Habit.objects.filter(user=user.pk).order_by("-importance")
        __check_day_changes_and_update_habits(user, habit_list)

        serializer = HabitSerializer(habit_list, many=True)
        return Response(serializer.data)

    elif request.method == "POST":
        habit = Habit()
        habit.create_from_request(request)
        DailyRecord().create_from_habit(habit)

        # Instead of DRF Response, you can use Django's built-in JsonResponse
        return JsonResponse({"id": habit.pk})

def __check_day_changes_and_update_habits(user: User, habits: list[Habit]):
    if user.is_day_changed():
        for habit in habits:
            if habit.is_today_due_date and not habit.is_done:
                lost_xp = habit.lose_xp()
                DailyRecord.get_today_record(habit).update_from_habit(habit, -lost_xp)

            habit.update_due()
            habit.save()

            # daily record must be created for due habits only
            if habit.is_today_due_date:
                DailyRecord().create_from_habit(habit, is_for_new_day=True)

        # user's next reset date must be updated
        user.update_reset_date()

@csrf_exempt
@api_view(["GET", "DELETE"])
@authenticate_and_authorize
def index_each(request: HttpRequest, habit_id: int):
    habit = get_object_or_404(Habit, pk=habit_id)

    if request.method == "GET":
        serializer = HabitSerializer(habit)
        return Response(serializer.data)

    elif request.method == "DELETE":
        habit.delete()
        return Response(
            {"success": True, "detail": "the habit's successfully deleted"},
        )

@csrf_exempt
@api_view(["PATCH"])
@authenticate_and_authorize
def update_importance(request: Request, habit_id: int):
    habit = get_object_or_404(Habit, pk=habit_id)

    habit.importance = request.data.get("importance")
    habit.save()
    return Response(
        {"success": True, "detail": "Updated successfully"},
        status=status.HTTP_200_OK,
    )

@csrf_exempt
@api_view(["GET"])
@authenticate_and_authorize
def get_daily_records(request: HttpRequest, habit_id: int):
    records = DailyRecord.objects.filter(habit=habit_id)
    serializer = DailyRecordSerializer(records, many=True)
    return Response(serializer.data)

@csrf_exempt
@api_view(["POST"])
@authenticate_and_authorize
def start_timer(request: Request):
    habit_id = request.data.get("habit_id")
    habit = Habit.objects.get(id=habit_id)

    habit.start_recording()
    return Response(
        {
            "success": True,
            "start_date": habit.start_datetime,
            "is_running": habit.is_running,
        }
    )

@csrf_exempt
@api_view(["POST"])
@authenticate_and_authorize
def finish_timer(request: Request):
    habit_id = request.data.get("habit_id")
    habit: Habit = Habit.objects.get(id=habit_id)
    progress = int(request.data.get("progress"))
    user: User = habit.user

    record = RoundRecord()
    record.create_from_habit_finished(habit, progress)
    habit.end_recording(progress)

    DailyRecord.create_or_update_from_habit(habit)

    serializer = RoundRecordSerializer(record)
    return Response(serializer.data)


import numpy as np
import scipy as sp
import scipy.optimize

_log2pi = np.log(2 * np.pi)

def fiml(data, bias=False):
    """FIML estimation of the mean/covariance of data with missing values.

    Estimate the mean and the covariance of data with missing values by
    full information maximum likelihood (FIML) method.

    Parameters
    ----------
    data : ndarray
        A 2-D array containing variables and observations.
        Each row is an observation and each column is a variable.
        A missing value is represented by `np.nan`.
    bias : bool, optional
        Must be True for now.

    Returns
    -------
    mean : ndarray
        Estimated means of the variables.
    cov : ndarray
        Estimated covariance of the variables.
    """

    if not bias:
        raise NotImplementedError("unbiased estimator is not yet implemented")

    size, dim = data.shape
    mean0 = np.zeros(dim)
    cov0 = np.eye(dim)
    params0 = _pack_params(dim, mean0, cov0)
    data_blocks = _sort_missing(data)
    result = sp.optimize.fmin_slsqp(
        _obj_func, params0, args=(dim, data_blocks), disp=False)
    mean, cov = _unpack_params(dim, result)
    return mean, cov

# Sort data by the missing patterns.
# The return value is in the following format.
# Missing variables (columns) are removed from the data blocks.
#  [(observation_pattern1, data_block1),
#   (observation_pattern2, data_block2),
#   ...]
def _sort_missing(data):
    # Argsort the rows of obsmap.
    obsmap = ~np.isnan(data)
    sortedidx = sorted(range(data.shape[0]), key=lambda i: list(obsmap[i]))
    # Split row indexes into blocks.
    blocks = [[sortedidx[0]]]
    for idx, prev in zip(sortedidx[1:], sortedidx[:-1]):
        if (obsmap[prev] == obsmap[idx]).all():
            blocks[-1].append(idx)
        else:
            blocks.append([idx])
    return [(obsmap[b[0]], data[b][:, obsmap[b[0]]]) for b in blocks]

# Pack the mean and the covariance into a 1-dimensional array.
# - The first N values are the means.
# - The remaining N (N + 1) / 2 values are the lower triangular matrix
#   of the covariance.
def _pack_params(dim, mean, cov):
    params = np.empty(dim + dim * (dim + 1) // 2)
    params[:dim] = mean
    params[dim:] = cov[np.tril_indices(dim)]
    return params

# Unpack the mean and the covariance from a 1-dimensional array.
def _unpack_params(dim, params):
    mean = params[0:dim]
    cov = np.empty((dim, dim))
    ii, jj = np.tril_indices(dim)
    cov[ii, jj] = params[dim:]
    cov[jj, ii] = params[dim:]
    return mean, cov

def _obj_func(params, dim, data_blocks):
    mean, cov = _unpack_params(dim, params)
    # Check if cov is positive semidefinite.
    # A matrix has a Cholesky decomposition iff it is symmetric and
    # positive semidefinite.  It is said that Cholesky decomposition is
    # faster and more numerically stable than finding eigenvalues.
    # However, numpy.linalg.cholesky() rejects singular matrices (i.e.,
    # strictly "semi"-definite ones).
    # try:
    #     _ = np.linalg.cholesky(cov)
    # except np.linalg.LinAlgError:
    #     return np.inf
    if (np.linalg.eigvalsh(cov) < 0).any():
        # XXX Returning inf is not a good idea, because many solvers
        # cannot cope with it.
        return np.inf
    objval = 0.0
    for obs, obs_data in data_blocks:
        obs_mean = mean[obs]
        obs_cov = cov[obs][:, obs]
        objval += _log_likelihood_composed(obs_data, obs_mean, obs_cov)
    return -objval

def _obj_func_1d(params, dim, data):
    mean, cov = _unpack_params(dim, params)
    objval = 0.0
    for x in data:
        obs = ~np.isnan(x)
        objval += _log_likelihood_1d(x[obs], mean[obs], cov[obs][:, obs])
    return -objval

# Composite function of _log_likelihood() and _pdf_normal().
def _log_likelihood_composed(x, mean, cov):
    xshift = x - mean
    t1 = x.shape[-1] * _log2pi
    sign, logdet = np.linalg.slogdet(cov)
    t2 = logdet
    t3 = xshift.dot(np.linalg.inv(cov)) * xshift
    size = x.shape[0] if x.ndim == 2 else 1
    return -0.5 * ((t1 + t2) * size + t3.sum())

# Log likelihood function.
# The input x can be one- or two-dimensional.
def _log_likelihood(x, mean, cov):
    return np.log(_pdf_normal(x, mean, cov)).sum()

# Log likelihood function.
def _log_likelihood_1d(x, mean, cov):
    return np.log(_pdf_normal_1d(x, mean, cov))

# Probability density function of multivariate normal distribution.
# The input x can be one- or two-dimensional.
def _pdf_normal(x, mean, cov):
    xshift = x - mean
    t1 = (2 * np.pi) ** (-0.5 * x.shape[-1])
    t2 = np.linalg.det(cov) ** (-0.5)
    t3 = -0.5 * (xshift.dot(np.linalg.inv(cov)) * xshift).sum(axis=-1)
    return t1 * t2 * np.exp(t3)

# Probability density function of multivariate normal distribution.
def _pdf_normal_1d(x, mean, cov):
    xshift = x - mean
    t1 = (2 * np.pi) ** (-0.5 * len(x))
    t2 = np.linalg.det(cov) ** (-0.5)
    t3 = -0.5 * xshift.dot(np.linalg.inv(cov)).dot(xshift)
    return t1 * t2 * np.exp(t3)


import argparse
import logging
import time

from src.sync.spider import Spider

def main():
    """
    Main function of the program. Provides command line facilities to crawl websites
    using a simple synchronous web crawler.
    """
    # Acquires input arguments from the user
    parser = argparse.ArgumentParser(description='A simple synchronous web crawler')
    parser.add_argument('website', help='the website you want to start the crawling from')
    parser.add_argument('-m', dest='max_pages', type=int, default=5,
                        help='the maximum number of pages that will be visited')
    parser.add_argument('-l', dest='hide_logs', action='store_true', default=False,
                        help='a flag that tells if logs should be hidden')
    parser.add_argument('-s', dest='path_to_file', type=str,
                        help='tells if the results should be saved to file and provides the full path for saving')
    args = parser.parse_args()
    # Sets up the main Logger of the program to the INFO level, this means that everything with a severity
    # greater than or equal to the INFO level will be shown (e.g.: warnings, errors)
    logging.getLogger().setLevel(logging.INFO)
    # Storing the current time
    start_time = time.time()
    # Setting up the Spider for crawling
    spider = Spider(enable_logging=not args.hide_logs)
    result = spider.crawl(args.website, args.max_pages)
    print('Result of the crawling for {} returned in {:.2f} seconds:'.format(args.website, time.time()-start_time))
    print(result)
    # In addition, saves the result to a file if needed
    if args.path_to_file:
        with open(args.path_to_file, 'w') as outfile:
            # Result is already a json string!
            outfile.write(result)
    # Cleans up the environment deleting spider
    del spider

if __name__ == '__main__':
    """
    Main entry point of the program. Simply calls the main function.
    """
    main()


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:

        res = []
        queue = []
        cnt = 1
        if root:
            queue.append(root)
        while len(queue) > 0:
            if cnt % 2 == 1:
                res.append([node.val for node in queue])    # 奇数层顺序放入
            else:
                res.append([node.val for node in queue[-1::-1]])    # 偶数层倒序放入
            queue_temp = []
            for node in queue:
                if node.left:
                    queue_temp.append(node.left)
                if node.right:
                    queue_temp.append(node.right)
            queue = queue_temp
            cnt += 1
        return res

Code/0103.二叉树的锯齿形层序遍历/Binary Tree Zigzag Level Order Traversal.py


#! /usr/bin/env python
import sys
import time
import argparse
from scapy.all import *
from scapy.utils import rdpcap

parser = argparse.ArgumentParser(description='Packet Scapy Utility to send packets from Host/Workload.')

parser.add_argument('--pcap-file', dest='pcap_file', required = True,
                    help='Packet PCAP file.')
parser.add_argument('--iface', dest='iface', required = True,
                    help='Interface to send the packet.')
parser.add_argument('--count', dest='count', type=int,
                    default=1, help='Packet send count.')
parser.add_argument('--interval', dest='interval', type=float,
                    default=0.01, help='Packet interval.')
args = parser.parse_args()

if args.count >= 100:
    args.interval = 0.001

pkts = rdpcap(args.pcap_file)
for itr in range(args.count):
    for pkt in pkts:
        sendp(pkt, inter=0.001, loop=False, iface=args.iface)
    time.sleep(args.interval)


#!/usr/bin/env python
'''importance sampling of the Hilbert space
   Chong Sun 2016 Jun. 10
'''

import numpy as np
import numpy.linalg as nl
import logger # this is my logger
import random

def smpl_hilbert(hop, ci0, T, ftlan, nblock = 100, genci = 0, nrot = 200, nw = 25, nsamp = 100, dr = 0.5, dtheta = 20.0):
    '''
       with 1 initial vector
       note that the probability and the energy is given by the same function (ftlan)
       ci0    ---- array, initial vector
       T      ---- float, temperature
       ftlan  ---- function giving the probability and energy evaluated from the initial vector
       nblock ---- the size of the block for block average
       genci  ---- int, the way to generate new ci
       nrot   ---- int, steps of rotations on ci0, only used when genci = 1
       nw     ---- number of warmup steps
       nsamp  ---- number of samples (initial vector generated)
       dr     ---- the size of the sampling box (or sphere)
    '''
    beta = 1./T  # kB = 1.
    # generate the starting vector ----NOTE can also be several starting vectors
    ci0 = ci0.reshape(-1).copy()
    lc = len(ci0)

    def gen_nci(v0, cases):
        if cases == 0: # generate new vector by displacement
            disp = np.random.randn(lc) * dr
            v1 = v0 + disp
            return v1/nl.norm(v1)
        if cases == 1: # generate new vector by rotational FIXME gives very bad result!!!!! -_-!!!
    #        print "generating new vectors by rotation"
            v1 = v0.copy()
            for i in range(nrot):
                addr = np.random.randint(lc, size = 2)
                theta = random.random() * dtheta # rotational angle
                vec = np.zeros(2)
                vec[0] = v1[addr[0]]
                vec[1] = v1[addr[1]]
                rotmat = np.array([[np.cos(theta), -np.sin(theta)],[np.sin(theta), np.cos(theta)]])
                vec = (rotmat.dot(vec)).copy()
                v1[addr[0]] = vec[0]
                v1[addr[1]] = vec[1]
            return v1/nl.norm(v1)

    # Warm-up
    logger.section("Warming up ......")
    Nar = 0 # acceptance number
    tp = ftlan(hop, ci0, T, m=20)[1]
    for i in range(nw):
        ci = gen_nci(ci0, genci)
        tp_n = ftlan(hop, ci, T, m=20)[1]
        acc = tp_n/tp
        if acc >= 1:
            ci0 = ci.copy()
            Nar += 1
        else:
            tmp = random.random()
            if tmp <= acc:
                ci0 = ci.copy()
                tp = tp_n
                Nar += 1
            else:
                continue

    logger.section("Sampling......")
    # Sampling with block average
    Nar = 0
    Eb = [] # the array of energies per block
    e, tp = ftlan(hop, ci0, T)
    for i in range(nsamp):
        E = 0.
        for j in range(nblock):
            E += e/tp
#            print "E", e/tp
            ci = gen_nci(ci0, genci)
            e_n, tp_n = ftlan(hop, ci, T)
            acc = tp_n/tp
            if acc >= 1:
                ci0 = ci.copy()
                e = e_n
                tp = tp_n
                Nar += 1
            else:
                tmp = random.random()
                if tmp <= acc:
                    ci0 = ci.copy()
                    tp = tp_n
                    e = e_n
                    Nar += 1
                else:
                    continue
        E = E/(1.*nblock)
        Eb.append(E)
    Eb = np.asarray(Eb)
    E = np.mean(Eb)
    dev = np.std(Eb)
    ar =  (1.* Nar)/(1.*nblock* nsamp)
    return E, dev, ar


import torch.nn as nn

class MiniCNN(nn.Module):
    """
    Mini CNN structure
    input -> (conv2d + relu)x3 -> flatten -> (dense + relu)x2  -> output
    """
    def __init__(self, input_dim, output_dim) -> None:
        super().__init__()
        c, h, w = input_dim
        self.conv1 = nn.Sequential(nn.Conv2d(in_channels=c,out_channels=32,kernel_size=8, stride=4),nn.ReLU())
        self.conv2 = nn.Sequential(nn.Conv2d(in_channels=32, out_channels=64, kernel_size=4, stride=2), nn.ReLU())
        self.conv3 = nn.Sequential(nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1), nn.ReLU())
        self.flatten = nn.Flatten()
        self.fc1 = nn.Sequential(nn.Linear(3136, 512), nn.ReLU())
        self.fc2 = nn.Linear(512, output_dim)

    def forward(self, input):
        """
        Forward Block of CNN
        """
        input = self.conv1(input)
        input = self.conv2(input)
        input = self.conv3(input)
        input = self.flatten(input)
        input = self.fc1(input)
        input = self.fc2(input)
        return input


'''
844. Backspace String Compare

Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.

Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".

Example 2:
Input: S = "ab##", T = "c#d#"
Output: true
Explanation: Both S and T become "".

Example 3:
Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".

Example 4:
Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".

Note:
1 <= S.length <= 200
1 <= T.length <= 200
S and T only contain lowercase letters and '#' characters.

Follow up:
Can you solve it in O(N) time and O(1) space?
'''

#Solution1
class Solution:

    def backspace(self, C):
        i=0

        while i < len(C):
            if C[i] == '#':
                C = C[:(i-1)]*min(i, 1) + C[(i+1):]
                i = max(0, i-1)
            else:
                i = i+1
        return C

    def backspaceCompare(self, S, T):
        return self.backspace(S) == self.backspace(T)

#Solution2
class Solution:
    def backspace(self, S):
        s = []
        for i in S:
            if i=='#':
                try:
                    s.pop()
                except:
                    pass
            else:
                s.append(i)
        return s
    def backspaceCompare(self, S: str, T: str) -> bool:
        return self.backspace(S) == self.backspace(T)


from sklearn import linear_model
from sklearn import preprocessing
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import scipy.stats as stats
import itertools

dataPeople = pd.read_csv("clientes.csv")
lst = dataPeople.columns
no_lst = ['Obs No.','Buy']

aux_acc=0
print(range(len(lst)))
for j in range(len(lst)-1):
	print (j)
	combinaciones = list(itertools.combinations([c for c in dataPeople.columns if c not in no_lst], j+1))
	for i in combinaciones:
		train_features = dataPeople[[c for c in dataPeople.columns if c in i]]
		print(i)
		log_model = linear_model.LogisticRegression(solver='lbfgs')
		log_model.fit(X = train_features ,
	             y = dataPeople["Buy"])
		preds = log_model.predict(X= train_features)
		tablePred=pd.crosstab(preds,dataPeople["Buy"])
		accuracy  = log_model.score(X=train_features,
	                           y=dataPeople["Buy"])
		print(accuracy)
		print(aux_acc)
		if accuracy>aux_acc:
			aux_acc=accuracy
			train_features_best = train_features

	#print("accuracy")
	#print(accuracy)

log_model = linear_model.LogisticRegression(solver='lbfgs')
log_model.fit(X = train_features_best, y = dataPeople["Buy"])
accuracy  = log_model.score(X=train_features_best, y=dataPeople["Buy"])
print(train_features_best)
print("Accuracy")
print(accuracy)
print("Intercección ")
print(log_model.intercept)
print("Coeficientes")
print(log_model.coef_)
print("Matriz de confusion")
aux_preds = log_model.predict(X= train_features_best)
tablePred=pd.crosstab(aux_preds,dataPeople["Buy"])
print (pd.crosstab(aux_preds,dataPeople["Buy"]))


import requests
from twilio.rest import Client
import os

def main():
    # Load environment variables
    weather_api_key = os.environ.get("API_KEY")
    account_sid = os.environ.get("ACCOUNT_SID")
    auth_token = os.environ.get("AUTH_TOKEN")
    my_num = os.environ.get("MY_NUM")

    # Coordinates for location (Hod Hasharon, Israel)
    my_lat = 32.149960
    my_lon = 34.883881

    # Test
    # manchester_lat = 53.480759
    # manchester_lon = -2.242631

    # API endpoint and parameters for OpenWeatherMap
    url_endpoint = "https://api.openweathermap.org/data/2.5/onecall"
    weather_params = {
        "lat": my_lat,
        "lon": my_lon,
        "appid": weather_api_key,
        "exclude": "current,minutely,daily"
    }

    try:
        # Fetch weather data
        response = requests.get(url=url_endpoint, params=weather_params)
        response.raise_for_status()
        weather_data = response.json()

        # Extract hourly weather data for the next 12 hours
        weather_slice = weather_data["hourly"][:12]

        # Check if rain is expected
        will_rain = any(int(hour_data["weather"][0]["id"]) < 700 for hour_data in weather_slice)

        # Send notification if rain is expected
        if will_rain:
            client = Client(account_sid, auth_token)
            message = client.messages.create(
                body="It's going to rain today. Remember to bring an ☂",
                from_=my_num,
                to="+972525523599"
            )
            print("Message sent:", message.status)

    except requests.exceptions.RequestException as e:
        print("Error:", e)

if __name__ == "__main__":
    main()


import config
from constant import ProcessDataSource
from tools.local_cache import local_stable_cache
from tools import utils

class LocalStableSource:

    STABLE_SOURCE_STORE = local_stable_cache

    @classmethod
    def get_device_fingerprint(cls):
        """Get the device's fingerprint from cache or file"""
        fingerprint = cls.STABLE_SOURCE_STORE.get(
            ProcessDataSource.FINGERPRINT
        )
        if not fingerprint:
            fingerprint = utils.get_fingerprint_from_file(config.FINGERPRINT_FILE)
            cls.set_device_fingerprint(fingerprint)
        return fingerprint

    @classmethod
    def set_device_fingerprint(cls, fingerprint):
        """Sets the device's fingerprint to the cache"""
        cls.STABLE_SOURCE_STORE.set(
            ProcessDataSource.FINGERPRINT,
            fingerprint
        )


import math
x,y,a,b = map(int, input().split())

n = int(math.log(b/x)/math.log(a))
if x * a**n < y:
    print((y - x * a ** n) // b + n)
else:
    print(int(math.log(y/x)/math.log(a)))
ans = 0
while x*a < y and x*a<=b+x:
    x *= a
    ans += 1
print(ans + (y-x)//b)