from os import path

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from scipy.signal import medfilt
import numpy as np

from .utils.filter import double_resample

def ioff(func):
    """Decorator to make plotting non interactive temporally ."""
    def make_ioff(*args, **kwargs):
        plt.ioff()
        func(*args, **kwargs)
        plt.ion()

    return make_ioff

def figures2pdf(fname, fignums=None, figures=None, close=False):
    """Save list of figures into a multipage pdf.

    **Arguments:**
      - **fname**: Name of the file to save to.

    **Keywords:**
      - **fignums**: list of figure numbers to save
        if None given, all currently open figures get saved into a pdf.
    """
    from matplotlib.backends.backend_pdf import PdfPages
    if fname[-4:] != '.pdf':
        fname += '.pdf'
    print('Saving to:', path.abspath(fname))

    if isinstance(fignums, type(None)) and isinstance(figures, type(None)):
        fignums = plt.get_fignums()
    elif isinstance(fignums, type(None)):
        fignums = [fig.number for fig in figures]

    with PdfPages(fname) as pdf:
        for num in fignums:
            fig = plt.figure(num)
            pdf.savefig()
            if close:
                plt.close(fig)
    print('DONE')

# Wrapper function for figures2pdf with easier to remember name
def savefig_multipage(*args, **kwargs):
    return figures2pdf(*args, **kwargs)

def multipage_pdf(plot_func):
    """
    Function can be used as a decorator, to loop over a given range
    and call a plot function with an index parameter in each loop
    incerement. E.g.

    ```
    @sfg2d.multipage_pdf
    def my_plot(index, record):
        record.plot_bleach(attribute="bleach", x_axis="wavenumber", pp_delays=[index]);
        title(r"Sample @ %i fs"%record.pp_delays[index])
        xlim(2100, 2800)
        ylim(-0.003, 0.002)

    somesfgrecord = SfgRecord()
    my_plot("delme", range(2), somesfgrecord)
    ```

    plot_func: function
        ploting function with index value as and pssibly further args
        and kwargs as parameter.
        each time the index is increased and plot_func is called
        with the new index again.
    """
    from matplotlib.backends.backend_pdf import PdfPages

    def make_multipage_pdf(name, inds, *args, **kwargs):
        """
        fname: string
            filename to save the multipage pdf in.
        indes: iterable
            iterable to loop over
        args and kwargs get passed to the plot function you use this
        decorator on.
        """
        if name[-4:] != '.pdf':
            name += '.pdf'
        with PdfPages(name) as pdf:
            for index in inds:
                fig, ax = plt.subplots()
                plot_func(index, *args, **kwargs)
                pdf.savefig()
                plt.close()

        print("Saved figure to: {}".format(path.abspath(name)))
    return make_multipage_pdf

def save_figs_to_multipage_pdf(figs, fpath):
    """Save a list of figures into a multipage pdf.

    figs: list of figures to save to a multipage pdf.
    fpath: filepath of the pdf to save to.
    """
    from matplotlib.backends.backend_pdf import PdfPages

    if fpath[-4:] != '.pdf':
        fpath += '.pdf'

    with PdfPages(fpath) as pdf:
        for fig in figs:
            pdf.savefig(fig)

    print("Saved figure to: {}".format(path.abspath(fpath)))

def plot_spec(xdata, ydata, *args, ax=None, xlabel='Wavenumber in 1/cm', ylabel='SFG Intensity in a.u.', **kwargs):
    """
    Plot data with pixel axis of ydata as x-axis

    xdata: 1d numpy array for x-axis values.
    ydata: 4d numpy array with [delay, frame, spec, pixel]
    ax: axis obj to plot on
    xlabel: Label of the x-axis

    **kwargs are passed to ax.plot

    """
    if not ax:
        ax = plt.gca()

    for delay in ydata:
        for frame in delay:
            for spec in frame:
                ax.plot(xdata, spec.T, *args, **kwargs)

    if xlabel:
        ax.set_xlabel(xlabel)
    if ylabel:
        ax.set_ylabel(ylabel)

def plot_track(ydata, *args, xdata=None, ax=None, xlabel="RunNumber", ylabel='SFG Intensity', **kwargs):
    """A Track is a Time wise plot of the data.

    **Arguments:**
      - **ydata**: 4d Numpy array to create plot from

    **Keywords:**

    """
    if not ax:
        ax = plt.gca()
    delays, frames, spectra, pixel = ydata.shape
    if pixel != 1:
        raise IOError

    if delays != 1:
        raise IOError

    data = ydata[0, :, :, 0]
    if isinstance(xdata, type(None)):
        plt.plot(data, *args, **kwargs)
    else:
        plt.plot(xdata, data, *args, **kwargs)

def plot_trace(xdata, ydata, ax=None, yerr=None, xlabel='Time in fs', ylabel='Bleach in a.u.', **kwargs):
    """
    data is the result of a subselection.

    This plot has delays on its x-axis.

    yerr Error bar for the trace. Must have no frame dimension.
    if yerr is given frame dimension must be 1.
    """
    if not ax:
        ax = plt.gca()

    # Transpose because we want the delay axis to be the last axis
    # of the array.
    kwargs.setdefault('marker', 'o')

    y = ydata.T
    for i in range(len(y)):
        pixel = y[i]
        for j in range(len(pixel)):
            spec = pixel[j]
            if isinstance(yerr, type(None)):
                for frame in spec:
                    ax.plot(xdata, frame.T, **kwargs)
            else:
                plt.errorbar(xdata, spec[0], yerr[:, j, i], axes=ax, **kwargs)

def plot_contour(
        x, y, z,
        colorbar=True,
        xlabel='Time in fs',
        ylabel='Wavenumber in 1/cm',
        levels=np.linspace(0.8, 1.1, 15),
        xlim=None,
        ylim=None,
        **kwgs
):
    """Make Contour plot.

    If no levels kwgs is given, a 5 t0 80 percentile with 15 levels is used.
    colorbar: boolean for colorbar
    xlabel: string for xlabel
    ylabel: string for ylabel

    **Keywords:**
      - **levels**: Contour levels  array or number of levels.

    kwgs are passed to *plt.contourf*
    """
    if isinstance(levels, int):
        levels = np.linspace(z.min(), z.max(), levels)
    kwgs.setdefault('extend', 'both')
    kwgs.setdefault('levels', levels)

    plt.contourf(x, y, z, **kwgs)
    if colorbar:
        plt.colorbar()
    if xlabel:
        plt.xlabel(xlabel)
    if ylabel:
        plt.ylabel(ylabel)
    if xlim:
        plt.xlim(*xlim)
    if ylim:
        plt.ylim(*ylim)

def plot_trace_fit(
        xdata,
        ydata,
        yerr=None,
        fit_func=None,
        box_str=None,
        box_coords=None,
        x_fit_range=None,
        y_fit_range=None,
        xsample=400,
        ax=None,
        xlabel='Time in fs',
        ylabel='Relative Bleach',
        data_kws={},
        fit_kws={},
        text_kws={},
):
    """
    xdata: data of the x axis
    ydata: data of the y axis
    yerr: yerr of the data
    fit_func: function of xdata that is the fit result
    x_fit_range: xmin and xmax of the effective fit region
    y_fit_range: ymin and ymax of the effective fit region
    xsample: number of samples to plot the fit func with
    ax: axes obj to draw on
    xlabel: xlabel of the plot
    ylabel: ylabel of the plot
    box_str: string of fit parameters to plot
    box_coords: tuple coordinates of the parameter box
    data_kws: keywords passed to the data plot.
    fit_kws: keywords passed to the plot of the fit.
    text_kws: keywords passed to the text box
    """
    if not ax:
        ax = plt.gca()
    else:
        plt.sca(ax)

    data_kws.setdefault('label', 'Data')
    if not isinstance(yerr, type(None)):
        data_kws.setdefault('fmt', 'o')
        plt.errorbar(xdata, ydata, yerr, **data_kws)
    else:
        ax.plot(xdata, ydata, **data_kws)

    if fit_func:
        xsample = np.linspace(xdata[0], xdata[-1], xsample)
        fit_kws.setdefault('label', 'Fit')
        ax.plot(xsample, fit_func(xsample), **fit_kws)
        color = ax.lines[-1].get_color()
        fit_kws['label'] = None
        ax.plot(xdata, fit_func(xdata), 'o', color=color, **fit_kws)

    if not isinstance(x_fit_range, type(None)) and not isinstance(y_fit_range, type(None)):
        ax.scatter(x_fit_range, y_fit_range, color='r', zorder=3)

    if box_str:
        text_kws.setdefault('fontdict', {})
        text_kws['fontdict'].setdefault('family', 'monospace')
        if isinstance(box_coords, type(None)):
            box_coords = xdata.mean(), ydata.mean()
        ax.text(*box_coords, box_str, **text_kws)

    ax.legend()
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

# Plots on Records.
def bleach_plot_slider(
        record,
        select_kws={},
        x_prop='wavenumber',
        plot_kwgs={},
        scale=1,
        fig=None,
        ax=None,
        ylim=None,
        xlim=None,
        l_kwgs={"loc": "lower left"},
):
    """Bleachplot, with slidable pp_delay index and autoscale.

    **Keywrords:**
      - **record**: The record to plot
      - **select_kw**: Select keywords to select data with.
         The default corresponds to:
         `{'prop': 'bleach', 'prop_kwgs':'{'prop':'basesubed'},
          'frame_med': True, 'medfilt_pixel':5}`
      - **scale**: Scaling factor for the data.
      - **fig**: figure
      - **ax**: axes
      - **ylim**: Optional tuple. Set fix ymin and ymax.
      - **xlim**: tuple to set xaxis.
      - **l_kwgs**: Keywordsfor the plot legend
    """
    from ipywidgets import interact, widgets

    if not fig and not ax:
        fig, ax = plt.subplots()
    else:
        if not fig:
            fig = plt.figure()
        if not ax:
            ax = fig.add_subplot(111)

    axes_lim_buffer = None

    select_y_kws = dict(**select_kws)
    select_y_kws.setdefault('prop', 'bleach')
    select_y_kws.setdefault('prop_kwgs', {'prop': 'basesubed'})
    select_y_kws.setdefault('frame_med', True)
    select_y_kws.setdefault('medfilt_pixel', 5)

    @interact(
        Autoscale=True,
        index=widgets.IntSlider(
            max=record.number_of_pp_delays-1,
            continuous_update=False
        )
    )
    def my_plot(Autoscale, index):
        global axes_lim_buffer

        ax.clear()
        y = record.select(
            roi_delay=slice(index, index+1),
            **select_y_kws,
        )
        plot_spec(record.select(x_prop), scale*y, **plot_kwgs)

        if Autoscale:
            axes_lim_buffer = ax.get_xlim(), ax.get_ylim()

        if not isinstance(ylim, type(None)):
            ax.set_ylim(*ylim)
        elif not Autoscale:
            ax.set_ylim(axes_lim_buffer[1])

        if not isinstance(xlim, type(None)):
            ax.set_xlim(*xlim)
        elif not Autoscale:
            ax.set_xlim(axes_lim_buffer[0])

        ax.legend(**l_kwgs)
        ax.figure.canvas.draw()

    return fig, ax

@ioff
def bleach_plot_pdf(
        record,
        sfile,
        sfolder="./figures/",
        select_kws={},
        plot_kwgs={},
        scale=1,
        xlim=None,
        ylim=None,
        x_prop='wavenumber',
        num_base='bl{}',
        xlabel='Wavenumber in 1/cm',
        ylabel=None,
        l_kwgs={"loc": "lower left"},
        title_prefix=None,
        delay_offset=0,
):
    """Multipage pdf for the bleach plot.

    **Arguments**:
      - **record**: Record to plot data of
      - **sfile**: String with filename to save.
    **Keywords**:
      - **sfolder**: String with foldername to save file in.
      - **select_kws**: Dict with keywords for selection of data.
        default corresponds to:
          {'prop': 'bleach', 'prop_kwgs':'{'prop':'basesubed'},
          'frame_med': True, 'medfilt_pixel':5}`
      - **plot_kwgs**: Keywords passed to the `plot_spce` function.
      - **scale**: Scaling factor for the data.
      - **ylim**: Optional tuple. Set fix ymin and ymax.
      - **xlim**: tuple to set xaxis.
      - **x_prop**: Propertie of the x axis
      - **num_base**: String to index the multiple plots with.
      - **xlabel**: String for the xlabel
      - **ylabel**: string for the y label
      - **l_kwgs**: Keywordsfor the plot legend
      - **title_prefix**: Optinal String to prefix the title with.
      - **delay_offset**: Offset to add to the delay.
    axes limits are always the same for all subplots.
    """

    select_y_kws = dict(**select_kws)
    select_y_kws.setdefault('prop', 'bleach')
    select_y_kws.setdefault('prop_kwgs', {'prop': 'basesubed'})
    select_y_kws.setdefault('frame_med', True)
    select_y_kws.setdefault('medfilt_pixel', 5)
    figs = []
    for index in range(record.number_of_pp_delays):
        fig, ax = plt.subplots(num=num_base.format(index))
        figs.append(fig)

        y = record.select(
            roi_delay=slice(index, index+1),
            **select_y_kws,
        )
        x = record.select(prop=x_prop)
        plot_spec(x, scale*y, ax=ax, **plot_kwgs)

        if not title_prefix:
            title_prefix = record.metadata.get('material', '')
        ax.set_title("{} @ {} fs".format(
            title_prefix, record.pp_delays[index]+delay_offset)
        )
        ax.set_xlim(xlim)
        if xlabel:
            ax.set_xlabel(xlabel)
        if ylabel:
            ax.set_ylabel(ylabel)

    # Prepare axes limits
    if isinstance(ylim, type(None)):
        ylim = [0, 0]
        for fig in figs:
            axes = fig.get_axes()
            for ax in axes:
                if ax.get_ylim()[0] < ylim[0]:
                    ylim[0] = ax.get_ylim()[0]
                if ax.get_ylim()[1] > ylim[1]:
                    ylim[1] = ax.get_ylim()[1]
    ymin, ymax = ylim

    for fig in figs:
        for ax in fig.get_axes():
            ax.set_ylim(ylim)

    save_figs_to_multipage_pdf(figs, sfolder+sfile)
    for fig in figs:
        plt.close(fig.number)

