# -*- coding: utf-8 -*-

__author__ = 'Daniel Donovan'
__email__ = 'spitfiredd@gmail.com'
__version__ = '0.5.41'

from collections import OrderedDict
import xmltodict
import requests
import json
import warnings
import urllib
import xml
from lxml import etree
from io import StringIO, BytesIO
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import requests.exceptions

warnings.filterwarnings('ignore')

field_map = {

    'piid': 'PIID',
    'idv_piid': 'REF_IDV_PIID',
    'idv_agency_id': 'REF_IDV_AGENCY_ID',
    'modification_number': 'MODIFICATION_NUMBER',

    'contracting_agency_id': 'CONTRACTING_AGENCY_ID',
    'contracting_agency_name': 'CONTRACTING_AGENCY_NAME',
    'contracting_office_id': 'CONTRACTING_OFFICE_ID',
    'contracting_office_name': 'CONTRACTING_OFFICE_NAME',
    'funding_agency_id': 'FUNDING_AGENCY_ID',
    'funding_office_id': 'FUNDING_OFFICE_ID',
    'funding_office_name': 'FUNDING_OFFICE_NAME',
    'agency_code': 'AGENCY_CODE',
    'agency_name': 'AGENCY_NAME',
    'department_id': 'DEPARTMENT_ID',
    'department_name': 'DEPARTMENT_NAME',
    'department_full_name': 'DEPARTMENT_FULL_NAME',

    'last_modified_date': 'LAST_MOD_DATE',
    'last_modified_by': 'LAST_MODIFIED_BY',
    'award_completion_date': 'AWARD_COMPLETION_DATE',
    'created_on': 'CREATED_DATE',
    'date_signed': 'SIGNED_DATE',
    'effective_date': 'EFFECTIVE_DATE',
    'estimated_completion_date': 'ESTIMATED_COMPLETION_DATE',

    'obligated_amount': 'OBLIGATED_AMOUNT',
    'ultimate_contract_value': 'ULTIMATE_CONTRACT_VALUE',
    'contract_pricing_type': 'TYPE_OF_CONTRACT_PRICING',

    'award_status': 'AWARD_STATUS',
    'award_type': 'AWARD_TYPE',
    'contract_type': 'CONTRACT_TYPE',
    'created_by': 'CREATED_BY',
    'description': 'DESCRIPTION_OF_REQUIREMENT',
    'modification_reason': 'REASON_FOR_MODIFICATION',
    'legislative_mandates': 'LEGISLATIVE_MANDATES',
    'local_area_setaside': 'LOCAL_AREA_SET_ASIDE',
    'socioeconomic_indicators': 'SOCIO_ECONOMIC_INDICATORS',
    'multiyear_contract': 'MULTIYEAR_CONTRACT',
    'national_interest_code': 'NATIONAL_INTEREST_CODE',
    'national_interest_description': 'NATIONAL_INTEREST_DESCRIPTION',

    'naics_code': 'PRINCIPAL_NAICS_CODE',
    'naics_description': 'NAICS_DESCRIPTION',
    'product_or_service_code': 'PRODUCT_OR_SERVICE_CODE',
    'product_or_service_description': 'PRODUCT_OR_SERVICE_DESCRIPTION',

    'place_of_performance_district': 'POP_CONGRESS_DISTRICT_CODE',
    'place_of_performance_country': 'POP_CONGRESS_COUNTRY',
    'place_of_performance_state': 'POP_STATE_NAME',

    'vendor_city': 'VENDOR_ADDRESS_CITY',
    'vendor_district': 'VENDOR_CONGRESS_DISTRICT_CODE',
    'vendor_country_code': 'VENDOR_ADDRESS_COUNTRY_CODE',
    'vendor_country_name': 'VENDOR_ADDRESS_COUNTRY_NAME',
    'vendor_duns': 'VENDOR_DUNS_NUMBER',
    'vendor_dba_name': 'VENDOR_DOING_BUSINESS_AS_NAME',
    'vendor_name': 'VENDOR_NAME',
    'vendor_state_code': 'VENDOR_ADDRESS_STATE_CODE',
    'vendor_state_name': 'VENDOR_ADDRESS_STATE_NAME',
    'vendor_zip': 'VENDOR_ADDRESS_ZIP_CODE',

}

def requests_retry_session(
    retries=3,
    backoff_factor=0.3,
    status_forcelist=(500, 502, 504),
    session=None,
):
    session = session or requests.Session()
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    return session

class Contracts():
    def __init__(self,
                 logger=None,
                 feed_url='https://www.fpds.gov/ezsearch/FEEDS/ATOM?s=FPDS&FEEDNAME=PUBLIC&VERSION=1.5.1&q=',
                 feed_size=10,
                 query_url='',
                 show_logs=False):
        self.feed_url = feed_url
        self.feed_size = feed_size
        self.query_url = query_url
        self.show_logs = show_logs
        if logger:
            self.log = logger
        else:
            self.log = print

    def pretty_print(self, data):
        self.log(json.dumps(data, indent=4))

    def convert_params(self, params):
        new_params = {}
        for k, v in params.items():
            new_params[field_map[k]] = v
        return new_params

    def combine_params(self, params):
        if len(params) == 1:
            return " ".join("{}:{}".format(k, v) for k, v in params.items())
        else:
            return "+".join("{}:{}".format(k, v) for k, v in params.items())

    def process_data(self, data):
        # todo
        if isinstance(data, dict):
            # make a list so it's consistent
            data = [data, ]
        return data

    def get(self, num_records=100, order='desc', **kwargs):

        client = requests.session()
        params = urllib.parse.quote(self.combine_params(self.convert_params(kwargs)),
                                    safe='+', encoding=None, errors=None)
        namespaces = {
            'http://www.fpdsng.com/FPDS': None,
            'http://www.w3.org/2005/Atom': None,
            'https://www.fpds.gov/FPDS': None,
        }
        data = []
        i = 0
        while num_records == "all" or i < num_records:
            if self.show_logs:
                self.log("querying {0}{1}&start={2}".format(self.feed_url,
                                                            params,
                                                            i))
            feed = self.feed_url + params + '&start={0}'.format(i)
            try:
                resp = requests_retry_session(session=client).get(feed,
                                                                  timeout=60,
                                                                  verify=False)
            except requests.exceptions.HTTPError as errh:
                print("Http Error:", errh)
                print(feed)
            except requests.exceptions.ConnectionError as errc:
                print("Error Connecting:", errc)
                print(feed)
            except requests.exceptions.Timeout as errt:
                print("Timeout Error:", errt)
                print(feed)
            except requests.exceptions.RequestException as err:
                print("Oops: Something Else", err)
                print(feed)
            self.query_url = resp.url
            if self.show_logs:
                self.log("finished querying {0}".format(resp.url))
            resp_data = xmltodict.parse(resp.text,
                                        process_namespaces=True,
                                        namespaces=namespaces,
                                        dict_constructor=dict)
            try:
                processed_data = self.process_data(resp_data['feed']['entry'])
                for pd in processed_data:
                    data.append(pd)
                    i += 1
                if len(processed_data) < 10:
                    break

            except KeyError as e:
                # no results
                if self.show_logs:
                    self.log("No results for query")
                break
        return data


import random

lst = []

keep_running = True

while keep_running:
    option = int(input('Please enter 1 to insert value or 2 to insert 500 ' +
                       'random values, 3 to get maximal value enter 4 to stop running: '))
    if option == 1:
        val = int(input('Please enter value to insert:'))
        lst.append(val)
    elif option == 2:
        for i in range(500):
            lst.append(random.randint(1, 1000))
    elif option == 3:
        if len(lst) == 0:
            print('There is no values yet in the list!')
        else:
            maximal_value = -1
            for val in lst:
                if val >= maximal_value:
                    maximal_value = val
            print('The maximal value is', maximal_value)
    elif option == 4:
        keep_running = False


#!/usr/bin/env python3
import random

import numpy as np
import torch

from spn.experiments.RandomSPNs_layerwise.distributions import RatNormal
from spn.experiments.RandomSPNs_layerwise.rat_spn import RatSpn, RatSpnConfig

def set_seed(seed: int):
    """
    Set the seed globally for python, numpy and torch.

    Args:
        seed (int): Seed.
    """
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)

def run(seed,):
    # Set the seed
    set_seed(seed)

    # Setup RatSpn Configuration
    config = RatSpnConfig()
    config.in_features = 4  # You can also use config.F as an alias
    config.R = 1  # Number of repetitions
    config.D = 2  # Tree depth
    config.I = 2  # Number of input distributions
    config.S = 2  # Number of parallel sum nodes per sum layer
    config.C = 1  # Number of classes (C=1 for density estimation)
    config.dropout = 0.0  # Dropout value
    config.leaf_base_class = RatNormal  # Leaf base distribution class
    config.leaf_base_kwargs = {}

    # Construct RatSpn from config
    device = torch.device("cuda:0")
    model = RatSpn(config).to(device)

    # Optimizer
    optimizer = torch.optim.SGD(model.parameters(), lr=0.1)

    # Train loop
    for i in range(10):
        x = torch.randn(10, config.in_features, device=device)

        # Reset gradients
        optimizer.zero_grad()

        # Inference
        output = model(x)

        # Compute loss
        loss = -output.mean()

        # Backprop
        loss.backward()
        optimizer.step()

    # Evaluate on a random tensor
    x = torch.randn(1, config.in_features, device=device)
    x[0, : config.in_features // 2] = float("nan")
    ll = model(x).mean()
    ll.backward()
    optimizer.step()
    print("--- Model ---")
    print(model)
    print()
    print("--- Likelihood ---")
    print(ll)
    print()
    print("--- Device ---")
    print(ll.device)

if __name__ == "__main__":
    run(0)


from main.py import Distribution
import math
import matplotlib.pyplot as plt

class Binomial(Distribution):
    def __init__(self, p = 0, n = 1):
        Distribution.__init__(self)
        self.p = p
        self.n = n

    def calculate_mean(self):
        self.mean = self.p * self.n
        return self.mean

    def calculate_stdev(self):
        self.stdev = math.sqrt(self.n * self.p * (1 - self.p))
        return self.stdev

    def replace_stats_with_data(self):
        """Function to calculate p and n from the data set. The function updates the p and n variables of the object."""
        self.n = len(self.data)
        self.p = sum(self.data) / self.n
        self.mean = self.calculate_mean()
        self.stdev = self.calculate_stdev()
        return self.p, self.n

    def plot_bar(self):

        plt.bar(self.data)
        plt.title('Bar Chart of Data')
        plt.xlabel('outcome')
        plt.ylabel('count')

    def pdf(self, k):
        n_f = math.factorial(self.n)
        k_f = math.factorial(k)
        nk_f = math.factorial(self.n-k)
        return (n_f/(k_f * nk_f)) * (self.p**k) * ((1-self.p)**(self.n-k))

    def plot_bar_pdf(self):

        """Function to plot the pdf of the binomial distribution

        Args:
            None

        Returns:
            list: x values for the pdf plot
            list: y values for the pdf plot

        """
        x = []
        y = []
        # calculate the x values to visualize
        for k in range(self.n + 1):
            x.append(k)
            y.append(self.pdf(k))

		# make the plots
        plt.bar(x,y)
        plt.title('Probability of Outcomes')
        plt.xlabel('probability')
        plt.ylabel('count')

        return x, y

    def __add__(self, other):
        try:
            assert self.p == other.p, 'p values are not equal'
        except:
            raise AssertionError

        result = Binomial()
        result.n = self.n + other.n
        result.p = self.p
        return result

    def __repr__(self):
        """Function to output the characteristics of the Binomial instance

        Args:
            None

        Returns:
            string: characteristics of the Binomial object

        """
        return "mean {}, standard deviation {}, p {}, n {}".format(self.mean, self.stdev, self.p, self.n)


#! /usr/bin/python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Name:     settings.py
# Purpose:  Store session settings and project parameters
#
# Author:   Fabrice MOUSSET
#
# Created:  2008/01/22
# Licence:  GPLv3 or newer
# ----------------------------------------------------------------------------
"""Session settings and project parameters"""

import os
import sys

from periphondemand.bin.utils.configfile import ConfigFile
from periphondemand.bin.utils.poderror import PodError
from periphondemand.bin.define import POD_PATH
from periphondemand.bin.define import POD_CONFIG

class Settings(object):
    """Settings class implements a Singleton design pattern to share the same
    state to all instance of this class.
    This class will store the application settings like directory location,
    active component and active project.
    """
    __instance = None
    __do_init = False

    def __new__(cls, *args, **kwargs):
        if cls.__instance:
            cls.__instance.__do_init = False
            return cls.__instance

        cls.__instance = object.__new__(cls, *args, **kwargs)
        cls.__instance.__do_init = True
        return cls.__instance

    def __init__(self):
        if self.__do_init:
            pathname, _ = os.path.split(sys.argv[0])
            self.history = []
            self.historyroot = []
            self.__script_dir = os.path.abspath(pathname)
            self.path = POD_PATH
            self.headertpl = "/headervhdl.tpl"
            self.script = 0
            self.projectpath = None
            self.color_status = 1
            # init personnal libraries path:
            try:
                self.configfile = ConfigFile(POD_CONFIG)
            except PodError:
                pass
            try:
                self.personal_lib_path_list = self.configfile.getLibraries()
                self.personal_lib_name_list =\
                    [pathlib.split("/")[-1]
                        for pathlib in self.personal_lib_path_list]
            except PodError:
                pass

            try:
                self.personal_platformlib_list =\
                    self.configfile.get_platform_lib_path()
                self.personal_platformlib_name_list =\
                    [pathlib.split("/")[-1]
                        for pathlib in self.personal_platformlib_list]
            except PodError:
                pass

            self.active_project = None
            self.active_component = None

    def get_platform_lib_path(self, platformlib_name):
        """ get platform lib path """
        for path in self.personal_platformlib_list:
            if path.split("/")[-1] == platformlib_name:
                return path

    def color(self):
        """ is color printed ?"""
        return self.color_status

    def set_color(self, value=1):
        """ set color status """
        self.color_status = value

    def get_directory(self, sub_dir=None):
        """ get directory """
        if sub_dir:
            return os.path.join(self.__script_dir, sub_dir)
        else:
            return ""

    def is_script(self):
        """ is script ? """
        return self.script

    def set_script(self, value):
        """ set as script """
        if value:
            self.script = 1
        else:
            self.script = 0

    def get_synthesis_tool_command(self, synthesisname):
        """ get the synthesis tool command """
        return self.configfile.get_synthesis_tool_command(synthesisname)

    def get_synthesis_value(self, syntesisname, value):
        """ Get the synthesis value """
        try:
            return self.configfile.get_synthesis_value(syntesisname, value)
        except PodError:
            return None

    components_dir = property(lambda self: self.get_directory("components"))
    board_dir = property(lambda self: self.get_directory("boards"))


import cv2
import glob
import numpy as np
import matplotlib.pyplot as plt
import pickle

def grayscale(img):
    '''

    :param img:
    :return:
    '''
    return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

def find_corners(img, nx, ny):
    '''

    :param img:
    :param nx:
    :param ny:
    :return:
    '''
    grayscale_img = grayscale(img)
    return cv2.findChessboardCorners(grayscale_img, (nx, ny), None)

def get_img_obj_points(images, nx, ny):
    '''
    get the object point and image point given (x, y) patterns.
    :param images:
    :param nx: the number of pattern on the x-axis
    :param ny: the number of pattern in the y-axis
    :return: a list of object points and image points.
    '''
    objp = np.zeros((nx * ny, 3), np.float32)
    objp[:, :2] = np.mgrid[0:nx, 0:ny].T.reshape(-1, 2)
    objpoints = []
    imgpoints = []
    for fname in images:
        img = cv2.imread(fname)
        ret, corners = find_corners(img, nx, ny)
        if ret == True:
            objpoints.append(objp)
            imgpoints.append(corners)
    return objpoints, imgpoints

def create_pickle_file(objpoints, imgpoints):
    points = {}
    points['objpoints'], points['imgpoints'] = objpoints, imgpoints
    with open('wide_dist.pickle', 'wb') as f:
        pickle.dump(points, f, protocol=pickle.HIGHEST_PROTOCOL)

def calibrate_camera(img, objpoints, imgpoints):
    '''
    Calculate the camera matrix and distortion coefficient given an image
    :param img: the images
    :param objpoints: list of (x, y, z) coordinate of the real world image pattern.
    :param imgpoints: list of (x, y) coordinate of the image point pattern
    :return: distortion matrix, and distortion coefficient
    '''
    ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, img.shape[1::-1], None, None)
    return mtx, dist

