# coding: utf-8
import os
import glob
import argparse
import re

from logging import getLogger, Formatter, StreamHandler, FileHandler, DEBUG, INFO
import matplotlib.pyplot as plt
import pandas as pd
import dataloader
from indicator_evaluation import CalcIndicator

import indicator_utils
import utils

def main(args):
    # File output handler for save folder
    if args.save_folder:
        log_file_name2 = os.path.join(args.save_folder, '{}.log'.format(__name__))
        file_handler2 = FileHandler(log_file_name2, 'a')
        file_handler2.setLevel(DEBUG)
        file_handler2.setFormatter(formatter)
        logger.addHandler(file_handler2)

    for track in args.track:
        logger.debug('- {}, {} evaluation START -'.format(args.trajection_folder, track))

        # Load data config
        data_config_path = glob.glob(os.path.join(args.ground_truth_folder, '*.ini'))[0]
        conf = dataloader.config(track, args.ground_truth_folder, config_file=data_config_path)

        # Directory path to evaluate
        tra_dname = os.path.join(args.trajection_folder, track)
        logger.debug('tra_dname:{}'.format(tra_dname))

        # Load groundtruth files
        map_size = dataloader.map_size(conf['map_dname'], conf['map_size_fname'])
        map_image = dataloader.map_image(conf['map_dname'], conf['map_image_fname'])
        area_info = dataloader.area_info(conf['map_dname'], conf['area_fname'])
        BLE_info = dataloader.BLE_info(conf['BLE_dname'], conf['BLE_info_fname'])
        map_color = dataloader.map_color(conf['map_obstacle_color'], conf['map_trajectory_color'], conf['map_ref_color'], conf['map_BLE_color'])
        map_makersize = dataloader.map_makersize(conf['map_trajectory_size'], conf['map_ref_size'], conf['map_BLE_size'], conf['map_grid'])

        # Create result save directory
        if args.save_folder:
            result_basedir = os.path.join(args.save_folder, track)
        else:
            result_basedir = os.path.join(tra_dname, 'result')
        indicator_savedir = os.path.join(result_basedir, 'indicator')

        for dir_path in [result_basedir, indicator_savedir]:
            utils.create_dir(dir_path)

        extension_types = ['*.txt', '*.csv']
        tra_files = []
        for ext_type in extension_types:
            keyword = os.path.join(tra_dname, ext_type)
            tra_files.extend([os.path.split(file_path)[-1] for file_path in sorted(glob.glob(keyword, recursive=True))])

        if args.file:
            tra_files = args.file

        logger.debug('trajection files:{}'.format(tra_files))

        # Instance to calculate indicator
        evaluation_indicator = CalcIndicator()
        indicator_holder = indicator_utils.IndicatorHolder()

        for tra_filename in tra_files:
            logger.debug('{} Evaluation START'.format(tra_filename))
            print('{} evaluation progress...'.format(tra_filename))

            # Load trajectory files
            tra_data = dataloader.load_point(tra_dname, tra_filename)
            tra_num = re.sub("\\D", "", tra_filename)

            # Load ground truth files
            ref_point = dataloader.load_point(conf['ref_dname'], conf['ref_fname'].format(tra_num))
            ans_point = dataloader.load_point(conf['ans_dname'], conf['ans_fname'].format(tra_num))
            ALIP_info = dataloader.ALIP_info(conf['ALIP_dname'], conf['ALIP_info_fname'].format(tra_num))

            indicator_holder.add_indicator_percentile('file_name', tra_filename)

            # prepare evaluation point
            if ref_point is None:
                evaluation_point = ans_point
            else:
                evaluation_point = dataloader.drop_ans_duplicated_with_ref(ans_point, ref_point)

            if ALIP_info is None:
                eval_point_ALAP = ans_point
                eval_point_ALIP = pd.DataFrame(index=[], columns=['unixtime', 'x_position_m', 'y_position_m'])
            else:
                eval_point_ALAP = dataloader.filter_evaluation_data_ALIP(evaluation_point, ALIP_info, ALIP_flag=False)
                eval_point_ALIP = dataloader.filter_evaluation_data_ALIP(evaluation_point, ALIP_info, ALIP_flag=True)

            """
            if area_info:
                which_area = indicator_utils.area_of_ans(eval_point_ALIP, area_info)
                which_area_all.extend(which_area)
            """

            # CE
            if 'CE' in args.indicators:
                CE = evaluation_indicator.CE_calculation(tra_data, eval_point_ALAP)
                CE_percentile = indicator_utils.calc_percentile(CE['CE'], args.CE_percentile)
                indicator_holder.add_indicator_percentile(f'CE{args.CE_percentile}', CE_percentile)

                indicator_holder.add_total_indicator(f'CE{args.CE_percentile}', CE['CE'])

                indicator_utils.calc_CE_map(CE, map_size)
                CE_savedir = os.path.join(indicator_savedir, 'CE')
                utils.create_dir(CE_savedir)

                indicator_utils.save_indicator(data=CE, save_dir=CE_savedir, save_filename=f'Traj_No{tra_num}_CE.csv')
                CE_hist = indicator_utils.draw_histgram(data=CE['CE'], indicator_name='CE', percentile=args.CE_percentile)
                indicator_utils.save_figure(CE_hist, save_dir=CE_savedir, save_filename=f'Traj_No{tra_num}_CE_histgram.png')

                CE_map = indicator_utils.draw_CE_map(CE, map_image, map_size, indicator_name='CE')
                indicator_utils.save_figure(CE_map, save_dir=CE_savedir, save_filename=f'Traj_No{tra_num}_CE_map.png')

            # CP
            if 'CP' in args.indicators:
                CP = evaluation_indicator.CP_calculation(tra_data, eval_point_ALAP, band_width=None)
                CP_percentile = indicator_utils.calc_percentile(CP['CP'], args.CP_percentile)
                indicator_holder.add_indicator_percentile(f'CP{args.CP_percentile}', CP_percentile)

                indicator_holder.add_total_indicator(f'CP{args.CP_percentile}', CP['CP'])

                CP_savedir = os.path.join(indicator_savedir, 'CP')
                utils.create_dir(CP_savedir)

                indicator_utils.save_indicator(data=CP, save_dir=CP_savedir, save_filename=f'Traj_No{tra_num}_CP.csv')
                CP_hist = indicator_utils.draw_histgram(data=CP['CP'], indicator_name='CP', percentile=args.CP_percentile)
                indicator_utils.save_figure(CP_hist, save_dir=CP_savedir, save_filename=f'Traj_No{tra_num}_CP_histgram.png')

            # Area-weighted CA
            if 'CA' in args.indicators:
                if args.area_weights is None:
                    area_weights = indicator_utils.get_CA_area_weights(evaluation_point, area_info)
                else:
                    area_weights = dataloader.area_weights_config(track, args.area_weights)

                if area_weights is None:
                    logger.debug('CA is calculated for whole area')
                    if args.CA_hist:
                        CA, CA_fig = evaluation_indicator.CA_2Dhistgram_calculation(tra_data, evaluation_point)
                    else:
                        CA, CA_fig = evaluation_indicator.CA_KernelDensity_calculation(tra_data, evaluation_point, band_width=None)
                    CA_df = pd.DataFrame({'CA': CA}, index=[0])

                else:
                    logger.debug('CA is calculated for each area division')
                    CA, CA_df, CA_fig = evaluation_indicator.Area_weighted_CA_calculation(tra_data, evaluation_point, area_info, area_weights, args.CA_hist)

                indicator_holder.add_indicator_percentile('CA', CA)
                CA_savedir = os.path.join(indicator_savedir, 'CA')
                utils.create_dir(CA_savedir)
                indicator_utils.save_dataframe(CA_savedir, f'Traj_No{tra_num}_CA.csv', CA_df)

                if isinstance(CA_fig, list):
                    for i in range(len(CA_fig)):
                        CA_fig[i].suptitle(f'Traj_No{tra_num}_area{i+1}_CA')
                        indicator_utils.save_figure(CA_fig[i], save_dir=CA_savedir, save_filename=f'Traj_No{tra_num}_area{i+1}_CA.png')
                else:
                    CA_fig.suptitle(f'Traj_No{tra_num}_CA')
                    indicator_utils.save_figure(CA_fig, save_dir=CA_savedir, save_filename=f'Traj_No{tra_num}_CA.png')

            # EAG
            if 'EAG' in args.indicators and not ref_point.empty and not eval_point_ALIP.empty:
                EAG = evaluation_indicator.EAG_calculation(tra_data, ref_point, eval_point_ALIP)

                EAG_percentile = indicator_utils.calc_percentile(EAG['EAG'], args.EAG_percentile)
                indicator_holder.add_indicator_percentile(f'EAG{args.EAG_percentile}', EAG_percentile)

                indicator_holder.add_total_indicator(f'EAG{args.EAG_percentile}', EAG['EAG'])

                EAG_savedir = os.path.join(indicator_savedir, 'EAG')
                utils.create_dir(EAG_savedir)

                indicator_utils.save_indicator(data=EAG, save_dir=EAG_savedir, save_filename=f'Traj_No{tra_num}_EAG.csv')
                EAG_hist = indicator_utils.draw_histgram(data=EAG['EAG'], indicator_name='EAG', percentile=args.EAG_percentile)
                indicator_utils.save_figure(EAG_hist, save_dir=EAG_savedir, save_filename=f'Traj_No{tra_num}_EAG_histgram.png')

            # Requirement for Moving Velocity
            if 'requirement_velocity' in args.indicators:
                moving_velocity_df = evaluation_indicator.requirement_moving_velocity_check(tra_data, args.velocity)
                indicator_holder.add_indicator_percentile('requirement_velocity', moving_velocity_df['velocity'].mean())
                velocity_savedir = os.path.join(indicator_savedir, 'requirement_velocity')
                utils.create_dir(velocity_savedir)
                indicator_utils.save_dataframe(velocity_savedir, f'Traj_No{tra_num}_moving_velocity.csv', moving_velocity_df)

            # Requirement for obstacle avoidance
            if 'requirement_obstacle' in args.indicators:
                obstacle_df = evaluation_indicator.requirement_obstacle_check(tra_data, map_image, map_size)
                if len(obstacle_df) == 0:
                    obstacle_ratio = -1
                else:
                    obstacle_ratio = sum(obstacle_df['obstacle_cordinate_count']) / sum(obstacle_df['check_cordinate_count'])

                indicator_holder.add_indicator_percentile('requirement_obstacle', obstacle_ratio)
                obstacle_savedir = os.path.join(indicator_savedir, 'requirement_obstacle')
                utils.create_dir(obstacle_savedir)
                indicator_utils.save_dataframe(obstacle_savedir, f'Traj_No{tra_num}_obstacle.csv', obstacle_df)

            if 'requirement_coverage' in args.indicators:
                eval_num = len(evaluation_point)
                corr_num = len(evaluation_indicator.extract_correspond_point(tra_data, evaluation_point))
                coverage = corr_num / eval_num * 100
                indicator_holder.add_indicator_percentile('requirement_coverage', coverage)

            logger.debug('{} Evaluation END'.format(tra_filename))

            # Draw trajectory
            Tra_savedir = os.path.join(indicator_savedir, 'Trajectory')
            utils.create_dir(Tra_savedir)
            Trajectory_image = indicator_utils.draw_trajectory(tra_data, map_image, map_size, f'Trajectory_No{tra_num}', ref_point, BLE_info, map_color, map_makersize)
            indicator_utils.save_figure(Trajectory_image, save_dir=Tra_savedir, save_filename=f'Tra_No{tra_num}.png')

        # Show each file's results
        file_indicator_summary = indicator_holder.summarize_file_indicator()
        utils.stdout_dataframe(file_indicator_summary, title='file indicator')
        utils.save_csv(save_file=file_indicator_summary, save_dir=indicator_savedir, save_filename='file_indicator.csv')

        # Show total results
        total_indicator = indicator_holder.summarize_total_indicator()
        utils.stdout_dataframe(total_indicator, title='total indicator')
        utils.save_csv(save_file=total_indicator, save_dir=indicator_savedir, save_filename='total_indicator.csv')

        # Draw histgram and cumulative sum for total CE and EAG
        if 'CE' in args.indicators:
            CE_total = indicator_holder.indicator_total[f'CE{args.CE_percentile}']
            CE_total_hist = indicator_utils.draw_histgram(data=CE_total, indicator_name='CE', percentile=args.CE_percentile)
            indicator_utils.save_figure(CE_total_hist, save_dir=CE_savedir, save_filename='CE_total_histgram.png')
            CE_cumulative_sum = indicator_utils.draw_cumulative_sum(CE_total.values.tolist(), 'CE')
            indicator_utils.save_figure(CE_cumulative_sum, save_dir=CE_savedir, save_filename='CE_total_cumulative_sum.png')

        if 'EAG' in args.indicators:
            EAG_total = indicator_holder.indicator_total[f'EAG{args.EAG_percentile}']
            EAG_total_hist = indicator_utils.draw_histgram(data=EAG_total, indicator_name='EAG', percentile=args.EAG_percentile)
            indicator_utils.save_figure(EAG_total_hist, save_dir=EAG_savedir, save_filename='EAG_total_histgram.png')
            EAG_cumulative_sum = indicator_utils.draw_cumulative_sum(EAG_total.values.tolist(), 'EAG')
            indicator_utils.save_figure(EAG_cumulative_sum, save_dir=EAG_savedir, save_filename='EAG_total_cumulative_sum.png')

        logger.debug('- {}, {} evaluation END -'.format(args.trajection_folder, track))

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='XDR Challenge Evaluation Setting')

    parser.add_argument('trajection_folder', type=str, help='Set trajection folder name')

    parser.add_argument('ground_truth_folder', type=str, help='Set ground truth folder name')

    parser.add_argument('--save_folder', type=str, help='Set save folder name')

    parser.add_argument('--VDR', action='store_const', dest='track', default=['VDR','PDR'],
                        const=['VDR'],help='Set  VDR track')

    parser.add_argument('--PDR', action='store_const', dest='track', default=['VDR','PDR'],
                        const=['PDR'],help='Set  PDR track')

    parser.add_argument('--file', nargs='*', help='Select file name for evaluation')

    parser.add_argument('--CE', action='append_const', dest='indicators', default=[],
                        const='CE', help='Calculate Circular Error')

    parser.add_argument('--CE_percentile', type=int, default=50,
                        help='Calculate percentile of Circular Error')

    parser.add_argument('--CP', action='append_const', dest='indicators', default=[],
                        const='CP', help='Calculate Circular Precision')

    parser.add_argument('--CP_percentile', type=int, default=50,
                        help='Calculate percentile of Circular Presicion')

    parser.add_argument('--CA', action='append_const', dest='indicators', default=[],
                        const='CA', help='Calculate Area-weighted Circular Error Distribution Deviation')

    parser.add_argument('--area_weights', default=None, help='area weights configuration path')

    parser.add_argument('--CA_hist', action='store_true', help='Calculate CA by 2D hisgram')

    parser.add_argument('--band_width', type=float, default=None, help='band width for kernel density')

    parser.add_argument('--EAG', action='append_const', dest='indicators', default=[],
                        const='EAG', help='Calculate Error Accumulation Gradient')

    parser.add_argument('--EAG_percentile', type=int, default=50,
                        help='Calculate percentile of Error Accumulation Gradient')

    parser.add_argument('--requirement_velocity', action='append_const', dest='indicators', default=[],
                        const='requirement_velocity', help='Calculate requirement for moving velocity')

    parser.add_argument('--velocity', type=float, default=1.5, help='appropriate walking velocity (unit: m/s)')

    parser.add_argument('--requirement_obstacle', action='append_const', dest='indicators', default=[],
                        const='requirement_obstacle', help='Calculate requirement for obstacle avoidance')

    parser.add_argument('--requirement_coverage', action='append_const', dest='indicators', default=[],
                        const='requirement_coverage', help='Calculate requirement for coverage')

    parser.add_argument('--debug', action='store_const', dest='level', default=INFO, const=DEBUG,
                        help='Logger debug mode')

    args = parser.parse_args()
    args.indicators = ['CE', 'CA', 'EAG', 'requirement_velocity', 'requirement_obstacle', 'requirement_coverage'] if not args.indicators else args.indicators

    #　Logger setting
    logger = getLogger(__name__)
    logger.setLevel(DEBUG)

    formatter = Formatter('%(asctime)s - %(name)s - %(message)s')

    # Standard output handler
    stream_handler = StreamHandler()
    stream_handler.setLevel(args.level)
    stream_handler.setFormatter(formatter)

    # File output handler
    log_file_name = os.path.basename(__file__) + '.log'
    file_handler = FileHandler(log_file_name, 'a')
    file_handler.setLevel(DEBUG)
    file_handler.setFormatter(formatter)

    logger.addHandler(stream_handler)
    logger.addHandler(file_handler)

    logger.debug('track:{}, indicators:{}'.format(args.track, args.indicators))
    print('track:{}, indicators:{}'.format(args.track, args.indicators))
    main(args)