def plot_record_static(
        record,
        save=True,
        scale=1000,
        select_kw={},
        x_prop='wavenumber',
        **kwargs
):
    """Figure of Static data from a record.

    High level function.

    record: Record to get data from
    save: Boolean, Save figure
    scale: Scale y axis.
    select_kw: dict passed to select method

    Returns
      fig and ax.
    """
    fig, ax = plt.subplots(num='{}_static'.format(record.name))
    fig.clf()
    select_kw.setdefault('delay_mean', True)
    select_kw.setdefault('frame_med', True)
    select_kw.setdefault('prop', 'unpumped')
    data = record.select(**select_kw)
    plot_spec(record.select(x_prop), scale*data, **kwargs)
    plt.title("{}".format(record.lname))
    fname = 'figures/{}_static.pdf'.format(record.name)
    print(fname)
    if save:
        plt.savefig(fname)
        print("saved")
    return fig, ax

def plot_record_contour(
        record,
        levels=(90, 105, 15),
        save=True,
        xlim=(-1000, 5000),
        fname_form='./figures/{}_contour_bleach_rel_pump{}.pdf',
        fig_num=None,
):
    if not fig_num:
        fig_num = '{}_contour'.format(record.name)
    fig, ax = plt.subplots(
        figsize=1*np.array([10, 6]), num=fig_num,
    )
    fig.clf()
    x, y, z = record.contour(
        z_property='bleach',
        prop_kwgs={'opt': 'rel', 'prop': 'basesubed'},
        resample_freqs=30,
        medfilt_pixel=7
    )
    plot_contour(x, y, 100*z, levels=np.linspace(*levels))
    plt.title("{} Pump @ {} 1/cm".format(record.lname, record.pump_freq))
    plt.tight_layout()
    plt.xlim(*xlim)
    if save:
        fname = fname_form.format(
            record.name, record.pump_freq
        )
        print('Saving to {}'.format(fname))
        plt.savefig(fname)
    return fig, ax

def plot_model_data(model, kwargs_data=None, kwargs_fit=None, plot_data=True, plot_fit=True, ax=None, **kwargs):
    """Plot data and fit of model  object.
    kwargs_data are passed to kwargs of data plot
    kwargs_fit are passed to kwargs of fit
    kwargs are passed to both plot functions of data and fit
    """
    if not ax:
        ax = plt.gca()
    if not kwargs_data:
        kwargs_data = {}
    if not kwargs_fit:
        kwargs_fit = {}
    kwargs_data.setdefault('fmt', 'o')

    if plot_data:
        ax.errorbar(
            model.xdata, model.ydata, model.sigma,
            **{**kwargs, **kwargs_data}
        )
    if plot_fit:
        ax.plot(
            model.xsample, model.ysample, **{**kwargs, **kwargs_fit}
        )
    return ax

def plot_model_trace(
        name,
        model,
        record,
        xlim=(-1200, 5100),
        ylim=(0.90, 1.02),
        save=True,
        fname_format='figures/{}_trace_bleach_rel_pump{}_{}_fit.pdf',
        title=None,
):
    fig, ax = plt.subplots(
        num='{}'.format(name)
    )
    fig.clf()
    if not title:
        plt.title(name)
    else:
        plt.title(title)
    plot_trace_fit(
        model.xdata,
        model.ydata,
        model.sigma,
        model.fit_res,
        model.box_str,
        model.box_coords,
        model.x_edges,
        model.y_edges,
    )
    if not isinstance(xlim, type(None)):
        plt.xlim(*xlim)
    if not isinstance(ylim, type(None)):
        plt.ylim(*ylim)
    fname = fname_format.format(
        record.name, record.pump_freq, name)
    print('Filename: ', fname)
    if save:
        print("Saved")
        plt.savefig(fname)
    return fig, ax