def undistort_image(img, camera_matrix, distortion_coef):
    '''
    undistort an image
    :param img: distorted image
    :param camera_matrix: camera matrix
    :param distortion_coef: distortion coefficient.
    :return: undistorted image
    '''
    return cv2.undistort(img, camera_matrix, distortion_coef, \
                         None, camera_matrix)

def perspective_transform(src, dst):
    '''
    Calculate the perspective transform from four pair of
    corresponding points
    :param src: a list of four source points.
    :param dst: a list of four destination points.
    :return: perspective transform
    '''
    return cv2.getPerspectiveTransform(src, dst)

def inverse_perspective_transform(src, dst):
    '''

    :param src:
    :param dst:
    :return:
    '''
    return cv2.getPerspectiveTransform(dst, src)

def warp_image(img, transform, img_size, flags=cv2.INTER_LINEAR):
    '''
    Apply a perspective transform to an image
    :param undist_image:
    :param transform:
    :param img_size:
    :param flags:
    :return: a transformed image
    '''
    return cv2.warpPerspective(img, transform, dsize=img_size, flags=flags)

################ Thresh
def abs_sobel_thresh(img, orient='x', sobel_kernel=3, thresh_min=0, thresh_max=255):
    '''
    calculate directional gradient
    :param img:
    :param orient:
    :param sobel_kernel:
    :param thresh:
    :return:
    '''
    gray = grayscale(img)
    if orient == 'x':
        abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))
    if orient == 'y':
        abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))
    scaled_sobel = np.uint8(255 * abs_sobel / np.max(abs_sobel))
    binary_output = np.zeros_like(scaled_sobel)
    binary_output[(scaled_sobel >= thresh_min) & (scaled_sobel <= thresh_max)] = 1
    return binary_output

def mag_tresh(img, sobel_kernel=3, thresh_min=0, thresh_max=255):
    '''
    calculate gradient magnitude
    :param img:
    :param sobel_kernel:
    :param thresh_min:
    :param thresh_max:
    :return:
    '''
    gray = grayscale(img)
    sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
    sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
    gradmag = np.hypot(sobelx, sobely)
    scale_factor = np.max(gradmag) / 255
    gradmag = (gradmag / scale_factor).astype(np.uint8)
    binary_output = np.zeros_like(gradmag)
    binary_output[(gradmag >= thresh_min) & (gradmag <= thresh_max)] = 1
    return binary_output

def dir_threshold(img, sobel_kernel=3, thresh_min=0, thresh_max=np.pi / 2):
    '''
    calculate gradient direction
    :param img:
    :param sobel_kernel:
    :param thresh_min:
    :param tresh_max:
    :return:
    '''
    gray = grayscale(img)
    sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
    sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
    absgraddir = np.arctan2(np.absolute(sobely), np.absolute(sobelx))
    binary_output = np.zeros_like(absgraddir)
    binary_output[(absgraddir >= thresh_min) & (absgraddir <= thresh_max)] = 1

    return binary_output

def combined_threshold(image, orientations, ksize, thresh):
    '''

    :param image:git
    :param orientations:
    :param ksize:
    :param thresh:
    :return:
    '''
    gradx = abs_sobel_thresh(image, orient='x', sobel_kernel=ksize, thresh_min=thresh[0], thresh_max=thresh[1])
    grady = abs_sobel_thresh(image, orient='y', sobel_kernel=ksize, thresh_min=thresh[0], thresh_max=thresh[1])
    mag_binary = mag_tresh(image, sobel_kernel=ksize, mag_thresh=(0, 255))
    dir_binary = dir_threshold(image, sobel_kernel=ksize, thresh=(0, np.pi / 2))
    combined = np.zeros_like(dir_binary)
    combined[((gradx == 1) & (grady == 1)) | ((mag_binary == 1) & (dir_binary == 1))] = 1
    return combined

def detect_edges(img, s_thresh=(170, 255), sx_thresh=(20, 100)):
    '''
    Detect vertical edges in an image
    :param img: image
    :param s_thresh: color threshold
    :param sx_thresh: sobel threshold
    :return:
    '''
    img = np.copy(img)
    # convert to HLS color space and separate the V channel
    hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
    l_channel = hls[:, :, 1]
    s_channel = hls[:, :, 2]

    # sobel x
    sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0)
    abs_sobelx = np.absolute(sobelx)
    scaled_sobel = np.uint8(255 * abs_sobelx / np.max(abs_sobelx))

    # Threshold x gradient
    sxbinary = np.zeros_like(scaled_sobel)
    sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1

    # Threshold color channel
    s_binary = np.zeros_like(s_channel)
    s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1
    # Stack each channel
    color_binary = np.dstack((np.zeros_like(sxbinary), sxbinary, s_binary))

    return color_binary