import enum
import abc
import math
import typing

class Figure(enum.Enum):
    CIRCLE = 1
    RECTANGLE = 2
    TRIANGLE = 3
    RHOMBUS = 4

class FieldCalculator(abc.ABC):
    @abc.abstractmethod
    def calculate_field(self, *args, **kwargs) -> float:
        pass

class CircleFieldCalculator(FieldCalculator):

    def calculate_field(self, r) -> float:
        r = float(r)
        if r < 0:
            raise ValueError(f'r must be positive (got: {r})')
        return math.pi * r * r

class RectangleFieldCalculator(FieldCalculator):

    def calculate_field(self, a, b) -> float:
        a = float(a)
        b = float(b)
        if a < 0 or b < 0:
            raise ValueError(f'one of input arguments is lesser than 0 (a: {a}, b: {b})')
        return a * b

class TriangleFieldCalculator(FieldCalculator):

    def calculate_field(self, a, h) -> float:
        a = float(a)
        h = float(h)
        if a < 0 or h < 0:
            raise ValueError(f'one of input arguments is lesser than 0 (a: {a}, h: {h})')
        return 0.5 * a * h

class RhombusFieldCalculator(FieldCalculator):

    def calculate_field(self, a, b, diagonals=True) -> float:
        a = float(a)
        b = float(b)
        diagonals = bool(diagonals)
        if a < 0 or b < 0:
            raise ValueError(f'one of input arguments is lesser than 0 (a: {a}, b: {b})')
        if diagonals:
            return 0.5 * a * b
        else:
            return a * b

_CALCULATORS = {
    Figure.CIRCLE: CircleFieldCalculator(),
    Figure.RECTANGLE: RectangleFieldCalculator(),
    Figure.TRIANGLE: TriangleFieldCalculator(),
    Figure.RHOMBUS: RhombusFieldCalculator()
}

def calculate_field(fig: Figure, *args) -> typing.Optional[float]:
    """
    #1 Write a function countField which calculates the field of a given figure. It takes the following input parameters:
    For circle we get only x which stands for radius. For Rectangle x&y are the figure's sides, for triangle they are
    accordingly the base and the height and for rhombus - diagonals (4p)
    :param fig: circle/rectangle/triangle/rhombus
    :param args: x & optional y

    >>> calculate_field(Figure.RECTANGLE, 3, 4)
    12.0

    >>> calculate_field(Figure.CIRCLE)
    Traceback (most recent call last):
        ...
    ValueError: Invalid arguments number (0)

    >>> calculate_field(Figure.CIRCLE, -1)
    Traceback (most recent call last):
        ...
    ValueError: Runtime exception during processing request. Selected figure: Figure.CIRCLE; Input arguments: (-1,)

    """
    if fig is None:
        raise ValueError('figure is none')
    try:
        return _CALCULATORS[fig].calculate_field(*args)
    except TypeError:
        raise ValueError(f'Invalid arguments number ({len(args)})')
    except (ValueError, ZeroDivisionError):
        raise ValueError(f'Runtime exception during processing request.'
                         f' Selected figure: {fig};'
                         f' Input arguments: {args}')

def _calculate_figure_fields(figure, *args):
    figure_t = type(figure)
    if figure_t is int:
        figure = Figure(figure)
    elif figure_t is Figure:
        pass
    else:
        figure = Figure[str(figure).upper()]
    return calculate_field(figure, *args)

def _assert_input_array(fig_arr):
    pass