# DEPRECATED
def plot_time(time, data, **kwargs):
    """ Wrapper function to plot formatted time on the x-axis
    and data on the y axis. If time is datetime obj, the time is
    plotted in HH:MM, if time is timedelta it is plotted as minuits

    Parameters
    ----------
    time: list of datetime or timedelta
        The times for the x-axis
    data: array like
        The data for the Y axis
    """
    import datetime
    from matplotlib.dates import DateFormatter

    fig = plt.gcf()
    ax = plt.gca()
    if isinstance(time[0], datetime.datetime):
        fig.autofmt_xdate()
        xfmt = DateFormatter('%H:%M')
        ax.xaxis.set_major_formatter(xfmt)
        plt.xlabel("Time")
    if isinstance(time[0], datetime.timedelta):
        time = [elm.seconds//60 for elm in time]
        plt.xlabel('Minutes')
        plt.xlabel("Time in min")

    l0 = plt.plot(time, data, **kwargs)
    plt.plot(time, data, 'o', color=l0[0].get_color())

    # Append 5% margin left and right to the plot,
    # so that it looks nicer
    x_range = max(time) - min(time)
    x_range *= 0.05
    plt.xlim(min(time) - x_range, max(time) + x_range)

def frame_track(
        record,
        ax=None,
        y_property='basesubed',
        frame_track_kwg={},
        **kwargs
):
    """Sane default for plotting a frame track.

    frame_track_kwg are passed to `SfgRecord.frame_track`"""
    if y_property:
        frame_track_kwg["y_property"] = y_property
    if not ax:
        ax = plt.gca()
    data = record.frame_track(**frame_track_kwg)
    ax.plot(data, "-o", **kwargs)
    ax.set_title("Mean Signal vs Frame Number")
    ax.set_xlabel("Frame Number")
    ax.set_ylabel("Mean Counts")

def time_track(
        record,
        ax=None,
        xlim=None,
        ylim=None,
        title='Time Track of Scan',
        **kwargs
):
    """Plot a time track.

    For kwargs see *SfgRecod.plot_time_track*
    """
    if not ax:
        ax = plt.gca()

    record.plot_time_track(ax=ax, **kwargs)
    plt.vlines(
        record.number_of_pp_delays*np.arange(record.number_of_frames),
        ax.get_ylim()[0],
        ax.get_ylim()[1],
    )
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    ax.set_title(title)


import itertools
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

def midpoints_to_edges(x_arr):
    if x_arr[0] < x_arr[-1]:
        flip = False
    else:
        flip = True
        x_arr = x_arr[::-1]
    new_x_arr = np.zeros(x_arr.size+1)
    dx = x_arr[1] - x_arr[0]
    new_x_arr[:-1] = x_arr - dx/2
    new_x_arr[-1] = new_x_arr[-2] + dx
    if flip:
        new_x_arr = new_x_arr[::-1]
    return new_x_arr

def log_midpoints_to_edges(x_arr):
    if x_arr[0] < x_arr[-1]:
        flip = False
    else:
        flip = True
        x_arr = x_arr[::-1]
    xa = x_arr[0]
    xb = x_arr[-1]
    n = x_arr.size
    exp_a = np.log10(xa)
    exp_b = np.log10(xb)
    exp_dt = np.log10(x_arr[1]) - np.log10(x_arr[0])
    new_x_arr = np.logspace(exp_a-exp_dt/2,exp_b+exp_dt/2,num=n+1)
    if flip:
        new_x_arr = new_x_arr[::-1]
    return new_x_arr

class Convergence():
    def __init__(self,spec_func,convergence_params,ref_params):
        """
        Args:
            spec_func (function) : must take as arguments Delta and M, and
                return a spectroscopy object that has already performed its
                calculation
            convergence_params (list) : must be a list of numpy arrays, lists,
                or tuples (if there is only one convergence parameter, the
                format must be [[a,b,c,...]])
            ref_param (list) : must be a list of reference parameters to be
                fed to spec_func to obtain a reference signal for convergence
                comparison
"""
        self.spec_func = spec_func
        self.convergence_params = convergence_params
        self.ref_params = ref_params

    def L2_norm(self,a,b):
        return np.sqrt(np.sum(np.abs(b-a)**2)/np.sum(np.abs(b)**2))

    def run(self):
        shape = tuple([len(params) for params in self.convergence_params])
        L2norms = []
        times = []
        Ms = []
        self.ref_obj = self.spec_func(*self.ref_params)
        ref_sig = self.ref_obj.signal

        param_combinations = itertools.product(*self.convergence_params)
        for p_comb in param_combinations:
            print(p_comb)
            spec_obj = self.spec_func(*p_comb)
            sig = spec_obj.signal
            calc_time = spec_obj.calculation_time
            L2norms.append(self.L2_norm(sig,ref_sig))
            times.append(calc_time)
            Ms.append(spec_obj.efields[0].size)
            print(calc_time)

        self.Ms = np.array(Ms).reshape(shape)
        self.L2norms = np.array(L2norms).reshape(shape)
        self.times = np.array(times).reshape(shape)

class efieldConvergence(Convergence):
    def __init__(self,spec_func,dts,Deltas):
        """
        Args:
            spec_func (function) : must take as arguments Delta and M, and
                return an ndarray, which should be a spectroscopic signal
"""
        max_Delta = Deltas[-1]
        min_dt = dts[0]
        super().__init__(spec_func,[dts[1:],Deltas[:-1]],[min_dt,max_Delta])

    def plot(self):
        fig, ax = plt.subplots()

        dts, Deltas = self.convergence_params

        X,Y = np.meshgrid(log_midpoints_to_edges(dts),midpoints_to_edges(Deltas),indexing='ij')
        Xcont,Ycont = np.meshgrid(dts,Deltas,indexing='ij')
        handle = ax.pcolormesh(X,Y,self.L2norms,norm=LogNorm(vmin=self.L2norms.min(), vmax=self.L2norms.max()),shading='flat')
        cb = fig.colorbar(handle)
        cb.set_label('Relative Error',fontsize=16)
        chandle = ax.contour(Xcont,Ycont,self.L2norms,levels=np.logspace(-7,-2,num=6),colors='w')
        min_M_coords = self.find_minimum_M()
        ax.plot(*min_M_coords,'r*')
        ax.set_xscale('log')
        ax.set_xlabel('d$t$ ($\sigma$)',fontsize=16)
        ax.set_ylabel('$\Delta$ ($\sigma$)',fontsize=16)
        ax.set_xlim([dts[0],dts[-1]])
        ax.set_ylim([Deltas[0],Deltas[-1]])
        fmt = {}
        lvl_strs = [r'$10^{-7}$',r'$10^{-6}$',r'$10^{-5}$',r'$10^{-4}$',r'$10^{-3}$',r'$10^{-2}$']
        for l,s in zip(chandle.levels,lvl_strs):
            fmt[l] = s

        ax.clabel(chandle,chandle.levels,fmt=fmt,fontsize=8)

        fig.tight_layout()
        #fig.subplots_adjust(wspace=0.25)
        # fig.savefig(os.path.join(folder,'Smallwood2017_UF2Comparison.pdf'))

    def find_minimum_M(self,*,signal_threshold = 1E-2):
        inds = np.where(self.L2norms > signal_threshold)
        dts, Deltas = self.convergence_params
        Ms = np.zeros((dts.size,Deltas.size))
        for i in range(dts.size):
            for j in range(Deltas.size):
                m = round(Deltas[j]/2/dts[i])
                Ms[i,j] = 2*m+1

        Ms[inds] = np.inf
        min_ind = np.argmin(Ms)
        dt_ind,Delta_ind = np.unravel_index(min_ind,Ms.shape)
        return dts[dt_ind],Deltas[Delta_ind]


"""
equal partition subset sum problem

"""
def findsubsetsum(arr,column,row):
    dp=[False]*row
    for i in range(row):
        dp[i]=[False]*column
        dp[i][0]=True

    for i in range(1,row):
        for j in range(1,column):
            if j<arr[i-1]: #if sum is smaller than the current number then we cant take it as it can't help in attaing the sum that os smaller than this number
                dp[i][j]=dp[i-1][j]
            else:
                dp[i][j]=dp[i-1][j] or dp[i-1][j-arr[i-1]]
    if dp[-1][-1]:
        return "YES"
    return "NO"

for _ in range(int(input())): #Test cse
    n=int(input())          #Total number of element in the array
    arr=list(map(int,input().split())) # numbers in the array
    k=sum(arr)
    if k%2!=0:
        print("NO")
    else:
        print(findsubsetsum(arr,(k//2)+1,n+1))


#!/usr/bin/python3

import unittest

from exchange.interface import Market
from exchange.mock_base import Trade, InvalidTradeResultRequestException

class TradeTest(unittest.TestCase):
    def test_profit(self):
        trade = Trade(Market("Base", "Target"))
        trade.enter(1, 1)
        trade.finish(2)
        self.assertAlmostEqual(trade.profit, 100.0)

    def test_profit_fail(self):
        trade = Trade(Market("Base", "Target"))
        trade.enter(1, 1)
        with self.assertRaises(InvalidTradeResultRequestException):
            print(trade.profit)


def detetive():
    print("\n---------------Exercício 25-----------------")
    perguntas=["\nTelefonou para a vítima? ","Esteve no local do crime? ","Mora perto da vítima? ","Devia para a vítima? ","Já trabalhou com a vítima? "]
    resp =[]

    print("\nResponda apenas com sim ou não: ")
    for pergunta in perguntas:
        print(pergunta)
        perg =str(input("Resp: "))

        if perg == "sim" or perg == "não":
            resp.append(perg)
        else:
            print("valor inválido")

    pontos = resp.count("sim")

    if pontos == 2:

        print("\nClassificado como: Suspeito")

    elif pontos == 3 or pontos == 4:

        print("\nClassificado como: Cúmplice")

    elif pontos == 5:

        print("\nClassificado como: Assassino")

    elif pontos == 0 or pontos == 1:

        print("\nClassificado como: Inocente")
    else:

        print("Valor inválido")

Exercicios Python Brasil_ EstruturasDDecisão/ex25.py


from tkinter import *
import tkinter.filedialog, struct

#创建应用程序的类
class App:
    def __init__(self, master):
        #创建一个Label配件
        self.label = Label(master)
        self.label.pack(anchor=W)
        #创建一个Button配件
        self.button = Button(master, text="Start", command=self.getBinaryData)
        self.button.pack(anchor=CENTER)

    def setBinaryData(self):
        #将数值数据100, 200, 300, 400, 转换成integer类型的二进制数据
        self.bytes = struct.pack("i"*4, 100, 200, 300, 400)

    def getBinaryData(self):
        self.setBinaryData()
        #将integer类型的二进制数据, 转换成原来的数值数据(100, 200, 300, 400)
        values = struct.unpack("i"*4, self.bytes)
        self.label.config(text = str(values))

#创建应用程序窗口
win = Tk()
win.title(string = "平面数据库")

#创建应用程序类的实例变量
app = App(win)

#开始程序循环
win.mainloop()

12_数据库的应用/12.1 读取二进制文件.py

12.1 读取二进制文件.py


travel_log = [
    {"Country":"France","timeVisited":6,"cities":["Paris","Nice"]},
    {"Country":"Italy","timeVisited":20,"cities":["Rome","Napoli"]}
    ]
def AddCountry(country,timeVisited,cities):
    country = {"Country":country,"timeVisited":timeVisited,"cities":cities}
    travel_log.append(country)

AddCountry('Russia', 2,["moscow","Vienna"])

print(travel_log)


UCs=int(input())
for UC in range(UCs):
    rb=input()
    names=input().split()
    names.sort()
    count=[names.count(names[0]),names[0]]
    for i in range(1,len(names)):
        if(names[i]!=names[i-1]):
            tmp=names.count(names[i])
            if(tmp>count[0]):
                count=[tmp,names[i]]
    print(count[1],count[0])


#!/usr/bin/env python

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('benchmarks.csv')

base_time = df['mean'][0]
df['speedups'] = df['mean'].apply(lambda x: base_time/x)
df.plot(x='parameter_threads',
        y='speedups',
        xlabel='Num of Threads',
        ylabel='Speedup',
        legend=False,
        ylim=(0,6),
        title='Line Graph for Speedup')
plt.savefig('speedup_graph.png',bbox_inches='tight')


from functools import reduce

def solve():
    n,r,avg=map(int,input().split())
    ab=[]
    for i in range(n):
        ab.append(list(map(int,input().split())))
    ab.sort(key=lambda x:x[1])
    total=avg*n
    now=0
    for i in range(n):
        now += ab[i][0]
    rest=total-now
    res=0
    while rest>0:
        while ab[0][0]>=r:
            del ab[0]
        ab[0][0]+=1
        rest-=1
        res+=ab[0][1]

    print(res)

if  __name__ == '__main__' :
    solve()


N = int(input())
orzFang = list(map(int, input().split()))
route = list(map(int, input().split()))
ans = []
for i in range(N):
    path = []
    total = 0
    cur = i
    while len(path) < N:
        if cur in path:
            break
        total += orzFang[cur]
        path.append(cur)
        cur = route[cur] - 1
    ans.append(total)
for num in ans:
    print(num)


def solution(S):
    result = int(S[0])

    for i in range(1, len(S)):
        number = int(S[i])

        if(number == 0 or number == 1 or result == 0 or result == 1):
            result += number
        else:
            result *= number

    return result

def main():
    S = input()
    print(solution(S))

if (__name__ == "__main__"):
    main()

submitted/이코테/곱하기 혹은 더하기 문제 조건.py

곱하기 혹은 더하기 문제 조건.py


"""전류 신호로부터 feature를 추출."""

import copy
from typing import List, Sequence, Tuple, Union

import numpy as np
from onebone.feature import rms
from onebone.signal import positive_fft
from scipy.signal import find_peaks

from motor_hysteresis_brake.algorithm.signal_processing import preprocess_raw_data

# from util.exception import NoRotorFrequencyError
# from dto.algorithm_dto import AlgorithmDto

# logger = AlgorithmDto.api.logger

# TODO: find_empirical_freq 로 찾도록 변경
def supply_freq(freq: np.ndarray, amp: np.ndarray) -> Tuple[float, float]:
    """
    전류 신호의 주파수로부터 공급주파수와 amplitude를 계산.
    Amplitude가 최대인 주파수가 공급주파수.

    Parameters
    ----------
    freq : numpy.ndarray
        입력 주파수
    amp : numpy.ndarray
        입력 주파수의 진폭

    Returns
    -------
    f_supply : float
        공급 주파수
    amp_supply : float
        공급 주파수의 진폭

    """
    amp_supply = float(np.max(amp))
    max_index = np.where(amp == amp_supply)
    f_supply = float(freq[max_index])

    return f_supply, amp_supply

def sync_speed(f_supply: float, num_poles: int) -> float:
    """
    회전 자계의 속도(동기 속도, Synchronous Speed) 계산.

    Parameters
    ----------
    f_supply : float
        공급 주파수. Supply frequency.
    num_poles: int
        모터의 극 수

    Returns
    -------
    f_sync : float
        동기 속도.

    """
    f_sync = 2 * f_supply / num_poles
    return f_sync

def slip_rate(f_sync: float, f_rotor: float) -> float:
    """
    슬립율 계산.

    Parameters
    ----------
    f_sync : float
        동기 주파수.
    f_rotor : float
        회전자 회전 주파수.

    Returns
    -------
    slip_rate : float
        슬립율.
    """
    f_slip = f_sync - f_rotor
    slip_rate = f_slip / f_sync

    return slip_rate

def _find_symmetric_frequency_ranges_indices(
    freq: np.ndarray,
    f_reference: float,
    target_distance: float,
    distance_tolerance: Union[float, Tuple[float, float]],
):
    """레퍼런스 주파수를 기준으로 양쪽으로 목표 거리만큼 떨어진
    두 개의 목표 주파수 근처의 주파수 샘플들의 인덱스 추출"""
    # Check input arguments.
    if not isinstance(target_distance, (int, float)):
        raise TypeError("The `target_distance` type should be int or float.")

    if not isinstance(distance_tolerance, (Sequence, int, float)):
        raise TypeError(
            "The `distance_tolerance` type should be int or float or Sequence."
        )

    if isinstance(distance_tolerance, Sequence):
        if len(distance_tolerance) != 2:
            raise ValueError(
                "If `distance_tolerance` is sequence, The `distance_tolerance` length should be 2."
            )
        if distance_tolerance[-1] <= distance_tolerance[0]:
            raise ValueError(
                "The first element of `distance_tolerance` must be smaller than the second element of `distance_tolerance`."
            )
        if distance_tolerance[0] * distance_tolerance[-1] > 0:
            raise ValueError(
                "Both elements of `distance_tolerance` should not be positive."
            )

    elif isinstance(distance_tolerance, (int, float)) & (distance_tolerance <= 0):
        raise ValueError("`distance_tolerance` must be higher than zero.")

    if target_distance < freq[0] or target_distance > freq[-1]:
        raise ValueError(
            "`target_distance` should be within the minimum and maximum values of `freq`."
        )
    if target_distance <= 0:
        raise ValueError("`target_distance` must be higher than zero.")

    # 관심 구간(f_reference 기준 lower-side, upper-side)의 인덱스 추출
    f_target_lower = f_reference - target_distance
    f_target_upper = f_reference + target_distance

    try:
        imin, imax = distance_tolerance
    except (TypeError, ValueError):
        imin, imax = -distance_tolerance / 2, distance_tolerance / 2
    imax = np.min((imax, target_distance))  # `target_distance`보다 `imax`가 크면 안됨.

    region_lower_indices = np.where(
        (f_target_lower + imin - 1e-14 <= freq)
        & (freq <= f_target_lower + imax + 1e-14)
    )
    region_upper_indices = np.where(
        (f_target_upper - imax - 1e-14 <= freq)
        & (freq <= f_target_upper - imin + 1e-14)
    )

    if (region_lower_indices[0].size < 3) or (region_upper_indices[0].size < 3):
        raise ValueError(
            "There should be at least three samples within the tolerance of the target frequency."
        )

    return region_lower_indices, region_upper_indices

def find_local_maxima_peak_idx(
    freq: np.ndarray,
    amp: np.ndarray,
    f_reference: float,
    target_distance: float,
    distance_tolerance: Union[float, Tuple[float, float]],
    peak_prominence: float = None,
):
    """
    레퍼런스 주파수를 기준으로 양쪽에 목표 거리만큼 떨어진
    두개의 목표 주파수로부터 국소적인 영역에서 최대 피크값의 주파수 인덱스를 구한다.

    Parameters
    ----------
    freq : np.ndarray
        신호의 주파수 샘플 array.
    amp : np.ndarray
        신호의 주파수 샘플의 amplitude array.
    f_reference : float
        대칭의 기준이 되는 주파수 샘플
    target_distance : float
        기준 주파수 샘플로부터 떨어진 목표 거리. 단위는 Hz.
    distance_interval : float
        `target_distance`의 허용오차. 단위는 Hz.
    peak_prominence : float, default=None
        피크로 판별하기 위한 돌출 높이 조건

    Returns
    -------
    idx_max_peak_lower : numpy.ndarray
        lower-side 피크의 주파수 인덱스
    idx_max_peak_upper : numpy.ndarray
        upper-side 피크의 주파수 인덱스
    """
    (
        region_lower_indices,
        region_upper_indices,
    ) = _find_symmetric_frequency_ranges_indices(
        freq, f_reference, target_distance, distance_tolerance
    )

    # 조건에 맞는 Peaks 추출
    amp_region_lower = amp[region_lower_indices]
    amp_region_upper = amp[region_upper_indices]

    peaks_lower_indices, _ = find_peaks(amp_region_lower, prominence=peak_prominence)
    peaks_upper_indices, _ = find_peaks(amp_region_upper, prominence=peak_prominence)
    if (peaks_lower_indices.size == 0) or (peaks_upper_indices.size == 0):
        raise ValueError("No peak can be found.")

    # 공급 주파수의 lower-side와 upper-side로부터 국소적인 영역에서 최대 피크값의 인덱스 추출
    lower_peaks_indices = region_lower_indices[0][peaks_lower_indices]
    upper_peaks_indices = region_upper_indices[0][peaks_upper_indices]

    idx_max_peak_lower = lower_peaks_indices[np.argmax(amp[lower_peaks_indices])]
    idx_max_peak_upper = upper_peaks_indices[np.argmax(amp[upper_peaks_indices])]

    return idx_max_peak_lower, idx_max_peak_upper

def rotor_rotation_freq(
    freq: np.ndarray,
    amp: np.ndarray,
    f_reference: float,
    target_distance: float,
    distance_tolerance: Union[float, Tuple[float, float]],
    peak_prominence: float = None,
):
    lower_idx, upper_idx = find_local_maxima_peak_idx(
        freq,
        amp,
        f_reference,
        target_distance,
        distance_tolerance,
        peak_prominence,
    )
    f_peaks_lower = freq[lower_idx]
    f_peaks_upper = freq[upper_idx]
    f_rotor_lower = f_reference - f_peaks_lower
    f_rotor_upper = f_peaks_upper - f_reference
    f_rotor = np.mean([f_rotor_lower, f_rotor_upper])
    return f_rotor

def d_q_z_transformation(
    current_u: np.ndarray, current_v: np.ndarray, current_w: np.ndarray
) -> Tuple[np.ndarray, np.ndarray]:
    """
    Direct-quadrature-zero transformation

    Parameters
    ----------
    current_u : np.ndarray
        u상 전류 신호.
    current_v : np.ndarray
        v상 전류 신호.
    current_w : np.ndarray
        w상 전류 신호.

    Returns
    -------
    current_d: np.ndarray
        values for d-axis
    current_q: np.ndarray
        values for q-axis
    """
    current_d = (2 * current_u - current_v - current_w) / np.sqrt(6)
    current_q = (current_v - current_w) / np.sqrt(2)

    return current_d, current_q

def mmcf(current_u: np.ndarray, current_v: np.ndarray, current_w: np.ndarray) -> float:
    """
    Maxmin Crest Factor. 고정자 특성 인자.

    Parameters
    ----------
    current_u : np.ndarray
        u상 전류 신호.
    current_v : np.ndarray
        v상 전류 신호.
    current_w : np.ndarray
        w상 전류 신호.

    Returns
    -------
    mmcf : float
        Maxmin crest factor

    """
    u, v, w = current_u**2, current_v**2, current_w**2
    rms_u, rms_v, rms_w = rms(u), rms(v), rms(w)

    max_avg_peak = max(
        [np.mean(u[u > rms_u]), np.mean(v[v > rms_v]), np.mean(w[w > rms_w])]
    )
    min_rms = min([rms_u, rms_v, rms_w])
    mmcf = max_avg_peak / min_rms
    return mmcf

def remove_frequency_region(
    freq: np.ndarray, amp: np.ndarray, f_target: float, band_width: float
) -> np.ndarray:
    """
    입력 신호에서 특정 주파수의 국소 영역을 제거.
    """
    amp[np.where(np.abs(freq - f_target) <= (band_width / 2))] = 0
    return amp

def find_empirical_freq(
    freq: np.ndarray,
    amp: np.ndarray,
    f_target: float,
    interval: Union[float, Tuple[float, float]],
) -> Tuple[np.ndarray, np.ndarray]:
    """
    이론상의 기준 특성 주파주 -> 실제 특성 주파수
    특정 범위 안의 max amplitude를 갖는 주파수를 찾는다.
    """
    if isinstance(interval, Sequence):
        if len(interval) != 2:
            raise ValueError(
                "If `interval` is sequence, The `interval` length should be 2."
            )
        elif interval[-1] <= interval[0]:
            raise ValueError(
                "The first element of `interval` must be smaller than the second element of `interval`."
            )

    elif isinstance(interval, (int, float)) & (interval <= 0):
        raise ValueError("`interval` must be higher than zero.")

    if f_target < freq[0] or f_target > freq[-1]:
        raise ValueError(
            "`f_target` should be within the minimum and maximum values of `freq`."
        )

    try:
        imin, imax = interval
        region_idx = np.where((f_target + imin <= freq) & (freq <= f_target + imax))
    except (TypeError, ValueError):
        region_idx = np.where(np.abs(freq - f_target) <= interval / 2)

    if not region_idx:
        region_idx = np.argmin(np.abs(freq - f_target))

    freq_region = freq[region_idx]
    amp_region = amp[region_idx]

    if freq_region.size == 1:
        f_empirical = float(freq_region[0])
        amp_empirical = float(amp_region[0])
        return f_empirical, amp_empirical

    maximum_idx = np.argmax(amp_region)
    amp_empirical = float(amp_region[maximum_idx])
    f_empirical = float(freq_region[maximum_idx])

    return f_empirical, amp_empirical

def find_sidebands_for_rotor_fault(
    freq: np.ndarray,
    amp: np.ndarray,
    f_reference: float,
    target_distance: float,
    tolerance: Union[float, Tuple[float, float]],
    prominence: float = None,
) -> Tuple[List[float], List[float]]:
    """
    회전자 고장 특성 주파수를 구함.

    Returns
    -------
    f_rotor_fault :
        회전자 고장 특성 주파수 (negative sideband, postive sideband)
    amp_rotor_fault :
        회전자 고장 특성 주파수의 amplitude (negative sideband, postive sideband)

    """
    try:
        idx_max_peak_lower, idx_max_peak_upper = find_local_maxima_peak_idx(
            freq, amp, f_reference, target_distance, tolerance, prominence
        )

        f_peak_lower = freq[idx_max_peak_lower]
        f_peak_upper = freq[idx_max_peak_upper]
        amp_peak_lower = amp[idx_max_peak_lower]
        amp_peak_upper = amp[idx_max_peak_upper]

    except Exception as e:
        # logger.info(e.args[0])
        f_peak_lower = f_reference - target_distance
        f_peak_upper = f_reference + target_distance
        amp_peak_lower = amp[np.argmin(np.abs(freq - f_peak_lower))]
        amp_peak_upper = amp[np.argmin(np.abs(freq - f_peak_upper))]

    finally:
        f_rotor_fault = (f_peak_lower, f_peak_upper)
        amp_rotor_fault = (amp_peak_lower, amp_peak_upper)
        return f_rotor_fault, amp_rotor_fault

def sum_filtered_amplitude(
    freq: np.ndarray,
    amp: np.ndarray,
    f_supply: float,
    f_rotor: float,
    slip_ratio: float,
    band_width: float,
) -> float:
    """
    본 신호에서 특성 주파수 부분을 제거한 신호의 amplitude sum 계산.
    공급 주파수의 1 ~ 5 harmonic 성분의 주파수 범위에서 특성 주파수 성분 제거 후 나머지의 amplitude 합을 구한다.
    특성 주파수:
        공급 주파수의 harmonics
        회전자 주파수
        회전자 결함 특성 주파수
    """
    # TODO: Energy로 계산해야하는가? (squared sum root)
    # TODO: 각 항을 Residual로 게산해야하는가? (residual squared sum root)
    df = np.median(np.diff(freq))
    lowerbound_idx = int((f_supply - band_width) // df)
    upperbound_idx = int((f_supply * 5 + band_width) // df + 1)

    # 특성 주파수 선택
    target_freqs = (
        [f_supply * k for k in range(1, 6)]
        + [f_supply + f_rotor]
        + [f_supply * (1 - (k * slip_ratio)) for k in [-4, -2, 2, 4]]
    )
    new_amp = copy.deepcopy(amp)
    for target_freq in target_freqs:
        old_amp = new_amp
        new_amp = remove_frequency_region(freq, old_amp, target_freq, band_width)

    sum_filtered_amp = np.sum(new_amp[lowerbound_idx - 1 : upperbound_idx])
    sum_filtered_amp = float(sum_filtered_amp)

    return sum_filtered_amp

def harmonic_distortion(
    freq: np.ndarray,
    amp: np.ndarray,
    f_supply: float,
    harmonics: List[int],
) -> List[float]:
    """
    Total harmonic distortion.
    """
    f_supply_rms = np.max(amp)

    # f_supply의 harmonic의 empirical freq를 구함
    amp_list = []
    for harmonic in harmonics:
        _, amp_h = find_empirical_freq(
            freq, amp, harmonic * f_supply, 0.02 * harmonic * f_supply
        )
        amp_list.append(amp_h)

    harmonic_amp_rms = np.sqrt(np.sum(np.array(amp_list) ** 2))
    hd = (harmonic_amp_rms / f_supply_rms) * 100

    return hd

def energy_pvm_near_rotor_freq(
    freq_pvm: np.ndarray, amp_pvm: np.ndarray, f_rotor: float, interval: float
) -> float:
    """
    베어링 진단을 위한 feature.
    PVM 상에서 회전자 주파수 주위의 일정 범위만큼의 에너지 총량을 계산.
    """
    target_idx = np.where(np.abs(freq_pvm - f_rotor) <= interval / 2)[0]
    amp_pvm_near = amp_pvm[target_idx]
    total_energy = np.sqrt(np.mean(np.square(amp_pvm)))
    local_energy = np.sqrt(np.mean(np.square(amp_pvm_near)))
    energy_near = local_energy / total_energy
    return energy_near

def extract_diagnosis_features(raw_data_dict: dict, config: dict) -> dict:
    # 함수 아웃풋 명시
    feature_diagnosis = dict(
        freq_fl=[],
        fl=[],
        mmcf=None,
        freq_rotor4=[],
        rotor4=[],
        freq_rotor2=[],
        rotor2=[],
        freq_me=[],
        me=[],
        freq_aspv=None,
        aspv=None,
        f_pvm_rotor=None,
        amp_pvm_rotor=None,
        energy_pvm_near_rotor=None,
        slip_rate=None,
        res_amp=[],
    )
    # raw_data_dict = {'u':[1,2,3,4,5], 'v':[1,2,3,4,5], 'w':[1,2,3,4,5]}

    # 원시 전류 데이터를 전처리
    preprocessed_signal_dict = preprocess_raw_data(raw_data_dict, config["ct_ratio"])
    # 각 상에 대한 전류 신호를 FFT 후, 주파수 샘플과 진폭을 변수에 저장
    signal_fft_set = {}
    for phase, signal in preprocessed_signal_dict.items():
        freq, amp = positive_fft(signal, config["fs"], hann=True, normalization=True)
        signal_fft_set[phase] = (freq, amp)

    # 특징 추출: 각 상으로부터 공급 주파수(supply frequency)와 해당 주파수의 진폭 추출
    for freq, amp in signal_fft_set.values():
        f_supply, amp_supply = supply_freq(freq, amp)
        feature_diagnosis["freq_fl"].append(f_supply)
        feature_diagnosis["fl"].append(amp_supply)
    # 각 상의 공급 주파수들을 평균하여 대표 공급 주파수 계산
    mean_f_supply = sum(feature_diagnosis["freq_fl"]) / len(
        feature_diagnosis["freq_fl"]
    )

    # 동기 속도(Synchronous speed) 추출 (회전자계의 회전 주파수)
    f_sync = sync_speed(mean_f_supply, config["poles"])

    # 각 상으로부터 회전자 회전 주파수 계산
    uvw_f_rotor = []
    for freq, amp in signal_fft_set.values():
        f_rotor = rotor_rotation_freq(
            freq,
            amp,
            mean_f_supply,
            f_sync * (1 - config["rotor_target_slip"]),
            f_sync
            * 2
            * (
                config["rotor_target_slip"] * 2
            ),  # TODO: 슬립율에 0.005 덧셈은 임시방편. Poles수가 높은 모터에 대해 피크를 못찾음. 문제 해결 1: DAQ의 샘플 사이즈 증가 / 문제 해결 2: 로직 개선
            config["prominence"],
        )
        uvw_f_rotor.append(f_rotor)
    # if not len(uvw_f_rotor):  # 회전자 회전주파수 계산 불가시 에러 발생
    #     raise NoRotorFrequencyError
    # 각 상의 회전자 회전 주파수들을 평균하여 대표 회전자 회전주파수 계산
    f_rotor = np.mean(uvw_f_rotor)

    # 특징 추출: Slip_rate = Slip speed / Sync speed
    feature_diagnosis["slip_rate"] = slip_rate(f_sync, f_rotor)
    # 슬립 주파수 계산
    f_slip = f_sync * feature_diagnosis["slip_rate"]

    # 특징 추출: Max min crest factor(고정자 특성인자) 추출
    feature_diagnosis["mmcf"] = mmcf(
        preprocessed_signal_dict["u"],
        preprocessed_signal_dict["v"],
        preprocessed_signal_dict["w"],
    )
    # Park's Vector Modulous(PVM) 계산
    d, q = d_q_z_transformation(
        preprocessed_signal_dict["u"],
        preprocessed_signal_dict["v"],
        preprocessed_signal_dict["w"],
    )
    pvm = np.sqrt(d**2 + q**2)
    freq_pvm, amp_pvm = positive_fft(pvm, config["fs"], hann=True, normalization=True)

    # 특징 추출: Amplitude of Supply frequency of Park's Vector
    feature_diagnosis["freq_aspv"], feature_diagnosis["aspv"] = find_empirical_freq(
        freq_pvm, amp_pvm, mean_f_supply, config["aspv_window_size"]
    )

    # 특징 추출: Amplitude of Rotational frequency of Park's Vector
    (
        feature_diagnosis["f_pvm_rotor"],
        feature_diagnosis["amp_pvm_rotor"],
    ) = find_empirical_freq(
        freq_pvm, amp_pvm, f_rotor, (-config["amp_pvm_rotor_window_size"], 0)
    )

    # 특징 추출: Energy of Near Rotational frequency Park's Vector: 에너지 계산 (전후 5%)
    feature_diagnosis["energy_pvm_near_rotor"] = energy_pvm_near_rotor_freq(
        freq_pvm, amp_pvm, f_rotor, config["energy_pvm_near_rotor_interval"]
    )

    # 3상 전류 신호(u, v, w)의 특성 구하기
    for freq, amp in signal_fft_set.values():
        # 특징 추출: 회전자의 회전 주파수에 관한 공급 주파수의 사이드밴드 추출
        f_supply_upper_sideband, amp_supply_upper_sideband = find_empirical_freq(
            freq,
            amp,
            mean_f_supply + f_rotor,
            (-config["me_window_size"], 0),
        )
        f_supply_lower_sideband, amp_supply_lower_sideband = find_empirical_freq(
            freq,
            amp,
            mean_f_supply - f_rotor,
            (0, config["me_window_size"]),
        )
        feature_diagnosis["freq_me"].append(
            [f_supply_lower_sideband, f_supply_upper_sideband]
        )
        feature_diagnosis["me"].append(
            [amp_supply_lower_sideband, amp_supply_upper_sideband]
        )

        # 특징 추출: 회전자의 고장 특성 주파수 추출
        freq_rotor_4_both, amp_rotor_4_both = find_sidebands_for_rotor_fault(
            freq,
            amp,
            mean_f_supply,
            4 * f_slip,
            config["rotor_feature_slip_multiple"] * f_slip,
        )
        feature_diagnosis["freq_rotor4"].append(freq_rotor_4_both)
        feature_diagnosis["rotor4"].append(amp_rotor_4_both)

        freq_rotor_2_both, amp_rotor_2_both = find_sidebands_for_rotor_fault(
            freq,
            amp,
            mean_f_supply,
            2 * f_slip,
            0.5 * config["rotor_feature_slip_multiple"] * f_slip,
        )
        feature_diagnosis["freq_rotor2"].append(freq_rotor_2_both)
        feature_diagnosis["rotor2"].append(amp_rotor_2_both)

        # 특징 추출: 축 결함 성분 진단 인자
        filtered_amp = sum_filtered_amplitude(
            freq,
            amp,
            mean_f_supply,
            f_rotor,
            feature_diagnosis["slip_rate"],
            config["res_amp_window_size"],
        )
        feature_diagnosis["res_amp"].append(filtered_amp)

    return feature_diagnosis

def extract_ems_features(
    raw_data_dict: dict, config: dict
) -> Tuple[Union[dict, None], str]:
    # 함수 아웃풋 명시
    feature_ems = dict(
        rms=None,
        max_current=None,
        min_current=None,
        mean_current=None,
        freq_3x=[],
        third_x=[],
        freq_5x=[],
        fifth_x=[],
        thd_0=[],
        thd_5=[],
    )
    # 원시 전류 데이터를 전처리
    preprocessed_signal_dict = preprocess_raw_data(raw_data_dict, config["ct_ratio"])

    # 3상 전류의 RMS와 해당 값들을 활용하여 최대, 최소, 평균값 추출
    rms_dict = {}
    for phase, signal in preprocessed_signal_dict.items():
        rms_dict[phase] = rms(signal)
    uvw_rms = [rms_dict["u"], rms_dict["v"], rms_dict["w"]]
    feature_ems["rms"] = uvw_rms
    feature_ems["max_current"] = max(uvw_rms)
    feature_ems["min_current"] = min(uvw_rms)
    feature_ems["mean_current"] = np.array(uvw_rms).mean()

    # 3상 전류 신호(u, v, w)의 특성 구하기
    for phase, signal in preprocessed_signal_dict.items():
        # 시간 영역의 전류 신호를 FFT
        freq, amp = positive_fft(signal, config["fs"], hann=True, normalization=True)
        # 공급 주파수(supply frequency) 계산
        f_supply, _ = supply_freq(freq, amp)
        # 고정자 진단 인자, 공급 주파수의 홀수 배의 harmonic 성분 확인
        f_3x, amp_3x = find_empirical_freq(
            freq, amp, f_supply * 3, config["third_x_window_size"]
        )
        feature_ems["freq_3x"].append(f_3x)
        feature_ems["third_x"].append(amp_3x)

        f_5x, amp_5x = find_empirical_freq(
            freq, amp, f_supply * 5, config["third_x_window_size"]
        )
        feature_ems["freq_5x"].append(f_5x)
        feature_ems["fifth_x"].append(amp_5x)

        # 에너지의 비율을 구하기 위한 특성 계산
        feature_ems["thd_0"].append(
            harmonic_distortion(freq, amp, f_supply, [3, 5, 7, 9])
        )
        feature_ems["thd_5"].append(
            harmonic_distortion(freq, amp, f_supply, [2 * i + 1 for i in range(1, 25)])
        )

    return feature_ems


# -*- coding: utf-8 -*-
# Project: local-spark
# Author: chaoxu create this file
# Time: 2018/2/6
# Company : Maxent
# Email: chao.xu@maxent-inc.com

from __future__ import division, print_function
import keras.backend as K
import numpy as np
from itertools import product

def w_categorical_crossentropy(y_true, y_pred, weights):
    nb_cl = len(weights)
    final_mask = K.zeros_like(y_pred[:, 0])
    y_pred_max = K.max(y_pred, axis=1)
    y_pred_max = K.expand_dims(y_pred_max, 1)
    y_pred_max_mat = K.equal(y_pred, y_pred_max)
    for c_p, c_t in product(range(nb_cl), range(nb_cl)):
        final_mask += (K.cast(weights[c_t, c_p], K.floatx()) *
                       K.cast(y_pred_max_mat[:, c_p], K.floatx()) *
                       K.cast(y_true[:, c_t], K.floatx())
                       )
    return final_mask

if __name__ == '__main__':
    w_array = np.ones((2, 2))
    w_array[1, 0] = 1.2
    w_array[0, 1] = 1.2
    a = K.variable(np.array([1, 0, 0]))
    b = K.variable(np.array([1, 1, 1]))
    s = K.eval(w_categorical_crossentropy(a, b, w_array))
    print(s)


from tkinter import *
App = Tk()
App.geometry('300x200')
option_menue= StringVar()
lst = ['red', 'white', 'green']
sld = OptionMenu(App, option_menue, *lst)
option_menue.set('white')
sld.pack()
def show():
    msg = Label(App, text = ' ', background = (option_menue.get()).lower())
    msg.pack()

B = Button(App, text = 'show', command = show)
B.pack()

App.mainloop()


from os import listdir, makedirs
from sys import argv
import numpy as np
import os

total, total_hq = 0, 0
base_path = argv[1]
base_path_hq = argv[2]
k = float(argv[3])

for lang_pair in sorted(listdir(base_path)):
    l = lang_pair.split('-')[-1]
    with open(os.path.join(base_path, lang_pair, f"train.{l}")) as fl, \
         open(os.path.join(base_path, lang_pair, "train.en")) as fe:
        indic = np.array(fl.readlines(), dtype=object)
        en = np.array(fe.readlines(), dtype=object)
        labse = np.loadtxt(os.path.join(base_path, lang_pair, "labse.txt"), dtype=float)
        # comet = np.loadtxt(os.path.join(base_path, lang_pair, "comet.txt"), dtype=float)

    u, s = labse.mean(), labse.std()
    total += len(indic)

    msk = (labse > (u + k*s))
    # msk = labse > k
    # indic_hq, en_hq = indic[msk], en[msk]
    indic_hq, en_hq, labse_hq = indic[msk], en[msk], labse[msk]
    # indic_hq, en_hq, labse_hq, comet_hq = indic[msk], en[msk], labse[msk], comet[msk]
    total_hq += len(indic_hq)

    print(lang_pair, len(indic_hq), len(indic), len(indic_hq)/len(indic))

    # makedirs(os.path.join(base_path_hq, lang_pair), exist_ok=True)

    # with open(os.path.join(base_path_hq, lang_pair, f"train.{l}"), 'w') as fl, \
    #      open(os.path.join(base_path_hq, lang_pair, "train.en"), 'w') as fe:
        # fl.write(''.join(indic_hq))
        # fe.write(''.join(en_hq))
        # np.savetxt(os.path.join(base_path_hq, lang_pair, "labse.txt"), labse_hq, delimiter='\n')
        # np.savetxt(os.path.join(base_path_hq, lang_pair, "comet.txt"), comet_hq, delimiter='\n')

print('total', total, total_hq, total_hq/total)


'''
bob_ltf 输出 bobLtf
'''
s='bob_ltf_lsq_fjf'
s1=''
s2=''
arr=s.split('_') #列表
print(arr)
s1=s1.join(arr[1:])
print(s1.capitalize())
s2=s2.join(arr[:1])
s3=s2+s1.capitalize()
print(s3)
'''
输出结果
['bob', 'ltf', 'lsq', 'fjf']
Ltflsqfjf
bobLtflsqfjf
'''


import pandas as pd
import matplotlib.pyplot as plt
from getProductList import getProductList
import numpy as np

def extract(x):
    x=x.replace("."," ")
    x=x.replace("+"," ")
    driver=getProductList()
    x=driver.preprocess(x)
    return x

df=pd.read_csv("customerRequest.csv",engine='python')
df["Products"]=df["Products"].apply(lambda x:extract(x))
df['Products'].replace('', np.nan, inplace=True)
df=df.dropna(how='any')
plt.title("Products Viewed by Customers")
plt.xlabel("Products")
plt.ylabel("Number of Customers")
plt.hist(df['Products'].values)
plt.show()


"""
This script randomly samples a set of hyperparameters for the evolutionary and WGAN explorers and runs them on a set of 50 sequences.

This enables us to benchmark the performance of many hyperparameter sets and choose the one with the best performance.
"""

# Importing standard packages
from scipy.stats import uniform
import traceback
import timeit
import argparse
import pandas as pd
import multiprocessing
from multiprocessing import set_start_method
import os.path as path
from collections import Counter
from operator import itemgetter
import time
import numpy as np
import os
import random

# Importing MEA packages
from mea.models.cas13_mult import Cas13Mult
from mea.models.cas13_diff import Cas13Diff

from mea.utils.cas13_landscape import Cas13Landscape
from mea.utils import prepare_sequences as prep_seqs
from mea.explorers.evolutionary import EvolutionaryExplorer
from mea.explorers.wgan_am import WGANExplorer
from mea.utils import import_fasta

def wgan_run(results_dir, alphabet, target_set1, target_set2, site_pos, seq_id, seed):
    # Run the WGAN-AM algorithm with randomly sampled hyperparameters

    f = open(results_dir + "job-tracker.txt", "a")
    f.write("\nwgan_seed{}_{}".format(seed, seq_id))
    f.close()
    start = timeit.default_timer()

    try:
        np.random.seed(seed)

        curr_grid = {'c': 1.0, 'a' : float(uniform.rvs(.1, 9, size=1)[0]), 'k': float(uniform.rvs(-4, 3, size=1)[0]),
        'o': float(uniform.rvs(-4.5, 3.0, size=1)[0]), 't2w' : float(uniform.rvs(.1, 10, size=1)[0])}

        learning_rate = 10**uniform.rvs(-2, 4, size=1)[0]

        outer_rounds = int(uniform.rvs(5, 10, size=1)[0])
        inner_rounds = int(uniform.rvs(50, 180, size=1)[0])

        hyperparams = pd.DataFrame({'optimizer': ['adam'], 'learning-rate': [learning_rate], 'seed': [seed], 'seq_id': [seq_id], 'species': [seq_id.split('.')[0]],
        'outer_rounds': [outer_rounds], 'inner_rounds': [inner_rounds],
        'c': [curr_grid['c']], 'a': [curr_grid['a']], 'k': [curr_grid['k']], 'o': [curr_grid['o']], 't2w': [curr_grid['t2w']]})

        cas13landscape = Cas13Landscape()

        cas13diff = Cas13Diff(cas13landscape, target_set1, target_set2, curr_grid)

        starting_sequence = prep_seqs.consensus_seq(cas13diff.target_set1_nt, nt = True)
        baseline_fitness = cas13diff.get_fitness([starting_sequence[10:-10]])

        wgan_explorer = WGANExplorer(
            cas13diff,
            rounds=outer_rounds,
            starting_sequence=starting_sequence,
            inner_iterations=inner_rounds,
            adam_lr = learning_rate,
            optimizer = optimizer,
            sequences_batch_size=100,
            model_queries_per_batch=2000,
            )

        wgan_sequences, metadata = wgan_explorer.run(cas13diff, seq_id)

        save_rand_results(wgan_sequences, hyperparams, 'wgan', results_dir, start, target_set1 + target_set2, starting_sequence[10:-10], cas13diff, seq_id)

    except Exception:
        f = open(results_dir + "job-tracker.txt", "a")
        print(traceback.format_exc())
        f.write("\nERROR")
        f.write(traceback.format_exc())
        f.close()

def evolutionary_run(results_dir, alphabet, target_set1, target_set2, site_pos, seq_id, seed):
    # Run the evolutionary algorithm with randomly sampled hyperparameters

    f = open(results_dir + "job-tracker.txt", "a")
    f.write("\nevolutionary_seed{}_{}".format(seed, seq_id))
    f.close()
    start = timeit.default_timer()

    try:
        np.random.seed(seed)

        curr_grid = {'c': 1.0, 'a' : float(uniform.rvs(.1, 9, size=1)[0]), 'k': float(uniform.rvs(-4, 3, size=1)[0]),
        'o': float(uniform.rvs(-4.5, 3.0, size=1)[0]), 't2w' : float(uniform.rvs(.1, 10, size=1)[0])}

        model_queries_per_batch = 1500 # Could try sampling, but 1500 is standard
        S = int(uniform.rvs(50, 200, size=1)[0])
        j = uniform.rvs(0.1, 0.8, size=1)[0]

        beta = 10**uniform.rvs(-2, 4, size=1)[0]

        gamma = float(uniform.rvs(0, 2, size=1)[0]/28)

        hyperparams = pd.DataFrame({'seed': [seed], 'seq_id': [seq_id], 'species': [seq_id.split('.')[0]], 'S': [S], 'j': [j],
        'beta': [beta], 'gamma': [gamma], 'model_queries': [model_queries_per_batch],
        'c': [curr_grid['c']], 'a': [curr_grid['a']], 'k': [curr_grid['k']], 'o': [curr_grid['o']], 't2w': [curr_grid['t2w']]
        })

        cas13landscape = Cas13Landscape()

        cas13diff = Cas13Diff(cas13landscape, target_set1, target_set2, curr_grid)

        starting_sequence = prep_seqs.consensus_seq(cas13diff.target_set1_nt, nt = True)
        baseline_fitness = cas13diff.get_fitness([starting_sequence[10:-10]])

        evolutionary_explorer = EvolutionaryExplorer(
            cas13diff,
            S=S,
            beta=beta,
            j=j,
            rounds=1,
            starting_sequence= starting_sequence,
            gamma = gamma,
            sequences_batch_size=50,
            model_queries_per_batch=model_queries_per_batch,
            alphabet=alphabet
            )

        evolutionary_seqs, metadata = evolutionary_explorer.run(cas13diff, seq_id)

        save_rand_results(evolutionary_seqs, hyperparams, 'evolutionary', results_dir, start, target_set1 + target_set2, starting_sequence[10:-10], cas13diff, seq_id)

    except Exception:
        f = open(results_dir + "job-tracker.txt", "a")
        print(traceback.format_exc())
        f.write("\nERROR")
        f.write(traceback.format_exc())
        f.close()

def save_rand_results(df, hyperparams, algo, results_dir, start, target_set, baseline_guide, cas13diff, seq_id):
    # Save the results of the random search to a csv file

    stop = timeit.default_timer()

    print('saving results...')

    hyperparams['runtime'] = (stop - start)/60

    start_df = df.iloc[0]
    guide_df = df.iloc[1:]
    best_guide_df = guide_df[guide_df.model_score == guide_df.model_score.max()].iloc[0]
    gen_guide_nt = best_guide_df.sequence
    score = best_guide_df.model_score

    hyperparams['nearest_hd'] = min([prep_seqs.amming_dist(gen_guide_nt, target[10:-10]) for target in target_set])
    hyperparams['fitness'] = cas13diff._fitness_function(gen_guide_nt, output_type='eval')[0][2]
    hyperparams['baseline_fitness'] = cas13diff._fitness_function(baseline_guide, output_type='eval')[0][2]

    hyperparams['t1_act'] = cas13diff._fitness_function(gen_guide_nt, output_type='eval')[0][0]
    hyperparams['t2_act'] = cas13diff._fitness_function(gen_guide_nt, output_type='eval')[0][1]

    hyperparams['baseline_t1_act'] = cas13diff._fitness_function(baseline_guide, output_type='eval')[0][0]
    hyperparams['baseline_t2_act'] = cas13diff._fitness_function(baseline_guide, output_type='eval')[0][1]

    hyperparams['delta_fitness'] = hyperparams['fitness'] - hyperparams['baseline_fitness']

    hyperparams['sequence'] = gen_guide_nt
    hyperparams['baseline_guide'] = baseline_guide

    results_path = results_dir + '{}_rand-search_{}.pkl'.format(algo, random.random())
    hyperparams.to_pickle(results_path)

    # if(path.exists(results_path)):
    #     time.sleep(np.random.choice(np.arange(10, 60)))
    #     old_results = pd.read_pickle(results_path)
    #     upd_results = old_results.append(hyperparams)
    #     upd_results.to_pickle(results_path)
    #     upd_results.to_csv(results_dir + '{}_rand-search_{}.pkl'.format(algo, random.random()))
    # else:
    #     hyperparams.to_pickle(results_path)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('run_id',
        help=("number of the seq to run"),
        type = int)

    args = parser.parse_args()

    set_start_method("spawn")
    num_cpu = 70

    data_dir = './figures/discrimination/50seqs_synmismatch.pkl'
    site_df = pd.read_pickle(data_dir).reset_index(drop=True)

    results_name = './discrimination/gen_results/parallel-final-random-search'
    results_dir = results_name + '/'

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

    alphabet = 'ACGT'

    cmd = []

    for explorer in ['evolutionary_run','wgan_run']:
            for seed in range(100):
                for idx, site in site_df.iterrows():
                    cmd.append([explorer, results_dir, alphabet, site.target_set1_nt, site.target_set2_nt , site.seq_id, site.target1_name + '_vs_' + site.target2_name, seed])

    print(len(cmd))
    cmd = cmd[args.run_id]

    explorer = cmd[0]
    results_dir = cmd[1]
    alphabet = cmd[2]
    target_set1_nt = cmd[3]
    target_set2_nt = cmd[4]
    site_id = cmd[5]
    seq_id = cmd[6]
    seed = cmd[7]

    exec(f'{explorer}(results_dir, alphabet, target_set1_nt, target_set2_nt , site_id, seq_id, seed)')


# Count the number of subset with given sum

arr = [1,1,2,3]
sum1= sum(arr)
n=len(arr)
lst=[]

t = [[-1 for j in range(sum1+1)] for i in range(n+1)]

# Initialization with Base Condition

for i in range(n+1):
    for j in range(sum1+1):
        if i == 0:
            t[i][j] = 0
        if j==0:
            t[i][j] = 1

# Start loop from 1 as 0th row and 0th col is already handled with base condition
# Replace n with i and W with j
for i in range(1,n+1):
    for j in range(1,sum1+1):
        if arr[i-1]<=j:
            op1 = t[i-1][j-arr[i-1]]
            op2 = t[i-1][j]
            t[i][j] = op1 + op2  # Just change or to + as we need to have count
        elif arr[i-1]>j:
            t[i][j] = t[i-1][j]

print(t[n][w])

DSA-in-Python-master/Dynamic Programming/Knapsack based Problems/Count the number of subset with given sum.py


#Function that organizes all packets recieved and forwards link-state packets
def receive_and_forward(packets_received):
    global our_router, already_sent
    our_router.settimeout(0.1)

    try:
        data, addr = our_router.recvfrom(1024)
        data = data.decode("utf-8")

        if "?" in data:
            data = data.split("?")
            if (data[0] not in already_sent):
                for neighbor in router_direct:
                    our_router.sendto(bytes("?".join(data),"utf-8"),(local_host, int(router_direct[neighbor])))

                already_sent.append(data[0])
                if (data not in packets_received):
                    packets_received.append(data)
        elif data in heartbeat_dict:
            beat = heartbeat_dict[data] + 1
            heartbeat_dict[data] = beat

    except socket.timeout:
        our_router = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        our_router.bind((local_host, int(router_direct[router_id])))

    return packets_received


from .base import *  # noqa

ENVIRONMENT = "test"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

# Run rq in async mode during test (force it to use test database)
for queue_config in RQ_QUEUES.values():  # noqa
    queue_config["ASYNC"] = False


from PIL import Image
import sys
import numpy as np

from .vid import VIDDataset
from mega_core.config import cfg

class VIDMEGADataset(VIDDataset):
    def __init__(self, image_set, data_dir, img_dir, anno_path, img_index, transforms, is_train=True):
        super(VIDMEGADataset, self).__init__(image_set, data_dir, img_dir, anno_path, img_index, transforms, is_train=is_train)
        if not self.is_train:
            self.start_index = []
            self.start_id = []
            if cfg.MODEL.VID.MEGA.GLOBAL.ENABLE:
                self.shuffled_index = {}
            for id, image_index in enumerate(self.image_set_index):
                frame_id = int(image_index.split("/")[-1])
                if frame_id == 0:
                    self.start_index.append(id)
                    if cfg.MODEL.VID.MEGA.GLOBAL.ENABLE:
                        shuffled_index = np.arange(self.frame_seg_len[id])
                        if cfg.MODEL.VID.MEGA.GLOBAL.SHUFFLE:
                            np.random.shuffle(shuffled_index)
                        self.shuffled_index[str(id)] = shuffled_index

                    self.start_id.append(id)
                else:
                    self.start_id.append(self.start_index[-1])

    def _get_train(self, idx):
        filename = self.image_set_index[idx]
        img = Image.open(self._img_dir % filename).convert("RGB")

        # if a video dataset
        img_refs_l = []
        img_refs_m = []
        img_refs_g = []
        if hasattr(self, "pattern"):
            offsets = np.random.choice(cfg.MODEL.VID.MEGA.MAX_OFFSET - cfg.MODEL.VID.MEGA.MIN_OFFSET + 1,
                                       cfg.MODEL.VID.MEGA.REF_NUM_LOCAL, replace=False) + cfg.MODEL.VID.MEGA.MIN_OFFSET
            for i in range(len(offsets)):
                ref_id = min(max(self.frame_seg_id[idx] + offsets[i], 0), self.frame_seg_len[idx] - 1)
                ref_filename = self.pattern[idx] % ref_id
                img_ref = Image.open(self._img_dir % ref_filename).convert("RGB")
                img_refs_l.append(img_ref)

            # memory frames
            if cfg.MODEL.VID.MEGA.MEMORY.ENABLE:
                ref_id_center = max(self.frame_seg_id[idx] - cfg.MODEL.VID.MEGA.ALL_FRAME_INTERVAL, 0)
                offsets = np.random.choice(cfg.MODEL.VID.MEGA.MAX_OFFSET - cfg.MODEL.VID.MEGA.MIN_OFFSET + 1,
                                           cfg.MODEL.VID.MEGA.REF_NUM_MEM, replace=False) + cfg.MODEL.VID.MEGA.MIN_OFFSET
                for i in range(len(offsets)):
                    ref_id = min(max(ref_id_center + offsets[i], 0), self.frame_seg_len[idx] - 1)
                    ref_filename = self.pattern[idx] % ref_id
                    img_ref = Image.open(self._img_dir % ref_filename).convert("RGB")
                    img_refs_m.append(img_ref)

            # global frames
            if cfg.MODEL.VID.MEGA.GLOBAL.ENABLE:
                ref_ids = np.random.choice(self.frame_seg_len[idx], cfg.MODEL.VID.MEGA.REF_NUM_GLOBAL, replace=False)
                for ref_id in ref_ids:
                    ref_filename = self.pattern[idx] % ref_id
                    img_ref = Image.open(self._img_dir % ref_filename).convert("RGB")
                    img_refs_g.append(img_ref)
        else:
            for i in range(cfg.MODEL.VID.MEGA.REF_NUM_LOCAL):
                img_refs_l.append(img.copy())
            if cfg.MODEL.VID.MEGA.MEMORY.ENABLE:
                for i in range(cfg.MODEL.VID.MEGA.REF_NUM_MEM):
                    img_refs_m.append(img.copy())
            if cfg.MODEL.VID.MEGA.GLOBAL.ENABLE:
                for i in range(cfg.MODEL.VID.MEGA.REF_NUM_GLOBAL):
                    img_refs_g.append(img.copy())

        target = self.get_groundtruth(idx)
        target = target.clip_to_image(remove_empty=True)

        if self.transforms is not None:
            img, target = self.transforms(img, target)
            for i in range(len(img_refs_l)):
                img_refs_l[i], _ = self.transforms(img_refs_l[i], None)
            for i in range(len(img_refs_m)):
                img_refs_m[i], _ = self.transforms(img_refs_m[i], None)
            for i in range(len(img_refs_g)):
                img_refs_g[i], _ = self.transforms(img_refs_g[i], None)

        images = {}
        images["cur"] = img
        images["ref_l"] = img_refs_l
        images["ref_m"] = img_refs_m
        images["ref_g"] = img_refs_g

        return images, target, idx

    def _get_test(self, idx):
        filename = self.image_set_index[idx]
        img = Image.open(self._img_dir % filename).convert("RGB")

        # give the current frame a category. 0 for start, 1 for normal
        frame_id = int(filename.split("/")[-1])
        frame_category = 0
        if frame_id != 0:
            frame_category = 1

        img_refs_l = []
        # reading other images of the queue (not necessary to be the last one, but last one here)
        ref_id = min(self.frame_seg_len[idx] - 1, frame_id + cfg.MODEL.VID.MEGA.MAX_OFFSET)
        ref_filename = self.pattern[idx] % ref_id
        img_ref = Image.open(self._img_dir % ref_filename).convert("RGB")
        img_refs_l.append(img_ref)

        img_refs_g = []
        if cfg.MODEL.VID.MEGA.GLOBAL.ENABLE:
            size = cfg.MODEL.VID.MEGA.GLOBAL.SIZE if frame_id == 0 else 1
            shuffled_index = self.shuffled_index[str(self.start_id[idx])]
            for id in range(size):
                filename = self.pattern[idx] % shuffled_index[
                    (idx - self.start_id[idx] + cfg.MODEL.VID.MEGA.GLOBAL.SIZE - id - 1) % self.frame_seg_len[idx]]
                img = Image.open(self._img_dir % filename).convert("RGB")
                img_refs_g.append(img)

        target = self.get_groundtruth(idx)
        target = target.clip_to_image(remove_empty=True)

        if self.transforms is not None:
            img, target = self.transforms(img, target)
            for i in range(len(img_refs_l)):
                img_refs_l[i], _ = self.transforms(img_refs_l[i], None)
            for i in range(len(img_refs_g)):
                img_refs_g[i], _ = self.transforms(img_refs_g[i], None)

        images = {}
        images["cur"] = img
        images["ref_l"] = img_refs_l
        images["ref_g"] = img_refs_g
        images["frame_category"] = frame_category
        images["seg_len"] = self.frame_seg_len[idx]
        images["pattern"] = self.pattern[idx]
        images["img_dir"] = self._img_dir
        images["transforms"] = self.transforms

        return images, target, idx


"""
Helper module for Odometry
"""

import create2
import math

class Odometry:
    """This class keeps the current state (x,y,theta) up-to-date based
    on wheel encoder readings.
    Call the update function as frequent as possible with the current
    encoder readings.
    """
    def __init__(self):
        """Constructor.
        """
        self.x = 0
        self.y = 0
        self.theta = 0

        self.last_left_encoder_counts = None
        self.last_right_encoder_counts = None

        self.d_l = create2.Specs.WheelDiameterInMM / 1000
        self.d_r = create2.Specs.WheelDiameterInMM / 1000
        self.n_l = create2.Specs.CountsPerRev
        self.n_r = create2.Specs.CountsPerRev
        self.w = create2.Specs.WheelDistanceInMM / 1000

    def update(self, left_encoder_counts, right_encoder_counts):
        """Update function to keep the state up-to-date

        Args:
            left_encoder_counts (int)
            right_encoder_counts (int)
        """
        if self.last_right_encoder_counts is not None:
            n_l_actual = left_encoder_counts - self.last_left_encoder_counts
            n_r_actual = right_encoder_counts - self.last_right_encoder_counts
            # account for overflow
            if n_l_actual > 32768:
                n_l_actual -= 65535
            if n_r_actual > 32768:
                n_r_actual -= 65535
            if n_l_actual < -32768:
                n_l_actual += 65535
            if n_r_actual < -32768:
                n_r_actual += 65535

            c_l = math.pi * self.d_l / self.n_l
            c_r = math.pi * self.d_r / self.n_r

            delta_l = c_l * n_l_actual
            delta_r = c_r * n_r_actual

            delta_d = (delta_r + delta_l) / 2
            delta_theta = (delta_r - delta_l) / self.w

            self.x += delta_d * math.cos(self.theta)
            self.y += delta_d * math.sin(self.theta)
            self.theta = math.fmod(self.theta + delta_theta, 2 * math.pi)
        self.last_left_encoder_counts = left_encoder_counts
        self.last_right_encoder_counts = right_encoder_counts


def dfs(i: int, j: int, row: int, col: int):
    if dp[i][j] > 0:
        return dp[i][j]
    maxi = 1
    for p in path:
        x = i + p[0]
        y = j + p[1]
        if 0 <= x < row and 0 <= y < col and matrix[x][y] > matrix[i][j]:
            len = 1 + dfs(x, y, row, col)
            maxi = max(maxi, len)
    dp[i][j] = maxi
    return maxi

matrix = []
while True:
    s = input().strip().strip(',')
    if s == ']':
        break
    elif s != '[':
        matrix.append(eval(s))
dp = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]
path = [[0, 1], [0, -1], [1, 0], [-1, 0]]  # 下，上，右，左
# print(matrix)
ans = 0
row, col = len(matrix), len(matrix[0])
for i in range(row):
    for j in range(col):
        ans = max(ans, dfs(i, j, row, col))
print(ans)


class Constant(object):
    @classmethod
    def all(cls):
        members = [getattr(cls, attr) for attr in dir(cls)
                   if not callable(getattr(cls, attr)) and not
                   attr.startswith("__")]
        return members

    @classmethod
    def isValid(cls, value):
        return value in cls.all()

    @classmethod
    def areValid(cls, values):
        return all([cls.isValid(value) for value in values])

class POLOPTS(Constant):
    XL = 'XL'
    YR = 'YR'
    AVG = 'Avg'

class CALOPTS(Constant):
    RAW = 'Raw'
    TOTALPOWER = 'TotalPower'
    DUALBEAM = 'DualBeam'
    BEAMSWITCH = 'BeamSwitch'
    BEAMSWITCHEDTBONLY = 'BeamSwitchedTBOnly'

class POLS(Constant):
    X = 'X'
    Y = 'Y'
    L = 'L'
    R = 'R'
    LINEAR = (X, Y)
    CIRCULAR = (L, R)

    @classmethod
    def all(cls):
        return cls.LINEAR + cls.CIRCULAR


import urllib.request              #import packages
from tkinter import *
from bs4 import BeautifulSoup
#=============GUI FORM==================

root=Tk()
root.geometry("1200x1200")
root.title("Current Weather")

TopFrame=Frame(root,width=1350,height=10,bd=14,relief='raise')
TopFrame.pack(side=TOP)

BottomFrame=Frame(root,width=350,height=50,bd=14,relief='raise')
BottomFrame.pack(side=BOTTOM)
LeftMidFrame=Frame(root,width=1350,height=1150,bd=14,relief="raise")
LeftMidFrame.pack(side=LEFT)

#======================TEXT FIELDS AND LEBLES===================
global city,weather;

city=StringVar()
weather=StringVar()
Title=Label(TopFrame,font=('arial',24,'bold'),text="Check the current temperature",bd=10,width=45,justify='center')
Title.grid(row=1,column=1)

enter=Label(LeftMidFrame,font=('arial',18,'bold'),text="Enter the name of a proper city in India :",bd=1,width=80,justify='left')
enter.grid(row=0,column=0)

cityname=Entry(LeftMidFrame,font=('arial',14,'bold'),textvariable=city,bd=10,width=30,relief="sunken")
cityname.grid(row=1,column=0)
output=Label(LeftMidFrame,font=('arial',14,'bold'),textvariable=weather,bd=10,width=50,relief="sunken")
output.grid(row=2,column=0)

#============function of button=============

def set_val():
    city=cityname.get()
    print(city)
    quote_page = "https://www.timeanddate.com/weather/india/"+city
    page = urllib.request.urlopen(quote_page)
    soup = BeautifulSoup(page, "html.parser")                                    #====scraping=======#
    name_box = soup.find("header",{'class':'fixed'})
    name = name_box.text.strip()
    temp_box = soup.find("div",{'class':'h2'})
    temp = temp_box.text.strip()
    outlook = soup.find("p")
    out = outlook.text.strip()
    time = soup.find("span",{'id':'wtct'})
    ti= time.text.strip()
    total=name+"\n"+"temperature :"+temp+"\n"+"Outlook :"+out+"\n"+"current date and time :"+ti
    print(total)
    weather.set(total)                                                                #---set value to the text field

btn=Button(BottomFrame,font=('arial',18,'bold'),text='Submit',bd=2,command=set_val)
btn.grid(row=1,column=0)


from __future__ import print_function

import os
import urllib.request

from selenium import webdriver

print("Testing Internet Connection")
print()
try:
    urllib.request.urlopen(
        "http://google.com", timeout=2
    )  # Tests if connection is up and running
    print("Internet is working fine!")
    print()
    question = input("Do you want to open a website? (Y/N): ")
    if question == "Y":
        print()
        search = input("Input website to open (http://website.com) : ")
    else:
        os._exit(0)

except urllib.error.URLError:
    print("No internet connection!")  # Output if no connection

browser = webdriver.Firefox()
browser.get(search)
os.system("cls")  # os.system('clear') if Linux
print("[+] Website " + search + " opened!")
browser.close()


from unittest.mock import patch

from django.test import TestCase

import vcr

from data_refinery_common.models.ontology_term import OntologyTerm, get_human_readable_name_from_api

class TestOntologyTerm(TestCase):
    @vcr.use_cassette("/home/user/data_store/cassettes/common.ontology_term.import_from_api.yaml")
    def test_get_or_create_from_api_fetches(self):
        self.assertEqual(
            "month", OntologyTerm.get_or_create_from_api("UO:0000035").human_readable_name
        )

    @vcr.use_cassette("/home/user/data_store/cassettes/common.ontology_term.invalid.yaml")
    def test_get_or_create_invalid_term(self):
        self.assertRaises(ValueError, OntologyTerm.get_or_create_from_api, "UO:9999999")

    @patch("data_refinery_common.models.ontology_term.get_human_readable_name_from_api")
    def test_get_or_create_from_api_returns_cached(self, mock_api_call):
        mock_api_call.return_value = "medulloblastoma"

        self.assertEqual(
            "medulloblastoma",
            OntologyTerm.get_or_create_from_api("EFO:0002939").human_readable_name,
        )

        mock_api_call.assert_called_once_with("EFO:0002939")
        mock_api_call.reset_mock()

        self.assertEqual(
            "medulloblastoma",
            OntologyTerm.get_or_create_from_api("EFO:0002939").human_readable_name,
        )

        mock_api_call.assert_not_called()

    @vcr.use_cassette(
        "/home/user/data_store/cassettes/common.ontology_term.import_entire_ontology.yaml"
    )
    @patch("data_refinery_common.models.ontology_term.get_human_readable_name_from_api")
    def test_import_entire_ontology(self, mock_api_call):
        # We shouldn't be hitting the API at all here, because we should have
        # the ontology already imported
        mock_api_call.return_value = "The wrong answer"

        # I used the UO ontology here because it is much smaller than other important
        # ontologies like EFO, which could take upwards of a minute to download and parse
        created_terms = OntologyTerm.import_entire_ontology("uo")

        self.assertEqual(
            OntologyTerm.objects.all().count(),
            559,  # Since we are using a VCR, this number should not change until we refresh it
        )
        self.assertEqual(OntologyTerm.objects.all().count(), created_terms)

        self.assertEqual(
            "month", OntologyTerm.get_or_create_from_api("UO:0000035").human_readable_name
        )

        mock_api_call.assert_not_called()

    @vcr.use_cassette("/home/user/data_store/cassettes/common.ontology_term.import_cl.yaml")
    @patch("data_refinery_common.models.ontology_term.get_human_readable_name_from_api")
    def test_import_cl(self, mock_api_call):
        """Try importing the CL ontology, which was updated at some point and
        broke the original parsing code"""

        # We shouldn't be hitting the API at all here, because we should have
        # the ontology already imported
        mock_api_call.return_value = "The wrong answer"

        created_terms = OntologyTerm.import_entire_ontology("cl")

        self.assertEqual(
            OntologyTerm.objects.all().count(),
            2493,  # Since we are using a VCR, this number should not change until we refresh it
        )
        self.assertEqual(OntologyTerm.objects.all().count(), created_terms)

        self.assertEqual(
            "hematopoietic cell",
            OntologyTerm.get_or_create_from_api("CL:0000988").human_readable_name,
        )

        mock_api_call.assert_not_called()

    @vcr.use_cassette(
        "/home/user/data_store/cassettes/common.ontology_term.import_cellosaurus.yaml"
    )
    @patch("data_refinery_common.models.ontology_term.get_human_readable_name_from_api")
    def test_import_cellosaurus(self, mock_api_call):
        """The cellosaurus ontology is not part of the OLS so we need to handle
        it separately. We still include it because metaSRA uses its terms.

        NOTE: the actual cellosaurus ontology is massive, so this VCR was
        created using a trimmed-down cellosaurus ontology where I went in and
        deleted a bunch of the publications and cell lines from the respective
        lists. Besides this, no alterations were made to the original."""

        # We shouldn't be hitting the API at all here, because we should have
        # the ontology already imported
        mock_api_call.return_value = "The wrong answer"

        created_terms = OntologyTerm.import_entire_ontology("cvcl")

        self.assertEqual(
            OntologyTerm.objects.all().count(),
            34,  # This is the number I counted in the file
        )
        self.assertEqual(OntologyTerm.objects.all().count(), created_terms)

        self.assertEqual(
            "#W7079",
            OntologyTerm.get_or_create_from_api("CVCL:E549").human_readable_name,
        )

        mock_api_call.assert_not_called()

    @vcr.use_cassette(
        "/home/user/data_store/cassettes/common.ontology_term.cellosaurus_import_from_api.yaml"
    )
    def test_get_or_create_from_cellosaurus_api(self):
        self.assertEqual(
            "LNCaP", OntologyTerm.get_or_create_from_api("CVCL:0395").human_readable_name
        )


from src.main.exceptions.already_exist_exception import AlreadyExistException
from src.main.exceptions.base_exception import ApplicationException
from src.main.exceptions.handler import ProcessException
from src.main.exceptions.unauthorized_exception import UnauthorizedException

def test_handler_unauthorized_exc():
    exception = UnauthorizedException
    response = ProcessException(request=None, exception=exception)
    assert response.status_code == 401

def test_handler_already_exist_exc():
    exception = AlreadyExistException
    response = ProcessException(request=None, exception=exception)
    assert response.status_code == 400

def test_handler_base_exc():
    exception = ApplicationException
    response = ProcessException(request=None, exception=exception)
    assert response.status_code == 500

def test_handler_another_exc():
    exception = Exception
    response = ProcessException(request=None, exception=exception)
    assert response.status_code == 500


#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import json
import datetime
import os

from base_cgi import TASK_DATA_PATH

def load_local_json(filename):
    with open(filename, encoding="utf8") as f:
        data = f.read()
    try:
        data = json.loads(data)
    except:
        data = {}

    return data

def save_local_json(data, filename):
    try:
        data = json.dumps(data)
    except:
        return False
    with open(filename, "w", encoding="utf8") as f:
        f.write(data)

    return True

def query_task_data_file():
    files_list = []
    for root, dirs, files in os.walk(TASK_DATA_PATH):
        files_list += files
    files_list = [os.path.splitext(x)[0].encode("utf8", errors='surrogateescape').decode("utf8") for x in files_list]

    return files_list

def query_task_file_name(task):
    files_list = []
    for root, dirs, files in os.walk(TASK_DATA_PATH):
        files_list += files
    filesname_list = [os.path.splitext(x)[0].encode("utf8", errors='surrogateescape').decode("utf8") for x in files_list]
    for idx, f in enumerate(filesname_list):
        if f == task:
            return files_list[idx]
    return None

def get_today_date():
    return datetime.datetime.now().strftime("%Y-%m-%d")

def get_now_date():
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")


import typing

def extGCD(a: int, b: int) -> typing.Tuple[int, int, int]:
    '''ax + by = gcd(a, b) を満たす整数解x, yを求める

    Returns:
        gcd(a, b), x, y

    Reference:
        https://qiita.com/akebono-san/items/f00c0db99342a8d68e5d
    '''

    x, y, u, v = 1, 0, 0, 1  # 単位行列
    p, q = a, b
    while q:
        k = p // q
        x -= k * u
        y -= k * v
        x, u = u, x
        y, v = v, y
        p, q = q, p % q
    return x * a + y * b, x, y

def inv_mod(a: int, m: int) -> int:
    '''法 m の元での a の逆元を求める

    Constraints:
        m と a は互いに素

    Returns:
        x (int): 法 m の元での a の逆元
        ※ m と a が互いに素でない場合は-1を返す

    Notes:
        ax = 1 (mod m)
        ax = 1 + -qm  (整数q)
        ax + mq = 1  -> (x, q)の解をextGCDで求める
    '''
    d, x, q = extGCD(a, m)
    x %= m
    if x < 0:
        x -= m
    return x if d == 1 or d == -1 else -1

def _crt_pair(b1: int, m1: int, b2: int, m2: int) -> typing.Tuple[int, int]:
    """以下の連立合同式を満たす最小の非負整数 r を求める
        r = b1 (mod m1)
        r = b2 (mod m2)

    Args:
        b1 (int): r = b1 (mod m1)
        m1 (int):
        b2 (int): r = b2 (mod m2)
        m2 (int):

    Returns:
        typing.Tuple[int, int]: R, M (0 <= R < M, M = gcd(m1, m2))を返す。解が存在しないとき(0, -1)を返す。

    Notes:
        > m1x + m2y = d  (d = gcd(m1, m2)) を満たすx, yを求める
        > r = b1 + m1 * x * ((b2 - b1) // d)
        > (b2 - b1) % d != 0 のとき解は存在しない

    """
    d, x, y = extGCD(m1, m2)
    if (b2 - b1) % d != 0:
        R, M = 0, -1
    else:
        c = (b2 - b1) // d
        M = (m1 * m2) // d
        R = (m1 * x * c + b1) % M
    return R, M

def crt(b: typing.List[int], m: typing.List[int]) -> typing.Tuple[int, int]:
    """連立合同式を満たす最小の非負整数 r を求める
        r = b1 (mod m1)
        r = b2 (mod m2)
        ...
        r = bn (mod mn)

    Args:
        b (typing.List[int]): r = bi (mod mi)
        m (typing.List[int]): r = bi (mod mi)

    Returns:
        typing.Tuple[int, int]: R, M (0 <= R < M, M = gcd(m1, m2))を返す。解が存在しないとき(0, -1)を返す。

    Reference:
        https://qiita.com/drken/items/ae02240cd1f8edfc86fd#%E5%95%8F%E9%A1%8C-2yukicoder-0187-%E4%B8%AD%E8%8F%AF%E9%A2%A8-hard

    Notes:
        > R = 0 (mod 1) (-> 任意の整数) を初期値として、順に_crt_pairを適用していく
    """
    N = len(b)
    assert len(m) == N, '!Size of arguments b and m must be equal!'

    R, M = 0, 1
    for i in range(N):
        R, M = _crt_pair(R, M, b[i], m[i])
        if M == -1:
            break
    return R, M

'''
[ABC186 - E]
ax + by = c の一般解
 x = b't + c'x'
 y = -a't + c'y'
 (a' = a // d,
  b' = b // d,
  c' = c // d,
  x', y': ax + by = gcd(a, b) の解の一つ)
'''

def validate_inv_mod():
    '''ABC186-E
    https://atcoder.jp/contests/abc186/tasks/abc186_e
    '''
    from math import gcd
    T = int(input())
    query = [tuple(map(int, input().split())) for _ in range(T)]
    for N, S, K in query:
        d = gcd(N, gcd(S, K))
        A, B, M = K // d, S // d, N // d
        x = inv_mod(A, M)
        if x == -1:
            print(-1)
        else:
            print((-B * x) % M)

def validate_crt():
    '''ABC193-E
    https://atcoder.jp/contests/abc193/tasks/abc193_e
    '''
    INF = (1 << 64)
    T = int(input())
    case = [tuple(map(int, input().split())) for _ in range(T)]
    for X, Y, P, Q in case:
        Z = 2 * (X + Y)
        R = P + Q
        ans = INF
        for i in range(X, X + Y):
            for j in range(P, P + Q):
                r, m = crt([i, j], [Z, R])
                if m >= 0:
                    ans = min(ans, r)
        print(ans if ans < INF else 'infinity')

def validate_crt_2():
    """yukicoder No.186
    https://yukicoder.me/problems/no/186
    """
    X = [0] * 3
    Y = [0] * 3
    for i in range(3):
        X[i], Y[i] = map(int, input().split())
    r, m = crt(X, Y)
    if m == -1:
        print(-1)
    else:
        print(r if r > 0 else m)

# validate_inv_mod()
# validate_crt()
validate_crt_2()


# -*- coding: utf-8 -*-
"""
Created on Mon May  3 18:24:01 2021

@author: krist
"""
import pandas as pd

# definerer funksjonen som blir kalt av hovedprogrammet(planer.py)
# funksjonen resetter alle midlertidige csv-filer slik at de er klase for ny informasjon
def resett():
    # Definerer dataframes ved hjelp av pandas
    room_df = pd.DataFrame(data={'Date': [], 'kWh': [], 'Temp': []})
    price_df = pd.DataFrame(data={'Date': [], 'kr/kWh': []})
    prod_h_df = pd.DataFrame(data={'Date': [], 'Time': [], 'kWh': []})
    bill_temp_df = pd.DataFrame(data={'Week': [], 'Date': [], 'Kr': []})
    consum_temp_df = pd.DataFrame(data={'Date': [], 'kWh': []})

    # lager csv-fila
    prod_h_df.to_csv('temp_csv/Panel_production_hour.csv', index=False)
    room_df.to_csv('temp_csv/Heating_Room.csv', index=False)
    price_df.to_csv('temp_csv/avg_price_day.csv', index=False)
    bill_temp_df.to_csv('temp_csv/bill_temp.csv', index=False)
    consum_temp_df.to_csv('temp_csv/El_consumption_temp.csv', index=False)

DataTekProsjektGitHub/Datatek Prosjekt Kode/Python Kode/resett_csv.py


import numpy as np

# Brute force by loading in primes.txt, containing prime numbers.
# Primes were also found by brute force (see is_prime.py).
# Could also just use some files you can find online. Could have used
# Sieve of Atkin, but too lazy to implement.

f = open("primes.txt", "r")
primes = f.readlines()
for x in range(0, len(primes)):
    primes[x] = int(primes[x].rstrip())

Limit = 600851475143
Found = False
max_prime_div = 2

while not Found:
    for num in primes:
        if Limit % num == 0:
            max_prime_div = num
            Limit /= num
            if Limit == 1:
                Found = True

print(max_prime_div)


from collections import OrderedDict

def getVariables(region):
    """
    Input region
    Output variable information dictionary according to your choice
    """

    defaultvariables = OrderedDict([
#        ('nsi_betweenness',{'latex':"betweenness^{*,euc}, l=12.0.",'units':'','nbins':21,'xmin':0.,'xmax':50000}), # 0.015
#        ('nsi_average_neighbors_degree',{'latex':"k_{nn,\nu}^{*,city}, l=20.0",'units':'','nbins':20,'xmin':0.5,'xmax':0.73}),
#        ('nsi_',{'latex':"k_{\nu}^{*,city}, l=100.0",'units':'','nbins':25,'xmin':0,'xmax':0.8}),
#        ('nsi_local_clustering',{'latex':"C_{\nu}^{*,city}, l=20.0"  ,'units':'','nbins':20,'xmin':0.6,'xmax':0.97}),
#        ('nsi_local_soffer_clustering',{'latex':"C_{\nu}^{*,euc}, l=70.0"  ,'units':'','nbins':25,'xmin':0.3,'xmax':1.1}),
#        ('nsi_max_neighbors_degree',{'latex':"k_{nnmax,\nu}^{*,city}, l=20.0",'units':'','nbins':22,'xmin':0.79,'xmax':0.865}),
        ('nsi_degree',{'latex':"k_{\nu}^{*,euc}, l=12.0"  ,'units':'','nbins':10,'xmin':0,'xmax':1.0}),

#      ('lept1Pt'                        ,{'latex':"p_{T}^{l1}"  ,'units':'GeV','nbins':25,'xmin':0,'xmax':500}),
#      ('jet1Pt'                        ,{'latex':"p_{T}^{j1}"  ,'units':'GeV','nbins':25,'xmin':0,'xmax':500}),
#      ('lept2Pt'                        ,{'latex':"p_{T}^{l2}"  ,'units':'GeV','nbins':20,'xmin':0,'xmax':400}),
#      ('lept3Pt'                        ,{'latex':"p_{T}^{l3}"  ,'units':'GeV','nbins':15,'xmin':0,'xmax':350}),
      #    ('lept1Phi'                       ,{'latex':"\phi^{l1}"  ,'units':'rad','nbins':15,'xmin':-3.2,'xmax':3.2}),
      #    ('lept2Phi'                       ,{'latex':"\phi^{l2}"  ,'units':'rad','nbins':15,'xmin':-3.2,'xmax':3.2}),
      #    ('lept3Phi'                       ,{'latex':"\phi^{l3}"  ,'units':'rad','nbins':15,'xmin':-3.2,'xmax':3.2}),
      #      ('NjS'                        ,{'latex':"n^{S}_{J}"           ,'units':'1'   ,'nbins':6,'xmin':0,'xmax':6}),
      #      ('NjISR'                        ,{'latex':"n^{ISR}_{J}"           ,'units':'1'   ,'nbins':6,'xmin':0,'xmax':6}),
#      ('mll'                          ,{'latex':"m_{ll}"        ,'units':'GeV','nbins':40,'xmin':0,'xmax':400}),
#      ('ptll'                          ,{'latex':"p_{T}^{ll}"        ,'units':'GeV','nbins':40,'xmin':0,'xmax':400}),
#      ('mTW'                       ,{'latex':"m_{T}^{W}"        ,'units':'GeV','nbins':25,'xmin':0,'xmax':250}),
#      ('met'     ,{'latex':"E_{T}^{miss}"  ,'units':'GeV','nbins':10,'xmin':0,'xmax':250}),
#      ('min_mt',{'latex':"m_{T}^{min}"  ,'units':'GeV','nbins':25,'xmin':0,'xmax':200}),
#        ('braycurtis_nsi_average_neighbors_degree',{'latex':"avg neigh deg"  ,'units':'','nbins':25,'xmin':0,'xmax':0.6})
#        ('nsi_degree',{'latex':"euc degree, l=100"  ,'units':'','nbins':25,'xmin':0,'xmax':1}),
#        ('nsi_average_neighbors_degree',{'latex':"cheb avg neighbors degree, l=60"  ,'units':'','nbins':25,'xmin':0,'xmax':1}),
#        ('nsi_exponential_closeness',{'latex':"CC_{EC,\nu}^{*,euc}, l=12.",'units':'','nbins':20,'xmin':0,'xmax':0.6}),
#        ('nsi_exponential_clustering',{'latex':"C_{EC,\nu}^{*,euc}, l=12.",'units':'','nbins':20,'xmin':0,'xmax':0.6}),
#        ('nsi_harmonic_closeness',{'latex':"CC_{HC,\nu}^{*,city}, l=100.0",'units':'','nbins':25,'xmin':0,'xmax':0.8}),
#        ('nsi_harmonic_closeness',{'latex':"CC_{HC,\nu}^{*,euc}, l=12.",'units':'','nbins':20,'xmin':0,'xmax':1.01}),
#        ('nsi_degree',{'latex':"k_{\nu}^{*,corr}, l=0.03",'units':'','nbins':25,'xmin':0,'xmax':0.95}),
#        ('nsi_degree',{'latex':"k_{\nu}^{*,euc}, l=12.",'units':'','nbins':20,'xmin':0,'xmax':0.95}), # 0.015
    ])

    jetvariables = OrderedDict([
      ('nJets'                        ,{'latex':"n^{20}_{J}"           ,'units':'1'   ,'nbins':6,'xmin':0,'xmax':6}),
      ('nBtagJets',{'latex':"n^{20,77}_{b}"        ,'units':'1'   ,'nbins':6,'xmin':0,'xmax':6}),
      ('jet1Pt'                        ,{'latex':"p_{T}^{jet,lead}"   ,'units':'GeV','nbins':25,'xmin':0,'xmax':500}),
      ('jet2Pt'                        ,{'latex':"p_{T}^{jet,sublead}",'units':'GeV','nbins':25,'xmin':0,'xmax':500}),
      #      ('jet1Phi'                        ,{'latex':"\phi^{jet,lead}"   ,'units':'GeV','nbins':25,'xmin':0,'xmax':500}),
    ])

    variables = OrderedDict()

    if ("my_custom_region" in region):
        variables.update(defaultvariables)
    else:
        variables.update(defaultvariables)
    return variables


from setuptools import setup, find_namespace_packages

with open('requirements.txt') as f:
    requirements = f.read().splitlines()

setup(
    # This is the name of your project. The first time you publish this
    # package, this name will be registered for you. It will determine how
    # users can install this project, e.g.:
    #
    # $ pip install sampleproject
    #
    # And where it will live on PyPI: https://pypi.org/project/sampleproject/
    #
    # There are some restrictions on what makes a valid project name
    # specification here:
    # https://packaging.python.org/specifications/core-metadata/#name
    name='tradeframework',  # Required

    # Versions should comply with PEP 440:
    # https://www.python.org/dev/peps/pep-0440/
    #
    # For a discussion on single-sourcing the version across setup.py and the
    # project code, see
    # https://packaging.python.org/en/latest/single_source_version.html
    version='0.2.0',  # Required

    # This is a one-line description or tagline of what your project does. This
    # corresponds to the "Summary" metadata field:
    # https://packaging.python.org/specifications/core-metadata/#summary
    description='A back testing framework',  # Required

    install_requires=requirements,

    # dependency_links=['-e git+https://github.com/cwilko/quantutils#egg=quantutils'],

    # You can just specify package directories manually here if your project is
    # simple. Or you can use find_packages().
    #
    # Alternatively, if you just want to distribute a single Python file, use
    # the `py_modules` argument instead as follows, which will expect a file
    # called `my_module.py` to exist:
    #
    #   py_modules=["my_module"],
    #
    packages=find_namespace_packages(include=['tradeframework.*']),  # Required

)