def hist(img):
    '''
    compute the distribution of x-axis value given a binary image
    :param img:
    :return: the count of number of pixel on the x-axis
    '''
    img = np.copy(img)
    # make the image binary
    img=img/255
    bottom_half = img[img.shape[0] // 2:, :]
    histogram = np.sum(bottom_half, axis=0)
    return histogram

def find_pixel_lane(binary_warped):
    '''
    Find the lane using sliding windows
    :param binary_warped:
    :return:
    '''
    # Take a histogram of the bottom half of the image
    histogram = hist(binary_warped)

    # create an output image to draw on and visualize the result
    out_img = np.dstack((binary_warped, binary_warped, binary_warped))
    midpoint = np.int(histogram.shape[0] // 2)
    leftx_base = np.argmax(histogram[:midpoint])
    rightx_base = np.argmax(histogram[midpoint:]) + midpoint

    # Hyperparameters
    nwindows = 9
    margin = 100
    minpix = 50

    # set heigh of windows
    window_height = np.int(binary_warped.shape[0] // nwindows)
    nonzero = binary_warped.nonzero()
    nonzeroy = np.array(nonzero[0])
    nonzerox = np.array(nonzero[1])

    # current positions to be updated later
    leftx_current = leftx_base
    rightx_current = rightx_base

    # Create empty list
    left_lane_inds = []
    right_lane_inds = []

    # Step through the windows one by one
    for window in range(nwindows):
        win_y_low = binary_warped.shape[0] - (window + 1) * window_height
        win_y_high = binary_warped.shape[0] - window * window_height
        win_xleft_low = leftx_current - margin
        win_xleft_high = leftx_current + margin
        win_xright_low = rightx_current - margin
        win_xright_high = rightx_current + margin

        # Draw the windows on the visualization image
        cv2.rectangle(out_img, (win_xleft_low, win_y_low), (win_xleft_high, win_y_high), (0, 255, 0), 2)
        cv2.rectangle(out_img, (win_xright_low, win_y_low), (win_xright_high, win_y_high), (0, 255, 0), 2)

        # Identify the nonzero pixels in x and y within the window #
        good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
                          (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]
        good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) &
                           (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]

        # Append these indices to the lists
        left_lane_inds.append(good_left_inds)
        right_lane_inds.append(good_right_inds)

        # If you found > minpix pixels, recenter next window on their mean position
        if len(good_left_inds) > minpix:
            leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
        if len(good_right_inds) > minpix:
            rightx_current = np.int(np.mean(nonzerox[good_right_inds]))

    try:
        left_lane_inds = np.concatenate(left_lane_inds)
        right_lane_inds = np.concatenate(right_lane_inds)
    except ValueError:
        # Avoids an error if the above is not implemented fully
        pass

        # Extract left and right line pixel positions
    leftx = nonzerox[left_lane_inds]
    lefty = nonzeroy[left_lane_inds]
    rightx = nonzerox[right_lane_inds]
    righty = nonzeroy[right_lane_inds]

    return leftx, lefty, rightx, righty, out_img

def fit_polynomial(binary_warped, ym_per_pix=30/720,  xm_per_pix = 3.7 / 700):
   '''
   Fit the polynomial on a binary image
   :param binary_warped:
   :param ym_per_pix:
   :param xm_per_pix:
   :return:
   '''
   # Find our lane pixel
   leftx, lefty, rightx, righty, out_img = find_pixel_lane(binary_warped)
   # Fit a second order polynomial to each using `np.polyfit` in pixel
   left_fit = np.polyfit(lefty, leftx, 2)
   right_fit = np.polyfit(righty, rightx, 2)
   # Colors in the left and right lane regions
   out_img[lefty, leftx] = [255, 0, 0]
   out_img[righty, rightx] = [0, 0, 255]
   # fit a second order polynomial in meter
   left_fit_cr = np.polyfit(lefty * ym_per_pix, leftx * xm_per_pix, 2)
   right_fit_cr = np.polyfit(righty * ym_per_pix, rightx * xm_per_pix, 2)

   return out_img, left_fit, right_fit, left_fit_cr, right_fit_cr

def plot_polynomial(img, out_img, left_fit, right_fit):
    '''
    Plot the fitted polynomial on the image
    :param img:
    :param out_img:
    :param left_fit:
    :param right_fit:
    :return:
    '''
    binary_warped = img[:, :, 0]
    # Generate x and y values for plotting
    ploty = np.linspace(0, binary_warped.shape[0] - 1, binary_warped.shape[0])
    try:
        left_fitx = left_fit[0] * ploty ** 2 + left_fit[1] * ploty + left_fit[2]
        right_fitx = right_fit[0] * ploty ** 2 + right_fit[1] * ploty + right_fit[2]
    except TypeError:
        # Avoids an error if `left` and `right_fit` are still none or incorrect
        print('The function failed to fit a line!')
        left_fitx = 1 * ploty ** 2 + 1 * ploty
        right_fitx = 1 * ploty ** 2 + 1 * ploty

    # Plots the left and right polynomials on the lane lines
    f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
    f.tight_layout()
    ax1.imshow(img)
    ax1.set_title('Binary Image', fontsize=50)
    ax2.imshow(out_img)
    ax2.plot(left_fitx, ploty, color='yellow')
    ax2.plot(right_fitx, ploty, color='yellow')
    ax2.set_title('Image with the fitted polynomial', fontsize=50)
    plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
    plt.show()

    #plt.imshow(out_img)
    #plt.plot(left_fitx, ploty, color='yellow')
    #plt.plot(right_fitx, ploty, color='yellow')
    #plt.show()

def hist(img):
    # TO-DO: Grab only the bottom half of the image
    # Lane lines are likely to be mostly vertical nearest to the car
    bottom_half = img[img.shape[0] // 2:, :]

    # TO-DO: Sum across image pixels vertically - make sure to set `axis`
    # i.e. the highest areas of vertical lines should be larger values
    histogram = np.sum(bottom_half, axis=0)

    return histogram

# # Create histogram of image binary activations
# histogram = hist(img)
#
# # Visualize the resulting histogram
# plt.plot(histogram)

def calculate_curvature_offset(binary_warped, left_fit, right_fit, ym_per_pix = 30/720, xm_per_pix = 3.7 / 700):
    '''

    :param ploty:
    :param left_fit:
    :param right_fit:
    :return:
    '''

    # generate y value
    ploty = np.linspace(0, binary_warped.shape[0] - 1, binary_warped.shape[0])
    y_eval = np.max(ploty)

    # curvature
    left_curverad = ((1 + (2 * left_fit[0] * y_eval * ym_per_pix + left_fit[1]) ** 2) ** 1.5) / np.absolute(
        2 * left_fit[0])
    right_curverad = ((1 + (2 * right_fit[0] * y_eval * ym_per_pix + right_fit[1]) ** 2) ** 1.5) / np.absolute(
        2 * right_fit[0])

    mean_curverad = np.mean([left_curverad, right_curverad])

    # vehicle position
    left_fitx = left_fit[0] * (y_eval * ym_per_pix) ** 2 + left_fit[1] * (y_eval * ym_per_pix) + left_fit[2]
    right_fitx = right_fit[0] *(y_eval * ym_per_pix) ** 2 + right_fit[1] * (y_eval * ym_per_pix) + right_fit[2]

    center_lane = np.mean([left_fitx, right_fitx])
    center_vehicle =  (binary_warped.shape[1]*xm_per_pix)/2
    offset = center_lane - center_vehicle

    return mean_curverad, offset

def weighted_img(img, initial_img, α=0.8, β=1., γ=0.):
    """
    `img` is the output of the hough_lines(), An image with lines drawn on it.
    Should be a blank image (all black) with lines drawn on it.
    `initial_img` should be the image before any processing.
    The result image is computed as follows:
    initial_img * α + img * β + γ
    NOTE: initial_img and img must be the same shape!
    """
    return cv2.addWeighted(initial_img, α, img, β, γ)

#def detect_lane_pipeline(img):
    ###todo
    ## distortion
    ## perspective transform
    ## find pixel lane
    ## fit lane


from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *

import resources

from qProf_QWidget import qprof_QWidget

class qProf_gui( object ):

    def __init__(self, interface):

        self.interface = interface
        self.main_window = self.interface.mainWindow()
        self.canvas = self.interface.mapCanvas()

    def initGui(self):

        self.qprof_QAction = QAction(QIcon(":/plugins/qProf/icon.png"), "qProf", self.interface.mainWindow())
        self.qprof_QAction.setWhatsThis( "Topographic and geological profiles" )
        self.qprof_QAction.triggered.connect( self.open_qprof )
        self.interface.addPluginToMenu("QProf", self.qprof_QAction)

    def unload(self):

        self.interface.removePluginMenu( "qProf", self.qprof_QAction )

    def open_qprof(self):

        qprof_DockWidget = QDockWidget( 'qProf', self.interface.mainWindow() )
        qprof_DockWidget.setAttribute(Qt.WA_DeleteOnClose)
        qprof_DockWidget.setAllowedAreas( Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea )
        self.qProf_QWidget = qprof_QWidget( self.canvas )
        qprof_DockWidget.setWidget( self.qProf_QWidget )
        qprof_DockWidget.destroyed.connect( self.qProf_QWidget.closeEvent )
        self.interface.addDockWidget( Qt.RightDockWidgetArea, qprof_DockWidget )


# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def sortList0(self, head: ListNode) -> ListNode:
        # 当没有或只有一个节点时, 直接返回
        if not head or not head.next:
            return head
        # 不存在第三个节点, 也就是只有两个节点
        elif not head.next.next:
            if head.val > head.next.val:
                head.next.next = head
                head = head.next
                # 此时, 原来的第二个节点为head, 原来的第一个节点为head.next
                # head.next.next指向原来的第二个节点
                head.next.next = None
            return head
        # 快慢指针寻找中点
        slow, fast = head, head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next

        # 截断使head所在的子链表只到中点为止, 然后分别递归前后两个子链表
        rhead = slow.next
        slow.next = None
        lf = self.sortList(head)
        lr = self.sortList(rhead)
        # 合并lf, lr, 此时二者均为有序的
        head = cur = ListNode(-1)
        # 子链表有一条不存在则返回另外一条
        while lf and lr:
            if lf.val < lr.val:
                cur.next = lf
                lf = lf.next
            else:
                cur.next = lr
                lr = lr.next
            # 结果链表进行到一个节点
            cur = cur.next
        cur.next = lf or lr
        return head.next

    def sortListArray(self, head: ListNode) -> ListNode:
        nums, cur = [], head
        while cur:
            nums.append(cur.val)
            cur = cur.next
        nums.sort()
        cur = head
        for i in nums:
            cur.val = i
            cur = cur.next
        return head

    def sortListArray2(self, head: ListNode) -> ListNode:
        nums, cur = [], head
        while cur:
            nums.append(cur)
            cur = cur.next
        nums.sort(key=lambda x: x.val)
        head = cur = ListNode(-1)
        for i in nums:
            cur.next = i
            cur = cur.next
        cur.next = None
        return head.next

    def sortList(self, head: ListNode) -> ListNode:
        if not head or not head.next:
            return head
        # fast = head.next: fix 2 nodes maximum recursion
        fast, slow = head.next, head
        # find middle
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        sec = slow.next
        slow.next = None
        # recursion
        front = self.sortList(head)
        second = self.sortList(sec)

        ans = cur = ListNode(-1)
        # merge
        while front and second:
            if front.val > second.val:
                cur.next = front
                front = front.next
            else:
                cur.next = second
                second = second.next
            cur = cur.next
        cur = front or second

        return ans.next

l4 = ListNode(4)
l2 = ListNode(2)
l1 = ListNode(1)
l3 = ListNode(3)
l4.next = l2
l2.next = l1
l1.next = l3

if __name__ == "__main__":
    s = Solution()
    s.sortList(l4)


import logging
import unittest

from ml_preproc.pipeline.features.clean_input import _map_abbreviations

class CleanInputTest(unittest.TestCase):

  def test_map_abbreviations(self):
    abbreviations = {'str': 'street', 'str.': 'street', 'rd': 'road'}
    result = _map_abbreviations("Main str. 8", abbreviations)
    expected = "Main street 8"
    self.assertEqual(result, expected)

if __name__ == '__main__':
  logging.getLogger().setLevel(logging.INFO)
  unittest.main()


import os
import numpy as np
import torch
import torch.nn.functional as F

os.environ["CUDA_VISIBLE_DEVICES"] = '0,1'
def pytorch_compute_single(im, target_interface, GPU_mode=1):
    input_pytorch_value = None
    output_pytorch_value = None
    input_pytorch_cpu_value = None
    output_pytorch_cpu_value = None
    pytorch_shape = [1]
    for shape_element in im.shape:
        pytorch_shape.append(shape_element)

    #print(pytorch_shape)
    input_pytorch = torch.reshape(torch.from_numpy(im), pytorch_shape)
    if GPU_mode != 0:
        input_pytorch_cpu_value = input_pytorch.numpy()

        if target_interface == 'conv1':
            weights_torch = torch.from_numpy(np.full((11, 11, 3, 1), 1, np.float64).transpose((3, 2, 0, 1)))
            output_pytorch_cpu = torch.from_numpy(
                F.conv2d(torch.from_numpy(input_pytorch.numpy().transpose((0, 3, 1, 2))), weights_torch, padding=0,
                         stride=4).numpy().transpose((0, 2, 3, 1)))
        elif target_interface == 'conv2':
            x_torch = torch.from_numpy(input_pytorch.numpy().transpose((0, 3, 1, 2)).astype(np.float64))
            weights_torch = torch.from_numpy(np.full((11, 11, 3, 1), 1, np.float64).transpose((3, 2, 0, 1)))
            stride = 4
            if x_torch.numpy().shape[2] % stride == 0:
                pad = max(weights_torch.numpy().shape[2] - stride, 0)
            else:
                pad = max(weights_torch.numpy().shape[2] - (x_torch.numpy().shape[2] % stride), 0)

            if pad % 2 == 0:
                pad_val = pad // 2
                padding = (pad_val, pad_val, pad_val, pad_val)
            else:
                pad_val_start = pad // 2
                pad_val_end = pad - pad_val_start
                padding = (pad_val_start, pad_val_end, pad_val_start, pad_val_end)
            x_torch = F.pad(x_torch, padding, "constant", 0)
            output_pytorch_cpu = torch.from_numpy(
                F.conv2d(x_torch, weights_torch, padding=0, stride=stride).numpy().transpose((0, 2, 3, 1)))

        elif target_interface == 'pool1':
            output_pytorch_cpu = torch.from_numpy(np.rollaxis(
                F.max_pool2d(torch.from_numpy(np.rollaxis(input_pytorch_cpu_value, 3, 1)), kernel_size=(2, 2),
                             stride=(2, 2)).numpy(), 1, 4))

        elif target_interface == 'pool2':
            output_pytorch_cpu = torch.from_numpy(np.rollaxis(
                F.avg_pool2d(torch.from_numpy(np.rollaxis(input_pytorch_cpu_value, 3, 1)), kernel_size=(2, 2),
                             stride=(2, 2)).numpy(), 1, 4))
        elif target_interface == 'relu1':
            output_pytorch_cpu = F.relu(input_pytorch)
        elif target_interface == 'dense1':
            output_pytorch_cpu = None
        elif target_interface == 'sigmoid1':
            output_pytorch_cpu = F.sigmoid(input_pytorch)

        elif target_interface == 'tanh1':
            output_pytorch_cpu = F.tanh(input_pytorch)

        elif target_interface == 'softmax1':
            output_pytorch_cpu =F.softmax(input_pytorch)

        elif target_interface == 'norm1':
            input_pytorch=torch.transpose(input_pytorch,1,3).to(torch.float32)
            torch_norm = torch.nn.BatchNorm2d(3, momentum=0.99)
            output_pytorch_cpu = torch_norm(input_pytorch)
            output_pytorch_cpu=torch.transpose(output_pytorch_cpu,1,3)

            #output_pytorch_cpu = F.batch_norm(input_pytorch,momentum = 0.99, eps = 1e-05)
            #print(output_pytorch_cpu.shape)
        else:
            output_pytorch_cpu = None

        if target_interface == 'norm1':
            output_pytorch_cpu_value = output_pytorch_cpu.detach().numpy()
        else:
            output_pytorch_cpu_value = output_pytorch_cpu.numpy()
        # print(output_pytorch_cpu_value.shape)

    if GPU_mode != 2:
        with torch.no_grad():
            input_pytorch_value = input_pytorch.to("cuda").numpy()
            if target_interface == 'conv1':
                weights_torch = torch.from_numpy(np.full((11, 11, 3, 1), 1, np.float64).transpose((3, 2, 0, 1)))
                output_pytorch = torch.from_numpy(
                    F.conv2d(torch.from_numpy(input_pytorch.numpy().transpose((0, 3, 1, 2))).to("cuda"),
                             weights_torch.to("cuda"), padding=0, stride=4).to("cpu:0").numpy().transpose((0, 2, 3, 1))).to(
                    "cuda")
            elif target_interface == 'conv2':
                x_torch = torch.from_numpy(input_pytorch.numpy().transpose((0, 3, 1, 2)).astype(np.float64))
                weights_torch = torch.from_numpy(np.full((11, 11, 3, 1), 1, np.float64).transpose((3, 2, 0, 1)))
                stride = 4
                if x_torch.numpy().shape[2] % stride == 0:
                    pad = max(weights_torch.numpy().shape[2] - stride, 0)
                else:
                    pad = max(weights_torch.numpy().shape[2] - (x_torch.numpy().shape[2] % stride), 0)

                if pad % 2 == 0:
                    pad_val = pad // 2
                    padding = (pad_val, pad_val, pad_val, pad_val)
                else:
                    pad_val_start = pad // 2
                    pad_val_end = pad - pad_val_start
                    padding = (pad_val_start, pad_val_end, pad_val_start, pad_val_end)
                x_torch = F.pad(x_torch, padding, "constant", 0)
                output_pytorch = torch.from_numpy(
                    F.conv2d(x_torch.to("cuda"), weights_torch.to("cuda"), padding=0, stride=4).to("cpu").numpy().transpose(
                        (0, 2, 3, 1))).to("cuda")

            elif target_interface == 'pool1':
                output_pytorch = torch.from_numpy(np.rollaxis(
                    F.max_pool2d(torch.from_numpy(np.rollaxis(input_pytorch_value, 3, 1)).to("cuda"), kernel_size=(2, 2),
                                 stride=(2, 2)).to("cpu").numpy(), 1, 4)).to("cuda")
            elif target_interface == 'pool2':
                output_pytorch = torch.from_numpy(np.rollaxis(
                    F.avg_pool2d(torch.from_numpy(np.rollaxis(input_pytorch_value, 3, 1)).to("cuda"), kernel_size=(2, 2),
                                 stride=(2, 2)).to("cpu").numpy(), 1, 4)).to("cuda")
            elif target_interface == 'relu1':
                output_pytorch = F.relu(input_pytorch.to("cuda"))
            elif target_interface == 'dense1':
                output_pytorch = None
            elif target_interface == 'sigmoid1':
                output_pytorch = F.sigmoid(input_pytorch.to("cuda"))
            elif target_interface == 'tanh1':
                output_pytorch = F.tanh(input_pytorch.to("cuda"))
            else:
                output_pytorch = None
            output_pytorch_value = output_pytorch.to("cpu").numpy()
    return output_pytorch_value, input_pytorch_value, output_pytorch_cpu_value, input_pytorch_cpu_value

# if __name__=='__main__':
#     a=np.ones([12,12,3])
#     pytorch_compute_single(a,"norm1",2)


# -*- coding: utf-8 -*-

import chainer
import chainer.links as L
import chainer.functions as F
import time

class CNNLSTM(chainer.Chain):
    def __init__(self, out_unit):
        super(CNNLSTM, self).__init__(
            # Convolution2D(in_channels,out_channels,ksize,stride,pad)
            # NStepLSTM(layer, in, out, dropout)
            conv1=L.Convolution2D(1, 32, 5, 1, 2),
            conv2=L.Convolution2D(32, 32, 5, 1, 2),
            conv3=L.Convolution2D(32, 64, 5, 1, 2),
            fc4=L.Linear(None, 64),
            lstm5=L.NStepLSTM(1, 64, 64, 0.5),
            fc6=L.Linear(64, out_unit),
        )

    def CNN(self, x):
        h1 = self.conv1(x)
        h2 = F.max_pooling_2d(h1, ksize=3, stride=2)
        h3 = F.relu(h2)
        h4 = self.conv2(h3)
        h5 = F.relu(h4)
        h6 = F.average_pooling_2d(h5, ksize=3, stride=2)
        h7 = self.conv3(h6)
        h8 = F.relu(h7)
        h9 = F.average_pooling_2d(h8, ksize=3, stride=2)
        h10 = self.fc4(h9)
        #h10 = F.dropout(self.fc4(h9), ratio=0.5)

        return h10

    def __call__(self, hx, cx, x):
        #             |-----シーケンス長-----|
        #x: Variable([[frame],[frame],...], [[frame],[frame],...], ...)
        #            |-------------------バッチサイズ---------------------|
        h10 = [self.CNN(item.reshape(item.shape[0], 1, item.shape[1], item.shape[2])) for item in x]
        hy, cy, h11 = self.lstm5(hx, cx, h10)
        y = [self.fc6(item) for item in h11]

        return y


#!/usr/bin/python
#-*-coding:utf-8
import os
import sys
import pdb
import re
import math
from pymongo import MongoClient
import pymongo
import time
import json
import time
import pdb
def load_model(f_name):
    ifp = open(f_name, 'rb')
    return eval(ifp.read())
# def viterbi(obs, states, start_p, trans_p, emit_p):
#     V = [{}] #tabular
#     path = {}
#     for y in states: #init
#         V[0][y] = start_p[y] * emit_p[y].get(obs[0],0)
#         path[y] = [y]
#     for t in range(1,len(obs)):
#         V.append({})
#         newpath = {}
#         for y in states:
#             (prob,state ) = max([(V[t-1][y0] * trans_p[y0].get(y,0) * emit_p[y].get(obs[t],0) ,y0) for y0 in states if V[t-1][y0]>0])
#             V[t][y] =prob
#             newpath[y] = path[state] + [y]
#         path = newpath
#     (prob, state) = max([(V[len(obs) - 1][y], y) for y in states])
#     return (prob, path[state])

def viterbi(obs,states,prob_start,prob_trans,prob_emit):
	"""
	obs=observed values
	states=['B','M','E','S'] (Begin, Middle, End, Single word)
	prob_start=probability of start
	prob_trans=state-transition matrix
	Status(i)＝f({Status(i-1), Status(i-2), Status(i-3), ... Status(i - n)})
	prob_emit＝emission probability EmitProbMatrix
	P(Observed[i], Status[j]) = P(Status[j]) * P(Observed[i]|Status[j])
	"""
	v=[{}]
	path={}
	#init the start node
	for state in states:
		if obs[0] in prob_emit[state]:
			v[0][state]=math.exp(prob_start[state]*prob_emit[state][obs[0]])
		else:
			v[0][state]=0
		path[state]=[state]
	#print(path)
	# for all
	for i in range(1,len(obs)):
		v.append({})
		newpath={}
		for state in states:
			est_list=[]
			for pstate in [s for s in states if v[i-1][s]>0]:
				if obs[i] in prob_emit[state]:
					est_list.append((v[i-1][pstate]*math.exp(prob_trans[pstate][state]*prob_emit[state][obs[i]]),pstate))
				else:
					est_list.append((v[i-1][pstate],pstate))
			p,ps=max([(p,ps) for (p,ps) in est_list])
			v[i][state]=p
			newpath[state]= path[ps] + [state]
		path=newpath
	(prob, state) = max([(v[len(obs) - 1][state], state) for state in states])
	try:
		if prob_emit['M'][obs[-1]]> prob_emit['S'][obs[-1]]:
			(prob, state) = max([(v[len(obs) - 1][state], state) for state in ('S','E')])
	except:
	 	pass
	raw=""
	if path:
		for i,char in enumerate(obs):
			#Sprint(path)
			if path[state][i]=="E":
				raw+=char+"  "
			elif path[state][i]=="S":
				raw+=char+"  "
			else:
				raw+=char

		return (raw,"".join(path[state]))
	else:
		return ("","")
def cut(sentence):
    #pdb.set_trace()
    prob, pos_list =  viterbi(sentence,('B','M','E','S'), prob_start, prob_trans, prob_emit)
    return (prob,pos_list)

if __name__ == "__main__":
    prob_start = load_model("/home/john/pythonspace/sina_crawler/weibo_crawler/FC/HMM/prob_start.py")
    prob_trans = load_model("/home/john/pythonspace/sina_crawler/weibo_crawler/FC/HMM/prob_trans.py")
    prob_emit = load_model("/home/john/pythonspace/sina_crawler/weibo_crawler/FC/HMM/prob_emit.py")

    db_uri = "mongodb://labUser:aaaaaa@localhost:27017/?authSource=blog"
    db_name = "blog"
    xlient = MongoClient(db_uri)
    db = xlient[db_name]
    print(db)

    myiter = db.blog.find({"blog.content.text_content":{"$exists":1}},{"blog.content.text_content":1})
    length = 1000
    print("##")
    print(myiter[7]['blog']['content']['text_content'])
    i=0
    while i<length:
        print(i)
        test_str = myiter[i]['blog']['content']['text_content'].strip().strip('#')
        # print(test_str)
        prob,pos_list = cut(test_str)
        print(prob)
        # print(pos_list)
        i=i+1

    test_str = "在党的十二届六中全会通过的《关于社会主义精神文明建设指导方针的决议》指引下。"
    # print(test_str)
    # prob,pos_list = cut(test_str)
    # print(prob)
    # test_str = "微卖 快来围观我的“微卖”小店，我又进了不少新货 http://t.cn/R4U3Dp1"
    # test_str = myiter[1000]['blog']['content']['text_content']
    # print(test_str)

    print(test_str)
    prob,pos_list = cut(test_str)
    print(prob)
    print(pos_list)

    # while i:
    #     i=i-1
    #     test_str = myiter[1000]['blog']['content']['text_content'].strip()
    #     # test_str    = "新华网东京电记者吴谷丰据日本共同社28日报道，日本行政改革担当大臣稻田朋美当天参拜了供奉有二战甲级战犯牌位的靖国神社。她成为第四个参拜靖国神社的安倍内阁成员。靖国神社位于东京千代田区，供奉有包括东条英机在内的14名第二次世界大战甲级战犯的牌位。长期以来，日本部分政客参拜靖国神社，导致日本与中国、韩国等亚洲国家关系"
    #     prob,pos_list = cut(test_str)
    #     print("HMM segment:",prob)
    # print(pos_list)
    #print(type(prob))


from __future__ import unicode_literals
from pn532 import PN532_SPI
import vlc
import random
import re
import unicodedata

import RPi.GPIO as GPIO

GPIO.setwarnings(False)

class Reader:

    TIMEOUT = 1  # seconds
    DEFAULT = "downloads/default/endline.wav"

    def __init__(self, player, playlist_map) -> None:
        self.player = player
        self.playlist_map = playlist_map
        self.playing = False
        self.reading = True
        self.last_tag = None

    def start(self) -> None:
        try:
            pn532 = PN532_SPI(debug=False, reset=20, cs=4)
            ic, ver, rev, support = pn532.get_firmware_version()
            print("Found PN532: {0}.{1}".format(ver, rev))
            pn532.SAM_configuration()
            print("Starting reader...")
            while self.reading:
                tag = pn532.read_passive_target(timeout=self.TIMEOUT)
                if tag is None:
                    self.player.stop()
                    self.playing = False
                    continue
                self.last_tag = str(tag.hex())
                if not self.playing:
                    print(f"looking for match: {self.last_tag}")
                    try:
                        joycon = self.playlist_map[self.last_tag]
                        print(f"Found: {joycon['name']}")
                        playlist = joycon["playlist"]
                        if joycon["shuffle"]:
                            random.shuffle(playlist)
                        self.player.set_media_list(vlc.MediaList(playlist))
                        if joycon["repeat"]:
                            self.player.set_playback_mode(vlc.PlaybackMode.loop)
                        else:
                            self.player.set_playback_mode(vlc.PlaybackMode.default)
                        self.player.play()
                        self.playing = True
                    except Exception as x:
                        self.player.set_media_list(vlc.MediaList([self.DEFAULT]))
                        self.player.play()
                        self.playing = True

        except Exception as e:
            print(e)


import argparse
import json
from utils.params import FT_Configer
from finetune.trainer import Trainer

def load(json_file):

    with open(json_file, 'r') as f:
        return json.load(f)

def main():

    parser = argparse.ArgumentParser(description="Argparser")
    parser.add_argument("--params",
                        default={},
                        help="JSON dict of model hyperparameters.")
    args = parser.parse_args()

    model_args = FT_Configer(load(args.params))

    trainer = Trainer(model_args)
    trainer.run_finetune()

if __name__ == '__main__':

    main()


from moe_scraper.util import *

AMIAMI_ITEM_PAGE_TEMPLATE = 'https://www.amiami.jp/top/detail/detail?gcode=%s'

AMIAMI_CATEGORY_CARD = 'CARD'
AMIAMI_CATEGORY_GAME = 'GAME'
AMIAMI_CATEGORY_FIGURE = 'FIGURE'
AMIAMI_CATEGORY_GOODS = 'GOODS'
AMIAMI_CATEGORY_LTD_DVD = 'LTD-DVD'
AMIAMI_CATEGORY_LTD_ETC = 'LTD-ETC'
AMIAMI_CATEGORY_LTD_FIG = 'LTD-FIG'
AMIAMI_CATEGORY_LTD_PCG = 'LTD-PCG'
AMIAMI_CATEGORY_MED_BOOK = 'MED-BOOK'
AMIAMI_CATEGORY_MED_CD2 = 'MED-CD2'
AMIAMI_CATEGORY_MED_DVD2 = 'MED-DVD2'
AMIAMI_CATEGORY_RAIL = 'RAIL'
AMIAMI_CATEGORY_TOY_SCL2 = 'TOY-SCL2'
AMIAMI_CATEGORY_TOY_SCL3 = 'TOY-SCL3'

# For padding 0 to the item code
AMIAMI_CATEGORY_CARD_LENGTH = 8
AMIAMI_CATEGORY_GAME_LENGTH = 7
AMIAMI_CATEGORY_FIGURE_LENGTH = 6
AMIAMI_CATEGORY_GOODS_LENGTH = 8
AMIAMI_CATEGORY_LTD_DVD_LENGTH = 5
AMIAMI_CATEGORY_LTD_ETC_LENGTH = 5
AMIAMI_CATEGORY_LTD_FIG_LENGTH = 5
AMIAMI_CATEGORY_LTD_PCG_LENGTH = 5
AMIAMI_CATEGORY_MED_BOOK_LENGTH = 6
AMIAMI_CATEGORY_MED_CD2_LENGTH = 5
AMIAMI_CATEGORY_MED_DVD2_LENGTH = 5
AMIAMI_CATEGORY_RAIL_LENGTH = 5
AMIAMI_CATEGORY_TOY_SCL2_LENGTH = 5
AMIAMI_CATEGORY_TOY_SCL3_LENGTH = 5

class AmiAmiItem:

    def __init__(self, id, category, name, updated_date):
        self.id = id
        self.category = category
        self.name = name
        self.updated_date = updated_date

    def __iter__(self):
        yield 'id', self.id
        yield 'category', self.category
        yield 'name', self.name
        yield 'updated_date', self.updated_date

def amiami_download_images(item_ids, category, save_jan_code=False):
    config = read_config_file()
    if AMIAMI_OUTPUT_IMAGE_FOLDER not in config:
        print('%s not found in app.config' % AMIAMI_OUTPUT_IMAGE_FOLDER)
        return
    if IMAGE_DOWNLOAD_LOG_PATH in config:
        log_path = config[IMAGE_DOWNLOAD_LOG_PATH]
    else:
        log_path = ''
    image_output = config[AMIAMI_OUTPUT_IMAGE_FOLDER]

    item_ids = convert_item_ids_to_list(item_ids)
    if item_ids is None:
        print('Invalid Item IDs')
        return

    category_length = get_category_length(category)
    if category_length == 0:
        print('Invalid category')
        return

    try:
        for item_id in item_ids:
            item_code = category + '-' + str(item_id).zfill(category_length)
            item_url = AMIAMI_ITEM_PAGE_TEMPLATE % str(item_code)
            soup = get_soup(item_url)

            if soup:
                if save_jan_code:
                    code = amiami_get_jan(soup)
                    if code is None:
                        code = item_code
                else:
                    code = item_code

                image_urls = amiami_get_image_urls(soup)
                download_images(image_urls, code, image_output, log_path)
    except Exception as e:
        print(e)

def amiami_download_images_expr(expr, category, save_jan_code=False):
    item_ids = get_numbers_from_expression(expr)
    return amiami_download_images(item_ids, category, save_jan_code)

def amiami_get_image_urls(soup):
    image_urls = []
    main_image = soup.find('div', class_='main_image_area_inner')
    if main_image:
        main_img_tag = main_image.find('img')
        if main_img_tag and main_img_tag.has_attr('src'):
            image_urls.append(main_img_tag['src'])
    gallery_items = soup.find_all('div', class_='gallery_item')
    for gallery_item in gallery_items:
        a_tag = gallery_item.find('a')
        if a_tag and a_tag.has_attr('href'):
            image_urls.append(a_tag['href'])
    return image_urls

def amiami_get_jan(soup):
    dd_tag = soup.find('dd', class_='jancode')
    if dd_tag:
        return dd_tag.text
    else:
        return None

def get_category_length(category):
    if category == AMIAMI_CATEGORY_CARD:
        return AMIAMI_CATEGORY_CARD_LENGTH
    elif category == AMIAMI_CATEGORY_GAME:
        return AMIAMI_CATEGORY_GAME_LENGTH
    elif category == AMIAMI_CATEGORY_FIGURE:
        return AMIAMI_CATEGORY_FIGURE_LENGTH
    elif category == AMIAMI_CATEGORY_GOODS:
        return AMIAMI_CATEGORY_GOODS_LENGTH
    elif category == AMIAMI_CATEGORY_LTD_DVD:
        return AMIAMI_CATEGORY_LTD_DVD_LENGTH
    elif category == AMIAMI_CATEGORY_LTD_ETC:
        return AMIAMI_CATEGORY_LTD_ETC_LENGTH
    elif category == AMIAMI_CATEGORY_LTD_FIG:
        return AMIAMI_CATEGORY_LTD_FIG_LENGTH
    elif category == AMIAMI_CATEGORY_LTD_PCG:
        return AMIAMI_CATEGORY_LTD_PCG_LENGTH
    elif category == AMIAMI_CATEGORY_MED_BOOK:
        return AMIAMI_CATEGORY_MED_BOOK_LENGTH
    elif category == AMIAMI_CATEGORY_MED_CD2:
        return AMIAMI_CATEGORY_MED_CD2_LENGTH
    elif category == AMIAMI_CATEGORY_MED_DVD2:
        return AMIAMI_CATEGORY_MED_DVD2_LENGTH
    elif category == AMIAMI_CATEGORY_RAIL:
        return AMIAMI_CATEGORY_RAIL_LENGTH
    elif category == AMIAMI_CATEGORY_TOY_SCL2:
        return AMIAMI_CATEGORY_TOY_SCL2_LENGTH
    elif category == AMIAMI_CATEGORY_TOY_SCL3:
        return AMIAMI_CATEGORY_TOY_SCL3_LENGTH
    else:
        return 0

def amiami_scan_front_page_new_items(is_english=False):
    if is_english:
        return [] # To be updated
    else:
        return amiami_scan_front_page_new_items_jp()

def amiami_scan_front_page_new_items_jp():
    soup = get_soup('https://amiami.jp/txt/item/index_all.html')
    top_updatedates = soup.find_all('div', class_='top_updatedate')
    items = []
    for top_updatedate in top_updatedates:
        if len(top_updatedate['class']) != 2:
            continue
        date_str = top_updatedate['class'][1].replace('update', '')
        products = soup.select('div.product_box.update' + date_str)
        for product in products:
            a_tag = product.find('a')
            if a_tag and a_tag.has_attr('href') and a_tag.has_attr('title'):
                title = a_tag['title']
                if 'gcode=' in a_tag['href']:
                    code = a_tag['href'].split('gcode=')[1].split('&')[0]
                    if '-' in code:
                        split1 = code.split('-')
                        id = split1[-1]
                        category = ''
                        for i in range(len(split1) - 1):
                            category += split1[i]
                        items.append(dict(AmiAmiItem(id, category, title, date_str)))
    return items

def amiami_output_front_page_result(updated_date=None, is_english=False):
    config = read_config_file()
    if AMIAMI_OUTPUT_FRONT_PAGE_RESULT_FOLDER not in config:
        print('%s not found in app.config' % AMIAMI_OUTPUT_FRONT_PAGE_RESULT_FOLDER)
        return

    output_folder = config[AMIAMI_OUTPUT_FRONT_PAGE_RESULT_FOLDER]
    output_file = config[AMIAMI_OUTPUT_FRONT_PAGE_RESULT_FOLDER] + '/' + config[AMIAMI_OUTPUT_FRONT_PAGE_RESULT_NAME]

    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    items = amiami_scan_front_page_new_items(is_english)
    if len(items) == 0:
        return

    with open(output_file, 'a+', encoding='utf-8') as f:
        f.write('===================\n')
        f.write(get_datetime_now_str('-', ' ', ':') + '\n')
        f.write('===================\n\n')
    for item in items:
        if (updated_date and updated_date == item['updated_date']) or updated_date is None:
            with open(output_file, 'a+', encoding='utf-8') as f:
                f.write(item['category'] + '-' + item['id'] + '\t' + item['name'] + '\n')
    with open(output_file, 'a+', encoding='utf-8') as f:
        f.write('\n\n\n')


import matplotlib.pyplot as plt
import time
import os
import platform
import sys
import copy
import numpy as np

platform = platform.system()

args = sys.argv

if "--size" in args:
    size = int(args[args.index("--size")+1])
    a, b = size, size
else:
    a,b = 40,40
if "--wait" in args:
    wait = int(args[args.index("--wait")+1])
else:
    wait = 0.05

print("Using board size {0}x{1} and wait value of {2}s.".format(a, b, wait))

board1 = [0] * a
for i in range(a):
    board1[i] = [0] * b
gen = 0
pop = 0
gens = []
pops = []
print("\nStructure each input like this: x/y.")
print("\nFor example: 10/10 would set (10,10) to be alive.")
print("\nFor multiple inputs, structure it like this: x/y;x/y;x/y")
print("\nREMEMBER: The matrix starts at index 0, which means the tile or cell \n          in the top left would be 0/0")
print("\nYou can also enter \"random/probability of 1\" to get a random board.\n")
inp = input("? ")
if inp.startswith("random"):
    prob1 = float(inp[inp.find("/")+1:len(inp)])
    prob2 = 1 - prob1
    board1 = np.random.choice([1,0], a*b, p=[prob1, prob2]).reshape(a, b)
else:
    inps = inp.split(";")
    for inp in inps:
        if inp == '':
            break;
        inp_split = inp.split("/")
        x = int(inp_split[0])
        y = int(inp_split[1])
        #useless code because I was an idiot and forgot .split() was a thing
        #but I spent too much time thinking about it so I don't want to remove it
        #x = int(inp[:inp.find("/")]) #finds the first /
        #y = int(inp[inp.find("/")+1:inp.find("/",inp.find("/")+1)]) #finds the first / after the first /, which is the second /
        #state = int(inp[inp.find("/",inp.find("/")+1)+1:(inp.find("/",inp.find("/",inp.find("/")+1))+1)+(len(inp)-inp.find("/",inp.find("/")+1)+1)]) #finds the first / after the first / after the first /, or the first / after the second /, or just the third /
        board1[y][x] = 1
        print("(" + str(x) + "," + str(y) + ") is now " + str(1))
iterations = int(input("\nHow many generations would you like to run? "))
for gen in range(1, iterations+1):
    board2 = copy.deepcopy(board1)
    boardstr = ""
    if platform == "Windows":
        os.system('cls')
    else:
        os.system('clear')
    pop = 0
    for y in range(0, a):
        for x in range(0,b):
            if board1[y][x] == 1:
                pop += 1
            if board1[y][x] == 1:
                boardstr += "██"
            else:
                boardstr += "  "
        boardstr += "\n"
    print(boardstr)
    print("GEN: " + str(gen))
    print("POP: " + str(pop))
    gens.append(gen)
    pops.append(pop)
    for y in range(0, a):
        for x in range(0,b):
            total = int(board1[(y-1) % a][(x-1) % b] + board1[(y-1) % a][x % b] + board1[(y-1) % a][(x+1) % b] +
                        board1[y % a][(x-1) % b] + board1[y % a][(x+1) % b] +
                        board1[(y+1) % a][(x-1) % b] + board1[(y+1) % a][x % b] + board1[(y+1) % a][(x+1) % b])
            if board1[y][x] == 1:
                if (total < 2) or (total > 3):
                    board2[y][x] = 0
            else:
                if total == 3:
                    board2[y][x] = 1
            #print(str(b*(y)+x) + " : " + str(total) + " : " + str(board1[y][x]) + " : " + str(board2[y][x]))
            #time.sleep(0.1)
    board1 = copy.deepcopy(board2)
    #print(board1)
    #R-Pentomino: 10/10;11/10;9/11;10/11;10/12
    time.sleep(wait)

print("\nDone!\n")

plt.plot(gens, pops)
plt.show()


import xlwt
import json
import time
import requests
import queue as Queue
import threading

# 本脚本主要通过用户身份证号，已经回溯时间获取用户历史借贷特征

# 设置队列长度
workQueue = Queue.Queue(40000)

class myThread(threading.Thread):
    def __init__(self, name, q,wf):
        threading.Thread.__init__(self)
        self.name = name
        self.q = q
        self.wf = wf

    def run(self):
        print("Starting " + self.name)
        while True:
            try:
                crawler(self.name, self.q,self.wf)
            except:
                break
        print("Exiting " + self.name)

# 创建5个线程名
threadList = ["Thread-1", "Thread-2"]
# 线程池
threads = []

def crawler(threadName, q,wf):
    # 从队列里获取url
    idNum_Date = q.get(timeout=2)
    idNum=idNum_Date[0]
    curr_date=idNum_Date[1]
    try:
        all_list = get_response(idNum,curr_date)
        if all_list:
            print('获取到特征值，开始写入到文本')
            wf.write(str(all_list)+'\n')
            wf.flush()
        # 打印：队列长度，线程名，响应吗，正在访问的url
        print(q.qsize(), threadName, idNum)
    except Exception as e:
        print(q.qsize(), threadName, "Error: ", e)

# 获取test.txt中所有身份证的107条规则并写入文本
def get_value(file):
    file_idNum=open('huaxiatest.txt',encoding='utf-8').readlines()
    for i in file_idNum:
        # 去掉结尾空格
        i=i.rstrip()
        # 取出身份证号码
        # order_id = i.split(',')[0]
        idNum=i.split(',')[0]
        curr_date = i.split(',')[1]
        if not idNum:
            break
        workQueue.put([idNum,curr_date])
    # 创建新线程
    with open(file,'w') as wf:
        for tName in threadList:
            thread = myThread(tName, workQueue,wf)
            thread.start()
            threads.append(thread)

        # 等待所有线程完成
        for t in threads:
            t.join()

        # all_list=get_response(idNum)
        # if all_list:
        #     print('获取到%s特征值，开始写入到文本'%idNum)
        #     file3.write(str(all_list)+'\n')
        #     file3.flush()
    print('写入完成')
    time.sleep(2)

# 根据身份证号码获取107条特征，并转换成list输出
def get_response(idNum,currDate):
    all_dic={}
    url='http://127.0.0.1:5000/getJinpanLoanFeatures?identityNo=%s'
    res=requests.get(url % (idNum,currDate))
    if res.status_code==200:
        all_list=[]
        res=res.json()
        result=res.get('result')
        all_dic['identity_no']=result.get('identity_no')
        features=result.get('features')
        if features:
            all_dic.update(features)
        for key in all_dic:
            all_list.append(all_dic[key])
        return all_list
    else:
        return None

# 将结果写入表格
def wirte_excle():
    file = 'value.txt'
    get_value(file)
    print("准备写表格")
    f = xlwt.Workbook()
    sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True)
    # #将列名写入第0行
    file_dict = {'idNum': '', "apply_pdl_7": 0, "apply_int_7": 0, "apply_sum_7": 0, "reject_pdl_7": 0,
                 "reject_int_7": 0, "reject_sum_7": 0, "approve_pdl_7": 0, "approve_int_7": 0, "approve_sum_7": 0,
                 "overdue_pdl_7": 0, "overdue_int_7": 0, "overdue_sum_7": 0, "loanamount_pdl_7": 0.0,
                 "loanamount_int_7": 0.0, "loanamount_sum_7": 0.0, "maxOverdue_pdl_7": -99999,
                 "maxOverdue_int_7": -99999, "maxOverdue_sum_7": -99999, "apply_pdl_14": 0, "apply_int_14": 0,
                 "apply_sum_14": 0, "reject_pdl_14": 0, "reject_int_14": 0, "reject_sum_14": 0, "approve_pdl_14": 0,
                 "approve_int_14": 0, "approve_sum_14": 0, "overdue_pdl_14": 0, "overdue_int_14": 0,
                 "overdue_sum_14": 0, "loanamount_pdl_14": 0.0, "loanamount_int_14": 0.0, "loanamount_sum_14": 0.0,
                 "maxOverdue_pdl_14": -99999, "maxOverdue_int_14": -99999, "maxOverdue_sum_14": -99999,
                 "apply_pdl_30": 0, "apply_int_30": 0, "apply_sum_30": 0, "reject_pdl_30": 0, "reject_int_30": 0,
                 "reject_sum_30": 0, "approve_pdl_30": 0, "approve_int_30": 0, "approve_sum_30": 0, "overdue_pdl_30": 0,
                 "overdue_int_30": 0, "overdue_sum_30": 0, "loanamount_pdl_30": 0.0, "loanamount_int_30": 0.0,
                 "loanamount_sum_30": 0.0, "maxOverdue_pdl_30": -99999, "maxOverdue_int_30": -99999,
                 "maxOverdue_sum_30": -99999, "apply_pdl_60": 0, "apply_int_60": 0, "apply_sum_60": 0,
                 "reject_pdl_60": 0, "reject_int_60": 0, "reject_sum_60": 0, "approve_pdl_60": 0, "approve_int_60": 0,
                 "approve_sum_60": 0, "overdue_pdl_60": 0, "overdue_int_60": 0, "overdue_sum_60": 0,
                 "loanamount_pdl_60": 0.0, "loanamount_int_60": 0.0, "loanamount_sum_60": 0.0,
                 "maxOverdue_pdl_60": -99999, "maxOverdue_int_60": -99999, "maxOverdue_sum_60": -99999,
                 "apply_pdl_90": 0, "apply_int_90": 0, "apply_sum_90": 0, "reject_pdl_90": 0, "reject_int_90": 0,
                 "reject_sum_90": 0, "approve_pdl_90": 0, "approve_int_90": 0, "approve_sum_90": 0, "overdue_pdl_90": 1,
                 "overdue_int_90": 0, "overdue_sum_90": 0, "loanamount_pdl_90": 0.0, "loanamount_int_90": 0.0,
                 "loanamount_sum_90": 0.0, "maxOverdue_pdl_90": 0, "maxOverdue_int_90": -99999,
                 "maxOverdue_sum_90": 0, "apply_pdl_180": 0, "apply_int_180": 0, "apply_sum_180": 0,
                 "reject_pdl_180": 0, "reject_int_180": 0, "reject_sum_180": 0, "approve_pdl_180": 0,
                 "approve_int_180": 0, "approve_sum_180": 0, "overdue_pdl_180": 0, "overdue_int_180": 0,
                 "overdue_sum_180": 0, "loanamount_pdl_180": 0.0, "loanamount_int_180": 0.0,
                 "loanamount_sum_180": 0.0, "maxOverdue_pdl_180": 0, "maxOverdue_int_180": -99999,
                 "maxOverdue_sum_180": 0, "apply_pdl_all": 0, "apply_int_all": 0, "apply_sum_all": 0,
                 "reject_pdl_all": 0, "reject_int_all": 0, "reject_sum_all": 0, "approve_pdl_all": 0,
                 "approve_int_all": 0, "approve_sum_all": 0, "overdue_pdl_all": 0, "overdue_int_all": 0,
                 "overdue_sum_all": 0, "loanamount_pdl_all": 0.0, "loanamount_int_all": 0.0,
                 "loanamount_sum_all": 0.0, "maxOverdue_pdl_all": 0, "maxOverdue_int_all": -99999,"maxOverdue_sum_all": 0,
                 "apply_pdl_label": 0, "apply_int_label": 0, "apply_sum_label": 0,
                 "reject_pdl_label": 0, "reject_int_label": 0, "reject_sum_label": 0, "approve_pdl_label": 0,
                 "approve_int_label": 0, "approve_sum_label": 0, "overdue_pdl_label": 0, "overdue_int_label": 0,
                 "overdue_sum_label": 0, "loanamount_pdl_label": 0.0, "loanamount_int_label": 0.0,
                 "loanamount_sum_label": 0.0, "maxOverdue_pdl_label": 0, "maxOverdue_int_label": -99999,
                 "maxOverdue_sum_label": 0
                 }

    s=0
    for key in file_dict:
        sheet1.write(0, s, key)
        s+=1
    print("表头设置完成")

    #然后将数据写入第 i 行，第 j 列
    i = 1
    file=open(file,encoding='utf-8').readlines()
    for data in file:
        data=eval(data)
        for j in range(len(data)):
            sheet1.write(i, j, data[j])
        i = i + 1
        print("正在写入第%s行"%i)
    print("内容写入完成")
    f.save('a_new.xls')  # 保存文件

if __name__ == '__main__':
    time1 = time.time()
    wirte_excle()
    # wirte_excle1()
    time2 = time.time()
    print(time2-time1)


from fastapi import FastAPI, Request, Depends, BackgroundTasks, background
from fastapi.templating import Jinja2Templates
from sqlalchemy import engine
import dbmodels
import yfinance as yf
from sqlalchemy.orm import Session
from database import SessionLocal, engine
from pydantic import BaseModel
from dbmodels import StockData
from twilio.rest import Client

account = "###########"
token = "###########"
client = Client(account,token)

client.region = 'us1'
client.edge = 'ashburn'

app = FastAPI()

dbmodels.Base.metadata.create_all(bind=engine)

templates = Jinja2Templates(directory="templates")

class StockReq(BaseModel):
    stockname: str

def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

def yahoo_data_fetch(id: int):
    db = SessionLocal()
    stock_data = db.query(StockData).filter(StockData.id == id).first()
    yahoo_stock_data = yf.Ticker(stock_data.stockname)
    stock_data.ma200 = yahoo_stock_data.info["twoHundredDayAverage"]
    stock_data.ma50 = yahoo_stock_data.info["fiftyDayAverage"]
    stock_data.price = yahoo_stock_data.info["previousClose"]
    stock_data.forward_pe = yahoo_stock_data.info["forwardPE"]
    stock_data.forward_eps = yahoo_stock_data.info["forwardEps"]
    if stock_data.dividend_yield is not None:
        stock_data.dividend_yield = yahoo_stock_data.info["dividendYield"] * 100
    db.add(stock_data)
    db.commit()

@app.get("/")
def dashboard(request: Request, forward_pe = None, dividend_yield = None, ma50 = None, ma200 = None, db: Session = Depends(get_db)):
    ''''''''''
    displays the dashboard
    '''''''''''
    Stocks = db.query(StockData)
    if forward_pe:
        Stocks = Stocks.filter(StockData.forward_pe < forward_pe)
    if dividend_yield:
        Stocks = Stocks.filter(StockData.dividend_yield > dividend_yield)
    if ma50:
        Stocks = Stocks.filter(StockData.price > ma50)
    if dividend_yield:
        Stocks = Stocks.filter(StockData.price > ma200)

    return templates.TemplateResponse("dashboard.html",{
        "request": request,
        "Stocks": Stocks,
        "dividend_yield": dividend_yield,
        "forward_pe": forward_pe,
        "ma200": ma200,
        "ma50": ma50
    })

@app.post("/stockname")
async def stockCreate(stock_req: StockReq, task_background : BackgroundTasks,db: Session = Depends(get_db)):
    ''''''''''
    stock creation
    '''''''''''
    stock = StockData()
    stock.stockname = stock_req.stockname
    db.add(stock)
    db.commit()
    task_background.add_task(yahoo_data_fetch, stock.id)
    message = client.messages.create(to= "###########", from_ = "###########", body = "New Stock " + stock.stockname + " added")
    return{
        "code": "success",
        "message": "stock has been created"
    }


from selenium import webdriver
import time

# Launch Firefox browser
driver = webdriver.Firefox()

# Open custom map URL
driver.get("https://webcam-live.creaweather.fr/Meteo60.html")
time.sleep(5)
# Execute JavaScript to get all pins on the map
pins = driver.execute_script("return document.querySelectorAll('.gm-style-iw-d');")

# Iterate through each pin
for pin in pins:
    # Click on the pin to open the popup window
    driver.execute_script("arguments[0].click();", pin)

    # Get the link attached to the pin using JavaScript
    link = driver.execute_script("return document.querySelector('.gm-style-iw-e a').href;")

    # Print the link
    print(link)

    # Close the popup window
    driver.execute_script("document.querySelector('.gm-style-iw-i-c').click();")

# Close the browser


from http import HTTPStatus
from typing import Dict, Iterable, List, Mapping, Optional, Union

from amundsen_common.entity.resource_type import ResourceType
from amundsen_common.models.dashboard import DashboardSummarySchema
from amundsen_common.models.table import TableSummarySchema
from flasgger import swag_from
from flask import request
from flask_restful import Resource

from metadata_service.proxy import get_proxy_client

class PopularResourcesAPI(Resource):
    """
    PopularResources API
    """

    def __init__(self) -> None:
        self.client = get_proxy_client()

    @swag_from('swagger_doc/popular_resources_get.yml')
    def get(self, user_id: Optional[str] = None) -> Iterable[Union[Mapping, int, None]]:
        limit = request.args.get('limit', 10, type=int)
        resource_types = request.args.get('types', 'table', type=str)
        resource_types = resource_types.split(',')
        popular_resources: Dict[str, List] = self.client.get_popular_resources(
            num_entries=limit,
            resource_types=resource_types,
            user_id=user_id)

        response: dict = dict()
        response[ResourceType.Table.name] = TableSummarySchema().dump(
            popular_resources.get(ResourceType.Table.name),
            many=True
        )
        response[ResourceType.Dashboard.name] = DashboardSummarySchema().dump(
            popular_resources.get(ResourceType.Dashboard.name),
            many=True
        )
        return response, HTTPStatus.OK


import os
import argparse
import time
import numpy as np
import utils
from config import get_algo_config, get_algo_class

dataset_root = 'data/'

parser = argparse.ArgumentParser()
parser.add_argument("--runs", type=int, default=1,
                    help="how many times we repeat the experiments to obtain the average performance")
parser.add_argument("--input_dir", type=str, default='ts/',
                    help="not use here for ts data")
parser.add_argument("--output_dir", type=str, default='&ts_record/',
                    help="the output file path")
parser.add_argument("--dataset", type=str, default='UCR_natural')
parser.add_argument("--entities", type=str,
                    default='FULL',
                    help='FULL represents all the csv file in the folder, or a list of entity names split by comma')
parser.add_argument("--model", type=str, default='dif', help="")
parser.add_argument("--note", type=str, default='')

# parameters of dif
parser.add_argument('--seq_len', type=int, default=100)
parser.add_argument('--stride', type=int, default=10)
parser.add_argument('--n_layer', type=int, default=2)
parser.add_argument('--hidden_dim', type=int, default=32)
parser.add_argument('--rep_dim', type=int, default=20)
args = parser.parse_args()

model_class = get_algo_class(args.model)
model_configs = get_algo_config(args.model)

if args.model == 'dif':
    ts_model_configs={
        'data_type': 'ts',
        'network_name': 'dilated_conv',
        'new_ensemble_method': 0,
        'batch_size': 64,
        'rep_dim': args.rep_dim,
        'layers': args.n_layer,
        'hidden_dim': args.hidden_dim
    }
    model_configs = dict(model_configs, **ts_model_configs)
print(model_configs)

# create and print results file header
os.makedirs(args.output_dir, exist_ok=True)
cur_time = time.strftime("%m-%d %H.%M.%S", time.localtime())
result_file = os.path.join(args.output_dir, f'{args.model}_{args.dataset}_results.csv')

f = open(result_file, 'a')
print(cur_time, file=f)
print('\n---------------------------------------------------------', file=f)
print(f'model: {args.model}, data dir: {args.input_dir}, dataset: {args.dataset}, {args.runs}runs, ', file=f)
for k in model_configs.keys():
    print(f'Parameters,\t [{k}], \t\t  {model_configs[k]}', file=f)
print(f'args,\t [seq_len], \t\t  {args.seq_len}', file=f)
print(f'args,\t [stride], \t\t  {args.stride}', file=f)
print(f'Note: {args.note}', file=f)
print(f'---------------------------------------------------------', file=f)
print(f'data, adj_auroc, std, adj_ap, std, adj_f1, std, adj_p, std, adj_r, std, time, model', file=f)
f.close()

train_df_lst, test_df_lst, label_lst, name_lst = utils.get_data_lst_ts(os.path.join(dataset_root, args.input_dir),
                                                                       args.dataset, entities=args.entities)
print(name_lst)
for train_df, test_df, labels, dataset_name in zip(train_df_lst, test_df_lst, label_lst, name_lst):
    x_train = train_df.values
    x_test = test_df.values

    entries = []
    t_lst = []
    for i in range(args.runs):
        start_time = time.time()
        print(f'\nRunning [{i+1}/{args.runs}] of [{args.model}] on Dataset [{dataset_name}]')

        clf = model_class(**model_configs, random_state=42+i)

        x_train_seq = utils.get_sub_seqs(x_train, seq_len=args.seq_len, stride=args.stride)
        x_test_seq = utils.get_sub_seqs(x_test, seq_len=args.seq_len, stride=1)
        clf.fit(x_train_seq)
        scores = clf.decision_function(x_test_seq)

        padding_list = np.zeros(args.seq_len-1)
        scores = np.hstack([padding_list, scores])

        entry = utils.eval_ts(scores=scores, labels=labels, test_df=test_df)
        entries.append(entry)
        print(dataset_name, end=', ')
        for e in entry:
            print(e, end=', ')
        print()

        t = round(time.time() - start_time, 1)
        t_lst.append(t)

    avg_entry = np.average(np.array(entries), axis=0)
    std_entry = np.std(np.array(entries), axis=0)

    f = open(result_file, 'a')
    txt = '%s, %.4f, %.4f, %.4f, %.4f, %.4f, %.4f, ' \
          '%.4f, %.4f, %.4f, %.4f, %.1f, %s ' % (dataset_name,
                                                 avg_entry[0], std_entry[0], avg_entry[1], std_entry[1],
                                                 avg_entry[2], std_entry[2], avg_entry[3], std_entry[3],
                                                 avg_entry[4], std_entry[4],
                                                 np.average(t_lst),  args.model)
    print(txt)
    print(txt, file=f)
    f.close()


from flask import Flask
from flask_cors import CORS # comm in deployment
import socket
import requests
from requests.auth import HTTPBasicAuth
HEADER = 64
PORT = 5050
PORT_2 = 5678
MSG_SIZE = 2048
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = '192.168.86.152'  # Run server first
ADDR = (SERVER, PORT)
ADDR_2 = (SERVER, PORT_2)

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)

client2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client2.connect(ADDR_2)

app = Flask(__name__)

CORS(app) # comm in deployment

@app.route("/image/<nflLogo>")
def get_image(nflLogo):
    logoLink = "https://us-central1-osu-project-342203.cloudfunctions.net/image-generator?query=" + nflLogo + "+nfl&size=small"
    image = requests.get(logoLink, auth = HTTPBasicAuth('admin_T42', 'admin_T42'))
    text_to_split = image.text.split("\"")
    return text_to_split[3]

def send_request(nflTeam):
    msg = nflTeam.encode(FORMAT)
    client.send(msg)
    paragraph = client.recv(2048).decode(FORMAT)
    return paragraph

@app.route("/teamdata/<nflTeam>")
def get_team_info(nflTeam):
    nflTeamCleaned = nflTeam.replace("+", " ")
    new_paragraph = send_request(nflTeamCleaned)
    return new_paragraph

def send_map_request(coordinates):
    message = coordinates.encode(FORMAT)
    msg_len = len(coordinates)
    send_length = str(msg_len).encode(FORMAT)
    send_length += b' ' * (MSG_SIZE - len(send_length))
    client2.send(send_length)
    client2.send(message)
    img_url = client2.recv(MSG_SIZE).decode(FORMAT)
    return img_url

@app.route("/homeMap/<coordinates>")
def get_team_map(coordinates):
    new_map = send_map_request(coordinates)
    return new_map


# -*- coding: utf8 -*-
import sys, csv, xlsxwriter
import numpy as np
import pandas as pd
import pandas.io.formats.excel
from PythonFuncionesVarias import ExcelExport

# strinpc01=sys.argv[1]
# strinpc02=sys.argv[2]
# stroutcsv=sys.argv[3]

strinpc01='Darwinion_no_encontradas.csv'
strinpc02='Indice_Especies.csv'
stroutcsv='Darwinion_consulta_01.csv'

csv_01 = pd.read_csv(strinpc01,sep='@')
csv_02 = pd.read_csv(strinpc02,sep='@', dtype={'codigo': object})
csv_01.columns = map(str.lower, csv_01.columns)
csv_01.columns = ['genero-especie', 'cruce-buscarv']

csv_02["genero-especie"] = csv_02["genero"].map(str) + " " + csv_02["especie"].map(str)
csv_02 = csv_02[['genero-especie', 'codigo', 'enlace', 'titulo', 'descripcion', 'genero', 'especie', 'subespecie', 'variedad', 'forma']]

csv_01_nodup = pd.DataFrame(csv_01.drop_duplicates(subset='genero-especie',keep='first'))
csv_01_nodup['totalwords'] = csv_01_nodup['genero-especie'].str.count(' ') + 1
csv_01_nodup = pd.DataFrame(csv_01_nodup[csv_01_nodup.totalwords > 1])
csv_01_nodup = csv_01_nodup.drop('totalwords', 1)
csv_02_nodup = pd.DataFrame(csv_02.drop_duplicates(subset='genero-especie',keep='first'))

csv_01_nodup['genero-especie'] = csv_01_nodup['genero-especie'].astype(str)
csv_02_nodup['genero-especie'] = csv_02_nodup['genero-especie'].astype(str)
csv_mr = pd.merge( csv_01_nodup , csv_02_nodup , on='genero-especie' , how='left' )
csv_mr.sort_values('genero-especie',inplace=True)

### Exportar csv
csv_mr.to_csv(stroutcsv, sep='@', encoding='utf-8', index=False)

### Exportar xlsx
ExcelExport( stroutcsv )


#day 1
import string
import hashlib
def make_sha1(s, encoding='utf-8'):
    return hashlib.sha1(s.encode(encoding)).hexdigest()
pw = ''
for u in string.ascii_uppercase:
    for l in string.ascii_lowercase:
        for d in range(0,10):
            for c in ['*', '@', '!', '#', '%', '&','(', ')', '^','~','{', '}']:
                pw = ''.join(sorted(u + l + str(d) + c))
                sum = 0
                for k in pw:
                    sum += ord(k)
                if(sum % 128) == 24:
                    hash = (make_sha1(pw, encoding='utf-8'))
                    if(hash == '42f82ae6e57626768c5f525f03085decfdc5c6fe'):
                        print(pw)


from random import sample,randint
def random_list():
    k = randint(1,10)
    l = randint(11,100)
    m = randint(5,7)
    print(k,l,m)
    lst = [num for num in range(k,l,m)]
    return (sample(lst,len(lst)))

print(random_list())


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from losoto.lib_operations import *
from losoto._logging import logger as logging

logging.debug('Loading STRUCTURE module.')

def _run_parser(soltab, parser, step):
    doUnwrap = parser.getbool( step, 'doUnwrap', False )
    refAnt = parser.getstr( step, 'refAnt', '')
    plotName = parser.getstr( step, 'plotName', '' )
    ndiv = parser.getint( step, 'ndiv', 1 )

    parser.checkSpelling( step, soltab, ['doUnwrap', 'refAnt', 'plotName', 'ndiv'])
    return run(soltab, doUnwrap, refAnt, plotName, ndiv)

def run( soltab, doUnwrap=False, refAnt='', plotName='', ndiv=1 ):
    """
    Find the structure function from phase solutions of core stations.

    Parameters
    ----------
    doUnwrap : bool, optional

    refAnt : str, optional
        Reference antenna, by default None.

    plotName : str, optional
        Plot file name, by default no plot.

    ndiv : int, optional

    """
    import numpy as np
    from losoto.lib_unwrap import unwrap, unwrap_2d

    logging.info("Find structure function for soltab: "+soltab.name)

    # input check
    solType = soltab.getType()
    if solType != 'phase':
       logging.warning("Soltab type of "+soltab._v_name+" is of type "+solType+", should be phase.")
       return 1

    if refAnt == '': refAnt = None
    elif refAnt != 'closest' and refAnt != 'auto' and not refAnt in soltab.getAxisValues('ant', ignoreSelection = True):
        logging.warning('Reference antenna '+refAnt+' not found. Using: atomatic search.')
        refAnt = 'auto'
    if refAnt is None and doUnwrap:
        logging.error('Unwrap requires reference antenna. Using: automatic search')
        refAnt = 'auto'

    soltab.setSelection(ant='CS*', update=True)

    posAll = soltab.getSolset().getAnt()

    if 'pol' in soltab.getAxesNames(): returnAxes = ['freq','pol','ant','time']
    else: returnAxes = ['freq','ant','time']

    for vals, weights, coord, selection in soltab.getValuesIter(returnAxes=returnAxes, weight=True, refAnt=refAnt):

        # order positions
        pos = np.array([list(posAll[ant]) for ant in coord['ant']])

        # avg pols
        if 'pol' in soltab.getAxesNames():
            # reorder axes
            vals = reorderAxes( vals, soltab.getAxesNames(), ['pol','ant','freq','time'] )
            weights = reorderAxes( weights, soltab.getAxesNames(), ['pol','ant','freq','time'] )

            vals = np.cos(vals) + 1.j * np.sin(vals)
            vals = np.nansum(vals, axis=0)
            vals = np.angle(vals)
            flags = np.array((weights[0]==0)|(weights[1]==0), dtype=bool)
        else:
            # reorder axes
            vals = reorderAxes( vals, soltab.getAxesNames(), ['ant','freq','time'] )
            weights = reorderAxes( weights, soltab.getAxesNames(), ['ant','freq','time'] )
            flags = np.array((weights==0), dtype=bool)

        # unwrap
        if doUnwrap:
            # remove mean to facilitate unwrapping
            for a, ant in enumerate(coord['ant']):
                if not (flags[a,:,:] == True).all() and ant != refAnt:
                    logging.debug('Unwrapping: '+ant)
                    mean = np.angle( np.nanmean( np.exp(1j*vals[a].flatten()) ))
                    vals[a] -= mean
                    vals[a] = np.mod(vals[a]+np.pi, 2*np.pi) - np.pi
                    vals[a,:,:] = unwrap_2d(vals[a,:,:], flags[a,:,:], coord['freq'], coord['time'])

        logging.debug('Computing differential values...')
        t1 = np.ma.array( vals, mask=flags ) # mask flagged data
        dph = t1[np.newaxis]-t1[:,np.newaxis] # ant x ant x freq x time
        D = pos[np.newaxis]-pos[:,np.newaxis] # ant x ant x 3
        D2 = np.triu(np.sqrt(np.sum(D**2,axis=-1))) # calc distance and keep only uppoer triangle larger than 0
        myselect = (D2>0)

        if not doUnwrap:
            logging.debug('Re-normalising...')
            dph = np.mod(dph+np.pi, 2*np.pi) - np.pi
            avgdph = np.ma.average(dph, axis=2) # avg in freq (can do because is between -pi and pi)
            #one extra step to remove most(all) phase wraps, phase wraps disturbe the averaging...
            dph = np.remainder(dph - np.ma.average(avgdph,axis=-1)[:,:,np.newaxis,np.newaxis]+np.pi,2*np.pi) + np.ma.average(avgdph,axis=-1)[:,:,np.newaxis,np.newaxis]-np.pi #center around the avg value

        logging.debug('Computing sructure function...')
        avgdph = np.ma.average(dph,axis=2) # avg in freq to reduce noise

        variances = []; pars = []
        avgdph = avgdph[...,avgdph.shape[-1]%ndiv:] # remove a few timeslots to make the array divisible by np.split
        avgdph[avgdph.mask] = np.nan
        for i, avgdphSplit in enumerate( np.split(avgdph, ndiv, axis=-1) ):
            variance = np.nanvar(avgdphSplit, axis=-1)*(np.average(coord['freq'])/150.e6)**2 # get time variance and rescale to 150 MHz

            # linear regression
            #A = np.ones((2,D2[myselect].shape[0]),dtype=float)
            #A[1,:] = np.log10(D2[myselect][~variance.mask])
            #par = np.dot(np.linalg.inv(np.dot(A,A.T)),np.dot(A,np.log10(variance[myselect])))
            mask = np.isnan(variance[myselect])
            A = np.vstack([np.log10(D2[myselect][~mask]), np.ones(len(D2[myselect][~mask]))])
            par = np.linalg.lstsq( A.T, np.log10(variance[myselect][~mask]) )[0]
            S0 = 10**(-1*par[1]/par[0])
            logging.info(r't%i: beta=%.2f - R_diff=%.3f km' % (i, par[0], S0/1.e3))
            variances.append(variance)
            pars.append(par)

        if plotName != '':
            if plotName.split('.')[-1] != 'png': plotName += '.png' # add png

            if not 'matplotlib' in sys.modules:
                import matplotlib as mpl
                mpl.use("Agg")
            import matplotlib.pyplot as plt

            fig = plt.figure()
            fig.subplots_adjust(wspace=0)
            ax = fig.add_subplot(111)
            ax1 = ax.twinx()

            for i, variance in enumerate(variances):
                if len(variances) > 1:
                    color = plt.cm.jet(i/float(len(variances)-1)) # from 0 to 1
                else: color = 'black'
                ax.plot(D2[myselect]/1.e3,variance[myselect],marker='o',linestyle='', color=color, markeredgecolor='none', label='T')

                # regression
                par = pars[i]
                x = D2[myselect]
                S0 = 10**(-1*par[1]/par[0])
                if color == 'black': color = 'red' # in case of single color, use red line that is more visible
                ax1.plot(x.flatten()/1.e3, par[0]*np.log10(x.flatten()) + par[1], linestyle='-', color=color, label=r'$\beta=%.2f$ - $R_{\rm diff}=%.2f$ km' % (par[0], S0/1.e3))

            ax.set_xlabel('Distance (km)')
            ax.set_ylabel(r'Phase variance @150 MHz (rad$^2$)')
            ax.set_xscale('log')
            ax.set_yscale('log')

            ymin = np.min(variance[myselect])
            ymax = np.max(variance[myselect])
            ax.set_xlim(xmin=0.1,xmax=3)
            ax.set_ylim(ymin,ymax)
            ax1.set_ylim(np.log10(ymin),np.log10(ymax))
            ax1.legend(loc='lower right', frameon=False)
            ax1.set_yticks([])

            logging.warning('Save pic: %s' % plotName)
            plt.savefig(plotName, bbox_inches='tight')

    return 0


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def generateTrees(self, n):
        if n < 1:
            return []
        if n == 1:
            return [TreeNode(1)]
        else:
            self.nlist = [i for i in range(1, n+1)]

            return self.treeHelper(self.nlist)

    def treeHelper(self, list):
        res = []
        if not list:  # => quit condition   callback
            return [None]
        if len(list) == 1:
            return [TreeNode(list[0])]  # => quit condition  callback
        else:
            for i in range(0, len(list)):  # index
                for l in self.treeHelper(list[:i]):
                    for r in self.treeHelper(list[i+1:]):
                        root = TreeNode(list[i])
                        root.left = l
                        root.right = r

                        res.append(root)

            return res  # => callback


import math
import itertools
from collections import defaultdict
import sys
from timeit import default_timer as timer
import numpy as np

def graphFromInput():
    edges = []
    nameToId = dict()
    idToName = dict()
    N = int(sys.stdin.readline())
    for line in sys.stdin.readlines():
        u,v = line.strip().split(" ")
        if u not in nameToId:
            nameToId[u] = len(nameToId)
        if v not in nameToId:
            nameToId[v] = len(nameToId)
        edges.append((nameToId[u],nameToId[v]))
        edges.append((nameToId[v],nameToId[u]))
    vertices = list(nameToId.values())
    for k,v in nameToId.items():
        idToName[v] = k

    if not N == len(vertices):
        print("Input error vertices size N wrong.")
        exit(0)

    return idToName, vertices, sorted(edges)

def adjMatrix(vertices, edges):
    # Create adjacency matrix
    N = len(vertices)
    adj = np.array([[0 for _ in range(0, N)] for _ in range(0, N)])
    for u,v in edges:
        adj[u][v] = 1
        adj[v][u] = 1
    return adj

def dpHC(vertices, edges):
    start = sorted(vertices)[0]
    adj = adjMatrix(vertices, edges)
    N = len(vertices)
    C = defaultdict(bool)
    excludingStart = list(filter(lambda x: x!= start, vertices))

    for i in range(1, N):
        perm = list(itertools.permutations(excludingStart, i))
        for S in perm:
            visited = tuple([start])+S
            for s in S:
                if i < 2 and adj[start][s]:
                        C[visited] = True
                else:
                    exLast = visited[:-1]
                    twoLast = visited[-2:]
                    if C.get(exLast) == True and adj[twoLast[0]][twoLast[1]] == 1:
                        C[visited] = True
    count = 0
    for k,v in C.items():
        # last = k[-1:]
        last = k[-1:]
        if len(k) == N and adj[last[0]][start]:
            # print(f"{k} -> {v}")
            count +=1
    return (int(count/2))

def createCompleteGraph(n):
    vertices = list(range(0,n))
    edges = []
    for i in range(n):
        for j in range(n):
            if i != j:
                edges.append((i,j))
    return vertices, sorted(edges)

if __name__ == "__main__":
    idToName, vertices, edges = graphFromInput()
    tStart = timer()
    res = dpHC(vertices, edges)
    tEnd = timer()
    print(f"House Vertices: {len(vertices)} Time {(tEnd-tStart):.4f}s HC Found: {res} ")

    for i in range(1,20):
        vertices, edges = createCompleteGraph(i)
        tStart = timer()
        res = dpHC(vertices, edges)
        tEnd = timer()
        print(f"Vertices: {i} Time {(tEnd-tStart):.4f}s HC Found: {res} ")


import random
import time
from FE_TestLevel import levelincrease
#print([int(random.randint(16,22)),int(random.randint(16,27)),int(random.randint(3,13)),int(random.randint(3,13)),int(random.randint(3,10))])
#print([int(random.randint(16,22)),int(random.randint(16,27)),int(random.randint(3,13)),int(random.randint(3,13)),int(random.randint(3,10))])
statsp =[20, 30, 11, 99, 5, 1]

statse = [19, 18, 6, 6, 8, 1]
xpe = 50
running = True

class Player():
    def __init__(self,stat):
        self.stat = stat
        self.stata = list(stat)
        self.Spd = self.stat[2]
        self.statold = list(stat)
        self.dif = list(stat)
        self.levelup = stat[5] * 60
        self.xp = 0

class Enemy():
    def __init__(self,stat,xpe):
        self.stat = stat
        self.stata = list(stat)
        self.Spd = self.stat[2]
        self.statold = list(stat)
        self.dif = list(stat)
        self.rewardxp = xpe

P = Player(statsp)
E = Enemy(statse,xpe)

def differenceh(x):
    i = 0
    x.dif[i] =  x.statold[i] - x.stata[i]

def attacking(defending,attacker):
    defending.stata[0] = defending.stata[0] - (attacker.stat[1] - defending.stat[3])

while running:
    print(f'''Enemies stats
    level {E.stat[5]}
        HP  {E.stat[0]}
        Atk {E.stat[1]}
        Spd {E.stat[2]}
        Def {E.stat[3]}
        Res {E.stat[4]}''')
    attack = input('attack ')
    time.sleep(1)

    if attack == 'y':
        attacking(E,P)
        #print(statse)
        differenceh(E)
        if E.stata[0] >= 0:
            attacking(P,E)
            differenceh(P)
        else:
            P.dif[0] = 0
        if P.Spd >= E.Spd + 5:
            attacking(E,P)
            differenceh(E)
        print(f'''Enemy                 Player
HP  {E.stata[0] } { f'-{E.dif[0]}'}             HP  {P.stata[0]} { f'-{P.dif[0]}'}''')
    time.sleep(1)
    if E.stata[0] <= 0 and P.stata[0] >= 0:
        newstat = [int(random.randint(16,22)),int(random.randint(16,27)),int(random.randint(3,13)),int(random.randint(3,13)),int(random.randint(3,10)),int(E.stat[5])]
        print(newstat)
        newstat[5],newstat = levelincrease(newstat[5],newstat,newstat[5],0)
        E = Enemy(newstat,E.rewardxp)
        exp = E.stat[5] * E.rewardxp
        if P.stat[5] % 2 == 0:
            E.rewardxp -= 5
        print(E.rewardxp)
        P.xp += exp
        if P.xp > P.levelup:
            print('level up')
            time.sleep(1)
            P.stat[5],P.stat = levelincrease(P.stat[5],P.stat,1,1)
            P.xp = 0
        P.stata = list(P.stat)
    if P.stata[0] <= 0:

        print('dead')
        time.sleep(1)
        running = False