def compare_figures_fields(figures: typing.List[typing.List[typing.Any]]):
    """
    #2 Write a function which takes sets of parameters of two figures and compares their fields. (4p)
    The exemplary input is [[Circle, 4], [Rhombus, 2, 4]]
    Expected output would be 'The first figure (Circle) has larger field'

    >>> compare_figures_fields([['rhombus', 3, 4, 1], ['Triangle', 6, 2.5]])
    The figure ['Triangle', 6, 2.5] has largest field (7.500)
    Figures fields sorted descending:
    - figure ['Triangle', 6, 2.5] with field: 7.500
    - figure ['rhombus', 3, 4, 1] with field: 6.000

    """
    if not figures:
        raise ValueError('no figures given')
    pairs_of_calculated_fields = [(fig, _calculate_figure_fields(fig[0], *fig[1:])) for fig in figures if fig and
                                  type(fig) in (tuple, list)]
    fields_pairs_sorted = sorted(pairs_of_calculated_fields, key=lambda x: x[1], reverse=True)
    print('The figure {0} has largest field ({1:.3f})'.format(*fields_pairs_sorted[0]))
    print('Figures fields sorted descending:')
    print('\n'.join([f'- figure {fig[0]} with field: {fig[1]:.3f}' for fig in fields_pairs_sorted]))

if __name__ == '__main__':
    import doctest
    doctest.testmod()


# Importing necessary libraries
import numpy as np
import matplotlib.pyplot as plt

# Defining constants and initial values
l = 1
m = 5
g = 9.81
theta_0 = 0.2
omega_0 = 0.0

# Timeconstants
T_i = 0
T_f = 10
T = T_f - T_i
samples = 10000
dt = T/samples

def euler_cromer_approx(theta_0, omega_0, dt, T_i):
    """
    Calculates angular displacement and angular velocity using the Euler-Cromer method

    theta_0: initial angular displacement
    omega_0: initial angular velocity
    dt: timestep
    """
    theta=np.zeros(samples)
    omega=np.zeros(samples)
    t=np.zeros(samples)
    theta[0]=theta_0
    omega[0]=omega_0
    t[0]=T_i

    for n in range(1,samples):
        """
        calculates new value for omega using old value of theta and omega
        """
        omega[n]=omega[n-1]-g/l*theta[n-1]*dt

        """
        Calculates new theta using new omega and old theta
        """
        theta[n]=theta[n-1]+omega[n]*dt

        """
        Time array in same dimension for ploting
        """
        t[n]=t[n-1]+dt

    """
    theta: array with values of angular displacement
    w: array with values of angular velocity
    t: array with time-values
    """
    return theta,omega,t

# Saves approximations in arrays
thetaArr,omegaArr,timeArr = euler_cromer_approx(theta_0,omega_0,dt,T_i)

plt.figure("Test")
plt.plot(timeArr,thetaArr,label="Theta")
plt.plot(timeArr,omegaArr,label="Omega")
plt.legend()
plt.grid()
# plt.show()

# Task 2
def energy_calculation(theta_0, omega_0, dt):
    """
    Calculates total energy for the system by Euler-Cromes method
    Inputs:
    theta_0: initial value of theta (displacement)
    omega_0: initial value of omega (angular velocity)

    """
    samples = int(T/dt) # Finds samplerate for chosen dt

    # Creat array of values using Euler-Cromer approx
    thetaArr, omegaArr, timeArr = euler_cromer_approx(theta_0,omega_0,dt,T_i)

    # Function for total energy
    energy_func = lambda m,l,omega,theta: (1/2)*m*(l**2)*(omega**2) + (1/2)*m*g*l*(theta**2)

    # Time array in same dimension
    t = np.linspace(T_i,T,samples)
    energy = np.zeros(samples)

    for i in range(len(t)):
        """
        Calculation of total energy for every time-element
        """
        energy[i] = energy_func(m,l,omegaArr[i],thetaArr[i])

    E_total = energy

    return t, E_total

# Values for dt to plot for
dt1 = 0.001
dt2 = 0.004
dt3 = 0.007

plt.figure(2)
plt.title("Total Energy")
plt.plot(energy_calculation(theta_0,omega_0,dt1)[0],energy_calculation(theta_0,omega_0,dt1)[1], label="dt = 0.001")
plt.plot(energy_calculation(theta_0,omega_0,dt2)[0],energy_calculation(theta_0,omega_0,dt2)[1], label="dt = 0.004")
plt.plot(energy_calculation(theta_0,omega_0,dt3)[0],energy_calculation(theta_0,omega_0,dt3)[1], label="dt = 0.007")
plt.xlabel("Time(s)")
plt.ylabel("Energy(J)")
plt.legend()
plt.grid()
# plt.show()

# Task 3
def energy_diff(time,E_tot):
    """
    Plots one period of total energy and finds difference between start and end of period
    Inputs:

    time: time array with same dimension as E_tot
    E_tot: Array of total energy

    """
    E_tot_0 = E_tot[0]

    # Expression for time by end of period
    T_p = 2*np.pi*np.sqrt(l/g)

    i = 0
    while time[i] < T_p:
        i += 1

    time_p = np.zeros(i)
    E_tot_p = np.zeros(i)
    for j in range(i):
        time_p[j] = time[j]
        E_tot_p[j] = E_tot[j]

    plt.figure("One period Total Energy")
    plt.title("One period Total Energy")
    plt.plot(time_p,E_tot_p,label="dt = 0.001")
    plt.grid()
    # plt.show()

    print("Delta E after one period: " + str(abs(E_tot_p[0]-E_tot_p[-1])))

energy_diff(energy_calculation(theta_0,omega_0,dt3)[0],energy_calculation(theta_0,omega_0,dt3)[1])

# Task 4
def euler_cromer_method(theta_0, omega_0, dt, T_i):
    """
    Calculates angular displacement and angular velocity using the Euler-Cromer method

    theta_0: initial angular displacement
    omega_0: initial angular velocity
    dt: timestep
    """
    theta=np.zeros(samples)
    omega=np.zeros(samples)
    t=np.zeros(samples)
    theta[0]=theta_0
    omega[0]=omega_0
    t[0]=T_i

    for n in range(1,samples):
        """
        calculates new value for omega using old value of theta and omega
        """
        omega[n]=omega[n-1]-g/l*np.sin(theta[n-1])*dt

        """
        calculates new value of omega by new omega and old theta
        """
        theta[n]=theta[n-1]+omega[n]*dt

        """
        time erray of same dimenion as earlier arrays
        """
        t[n]=t[n-1]+dt

    """
    theta: array with values of angular displacement
    w: array with values of angular velocity
    t: array with time-values
    """
    return theta,omega,t

# Assigns arrays to function outputs
thetaArr,omegaArr,timeArr = euler_cromer_method(theta_0,omega_0,dt,T_i)

plt.figure("New Test")
plt.plot(timeArr,thetaArr,label="Theta")
plt.plot(timeArr,omegaArr,label="Omega")
plt.legend()
plt.grid()
# plt.show()

# Task 5

# New constants

theta_0 = np.radians(15)
omega_0 = 0
dt = 0.001

thetaArr_a,omegaArr_a,timeArr_a = euler_cromer_approx(theta_0,omega_0,dt,T_i)
thetaArr_m,omegaArr_m,timeArr_m = euler_cromer_method(theta_0,omega_0,dt,T_i)

plt.figure("Diff 15deg")
plt.title("Diff 15deg")
plt.plot(timeArr_a,thetaArr_a,label="Approx")
plt.plot(timeArr_m,thetaArr_m,label="Method")
plt.legend()
plt.grid()
# plt.show()

theta_0 = np.radians(40)
omega_0 = 0
dt = 0.001

thetaArr_a,omegaArr_a,timeArr_a = euler_cromer_approx(theta_0,omega_0,dt,T_i)
thetaArr_m,omegaArr_m,timeArr_m = euler_cromer_method(theta_0,omega_0,dt,T_i)

plt.figure("Diff 40deg")
plt.title("Diff 40deg")
plt.plot(timeArr_a,thetaArr_a,label="Approx")
plt.plot(timeArr_m,thetaArr_m,label="Method")
plt.legend()
plt.grid()
# plt.show()

def equation(t, vals):
    """
    Function takes in time (float), and vals (array with two elements [val1,val2])
    returns RHS of vals

    t: float, time
    vals: [theta, omega]

    Return: array with RHS of equations, as [eq1, eq2]
    """
    theta,omega = vals[0],vals[1]

    # Expression for dw
    dw = -g/l*np.sin(theta)

    # Expression for dtheta
    dtheta = omega

    return [dtheta, dw]

"""
Note:
scipy.integrate.solve_ivp requires that fun returns
an object which is of type array_like.
An ordinary list is of this type (aswell as e.g. integers, floats and numpy arrays)
so we can return a list, and do not have to first convert into an np.array.
"""

from scipy.integrate import solve_ivp as DestoryerOfOrdinaryDifferentialEquations

def RK45_method(RHS, theta_0, omega_0, t_1, dt):
    """
    Calculates theta and omega using the scipy.integrate.solve_ivp function (RK54)

    RHS: right hand side of differential equations
    t_1: time-value to calculate up to (e.g. 10 seconds)
    dt: timestep

    return:
    -------
    theta: array of theta values
    w: array of omega values
    t: timevalues
    """
    initialValues = [theta_0,omega_0]

    timeSpan = [0,t_1 + dt]

    timeArr = np.arange(0,t_1+dt,dt)

    solution = DestoryerOfOrdinaryDifferentialEquations(RHS,timeSpan,initialValues,method="RK45",t_eval=timeArr)

    theta = solution.y[0, : ]
    omega = solution.y[1, : ]
    times = solution.t

    return theta, omega, times

theta,omega,times = RK45_method(equation, 0.2, 0, 10, 0.01)

plt.figure("Scipy")
plt.plot(times,theta,label="Theta")
plt.plot(times,omega,label="omega")
plt.show()


# coding:utf8

from datetime import datetime
import requests
from log import error, warn
from util.utils import json_loads_utf8_util, get_int, random_int_str
import time

try:
    from settings_cms import NOTIFY_COMMAND, NOTIFY_SERVICE_URL
except:
    NOTIFY_COMMAND = {}
    NOTIFY_SERVICE_URL = ''

def send_http_client(url, params, time_out=30, callback=None):
    _t = datetime.now().strftime("%y%m%d%H%M%S%f")[:20] + random_int_str(5)
    result = dict(success=False, message='服务器链接超时!')
    command = params.get('command', '')
    if command in NOTIFY_COMMAND:
        url = NOTIFY_SERVICE_URL

    try:
        ts = time.time()
        res = requests.post(url, params, **dict(timeout=time_out))
        delta = time.time() - ts
        if delta >= 2.0:
            warn("slow_api: %s %s %s %2.4f %s %s" % (params.get('login_ip', ''), _t, command or "-",
                                                     delta, params.get('login_id', ''), params.get('content', '')))
        if res.status_code == 200:
            result = json_loads_utf8_util(res.text)
            if isinstance(result, dict):
                result.update(dict(success=get_int(result.get('success', 0)),
                                   error_code=get_int(result.get('error_code', 0))))
        else:
            result['message'] = '服务器未响应!'
    except Exception as e:
        error('send http client exception >>> url:%s\r\n params:%s\r\n result:%s\r\n Exception:%s'
              , url, str(params), result, e)
        result['message'] = '服务器未响应!'
    finally:
        if callback:
            callback(result)
        else:
            return result


import sqlite3
# import urllib.parse, urllib.request, urllib.error
import ssl
import requests
from bs4 import BeautifulSoup

def find_image(html_doc):
    soup = BeautifulSoup(html_doc, 'html.parser')
    link = soup.find_all('div', id = 'comic')
    link = link[0].find_all('img')
    link = link[0].get('src')
    link = 'https://xkcd.com' + link
    return(link)

def save_image(im_link):
    i = requests.get(im_link)

    with open(f'gb/comic{page_num}.png', 'wb') as f:
        f.write(i.content)

def page_valid(html_doc):
    soup = BeautifulSoup(html_doc, 'html.parser')
    if soup.title.string == '404 Not Found' : return(False)
    else : return(True)

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

conn = sqlite3.connect('Fun_3.sqlite')
cursor = conn.cursor()
page_num = 320
r = requests.get('https://xkcd.com/1/')
html_doc = r.text

while page_valid(html_doc):
    im_link = find_image(html_doc)
    save_image(im_link)
    page_num += 1
    url = f"https://xkcd.com/{page_num}/"
    r = requests.get(url)
    html_doc = r.text


import enum

from flask import Flask, redirect, url_for
from werkzeug.routing import BaseConverter, ValidationError
from werkzeug.urls import url_quote

from ..const import Brother, Nickname, NormalCouple

__all__ = 'app',

class PersonNameConverter(BaseConverter):

    def to_python(self, value):
        try:
            return Brother[value.lower()]
        except KeyError:
            raise ValidationError()

    def to_url(self, value):
        if isinstance(value, str) and value in Brother.__members__:
            return url_quote(value)
        elif isinstance(value, enum.Enum) and value in Brother:
            return url_quote(value.name)
        else:
            return url_quote('oso')

class NicknameConverter(BaseConverter):

    def to_python(self, value):
        try:
            return Nickname.find_by_subdomain(value)
        except KeyError:
            raise ValidationError()

    def to_url(self, value):
        if isinstance(value, str) and value in Nickname.subdomains():
            return url_quote(value)
        elif isinstance(value, enum.Enum) and value in Nickname:
            return url_quote(value.subdomain)
        else:
            return url_quote('lesser.oso')

class NormalCoupleConverter(BaseConverter):

    def to_python(self, value):
        try:
            return NormalCouple[value.lower()]
        except KeyError:
            raise ValidationError()

    def to_url(self, value):
        if isinstance(value, str) and value in NormalCouple.__members__:
            return url_quote(value)
        elif isinstance(value, enum.Enum) and value in NormalCouple:
            return url_quote(value.name)
        else:
            return url_quote('chyoukei')

def build_url(host: str, config) -> str:
    try:
        if config['DEBUG']:
            return host.replace('matsu.moe', 'matsu.san:5000')
    except AttributeError:
        pass
    return host

def create_app(config) -> Flask:
    app = Flask(__name__)

    app.config.update(config)

    app.url_map.converters['person'] = PersonNameConverter
    app.url_map.converters['nickname'] = NicknameConverter
    app.url_map.converters['normal_couple'] = NormalCoupleConverter
    app.url_map.host_matching = True

    @app.route('/', host=build_url('<person:matsu>.matsu.moe', app.config))
    def index_single(matsu: Brother):
        return "Welcome to {}'s personal homepage!".format(matsu.ja_name)

    @app.route('/', host=build_url('<normal_couple:matsu>.matsu.moe',
               app.config))
    def index_normal_couple(matsu: NormalCouple):
        if matsu.redirect_to:
            return redirect(url_for(
                'index_normal_couple',
                matsu=NormalCouple[matsu.redirect_to]
            ))

        if len(matsu.members) == 2:
            category = 'couple'
        else:
            category = 'team'

        member_names = ', '.join(p.ja_name for p in matsu.members)

        return ("Welcome to {0}'s {1} homepage!"
                "
"
                "{0} is group of {2}").format(
            matsu.ja_name,
            category,
            member_names,
        )

    @app.route('/', host=build_url('<nickname:matsu>.matsu.moe', app.config))
    def index_nickname(matsu):
        if matsu.redirect_to:
            return redirect(url_for(
                'index_nickname',
                matsu=Nickname[matsu.redirect_to]
            ))
        return ("Welcome to {0}'s special homepage!"
                "
"
                "{0} is {1}'s nickname.").format(
            matsu.ja_name,
            matsu.character.ja_name,
        )

    @app.route('/', host=build_url('matsu.moe', app.config))
    @app.route('/', host=build_url('www.matsu.moe', app.config))
    @app.route('/', host=build_url('.matsu.moe', app.config))
    def noname(sub=None):
        return redirect(url_for('index_single', matsu=Brother.oso))

    return app


from numpy import double, eye
from time import perf_counter
import matplotlib as plt

#tipo de dato double
def matriz_laplaciana(N, t=double):
    e= eye(N)-eye(N,N,1)
    return t(e+e.T)

Ns = [10,100,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000,6500,7000]

dts1 = []
dts2 = []

archivo= open("Matmul_laplaciana.txt","w")

for i in range (10):
    for N in Ns:
        t1= perf_counter()
        A= matriz_laplaciana(N)
        B= matriz_laplaciana(N)
        t2 = perf_counter()
        C =A@B
        t3 = perf_counter()

        dt1= t2-t1
        dt2= t3-t2
        dts1.append(dt1)
        dts2.append(dt2)

        print(f"N = {N} dt1 = {dt1} s dt2 = {dt2} s")
        archivo.write(f"{N} {dt1} {dt2} \n")

archivo.close()


import numpy as np
from bs4 import BeautifulSoup
from PIL import Image

def crop(png_path, svg_path):
    """Crops the image in png_path using the data in svg_path.
    crops the image so that the clef, key, and time signatures are cropped out."""
    with open(svg_path) as f:
        soup = BeautifulSoup(f, 'xml')
    image = Image.open(png_path)

    svg_tag = soup.find('svg')
    width = float(svg_tag['width'].strip('px'))
    height = float(svg_tag['height'].strip('px'))

    barline = [x for x in soup.find_all('polyline') if x['class'] == 'BarLine'][1]
    right = float(barline['points'].split(',')[0])
    time_sigs = [x for x in soup.find_all('path') if x['class'] == 'TimeSig']
    def get_coords(s):
        # s is a string like M425.006,618.084
        # returns a pair of floats (425.006, 618.084)
        x = s.split()
        x = [y.strip('MCL') for y in x]
        x = np.array(list(map(lambda y: list(map(float, y.split(','))), x)))
        return x

    all_coords = np.concatenate([get_coords(time_sigs[0]['d']), get_coords(time_sigs[1]['d'])], axis=0)
    left = np.max(all_coords[:, 0])

    left_frac = left/width
    right_frac = right/width

    im_width, im_height = image.size
    image = image.crop((left_frac*im_width, 0, right_frac*im_width, im_height))
    image = image.crop(image.getbbox())
    image_np = np.array(image)[:, :-3, 3]
    image_np = 1-image_np/255
    return(image_np)


#!/usr/bin/python3

"""
Simple script to download images and replace image links in markdown documents.
"""

import argparse
import markdown
from markdown.treeprocessors import Treeprocessor
from markdown.extensions import Extension
from markdown.inlinepatterns import SimpleTagPattern
from mimetypes import guess_extension, types_map
import os
import re
import requests
import sys
import unicodedata

from typing import Optional, List, NoReturn

del types_map['.jpe']

class ImgExtractor(Treeprocessor):
    def run(self, doc):
        """
        Find all images and append to markdown.images.
        """

        self.md.images = []
        for image in doc.findall('.//img'):
            self.md.images.append(image.get('src'))

class ImgExtExtension(Extension):
    def extendMarkdown(self, md, md_globals):
        img_ext = ImgExtractor(md)
        md.treeprocessors.register(img_ext, 'imgext', 20)

def slugify(value):
    """
    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.
    """

    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
    value = re.sub('[^\w\s-]', '', value.decode()).strip().lower()
    value = re.sub('[-\s]+', '-', value)

    return value

def get_filename_from_url(req: requests.Response) -> Optional[str]:
    """
    Get filename from url and, if not found, try to get from content-disposition.
    """

    result = None
    if req.url.find('/'):
        result = req.url.rsplit('/', 1)[1]
    else:
        cd = req.headers.get('content-disposition')

        if cd is None:
            return None

        fname = re.findall('filename=(.+)', cd)

        if len(fname) == 0:
            return None

        result = fname[0]

    f_name, f_ext = os.path.splitext(result)

    if not f_ext:
        result = f'{slugify(f_name)}{guess_extension(req.headers["content-type"].partition(";")[0].strip())}'
    else:
        result = f'{slugify(f_name)}.{slugify(f_ext)}'

    return result

class ArticleTransformer:
    """
    Markdown article transformation class.
    """

    def __init__(self, article_path: str, skip_list: Optional[List[str]] = None, skip_all: bool = False, img_dirname: str = "images", img_publicpath: str = ""):
        self.img_dirname = img_dirname
        self.img_publicpath = img_publicpath
        self._article_file_path = article_path
        self._skip_list = sorted(skip_list) if skip_list is not None else []
        self._imgs_dir = os.path.join(os.path.dirname(self._article_file_path), self.img_dirname)
        self._md_conv = markdown.Markdown(extensions=[ImgExtExtension()])
        self._replacement_mapping = {}
        self._skip_all = skip_all

    def _read_article(self) -> List[str]:
        with open(self._article_file_path, 'r') as m_file:
            self._md_conv.convert(m_file.read())

        print(f'Images links count = {len(self._md_conv.images)}')
        images = set(self._md_conv.images)
        print(f'Unique images links count = {len(images)}')

        return images

    def _download_images(self, images: List[str]) -> NoReturn:
        path_join = os.path.join
        img_dirname = self.img_dirname
        img_publicpath = self.img_publicpath
        imgs_dir = self._imgs_dir
        replacement_mapping = self._replacement_mapping
        skip_list = self._skip_list
        img_count = len(images)

        try:
            os.makedirs(self._imgs_dir)
        except FileExistsError:
            # Existing directory is not error.
            pass

        for img_num, img_url in enumerate(images):
            assert img_url not in replacement_mapping.keys(), f'BUG: already downloaded image "{img_url}"...'

            if img_url in skip_list:
                print(f'Image {img_num + 1} ["{img_url}"] was skipped, because it\'s in the skip list...')
                continue

            if not img_url.startswith('http'):
                print(f'Image {img_num + 1} ["{img_url}"] was skipped, because it has incorrect URL...')
                continue

            print(f'Downloading image {img_num + 1} of {img_count} from "{img_url}"...')

            try:
                try:
                    img_response = requests.get(img_url, allow_redirects=True)
                except requests.exceptions.SSLError:
                    print('Incorrect SSL certificate, trying to download without verifying...')
                    img_response = requests.get(img_url, allow_redirects=True, verify=False)

                if img_response.status_code != 200:
                    raise OSError(str(img_response))
            except Exception as e:
                if self._skip_all:
                    print(f'Warning: can\'t download image {img_num + 1}, error: [{str(e)}], '
                          'but processing will be continued, because `skip_all` flag is set')
                    continue
                raise

            img_filename = get_filename_from_url(img_response)
            img_path = path_join(imgs_dir, img_filename)
            print(f'Image will be written to the file "{img_path}"...')
            replacement_mapping.setdefault(img_url, path_join(img_publicpath or img_dirname, img_filename))

            with open(img_path, 'wb') as img_file:
                img_file.write(img_response.content)
                img_file.close()

    def _fix_document_urls(self) -> NoReturn:
        print('Replacing images urls in the document...')
        replacement_mapping = self._replacement_mapping
        lines = []
        with open(self._article_file_path, 'r') as infile:
            for line in infile:
                for src, target in replacement_mapping.items():
                    line = line.replace(src, target)
                lines.append(line)

        with open(self._article_file_path, 'w') as outfile:
            for line in lines:
                outfile.write(line)

    def run(self):
        """
        Run article conversion.
        """

        self._download_images(self._read_article())
        self._fix_document_urls()

def main(args):
    """
    Entrypoint.
    """

    article_file = os.path.expanduser(args.article_file_path)
    skip_list = args.skip_list
    skip_all = args.skip_all_incorrect

    print('Processing started...')

    if isinstance(skip_list, str):
        if skip_list.startswith('@'):
            skip_list = skip_list[1:]
            print(f'Reading skip list from a file "{skip_list}"...')
            with open(os.path.expanduser(skip_list), 'r') as fsl:
                skip_list = [s.strip() for s in fsl.readlines()]
        else:
            skip_list = [s.strip() for s in skip_list.split(',')]

    ArticleTransformer(article_file, skip_list, skip_all, args.images_dirname, args.images_publicpath).run()

    print('Processing finished successfully...')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('article_file_path', type=str,
                        help='an integer for the accumulator')
    parser.add_argument('-s', '--skip-list', default=None,
                        help='skip URL\'s from the comma-separated list (or file with a leading \'@\')')
    parser.add_argument('-d', '--images-dirname', default="images",
                        help='Folder in which to download images')
    parser.add_argument('-p', '--images-publicpath', default="",
                        help='Public path to the folder of downloaded images')
    parser.add_argument('-a', '--skip-all-incorrect', default=False, action='store_true',
                        help='skip all incorrect images')

    args = parser.parse_args()

    main(args)


class Maximal:
    def maximalSquare(self, matrix):
        n=len(matrix)
        if n==0:
            return 0
        m=len(matrix[0])
        maxim=0
        dp=[[0 for _ in range(m+1)] for _ in range(n+1)]
        for i in range(1,n+1):
            for j in range(1,m+1):
                if matrix[i-1][j-1]=="1":
                    dp[i][j]=min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1
                    maxim=max(maxim,dp[i][j])
        return maxim*maxim


# app.py
import requests

from flask import Flask
app = Flask(__name__)

@app.route("/time_to_load/<url>", methods=["GET"])
def funct(url):
  response = requests.post(url)
  return response.elapsed.total_seconds()


import os
import shutil

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
import django
django.setup()

from mysite.settings import BASE_DIR
from mdict.mdict_utils.search_utils import get_mdict_content
from mdict.models import MyMdictEntry

builtin_dic_prefix = '''
<link rel='stylesheet' href='/static/bootstrap-4.4.1/css/bootstrap.min.css'>
<link rel='stylesheet' href='/static/mdict/css/mdict.css'>
<script>
    function elementDisplay(objname){
        var obj=document.getElementsByName(objname);
        for(var i=0;i<obj.length;i++){
            if(obj[i].style.display !='none'){
                obj[i].style.display='none';
            }else{
                obj[i].style.display='block';
            }
        }
    }
</script>
'''

static_list=[r'static\bootstrap-4.4.1\css\bootstrap.min.css',r'mdict\static\mdict\css\mdict.css']
# r'mdict\static\mdict\MathJax-master'

export_txt_root_path=os.path.join(BASE_DIR,'export')
export_txt_path=os.path.join(BASE_DIR,'export','export.txt')

export_data_root_path=os.path.join(export_txt_root_path,'data')

uploads_path=os.path.join(BASE_DIR,'media','uploads')
export_uploads_path=os.path.join(export_data_root_path,'media','uploads')

def export_to_txt():
    entry_list = MyMdictEntry.objects.all()
    i=1
    mdict_list=[]
    for entry in entry_list:
        mdict_entry=entry.mdict_entry
        mdict_content=''.join(get_mdict_content(entry)).replace('\r','').replace('\n','')
        mdict=mdict_entry+builtin_dic_prefix+mdict_content+'\n</>'
        #mdict_static_file前后自动带\n

        i += 1
        mdict_list.append(mdict)
    if not os.path.exists(export_txt_root_path):
        os.mkdir(export_txt_root_path)
    if os.path.exists(export_data_root_path):
        shutil.rmtree(export_data_root_path)
    os.mkdir(export_data_root_path)
    if os.path.exists(export_uploads_path):
        shutil.rmtree(export_uploads_path)

    with open(export_txt_path,'w',encoding='utf-8') as f:
        f.write('\n'.join(mdict_list))

    for s in static_list:
        data_path=os.path.join(BASE_DIR,s)
        if os.path.isfile(data_path):
            s_name=os.path.basename(data_path)
            target_path=os.path.join(export_data_root_path,s_name)
            print(target_path)
            shutil.copy(data_path,target_path)
        else:
            a=s[s.find('static'):]
            target_path=os.path.join(export_data_root_path,a)
            print(target_path)
            shutil.copytree(data_path,target_path)
    print(uploads_path)
    shutil.copytree(uploads_path,export_uploads_path)

    print('已导出到mynav/export，导出完成。')

export_to_txt()


import random

def game():

    random_game = random.randint(1, 10)
    guesses = []

    while len(guesses) < 5:

        try:

            our_guess = int(input('Guess a number from 1 to 10'))

        except ValueError:
            print('{} is not a number!!!'.format(our_guess))

        else:
            if our_guess == random_game:
                print('GREAT. You got it! My number was {}'.format(random_game))
                break
            elif our_guess < random_game:
                print('My number is higher than {}'.format(our_guess))
            else:
                print("My number is lower than {}".format(our_guess))

            guesses.append(our_guess)

    else:
        print("You didnt get it right. My number was {}".format(random_game))
    play_again = input("Do you wanna play again? Y/n")
    if play_again.lower() != 'n':
        game()
    else:
        print("BYE")

game()


import collections
import syntax

#Flatten nested list to single list
def flatten(L):
    if(type(L) != list):
        return [L]
    if len(L) == 1:
        if type(L[0]) == list:
            result = flatten(L[0])
        else:
            result = L
    elif type(L[0]) == list:
        result = flatten(L[1:])
        result = flatten(L[0]) + result
    else:
        if L[0] == "if":
            res1 = flatten(L[1])
            res2 = flatten(L[2])
            res3 = flatten(L[3])
            result = ["if", "("] + res1 + [")", "then", "("] + \
                res2 + [")", "else", "("]+res3+[")"]
            return result
        elif L[0] == "and":
            res1 = flatten(L[1])
            res2 = flatten(L[2])
            res3 = flatten(L[3])
            result = ["and", "("] + res1 + [")", "or", "("] + \
                res2 + [")", "not", "("]+res3+[")"]
            return result
        else:
            result = flatten(L[1:])
            result = [L[0],"("] + result + [")"]
    return result

#Convert nested list to string
def listToString(s):

    if isinstance(s, (str)):
        return s
    # initialize an empty string
    str1 = ""
    s1 = flatten(s)
    # return string
    return (str1.join(s1))

#Starts evaluation
def evaluation(t):
    ls = eval_term(t)
    return listToString(ls)

#Recursive function
def eval_term(t):

    if t == ['true'] or t == ['false'] or t == ['0']:
        return t

    #iszero t
    elif t[0] == 'iszero':
        val = (eval_term(t[1]))
        if (val == ['0']):
            return ['true']
        elif val[0]  == 'succ':
            return ['false']

    #succ t
    elif t[0] == 'succ':
        val = (eval_term(t[1]))
        s = ['succ', val]
        return s

    #pred t
    elif t[0] == 'pred':
        val = (eval_term(t[1]))
        if val == ['0']:
            return ['0']
        elif val[0] == 'succ':
            s = val[1:]
            return s

    #and t or t not t
    elif t[0] == 'and':
        t1 = eval_term(t[1])
        if t1 == ['false']:
            return ['false']
        elif t1 == ['true']:
            t2 = eval_term(t[2])
            if t2 == ['true']:
                return ['true']
            elif t2 == ['false']:
                t3 = eval_term(t[3])
                if t3 == ['true']:
                    return ['false']
                elif t3 == ['false']:
                    return ['true']

    #if-then-else
    elif t[0] == 'if':
        val = eval_term(t[1])
        if val == ['true']:
            return eval_term(t[2])
        elif val == ['false']:
            return eval_term(t[3])

   #others
    else:
        return listToString(t)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx, wx.lib.mixins.listctrl as wxlc

class EditVariable(wx.Dialog):
    def __init__(self, parent, data=None):
        wx.Dialog.__init__(self, parent, title='VQ: Edit Variable')

        sizer = wx.BoxSizer(wx.VERTICAL)
        grid = wx.GridBagSizer(6, 6)
        # grid.AddGrowableCol(1)

        grid.Add(wx.StaticText(self, label='Type:'), (0, 0))
        self.choType = wx.Choice(self, choices=['Distributed value',
                                                'Enumerated choice'])
        self.choType.Bind(wx.EVT_CHOICE, self.choType_change)
        grid.Add(self.choType, (0, 1), flag=wx.EXPAND)

        self.lblDistribution = wx.StaticText(self, label='Distribution:')
        self.choDistribution = wx.Choice(self, choices=['Normal',
                                                        'Uniform',
                                                        'Uniform discrete',
                                                        'Geometric',
                                                        'Binomial',
                                                        'Poisson'])
        grid.Add(self.lblDistribution, (1, 0))
        grid.Add(self.choDistribution, (1, 1), flag=wx.EXPAND)
        self.choDistribution.Bind(wx.EVT_CHOICE, self.choDistribution_change)

        self.lblMean = wx.StaticText(self, label='Mean:')
        self.txtMean = wx.TextCtrl(self)
        grid.Add(self.lblMean, (2, 0))
        grid.Add(self.txtMean, (2, 1), flag=wx.EXPAND)

        self.lblVariance = wx.StaticText(self, label='Variance:')
        self.txtVariance = wx.TextCtrl(self)
        grid.Add(self.lblVariance, (3, 0))
        grid.Add(self.txtVariance, (3, 1), flag=wx.EXPAND)

        self.lblStep = wx.StaticText(self, label='Step:')
        self.txtStep = wx.TextCtrl(self)
        grid.Add(self.lblStep, (4, 0))
        grid.Add(self.txtStep, (4, 1), flag=wx.EXPAND)

        self.lblSigFigs = wx.StaticText(self, label='Significant figures:')
        self.txtSigFigs = wx.TextCtrl(self)
        grid.Add(self.lblSigFigs, (5, 0))
        grid.Add(self.txtSigFigs, (5, 1), flag=wx.EXPAND)

        self.lstEnum = EditListCtrl(self)
        self.lstEnum.InsertColumn(0, 'Text')
        self.lstEnum.InsertColumn(1, 'Value')
        self.lstEnum.SetColumnWidth(0, wx.LIST_AUTOSIZE_USEHEADER)
        self.lstEnum.SetColumnWidth(1, wx.LIST_AUTOSIZE_USEHEADER)
        self.lstEnum.setResizeColumn(0)
        self.lstEnum.Append(['', '0'])
        self.lstEnum.SetInitialSize((120, 240))
        grid.Add(self.lstEnum, (6, 0), span=(1, 2), flag=wx.EXPAND | wx.ALL)

        self.btnAdd = wx.Button(self, label='Add')
        self.btnAdd.Bind(wx.EVT_BUTTON, self.btnAdd_click)
        self.btnRemove = wx.Button(self, label='Remove')
        self.btnRemove.Bind(wx.EVT_BUTTON, self.btnRemove_click)
        grid.Add(self.btnAdd, (7, 0))
        grid.Add(self.btnRemove, (7, 1))

        grid.Add(wx.Button(self, label='Test'), (8, 0), span=(1, 2))
        grid.Add(wx.StaticText(self, label='Text:'), (9, 0))
        grid.Add(wx.StaticText(self), (9, 1))
        grid.Add(wx.StaticText(self, label='Value:'), (10, 0))
        grid.Add(wx.StaticText(self), (10, 1))

        buttonsSizer = wx.BoxSizer(wx.HORIZONTAL)
        buttonsSizer.Add(wx.Button(self, label='Save && close'),
                         flag=wx.ALIGN_RIGHT)
        grid.Add(buttonsSizer, (11, 0), span=(1, 2), flag=wx.ALIGN_RIGHT)

        sizer.Add(grid, 0, wx.EXPAND | wx.ALL, 6)

        self.SetSizer(sizer)
        # self.CreateStatusBar()
        self.SetAutoLayout(1)
        sizer.Fit(self)
        self.Show(True)

        grid.SetEmptyCellSize((0, 0))  # added by Jerry
        self.UpdateFields()

    def choType_change(self, e):
        self.UpdateFields()

    def choDistribution_change(self, e):
        self.UpdateFields()

    def UpdateFields(self):
        isDistr = self.choType.GetSelection() == 0

        self.choDistribution.Show(isDistr)
        self.lblMean.Show(isDistr)
        self.txtMean.Show(isDistr)
        self.lblVariance.Show(isDistr)
        self.txtVariance.Show(isDistr)
        self.lblStep.Show(isDistr)
        self.txtStep.Show(isDistr)
        self.lblSigFigs.Show(isDistr)
        self.txtSigFigs.Show(isDistr)

        self.lstEnum.Show(not isDistr)
        self.btnAdd.Show(not isDistr)
        self.btnRemove.Show(not isDistr)

        if isDistr:
            self.lblDistribution.SetLabel('Distribution:')
            n = self.choDistribution.GetSelection()
            if n == 0:
                # Normal
                self.lblMean.SetLabel('Mean:')
                self.lblVariance.SetLabel('Variance:')
                self.lblStep.Hide()
                self.txtStep.Hide()
            elif n == 1:
                # Uniform
                self.lblMean.SetLabel('Minimum:')
                self.lblVariance.SetLabel('Maximum:')
                self.lblStep.Hide()
                self.txtStep.Hide()
            elif n == 2:
                # Uniform discrete
                self.lblMean.SetLabel('Minimum:')
                self.lblVariance.SetLabel('Maximum:')
                self.lblStep.SetLabel('Step:')
            elif n == 3:
                # Geometric
                self.lblMean.SetLabel('Probability:')
                self.lblVariance.Hide()
                self.txtVariance.Hide()
                self.lblStep.Hide()
                self.txtStep.Hide()
            elif n == 4:
                # Binomial
                self.lblMean.SetLabel('Number:')
                self.lblVariance.SetLabel('Probability:')
                self.lblStep.Hide()
                self.txtStep.Hide()
            elif n == 5:
                # Poisson
                self.lblMean.SetLabel('Mean:')
                self.lblVariance.Hide()
                self.txtVariance.Hide()
                self.lblStep.Hide()
                self.txtStep.Hide()
        else:
            self.lblDistribution.SetLabel('Options:')
        # self.Layout()
        self.Fit()  # added by Jerry

    def btnAdd_click(self, e):
        self.lstEnum.Append(['', '0'])
        for i in range(self.lstEnum.GetItemCount() - 1):
            self.lstEnum.Select(i, 0)
        self.lstEnum.Select(self.lstEnum.GetItemCount() - 1)

    def btnRemove_click(self, e):
        item = self.lstEnum.GetFirstSelected()
        while item != -1:
            self.lstEnum.DeleteItem(item)
            item = self.lstEnum.GetFirstSelected()

class EditListCtrl(wx.ListCtrl, wxlc.TextEditMixin,
                   wxlc.ListCtrlAutoWidthMixin):
    def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.LC_REPORT):
        wx.ListCtrl.__init__(self, parent, id, pos, size, style | wx.LC_REPORT)
        wxlc.TextEditMixin.__init__(self)
        wxlc.ListCtrlAutoWidthMixin.__init__(self)

if __name__ == '__main__':
    app = wx.App(redirect=False)
    main = EditVariable(None, 'VQ')
    app.MainLoop()


#!/usr/bin/python3
# written by: atholcomb
# try.py

if x > 10:
    score = 3 * scale
else:
    score = 4 * scale

if income > 10000:
    tax = income * 0.2
else:
    income * 0.17 + 100

if number % 3 == 0:
    print(i)
else:
    print(j)


import tensorflow as tf
import numpy as np
import time
from imageLoader import getPaddedROI,training_data_feeder
import math
'''
created by Cid Zhang
a sub-model for human pose estimation
'''

#function to locate the point with maximum value on similarity map
def max_sim_point( sim_map , orig_feature_map_size, image_input_size ):

    #get the position of  max value
    max_pos = tf.argmax( sim_map , output_type=tf.int32)

    max_value = sim_map[max_pos]
    #reshape the similarity map to 2d format
    sim_map= tf.reshape(sim_map,[orig_feature_map_size , orig_feature_map_size])
    p = tf.where (tf.equal (sim_map,max_value ) )

    def cond_t(p):
        return p[0]
    def cond_f(p):
        return p
    joint = tf.cond(tf.shape(p)[0] > 1 , lambda:cond_t(p) , lambda:cond_f(p) )
    x = tf.cast(joint[0], tf.float32) * tf.cast((image_input_size/orig_feature_map_size),tf.float32)
    y = tf.cast(joint[1], tf.float32) * tf.cast((image_input_size/orig_feature_map_size),tf.float32)
    return ( x , y )

def truncated_normal_var(name,shape,dtype):
    return(tf.get_variable(name=name, shape=shape, dtype=dtype, initializer=tf.truncated_normal_initializer(stddev=0.01)))
def zero_var(name,shape,dtype):
    return(tf.get_variable(name=name, shape=shape, dtype=dtype, initializer=tf.constant_initializer(0.0)))

roi_size = 23
image_input_size = 301

#input placeholders
#batch1 hints
inputs_b1h1 = tf.placeholder(tf.float32, ( 16, roi_size, roi_size, 3), name='inputs_b1h1')
inputs_b1h2 = tf.placeholder(tf.float32, ( 16, roi_size, roi_size, 3), name='inputs_b1h2')

inputs_s = tf.placeholder(tf.float32, (None, image_input_size, image_input_size, 3), name='inputs_s')
labels = tf.placeholder(tf.float32,(16,76,76), name='labels')

#define the model
def paraNet(input):
    out_l1 = tf.layers.conv2d(input, 8, [3, 3],strides=(2, 2), padding ='valid' ,name='para_conv_1')
    out_l1 = tf.nn.relu6(out_l1)
    out_l2 = tf.layers.conv2d(out_l1, 16, [3, 3],strides=(2, 2), padding ='valid' ,name='para_conv_2')
    out_l2 = tf.nn.relu6(out_l2)
    out_l3 = tf.layers.conv2d(out_l2, 32, [5, 5],strides=(1, 1), padding ='valid' ,name='para_conv_3')
    return out_l3

#network pipeline to create the first Hint Hash Sets (Three batches)
with tf.variable_scope('conv'):
    out_b1h1_l3 = paraNet(inputs_b1h1)
    #flatten and binerize the hashs
    out_b1h1_l3 =tf.squeeze(  tf.round(tf.nn.sigmoid(out_b1h1_l3)) )

#network pipeline to create the Second Hint Hash Sets
with tf.variable_scope('conv', reuse=True):
    out_b1h2_l3 = paraNet(inputs_b1h2)
    #flatten and binerize the hashs
    out_b1h2_l3 =tf.squeeze( tf.round(tf.nn.sigmoid(out_b1h2_l3)) )

with tf.variable_scope('conv', reuse=True):
    out_2_l1 = tf.layers.conv2d(inputs_s,  8, [3, 3],strides=(2, 2), padding ='same' ,name='para_conv_1')
    out_2_l1 = tf.nn.relu6(out_2_l1)
    out_2_l2 = tf.layers.conv2d(out_2_l1, 16, [3, 3],strides=(2, 2), padding ='same' ,name='para_conv_2')
    out_2_l2 = tf.nn.relu6(out_2_l2)
    out_2_l3 = tf.layers.conv2d(out_2_l2, 32, [5, 5],strides=(1, 1), padding ='same' ,name='para_conv_3')
    #binerize the value
    out_2_l3 = tf.round(tf.nn.sigmoid(out_2_l3))
    #iterate through each pixel of the final feature map
    #turn the value into hashes
    orig_feature_map_size = tf.shape(out_2_l3)[1]

    #calculate Hamming distance maps
    map0 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[0] )) , axis=3 ),
                       tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[0] )) , axis=3 )  )
    map1 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[1] )) , axis=3 ),
                       tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[1] )) , axis=3 )  )
    map2 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[2] )) , axis=3 ),
                       tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[2] )) , axis=3 )  )
    map3 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[3] )) , axis=3 ),
                       tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[3] )) , axis=3 )  )
    map4 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[4] )) , axis=3 ),
                       tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[4] )) , axis=3 )  )
    map5 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[5] )) , axis=3 ),
                       tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[5] )) , axis=3 )  )
    map6 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[6] )) , axis=3 ),
                       tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[6] )) , axis=3 )  )
    map7 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[7] )) , axis=3 ),
                       tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[7] )) , axis=3 )  )
    map8 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[8] )) , axis=3 ),
                       tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[8] )) , axis=3 )  )
    map9 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[9] )) , axis=3 ),
                       tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[9] )) , axis=3 )  )
    map10 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[10] )) , axis=3 ),
                        tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[10] )) , axis=3 )  )
    map11 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[11] )) , axis=3 ),
                        tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[11] )) , axis=3 )  )
    map12 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[12] )) , axis=3 ),
                        tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[12] )) , axis=3 )  )
    map13 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[13] )) , axis=3 ),
                        tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[13] )) , axis=3 )  )
    map14 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[14] )) , axis=3 ),
                        tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[14] )) , axis=3 )  )
    map15 = tf.minimum( tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h2_l3[15] )) , axis=3 ),
                        tf.reduce_sum (tf.abs(tf.subtract( out_2_l3, out_b1h1_l3[15] )) , axis=3 )  )
    totoal_map =tf.div( tf.concat([map0, map1, map2, map3, map4, map5, map6, map7,
                                   map8, map9, map10,map11,map12, map13, map14, map15], 0) , 32)
    loss = tf.nn.l2_loss(labels- totoal_map  , name = 'loss'  )

#ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables
    train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss )

init =  tf.global_variables_initializer()
batchsize = 3

with tf.Session() as sess:
    #writer = tf.summary.FileWriter("./variable_graph",graph = sess.graph)
    sess.run(init)

    #load image from dataset(train set)
    joint_data_path = "./custom_data.json"
    train_val_path = "./train_val_indices.json"
    imgpath = "./000/"
    input_size = 301
    hint_roi_size = 23

    hintSet01_norm_batch = []
    hintSet02_norm_batch = []
    t_img_batch = []
    t_label_norm_batch = []
    #load data
    hintSet01,hintSet02,t_img,t_label_norm = training_data_feeder(joint_data_path, train_val_path, imgpath, input_size, hint_roi_size )
    #Normalize the image pixel values to 0~1
    hintSet01_norm = []
    hintSet02_norm = []

    t_img = np.float32(t_img /255.0)
    #print(type(t_label_norm))
    for rois in hintSet01:
        tmp = np.float32(rois / 255.0)
        hintSet01_norm.append(tmp.tolist())
    for rois in hintSet02:
        tmp = np.float32(rois / 255.0)
        hintSet02_norm.append(tmp.tolist())

    print(tf.trainable_variables())
    #print(hash_set01)
    #print(out_2_l3)
    temp = sess.run(totoal_map , feed_dict={inputs_s:  [t_img]  ,
                                        inputs_b1h1: hintSet01_norm, inputs_b1h2: hintSet02_norm, #batch no.1
                                        labels: t_label_norm
                                                       })
    print(temp)
    print(np.shape(temp))

'''
    for i in range(1000):
        hintSet01_norm, hintSet02_norm, t_img, t_label_norm = get_train_data(batchsize)
        sess.run(train_step, feed_dict={inputs_s: [ t_img ] ,
                                        inputs_b1h1: hintSet01_norm[0], inputs_b1h2: hintSet02_norm[0], #batch no.1
                                        inputs_b2h1: hintSet01_norm[1], inputs_b2h2: hintSet02_norm[1], #batch no.2
                                        inputs_b3h1: hintSet01_norm[2], inputs_b3h2: hintSet02_norm[2], #batch no.3
                                        labels: t_label_norm
                                                        })
        if i % 50 == 0:
            print(total_loss)

'''


import os
import pydot
import subprocess

# out = subprocess.Popen(['wc', '-l', 'TripCombo.txt'],
#                        stdout=subprocess.PIPE,
#                        stderr=subprocess.STDOUT)
#
# stdout, stderr = out.communicate()
# print(stdout)

os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'

def returnParentheticalFormat(fileName):
    parentheticalFormat = ''
    for line in reversed(list(open(fileName))):
        if line.__contains__('eNewick'):
            parentheticalFormat = line[28:]
            # print(parentheticalFormat)
            # print(line.rstrip())
    return parentheticalFormat.rstrip()

def convertDotToPNG(fileName):
    (graph,) = pydot.graph_from_dot_file(fileName)
    graph.write_png('cExample1.png')

def convertDotToPNGJulia(fileName):
    paren = returnParentheticalFormat(fileName)
    with open("NetworkParen.net", "w") as text_file:
        text_file.write(paren)
    # write it to a file
    # then use the julia command
    cmd = 'julia plot-network.jl NetworkParen.net'
    os.system(cmd)

def removoeLeaves(leafNodes):
    with open("leaves.txt", "w") as text_file:
        text_file.write(leafNodes)
    # write it to a file
    # then use the julia command
    cmd = 'julia .\\remove-leaves.jl .\\NetworkParen.net .\\leaves.txt'
    os.system(cmd)
    # convert Parenthetical format to png
    cmd = 'julia plot-network.jl reduced-net.txt'
    os.system(cmd)

def tripletsToDot(tripletsFName):
    cmd = 'java -jar Lev1athan.jar ' + tripletsFName + ' > cExample1.dot'
    os.system(cmd)

if __name__ == '__main__':
    print("Hello")
    tripletsToDot('cExample1.trips')
    # convertDotToPNG('cExample1.dot')
    convertDotToPNGJulia('cExample1.dot')
    # removoeLeaves('1\n3\n4')
    print("Hello")

#  1) Return Parenthetical fiel and return the image
# Download image or text file
# Two buttons one for image other for text
#  Filtering the graph
# Remove Leaf Nodes
# Change Root and checbox to filter leaves

# checkbox with all the leaves and uncheck the nodes

# last line if you use please site the following
# manuscript
# Download button to


import re

from django.db import transaction
from django.core.management.base import BaseCommand
from news.models import Article

class Command(BaseCommand):
    help = 'Clean body text from markdown trash'

    def clean_body(self, txt):
        regex = r'\(\/.+.htm\)'
        match = re.search(regex, txt)
        if not match:
            return
        start, end = match.start(), match.end()
        body = txt[:start] + txt[end:]
        return body.replace('[', '').replace(']', '')

    @transaction.atomic
    def handle(self, *args, **kwargs):
        arts = Article.objects.all()
        for article in arts:
            if not article.body:
                continue

            body = self.clean_women_ru(article.body)
            description = self.clean_women_ru(article.description)

            if not body:
                continue

            article.body = body
            article.description = description

            article.save()


import numpy as np
from scipy import signal
import shapers
import matplotlib.pyplot as py
from argparse import ArgumentParser
from scipy.integrate import trapz
p = ArgumentParser()
p.add_argument('peaking_time',type=float)
p.add_argument('shape')
p.add_argument('order',type=int)
p.add_argument('--decay',type=float,default=1E12)
a = p.parse_args()

dt = 1E-9
times = np.arange(-1 * a.peaking_time,10 * a.peaking_time,dt)
step = np.zeros_like(times)
step[times > 0] = np.exp(-times[times > 0]/a.decay)
tp = times * 1E6

sos = shapers.shaper(a.shape,a.order,a.peaking_time,dt=dt,pz=1./a.decay)
step_response = signal.sosfilt(sos,step)
step_response_ddt = np.gradient(step_response,dt)
w = trapz(np.power(step_response,2),times) #correct answer for CR-RC if divded by 2*peaktime
wp = trapz(np.power(step_response_ddt,2),times) #correct answer if multiplied by peaktime/2
print('w = %.6e   wp = %.6e' % (w,wp))
print('Fv = %.6e   Fi = %.6e' % (wp*a.peaking_time/2.,w/(2*a.peaking_time)))

py.plot(tp,step,'k',linewidth=0.5)
py.plot(tp,step_response,'r',linewidth=0.5)
py.plot(tp,np.power(step_response,2),'g',linewidth=0.5)
py.xlabel('time (microseconds)')
py.ylabel('amplitude')
py.show()


class Solution(object):
    def minSubArrayLen(self, s, nums):
        """
        :type s: int
        :type nums: List[int]
        :rtype: int
        """

        if len(nums) == 0: return 0
        if len(nums) == 1:
            return int(nums[0] >= s)

        minLength = float('inf')
        start, end = 0, 0
        currSum = 0
        for i in range(len(nums)):
            end = i
            currSum += nums[i]
            if currSum >= s:
                while currSum >= s:
                    minLength = min(minLength, end-start+1)
                    currSum -= nums[start]
                    start += 1

        if minLength == float('inf'): return 0
        else: return minLength


"""Writes timestamp file for ORBSLAM2"""

import argparse

parser = argparse.ArgumentParser("Writes timestamp file for ORBSLAM2")
parser.add_argument('fps', type=float, help='fps')
parser.add_argument('file_len', type=int, help='number of images')
args = parser.parse_args()
fps = args.fps
file_len = file_len

file = open("times.txt","a")
for i in range(file_len):
    out_fname = "{:06f}".format((i+1)/fps)
    file.write(out_fname+"\n")
file.close()


try:
    from egovScDoc.spiders.docSpider.base_spider import *
except ImportError:
    from egovResearch.egovScDoc.spiders.docSpider.base_spider import *

class JinanSpiderOld(BaseSpider):
    def resolve_detail_page(self, item, html):
        soup = BeautifulSoup(html, 'lxml')
        table = soup.find("table", attrs={
            "style": "border:solid 1px #C4C4C4"
        })
        if table is None:
            return
        links = table.find_all("a")
        for a in links:
            try:
                a["href"] = "http://xxgk.jinan.gov.cn{}".format(a["href"]).replace("&", "&")
            except:
                pass
        item.update_content(table)
        item.update()
        """supplement"""
        links = soup.find_all("a", class_="bt_link")
        cates = ("政府规章", "规范性文件", "其他文件", "政策解读")
        if item.remarks not in cates:
            if len(links) < 2:
                item.full_print()
                return
            if links[-2].text in cates:
                print(item.remarks, " ", links[-2].text)
                item.remarks = links[-2].text
            item.update()
        pass

    def save_all_files(self):
        base_url = "http://xxgk.jinan.gov.cn/xxgk/jcms_files/jcms1/web1/site/zfxxgk/search.jsp?showsub=0&orderbysub=0&cid=7&vc_title=&vc_number=&currpage={page_index}&binlay=&c_issuetime=&cid=7&jdid=1&divid=div9265&vc_title=&vc_number=&c_issuetime=&vc_keyword=&vc_abs=&vc_ztfl=&vc_service=&c_createtime="
        config_list = self.config_list
        for config in config_list:
            for i in range(config.loop_start, config.loop_stop):
                page_dir = "{}{}\{}".format(self.base_dir, config.class_id, i + config.page_start)
                print(i)
                request_url = base_url.format(page_index=i)
                res = requests.get(request_url, headers=requests_header)
                soup = BeautifulSoup(res.text, "lxml")
                time.sleep(3)
                if not os.path.exists(page_dir):
                    os.makedirs(page_dir)

                table = soup.find("table", attrs={
                    "style": "margin-top:6px;"
                })
                trs = table.find_all("tr")
                for tr in trs:
                    tds = tr.find_all("td")
                    a = tds[1].find("a")
                    url = a.get("href")
                    title = a.get("mc")
                    organization = a.get("jg")
                    release_time = a.get("rq")
                    subject = a.get("zt")

                    item = EGOVSCPolicyPaper()

                    item.organization = organization
                    item.release_time = release_time
                    item.title = title
                    item.url = url
                    item.origin_page_index = i
                    item.remarks = subject  # 主题分类
                    # item.remarks = config.remarks
                    item.save(self)

                    sub_res = requests.get(url, headers=requests_header)
                    sub_res.encoding = "UTF-8"
                    with open("{}\{}.html".format(page_dir, item.id), "w", encoding="utf-8") as f:
                        f.write(sub_res.text)
                    self.resolve_detail_page(item, sub_res.text)
                    time.sleep(3)

    def run(self):
        self.crawl("jinan")

class JinanSpider(BaseSpider):
    __city_abbreviation__ = "jinan"

    # ---/---更新页码信息
    def _update_page_count(self):
        """
        更新页码信息
        :return:
        """
        base_url = "http://www.jinan.gov.cn/module/xxgk/search.jsp?texttype=&fbtime=&vc_all=&vc_filenumber=&vc_title=&vc_number=&currpage={page_index}&sortfield=createdatetime:0,orderid:0&fields=&fieldConfigId=&hasNoPages=&infoCount="
        for config in self.config_list:
            post_data = {
                "infotypeId": config.class_id,
                "jdid": 1,
                "area": "1137010000418859XL",
                "divid": "div1728",
                "vc_title": "",
                "vc_number": "",
                "sortfield": "createdatetime:0,orderid:0",
                "currpage": config.loop_start,
                "vc_filenumber": "",
                "vc_all": "",
                "texttype": "",
                "fbtime": "",
            }
            request_url = base_url.format(page_index=config.loop_start)
            res = requests.post(request_url, post_data, headers=requests_header)
            soup = BeautifulSoup(res.text, "lxml")
            form = soup.find("form",attrs={
                "name":"pageForm"
            })
            text = form.find("tr").find("td").text
            pages = re.findall("共(\d+)页",text)

            page_count = int(pages[0]) + 1
            print(" --page_num--:", page_count)
            config.loop_stop = page_count
            config.update()

    def resolve_detail_page(self, item, html):
        soup = BeautifulSoup(html, 'lxml')
        content = soup.find("div",id="zoom")
        item.update_content(content)
        table = soup.find("div",class_="wz").find("table")
        tds = table.find_all("td")
        meta = {
            "origin_elem_id":"索引号",
            "reference_number":"文件编号",
        }
        for index,td in enumerate(tds):
            for key,value in meta.items():
                if value in td.text:
                    setattr(item,key,tds[index+1].text.strip())
        item.update()

    def save_all_files(self):
        base_url = "http://www.jinan.gov.cn/module/xxgk/search.jsp?texttype=&fbtime=&vc_all=&vc_filenumber=&vc_title=&vc_number=&currpage={page_index}&sortfield=createdatetime:0,orderid:0&fields=&fieldConfigId=&hasNoPages=&infoCount="
        config_list = self.config_list
        for config in config_list:
            for i in range(config.loop_start, config.loop_stop):
                page_dir = "{}{}\{}".format(self.base_dir, config.class_id, i + config.page_start)
                if not os.path.exists(page_dir):
                    os.makedirs(page_dir)
                print("------------page_index:---------", i)
                post_data = {
                    "infotypeId": config.class_id,
                    "jdid": 1,
                    "area": "1137010000418859XL",
                    "divid": "div1728",
                    "vc_title": "",
                    "vc_number": "",
                    "sortfield": "createdatetime:0,orderid:0",
                    "currpage": i,
                    "vc_filenumber": "",
                    "vc_all": "",
                    "texttype": "",
                    "fbtime": "",
                }
                request_url = base_url.format(page_index=i)
                res = requests.post(request_url, post_data, headers=requests_header)
                soup = BeautifulSoup(res.text, "lxml")
                odd = soup.find_all("tr", class_="tr_main_value_odd")
                even = soup.find_all("tr", class_="tr_main_value_even")
                odd.extend(even)
                trs = odd
                time.sleep(3)

                for tr in trs:
                    a = tr.find("a")

                    item = EGOVSCPolicyPaper()
                    url = a.get("href").strip()
                    title = a.get("title").strip()
                    tds = tr.find_all("td")
                    organization = tds[1].text.strip()
                    release_time = tds[2].text.strip()

                    item.organization = organization
                    item.release_time = release_time
                    item.title = title
                    item.url = url
                    item.origin_page_index = i

                    item.remarks = config.remarks
                    item.save(self)

                    sub_res = requests.get(url, headers=requests_header)
                    sub_res.encoding = "UTF-8"
                    with open("{}\{}.html".format(page_dir, item.id), "w", encoding="utf-8") as f:
                        f.write(sub_res.text)
                    self.resolve_detail_page(item, sub_res.text)
                    item.print()
                    time.sleep(3)

if __name__ == '__main__':
    with app.app_context():
        JinanSpider(True).update()


#   Projektarbeit "Recherche und Tool zur Simulation von Quantenschaltungen im Bereich Quantencomputing"
#   Author: Lukas Lepper, 14.12.2020
#   Betreuer: Dipl.-Ing. Martin Hardieck
#   Dateiname: G_Rotation.py
#   Version: 0.6

import numpy as np
from QGate import QGate
import cmath

class Rotation(QGate):
    """
    Klasse für das algemeine Rotations-Gatter. Rotation um phi und theta. Speichert den Typ und erweitert die Matrix
    dieses Gatters auf Größe des Zustandsvektors.
    """

    def __init__(self, list_affected_qubits, list_of_parameters):
        """
        Konstruktor erstellt Matrix in der Größe der Quantenschaltung (Anzahl der Qubits), die das Gatter auf ein
        bestimmtes Qubit beschreibt.

        :param list_affected_qubits: Index des Qubits, auf welches das Gatter angewendet wird
        :param list_of_parameters: Liste der Parameter, hier die Winkel Theta und Phi.
        """

        #   list_affected_qubits wird in der Elternklasse in qsim_obj.list_affected_qubits gespeichert
        super().__init__(list_affected_qubits)
        theta = list_of_parameters[0]
        phi = list_of_parameters[1]

        #   Bezeichnung des Gatters
        self.type = 'r'

        #   Spezifische Matrix des Gatters
        self.general_matrix = np.array([[cmath.cos(theta / 2), -1j * cmath.exp(-1j * phi) * cmath.sin(theta / 2)],
                                        [-1j * cmath.exp(1j * phi) * cmath.sin(theta / 2), cmath.cos(theta / 2)]], dtype=complex)

        #   Die Matrix wird auf die Größe der Quantenschaltung erweitert
        self.general_matrix = self.expandmatrix(self.getnqubits(), list_affected_qubits[0])


from logreg import logreg_model

import time
import pickle
import gc

with open("klassebetegnelser_dict2209_alldigits.pckl", "rb") as open_file:
	klassebetegnelser = pickle.load(open_file)

tid=time.time()
test=logreg_model("config/logreg.yml")
print("det tok:",time.time()-tid)
tid=time.time()

for i in range(1):
	if i%100==0:
		print(i)
	test.predict("Heisann, dette er en prøve tekst, ikkje les for mye inn i den. dette er enda lengre enn det det har pleid å være før",3)
print("det tok:",time.time()-tid)
gc.collect()


class LLNode(object):
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

class LinkedList(object):
    def __init__(self, values=None):
        self.head = None
        if values:
            if hasattr(values, '__iter__'):
                for value in values:
                    self.add(value)
            else:
                self.add(value)

    def __iter__(self):
        current = self.head
        while current != None:
            yield current.value
            current = current.next

    def add(self, value):
        self.head = LLNode(value, self.head)

    def size(self):
        current = self.head
        size = 0
        while current != None:
            size += 1
            current = current.next
        return size

    def reverse(self):
        current = self.head
        next = None
        prev = None
        if current:
            while current.next != None:
                next = current.next
                current.next = prev;
                prev = current;
                current = next;
            current.next = prev
            self.head = current
        return self.head


from your_package.your_module import TemplateClass

def main():
    first = TemplateClass(5, 2)
    second = TemplateClass(10, 4)

    print("Wow I got a result of {} adding these".format(first + second))

if __name__ == "__main__":
    main()